Encrypting query string for both normal and postback request

This code is to encrypt the query string send back and forth in web navigation.  If you are dealing with normal navigation then you don’t need to create ActionlessForm.dll and reference it. Simply add QueryStringModule class and add QueryStringModule in web.config.

But if you have post back events in page then you need to create ActionlessForm.dll and reference it and registered it in aspx page.

 // 1. Save this QueryStringModule class in App_Code under main ASP.NET Web Application

#region Using

using System;
using System.IO;
using System.Web;
using System.Text;
using System.Security.Cryptography;

#endregion

/// <summary>
/// Summary description for QueryStringModule
/// </summary>
public class QueryStringModule : IHttpModule
{

#region IHttpModule Members

public void Dispose()
{
// Nothing to dispose
}

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}

#endregion

private const string PARAMETER_NAME = “encString=”;
private const string ENCRYPTION_KEY = “yourEncryptionKey”;

void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Request.Url.OriginalString.Contains(“aspx”) && context.Request.RawUrl.Contains(“?”))
{
string query = ExtractQuery(context.Request.RawUrl);
string path = GetVirtualPath();

if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
{
// Decrypts the query string and rewrites the path.
string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
string decryptedQuery = Decrypt(rawQuery);
context.RewritePath(path, string.Empty, decryptedQuery);
}
else if (context.Request.HttpMethod == “GET”)
{
// Encrypt the query string and redirects to the encrypted URL.
// Remove if you don’t want all query strings to be encrypted automatically.
string encryptedQuery = Encrypt(query);
context.Response.Redirect(path + encryptedQuery);
}
}
}

/// <summary>
/// Parses the current URL and extracts the virtual path without query string.
/// </summary>
/// <returns>The virtual path of the current URL.</returns>
private static string GetVirtualPath()
{
string path = HttpContext.Current.Request.RawUrl;
path = path.Substring(0, path.IndexOf(“?”));
path = path.Substring(path.LastIndexOf(“/”) + 1);
return path;
}

/// <summary>
/// Parses a URL and returns the query string.
/// </summary>
/// <param name=”url”>The URL to parse.</param>
/// <returns>The query string without the question mark.</returns>
private static string ExtractQuery(string url)
{
int index = url.IndexOf(“?”) + 1;
return url.Substring(index);
}

#region Encryption/decryption

/// <summary>
/// The salt value used to strengthen the encryption.
/// </summary>
private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());

/// <summary>
/// Encrypts any string using the Rijndael algorithm.
/// </summary>
///inputText”>The string to encrypt.
/// A Base64 encrypted string.
public static string Encrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] plainText = Encoding.Unicode.GetBytes(inputText);
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
return “?” + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}

/// <summary>
/// Decrypts a previously encrypted string.
/// </summary>
/// <param name=”inputText”>The encrypted string to decrypt.</param>
/// <returns>A decrypted string.</returns>
public static string Decrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}

#endregion

}

//  2. For postback create dll file and add as reference (Add new ASP.NET Web Application called ‘ActionlessForm’)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace ActionlessForm
{
public class Form : System.Web.UI.HtmlControls.HtmlForm
{
protected override void RenderAttributes(HtmlTextWriter writer)
{
writer.WriteAttribute(“name”, this.Name);
base.Attributes.Remove(“name”);

writer.WriteAttribute(“method”, this.Method);
base.Attributes.Remove(“method”);

this.Attributes.Render(writer);

base.Attributes.Remove(“action”);

if (base.ID != null)
writer.WriteAttribute(“id”, base.ClientID);
}
}
}

// 3. Finally add this in Web.config of main ASP.NET Web Application

<httpModules>
// <add type = “QueryStringModule” name = “QueryStringModule”/>
</httpModules>

 

//4. Register that ActionlessForm.dll assembly in aspx page

//  include this in aspx page.

<%@ Register TagPrefix=”skm” Namespace=”ActionlessForm” Assembly=”ActionlessForm” %>

// replace

<form id=”form1″ runat=”server”>

//with

<skm:Form id=”Form1″ method=”post” runat=”server”>

//and

</form>

//with

</skm:Form>

Advertisements

Merging multiple files

//Trigger file is to represent completion of process.

StreamWriter wrTrigger = null;
StreamWriter wrError = null;

// retrieve file and path info from configuration
string inputFolderName = ConfigurationSettings.AppSettings[“InputFolder”];
string outputFolderName = ConfigurationSettings.AppSettings[“OutputFolder”];
string outputFileName = ConfigurationSettings.AppSettings[“OutputFile”];
string outputFilePath = outputFolderName + outputFileName;
string outputTriggerFile = ConfigurationSettings.AppSettings[“OutputTriggerFile”];
string outputTriggerFilePath = outputFolderName + outputTriggerFile;
string numberofFiles = ConfigurationSettings.AppSettings[“NumberOfFiles”];
string outputErrorLogFile = ConfigurationSettings.AppSettings[“OutputErrorLogFile”];
string outputErrorLogFilePath = outputFolderName + outputErrorLogFile;
string ErrorLogfileBegins = ConfigurationSettings.AppSettings[“InnerErrorLogFile”];
bool exists = File.Exists(inputFolderName + ErrorLogfileBegins+”*.txt”);
int totalExpectedFiles = Convert.ToInt32(numberofFiles);
var inputFiles = Directory.GetFiles(inputFolderName, “netIDs*.txt”);

const int chunkSize = 2 * 1024; // 2KB

try
{
int countInputTriggerFiles = Directory.GetFiles(inputFolderName, “trigger*.txt”,     SearchOption.TopDirectoryOnly).Length;
if (countInputTriggerFiles > (totalExpectedFiles – 1) && !exists)
{
using (var output = File.Create(outputFilePath))
{
foreach (var file in inputFiles)
{
using (var input = File.OpenRead(file))
{
var buffer = new byte[chunkSize];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
wrTrigger = File.CreateText(outputTriggerFilePath);
wrTrigger.Write(“Ok”);
}
else
{
wrError = File.CreateText(outputErrorLogFilePath);
wrError.Write(“Error Occured while generating Student/Employee/DSV/Member files”);
}
}
catch (Exception ex)
{
wrError = File.CreateText(outputTriggerFilePath);
wrError.Write(ex);
}
finally
{
if (wrTrigger != null)
{
wrTrigger.Close();
}
if (wrError != null)
{
wrError.Close();
}

}

 

App.config

<!–?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<appSettings>
<add key=”InputFolder” value=”C:\\EDS\AllNetIDs\” />
<add key=”OutputFolder” value=”C:\\EDS\AllNetIDs\”/>
<add key=”OutputFile” value=”NetIDsAll.txt”/>
<add key=”OutputTriggerFile” value=”trigger_netids.txt”/>
<add key=”InnerErrorLogFile” value=”Error”/>
<add key=”OutputErrorLogFile” value=”ErrorLog.txt”/>
<add key=”NumberOfFiles” value=”4″/>
</appSettings>
</configuration>

Spliting file to multiple files

//This program simply read rows in text file and create multiple files and distribute rows in those files.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace SplitFile
{
class Program
{
static void Main(string[] args)
{
//get file path information
string destinationFolder = ConfigurationSettings.AppSettings[“DestFolderPath”].ToString();
string sourceFolder = ConfigurationSettings.AppSettings[“SourceFolderPath”].ToString();
string filename = ConfigurationSettings.AppSettings[“TxtFileName”].ToString();
string filePath = sourceFolder + filename;

// read number of files to divide to
int num = Convert.ToInt32(ConfigurationSettings.AppSettings[“NumberOfSplitFiles”]);

// get the size of each divided file to create
int size = (int)Math.Ceiling((double)((double)File.ReadAllLines(filePath).Length / (double)num));
// call the method
SplitCSV(destinationFolder, filePath, size);
}
public static void SplitCSV(string destFolder, string file, int size)
{
// get the file name (without extension and full path) to use as a base name to the series of files to be created
string fName= System.IO.Path.GetFileNameWithoutExtension(file);
// Read lines from source file
string[] arr = System.IO.File.ReadAllLines(file);

int filenum = 1;
var writer = new System.IO.StreamWriter(destFolder + GetFileName(fName, filenum));

int lineCount = 1;
// Loop through all source lines
for (int i = 0; i < arr.Length; i++)
{
// Current line
string line = arr[i];

// See if adding this line would exceed the size threshold
if (lineCount > size)
{
// Create a new file
filenum++;
lineCount = 1;
writer.Dispose();
writer = new System.IO.StreamWriter(destFolder + GetFileName(fName, filenum));
}
// Write the line to the current file
writer.WriteLine(line);
lineCount++;

}
writer.Dispose();
}

/// Get an output file name based on a number.

static string GetFileName(string prefix, int num)
{
return prefix + “-” + num.ToString(“000”) + “.txt”;
}
}
}

// Feel free to leave questions in comment section.

VBScript to read file and send email with SMTP installed on a server

If you have Microsoft IIS with SMTP installed on a server, you can use the following code to send a basic email message from within a script. Here I have included additional feature that reads entire text file and send email.

—————————————————————————————————

‘ Insure all variables are defined.

Option Explicit

‘ Define constants.
Const ForReading = 1
Const strFolderLocation = “D:\DemoVBScript\”
Const strSender = “yourname1@yourdomain.com”
Const strSendTo = “yourname2@yourdomain.com”
Const strSendTo2 = “yourname3@yourdomain.com”
Const Cc = “yourname4@yourdomain.com”
Const Bcc = “yourname5@yourdomain.com”
Dim strErrorLogFile : strErrorLogFile = “ErrorLog.txt”
Dim strTemp : strTemp = “”

‘ Define File System object used for file operations.
Dim oFSO : Set oFSO = CreateObject(“Scripting.FileSystemObject”)

If oFSO.FileExists(strFolderLocation & strErrorLogFile) Then
‘Call function to read all text from  file
strTemp = Replace(ReadAllFromFile(strFolderLocation & strErrorLogFile), vbcrlf, ”
“)
Call SendEmail(strSendTo & “; ” & strSendTo2, “Your Subject Line”, “Your heading of body message:

” & vbcrlf & vbcrlf & strTemp)
End If

‘ Undefine File System object.
Set oFSO = Nothing

‘ Call sendEmail function to send email
Sub SendEmail(strSendTos, strSubject, strTextBody)

On Error Resume Next
Err.Clear

Dim objMessage : Set objMessage = CreateObject(“CDO.Message”)

With objMessage
.Sender = strSender
.To = strSendTos
.Bcc = Bcc
.Cc = Cc
.Subject = strSubject
.HTMLBody = strTextBody
.Send
End With
Err.Clear
On Error Goto 0

end Sub

Function ReadAllFromFile(strFileName)
Dim F : Set f = oFSO.OpenTextFile(strFileName, ForReading)
ReadAllFromFile = f.ReadAll
Set F = Nothing
End Function

—————————————————————————————

Save above in file, say ‘FileEmailDemoScript.vbs’

Assume that you are in directory that has above vb script file and run following command from command prompt

> wscript FileEmailDemoScript.vbs

SET DIfference in SQL – M SQL Server

If you would like to represent Set Difference (A-B) in SQL, here is solution for you.

If you have two table say A and B and you want to retrieve all records that exists only in A but not in B and let us assume that A and B has relationship via attribute named ID.

Best way of doing and most efficient one:

SELECT DISTINCT A.* FROM (A LEFT OUTER JOIN B on A.ID=B.ID) WHERE B.ID IS NULL

Other way of doing same but not efficient ways:

1.

SELECT ID FROM A
EXCEPT
SELECT ID FROM B;

2.

SELECT DISTINCT *
FROM A
WHERE NOT EXISTS (SELECT * FROM B WHERE A.ID = B.ID);

3.

SELECT DISTINCT *
FROM A
WHERE NOT IN (SELECT * FROM B WHERE A.ID = B.ID);

If you have other way of doing same thing in more efficient way, I would appreciate if you share.

Enterprise Directory Service (EDS) LDAP programming in .NET

//This program simply retrieve result attributes value from EDS Server. You can now simply omit the //entry by comparison of attribute or attribute value OR simply can add attribute if not exists for entry //and set the default value.

public static void Main(string[] args)
{
StringBuilder sb;

//create text file to write result
StreamWriter wr;
string filepath = ConfigurationSettings.AppSettings[“FilePath”];
wr = File.CreateText(filepath);

//To pass connection, hostname and serverinformation to the LdapConnection object and you need to specify port 636 if you are using SSL
// string hostName =”eds.yourdomain.com:636″;
string hostName = ConfigurationSettings.AppSettings[“HostName”];
LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(hostName);

//  Set the connection.
LdapConnection connection = new LdapConnection(identifier);

//Create a NetworkCredential object named credential and pass it a valid user name and password.
string edsUserName = ConfigurationSettings.AppSettings[“EDSUserName”];
string edsPassword = ConfigurationSettings.AppSettings[“EDSPassword”];
NetworkCredential credential = new NetworkCredential(edsUserName, edsPassword);
LdapSessionOptions options = connection.SessionOptions;
options.ProtocolVersion = 3;
options.SecureSocketLayer = true;

//Set the Auth Type to Basic.
connection.AuthType = AuthType.Basic;

//Connect the credentials.Set the Credential property of the connection equal to the credential object.
connection.Credential = credential;

//specify a target directory object. This is equivalent to the starting
// string strTargetOU = “ou=People,dc=com,dc=yourcompany,dc=com”;
string strTargetOU = ConfigurationSettings.AppSettings[“TargetOU”];

//Set the search filter and attributes to return
// string strSearchFilter = “(&(objectClass=user)(email=*))”;
string strSearchFilter = ConfigurationSettings.AppSettings[“SearchFilter”];
string[] attributesToReturn = new string[] { “sn”, “givenName”, “mail”};

try
{
//create searchRequent object using target, filter and return attributes
SearchRequest searchRequest = new SearchRequest(strTargetOU, strSearchFilter, SearchScope.Subtree, attributesToReturn);

//  Cast the returning item as a search response object.
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);

//loop through search result entity collection
foreach (SearchResultEntry entry in searchResponse.Entries)
{

//Attributes collection for entity. Collection don’t hold the attribute if attribute’s value is not available for associated entity.
SearchResultAttributeCollection attributes = entry.Attributes;
// create list to store key, value (atrribute,value) pair
List> empList = new List>();
sb = null;

foreach (DirectoryAttribute attribute in attributes.Values)
{
//create stringbuilder object to store attribute value. if attribute has one-to-many relationship, do append it.
sb = new StringBuilder();
for (int i = 0; i < attribute.Count; i++)
{
if (attribute.Count == 1)
{
sb.Append(attribute[i].ToString());
}
//append value for one-to-many. Eg. one employee can be affiliated with list of groups like employee,member,staff,former-student
else
{
sb.Append(attribute[i].ToString());
if (i < attribute.Count – 1)
{
sb.Append(“,”);
}
}
}
//add to list
empList.Add(new KeyValuePair(attribute.Name, sb.ToString()));
}

//Sort list by key
empList.Sort(CompareKVPByKey);

//write result in file
writeInFile(empList, finduid, wr);
}
}
catch (Exception e)
{
Console.WriteLine(“\nUnexpected Exception:\n\t{0}: {1}”, e.GetType().Name, e.Message);
}
wr.Close();
}

//write in file
private static void writeInFile(List> empList, bool fuid, StreamWriter wrt)
{
for (int i = 0; i < empList.Count; i++)
{
wrt.Write(“{0}\t”, empList[i].Value);
}

//write in new line
wrt.WriteLine();
}

//compare by key in KeyValuePair<string, string>
private static int CompareKVPByKey(KeyValuePair x, KeyValuePair y)
{
return string.Compare(x.Key, y.Key, StringComparison.CurrentCultureIgnoreCase);
}
}

//You probably already know why I am using app.config file.

IT brain drain? No, it’s brain circulation

Nepal has already stepped for the age of Information Technology. Country can produce about eleven thousands IT graduates annually. Most of them are about to migrate to western countries. People are saying that country is at risk of a new wave of IT brain drain. Graduates ask that where are the facilities and career opportunities in the country for them? If not, then what is the option except migration? Here companies pay more for cleaning lady than a computer professional gets. Let’s think being a positive. The situation is not that serious. It is true that western countries are the most popular destinations for highly mobile IT professionals, and Nepalese professionals are not the exceptions. If the world of financial capital is mobile so is the world of human capital. Skilled professionals will continue to migrate to those markets that are efficient and competitive and salary is always going to be the real point. The current movement is not a brain drain and merely reflects the continuing mobility of the IT workforce.

Nepal is not experiencing an IT brain drain, but experiencing a mobile workforce, which is very typical of the IT industry anyway. It is also creating a highly skilled market of candidates in the country due to their worldly experiences. IT professionals have traditionally headed to the US and UK because they could earn more money than in Nepal and had the chance to work on leading edge technologies. It is not really affecting country as they are going to there for short periods then coming back to homeland to work in the long-term. Home really is where the heart is. On the other side those who can’t find work may have to look at alternatives. However there is not widespread unemployment amongst IT professionals in the country. There is still a significant net shortage of IT professionals in the country and local companies will compete strongly to attract and retain staff. People always chase good technology and good wages and so do IT professionals but the short-term lifestyle is not that important as they always have the option to come back to homeland. Not all stay abroad and when one-time expatriates return they may return with greater experience, knowledge, and savings. Technology and knowledge are transferred home; and an expatriate population may stimulate experts. Taken individually or together, these feedbacks may make an initial brain drain a long-term brain gain.It is always blamed for national education system but technical education is different from other as it has capability of producing international quality manpower. Nepal-funded colleges pay to educate students and then country sends them aboard and the jobs follow them. In fact, talent moving to aboard are bringing home their new expertise in droves – leading to a more complex, called ‘brain circulation’ not brain drain. As a result, economies can benefit from having professionals who work in, and/or have direct connections to places like Silicon Valley in the western countries. Many reports show that about 40 per cent of immigrants have helped to arrange business contracts back in their homelands; over 25 per cent are advising or consulting for companies back home, and some 18 per cent have invested their own money in start-ups or venture funds in their home countries. It is common for immigrants who have become a staple of Silicon Valley’s growth to export their experience, western entrepreneurial culture, back to their homelands. Theory and research suggest that the direct impact of a brain drain, that is a sizable loss of highly educated natives abroad, represents a reduction in the accumulation of human capital or knowledge. Still, many observers note that a brain drain can generate feedback effects that may yield positive economic gains for the migrant source countries.

Academic literature is uncomfortable with the term brain drain and prefers terms such as brain gain or brain circulation. With the comparatively low salaries offered here, Nepal also has to be considered not merely an excellent sourcing ground for talent, but also a low-cost center for IT projects. It wouldn’t be surprised if companies start to ramp up the outsourcing of IT projects to Nepal. It would be highly cost-effective. Further, remittances are a significant source of income for country. It has been calculated that 12 percentage of national budget is depend on remittances, although what proportion was sent by skilled emigrants is unknown.But policies must encourage return migration in the best long-term interest of the country and nation should have “knowledge-economy master plan” with mission of making competitive and dynamic knowledge-based economy in the world. But they must come with flexible mind that changing technology requires innovative brain circulation .We can’t keep the professionals at home if we can’t give them the same environment to work in. In the name of brain drain, country should not introduce any restrictions on professionals and shamelessly detain them from achieving desired goals in their life. Still our final challenge is nation’s weak IT infrastructure. If we want to progress in information play space, we have to continue to invest in IT with clear vision.