Use this regex
/^_?[a-zA-Z0-9]([a-zA-Z0-9]*[._+-])*[a-zA-Z0-9_]+@(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))*\.[A-Za-z]{2,}$/
Works like examples shows below:
Monday, January 19, 2026
Regex Email validation in c# dot net core
Monday, March 10, 2025
Regex obfuscate email
Use this code in C# to obfuscate email using regex
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
using System.Text.RegularExpressions;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine ("Try programiz.pro");
string _PATTERN = @"(?<=.{4}).(?=[^@]*?@)|(?:(?<=@.)|(?!^)\G(?=[^@]*$))(.)(?=.*\.)[a-zA-Z0-9]";
string s = "john.travolta12+-3878787@gmail.com";
string replacement = "*";
if (!s.Contains("@"))
Console.WriteLine( new String('*', s.Length));
if (s.Split('@')[0].Length < 4)
Console.WriteLine( @"*@*.*");
string result = Regex.Replace(s, _PATTERN, replacement);
Console.WriteLine(result);
}
}
Monday, September 9, 2024
c# httpclient The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch
If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remote server. In this case we could get around the issue by overriding certification validation logic like so:
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback = (httpRequestMessage, cert,
cetChain, policyErrors) => true
};
handler.AllowAutoRedirect =
false;
handler.ServerCertificateCustomValidationCallback
= (cert, chain, erros, flag)=> { return true; };
var apiClient = new HttpClient(handler);
apiClient.SetBearerToken(tokenResponse.AccessToken);
var response =
apiClient.GetAsync(apiUrl).Result;
Wednesday, April 24, 2024
SSL Error - The connection for this site is not secure
After cloning a git repo of dot net framework website and trying to run it all I could see was this error
Monday, March 25, 2024
C# generic type converter
Here is a way to create a generic type converter in c#
c# - How to Convert a String to a Nullable Type Which is Determined at Runtime? - Stack Overflow
Share cookies between dot net framework and dot net core
c# - share authentication cookie between .NET Framework and .Net Core - Stack Overflow
Monday, March 11, 2024
Visual Studio ( or VS Code) strip all attributes from html tags
This is a very simple shortcut, find and replace using following regex
Find - <(table|tr|td|p|div|span)[\S\s]*?\n?>
Replace - <$1>
Sunday, February 27, 2022
Winforms database first application
This guide explains the steps to create a winforms database first application
http://codehelper.net/entity-framework/winforms-net-core-tips/
Wednesday, February 23, 2022
SharePoint provider hosted app certificate trust issues
It is important to configure certificates correctly for a provider hosted app in SharePoint website since the authentication requires communication between Azure AD, SharePoint, and our app, which is hosted on a different IIS server.
I have added this method to TokenHelper class and call it in CSOM webpart methods to trust certificates
public class TokenHelper
{
#region public methods
/// <summary>
/// Configures .Net to trust all certificates when making network
calls. This is used so that calls
/// to an https SharePoint server without a valid certificate are not
rejected. This should only be used
during
/// testing, and should never be used
in a production app.
/// </summary>
public static void TrustAllCertificates()
{
//Trust
all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate,
chain, sslPolicyErrors) => true);
}
}
Also there are some articles which describe certificates trust configuration on a sharepoint farm
https://docs.microsoft.com/en-us/sharepoint/administration/exchange-trust-certificates-between-farms
https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/create-high-trust-sharepoint-add-ins
SharePoint CSOM get absolute url from FileRef
This one liner can return absolute url of an item using its FileRef property
SharePoint add in part - postback error localhost refused to connect
While developing an addin part using CSOM I was able to use a button to postback the data, but the addin part would show the error 'Localhost refused to connect'. So I was trying to find out why the addin part work on initial load but fails to load when postback method return the view.
After investingating the forms collection I noticed that there are some tokens added to the forms collection by sharepoint in the inital part load request. These tokens are used by IIS to validate the user request, thus they need to be sent with every request. The code below solved this issue:
In the controller I added the method CopyTokens
private void CopyTokens(AddInViewmodel
viewModel)
{
if (Request.Form["SPAppToken"] != null)
{
viewModel.SPAppToken =
Request.Form["SPAppToken"];
}
if (Request.Form["SPSiteUrl"] != null)
{
viewModel.SPSiteUrl =
Request.Form["SPSiteUrl"];
}
if (Request.Form["SPSiteTitle"] != null)
{
viewModel.SPSiteTitle =
Request.Form["SPSiteTitle"];
}
if (Request.Form["SPSiteLogoUrl"] != null)
{
viewModel.SPSiteLogoUrl =
Request.Form["SPSiteLogoUrl"];
}
if (Request.Form["SPSiteLanguage"] != null)
{
viewModel.SPSiteLanguage
= Request.Form["SPSiteLanguage"];
}
if (Request.Form["SPSiteCulture"] != null)
{
viewModel.SPSiteCulture =
Request.Form["SPSiteCulture"];
}
if (Request.Form["SPRedirectMessage"] != null)
{
viewModel.SPRedirectMessage =
Request.Form["SPRedirectMessage"];
}
if (Request.Form["SPCorrelationId"] != null)
{
viewModel.SPCorrelationId =
Request.Form["SPCorrelationId"];
}
if (Request.Form["SPErrorCorrelationId"] != null)
{
viewModel.SPErrorCorrelationId
= Request.Form["SPErrorCorrelationId"];
}
if (Request.Form["SPErrorInfo"] != null)
{
viewModel.SPErrorInfo =
Request.Form["SPErrorInfo"];
}
I called this method just before completing the postback handler
public ActionResult Index()
{
var viewModel = new AddInViewmodel();
TokenHelper.TrustAllCertificates();
string contextTokenString =
TokenHelper.GetContextTokenFromRequest(Request);
if (contextTokenString != null)
{
// Get
context token
var contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString,
Request.Url.Authority);
// Get
access token
Uri sharepointUrl = null;
if (Request.QueryString["SPAppWebUrl"] != null)
{
sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
var accessToken =
TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
}
var spContext =
SharePointContextProvider.Current.GetSharePointContext(HttpContext);
if (spContext != null)
{
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
// Code to fetch data from SharePoint site into view model
}
}
}
}
CopyTokens(viewModel);
return View(viewModel);
}
Lastly, I have added some hidden controls in the view to persist and send these tokens in each new postback request, also note the querystring parameters added to reqeust.
@using (Html.BeginForm(actionName: "Index", controllerName: "MyAddInWebpart",
routeValues: new
{
SPHostUrl = Request.QueryString["SPHostUrl"],
SPHostTitle = Request.QueryString["SPHostTitle"],
SPAppWebUrl = Request.QueryString["SPAppWebUrl"],
SPLanguage = Request.QueryString["SPLanguage"],
SPClientTag = Request.QueryString["SPClientTag"],
SPProductNumber = Request.QueryString["SPProductNumber"],
SenderId = Request.QueryString["SenderId"]
}, method: FormMethod.Post, htmlAttributes: new { }))
{
@*@Html.AntiForgeryToken()*@
@Html.HiddenFor(model => model.SPAppToken)
@Html.HiddenFor(model => model.SPSiteUrl)
@Html.HiddenFor(model => model.SPSiteTitle)
@Html.HiddenFor(model => model.SPSiteLogoUrl)
@Html.HiddenFor(model => model.SPSiteLanguage)
@Html.HiddenFor(model => model.SPSiteCulture)
@Html.HiddenFor(model =>
model.SPRedirectMessage)
@Html.HiddenFor(model => model.SPCorrelationId)
@Html.HiddenFor(model =>
model.SPErrorCorrelationId)
@Html.HiddenFor(model => model.SPErrorInfo)
<div class="form"><div class="form-group"><div class="form-row">
<input type="submit" class="btn btn-default" value="Save" />
</div></div></div>
}
Tuesday, December 14, 2021
c# mvc extended select List
The last solution in this post explains how extended select list can be implemented in MVC
https://stackoverflow.com/questions/7536631/adding-html-class-tag-under-option-in-html-dropdownlist/
Tuesday, October 26, 2021
MVC Error Handling
A good approach to error handling in MVC sites can be found at https://tech.trailmax.info/2013/08/error-handling-in-mvc-and-nice-error-pages/
Tuesday, July 27, 2021
SQL Snippet for transaction query
SQL snippets in SSMS is a very handy (thouth probably underused) feature to automate some repetative tasks. A collection of some useful snippets can be found at https://github.com/asathkumara/SSMS17-Code-Snippets
I decided to add a snippet to SSMS for frequently used query template like this
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<_locDefinition xmlns="urn:locstudio">
<_locDefault _loc="locNone" />
<_locTag _loc="locData">Title</_locTag>
<_locTag _loc="locData">Description</_locTag>
<_locTag _loc="locData">Author</_locTag>
<_locTag _loc="locData">ToolTip</_locTag>
<_locTag _loc="locData">Default</_locTag>
</_locDefinition>
<CodeSnippet Format="1.0.0">
<Header>
<Title>Transaction
Query Snippet</Title>
<Shortcut></Shortcut>
<Description>Code
Snippet for Transaction Query</Description>
<Author>Pranav
Kulkarni</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>query_statement</ID>
<ToolTip>Enter your Query statement(s) here.</ToolTip>
<Default>[...]</Default>
</Literal>
<Literal>
<ID>verify_statement</ID>
<ToolTip>Enter your verify statement(s) here.</ToolTip>
<Default>[...]</Default>
</Literal>
</Declarations>
<Code Language="SQL"><![CDATA[
DECLARE @exec int = 1
DECLARE @commit int = 0
DECLARE @verify int = 0
BEGIN TRAN
IF @exec = 1 BEGIN
--
Query Statements --
$query_statement$
END
if @verify = 1 begin
--
Verify Statements --
$verify_statement$
END
IF @commit = 1 BEGIN
COMMIT
TRAN
END
ELSE BEGIN
ROLLBACK
TRAN
END
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Regex Email validation in c# dot net core
Use this regex /^_?[a-zA-Z0-9]([a-zA-Z0-9]*[._+-])*[a-zA-Z0-9_]+@(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))*\.[A-...
-
If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remo...
-
While querying for events in a list which fall under a specified time period, the infopath form works correctly in client side editor, but ...
-
To download a file from web api 2 controller method, the approach described in this article works well: http://stackoverflow.com/question...