Encryption Using MachineKey in .NET Framework

In .NET Framework 4.6, 4.5, 4 you can now encrypt your text using MachineKey in your web.config file. This encryption depend on System.Web.dll so you need to add reference of it before. NOTES:

  • If you have multiple web front end server, then the machine key should be same on all WFEs.
  • You may need to use Base64 encoding to convert encrypted or decrypted bytes to text so you can send it over HTTP,email or any textual transfer system.

Encrypt Method

 private static string Encrypt(string plainText)
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

     byte[] encryptedBytes = MachineKey.Protect(plainTextBytes);

     string encryptedText = Convert.ToBase64String(encryptedBytes);

     return encryptedText;

Decrypt Method

 private static string Decrypt(string encryptedText)
     byte[] encryptedBytes = Convert.FromBase64String(encryptedText);

     byte[] plainTextBytes = MachineKey.Unprotect(encryptedBytes);

     string plainText = Encoding.UTF8.GetString(plainTextBytes);

     return plainText;

Using New Code Nuggets in ASP.NET4

We will talk about new feature in ASP.NET 4.

Suppose you have the following code-behind property and you need to use it in ASPX page.



In ASPX page you can render the property MyContent like below:



And this will render the below output:

This is an XSS (cross-site script injection) and the developer should be aware of this, so he should do an HTMLEncode


Because of many developer may forget to do this, ASP.NET introduced the below code nugget

Now, the result will be;


Updating Active Directory Field Using C#

In some cases you need to update one or more fields using C#, to do this follow-up the below code.

  • Make sure your application build is .Net 3.5

  • You need to add the following assemblies in your application reference
    • System.DirectoryServices.dll [C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll]
    • System.DirectoryServices.AccountManagement.dll [C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.DirectoryServices.AccountManagement.dll]
  • You need the following namespaces
    • using System.DirectoryServices.AccountManagement;
    • using System.DirectoryServices;

Here is the code

        public static bool UpdateFields(string Property, string sUserName, string Value)
            bool result = false;
            PrincipalContext domain = new PrincipalContext(ContextType.Domain, "", "OU=Users,DC=dev,DC=loc", ContextOptions.SimpleBind);
                // Search for the user in the domain
                PrincipalSearcher searcher = new PrincipalSearcher();
                UserPrincipal findUser = new UserPrincipal(domain);
                findUser.SamAccountName = sUserName;
                searcher.QueryFilter = findUser;
                UserPrincipal foundUser = (UserPrincipal)searcher.FindOne();
                if (foundUser != null)
                    using (DirectoryEntry baseEntry = foundUser.GetUnderlyingObject() as DirectoryEntry)
                        using (DirectoryEntry entry = new DirectoryEntry(baseEntry.Path, baseEntry.Username, "P@ssw0rd"))
                            entry.Properties[Property].Value = Value;
                            result = true;
                    return false;
            return result;

HTTP Error 404.2 – Not Found – WCF on Windows 7 and IIS7.5

When deploying a WCF service to IIS7 on top of Windows 7 and browse it, you may got the following error

HTTP Error 404.2 – Not Found

The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

Solution Open IIS Manager This will open the below screen. httperror403 Put check on below screen After the two changes, the screen should be like below Try now

Save InfoPath Attachment to SharePoint 2010 Document Library

I have a requirement where the business needs to save an attachment form InfoPath form to SharePoint document library direct.

1: Build the InfoPath form

Create three fields

  • WebSiteURL: string
  • DocLibName: string
  • Attachment: base64Binary

2: Build the Web Service

3: Connect InfoPath to Web Service

For more information, Calling Web Service from InfoPath 2010 with Parameters

4: Verify

Download source files (InfoPath & Web service)

How to Read from SharePoint 2013 List in 6 Ways

Suppose we have SharePoint 2013 and contains a list called “Users”

Now, there are 6 ways to ready the items for this list:

  • SharePoint 2013 Object Model (C#)
  • Client Side Object Model (CSOM)
  • SharePoint 2013 Web Services
  • REST/OData
  • Power Shell
  • LINQ

First, we need to install Microsoft Office Developer Tool for VS 2012 from this link,

because the VS 2012 come without and project for SharePoint 2013


After installing this your VS new project window will be like:

SharePoint 2013 Object Model (C#)

In this example I will create a new project of type “SharePoint 2013 – Visual Web Part”

In the user control, add a GrivView:

<asp:GridView runat=”server” ID=”grvUsers” />

In the Page Load event write the following code snippet

using (SPSite site=new SPSite(SPContext.Current.Site.Url))


using (SPWeb web=site.OpenWeb())


SPList list = web.Lists[“Users”];

grvUsers.DataSource = list.Items.GetDataTable();




  • Right click on the project and deploy it
  • Go to any SharePoint page and edit the page
  • Insert your web part into your page from “Custom” group
  • Save and close the page

Client Side Object Model (CSOM)

CSOM is a good choice for running a console or windows application on the end user machine and interact with

SharePoint 2013

Create a new project of type “Console Application”

For this, we need to add the following references:

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Client.Runtime

In the Main method write:

ClientContext cc = new ClientContext(“http://sp2013:2000&#8221;);

Web web = cc.Web;

List list = web.Lists.GetByTitle(“Users”);

CamlQuery caml=new CamlQuery();

ListItemCollection items = list.GetItems(caml);




foreach (Microsoft.SharePoint.Client.ListItem item in items)





SharePoint 2013 Web Services

To read from SharePoint list using web services and jQuery, use http://SPServices.codeplex.com

And for full documentation follow this link http://spservices.codeplex.com/wikipage?title=$().SPServices&referringTitle=Documentation

  • Copy the following JS files to SharePoint layouts “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS”
    • jQuery
    • SPServcies
  • Open SharePoint Designer 2013
  • Open the your site collection
  • Go to your master page
  • Open it and write the following scripts

<script src=”/_layouts/15/jQuery.js” type=”text/javascript” ></script>

<script src=”/_layouts/15/jQuery.js” type=”text/javascript” ></script>


operation: “GetListItems”,

async: false,

listName: “Users”,

CAMLViewFields: “<ViewFields><FieldRef Name=’Title’ /></ViewFields>”,

completefunc: function (xData, Status) {

$(xData.responseXML).SPFilterNode(“z:row”).each(function() {





Power Shell

In Power Shell you can use the following script:

$web=Get-SPWeb http://sp2013:2000




You use for-each in Power Shell to iterate through all items.

foreach ($item in $list.Items)

{Write-Host $item.Title}


For using REST you have two options:

  • jQuery
  • C# (HttpRequest & HttpResponse)

For REST reference follow this link OData in SharePoint 2013 – Lists and Items


To use LINQ, we will use SPMETAL

This will generate a CS file in C:\

Add this file to your application (Console or Windows)

Also, you need to add the following assembly

  • Microsoft.SharePoint.Linq

  • Add the generated class in Power Shell script to your project
  • Wirte the following code

MyWebDataContext context = new MyWebDataContext(“http://sp2013:2000&#8221;);

List<UsersItem> items=context.Users.ToList();

foreach (UsersItem item in items)





Getting Windows Certificate using C# By Serial Number

After installing a certificate in windows store, you need to use it in your code to encrypt or decrypt the message.


You can get the serial number of the certificate by double click on the certificate.

X509Store store = new X509Store(StoreLocation.LocalMachine); 
string sn = " put here your certificate serial number "; 
X509Certificate2Collection coll = 
store.Certificates.Find(X509FindType.FindBySerialNumber, sn, true); 
if (coll[0] != null)
   X509Certificate2 myCert = coll[0];