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;

Summery

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

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

http://www.microsoft.com/web/handlers/WebPI.ashx?command=GetInstallerRedirect&appid=OfficeToolsForVS2012GA

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();

grvUsers.DataBind();

}

}

  • 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);

cc.Load<List>(list);

cc.Load<ListItemCollection>(items);

cc.ExecuteQuery();

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

{

Console.WriteLine(item.FieldValues[“Title”]);

}

Console.ReadLine();

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>

$().SPServices({

operation: “GetListItems”,

async: false,

listName: “Users”,

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

completefunc: function (xData, Status) {

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

    alert($(this).attr(“ows_Title”));

});

}

});

Power Shell

In Power Shell you can use the following script:

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

$list=$web.Lists[“Users”]

$list.Items[0]

$list.Items[0][“Title”]

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

foreach ($item in $list.Items)

{Write-Host $item.Title}

REST/OData

For using REST you have two options:

  • jQuery
  • C# (HttpRequest & HttpResponse)

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

LINQ

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)

{

Console.WriteLine(item.Title);

}

Console.ReadLine();

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.

Certificate

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

X509Store store = new X509Store(StoreLocation.LocalMachine); 
store.Open(OpenFlags.ReadOnly); 
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];

The source was not found, but some or all event logs could not be searched.

The complete exception is :

System.Security.SecurityException: The source was not found, but some or all event logs could not be searched.

This happen when you are using in your code (C#) windows log events.

EventLog.WriteEntry(method, log_message, type);

Now, how to create this source in windows event log.

Solution

Using windows powershell.

  1. Run windows powershell under administrative privileges
  2. Run the following command New-EventLog -LogName Application -Source <YOUR SOURCE>