Thursday, July 09, 2009

Ever wondered about programming in Hindi !!

Sounds crazy and completely useless, doesn't it? But I am sure I will be able to change you mind about that but then end of this post. However it wont be feasible in the real world as we all work in teams and English remains the primary programming language.

I started, as always, with google and ended up here on my blog which rarely meets anyone (including me).

Anyway I started a new project in Visual Studio 2008 and voila! Magic happens -

public class myClass
{
public void MyHindiTextFunction()
{
प्रबंधक<कंपनी<int>, List<कंपनी<int>>> प्रबंधक१ = new प्रबंधक<कंपनी<int>, List<कंपनी<int>>>();
प्रबंधक<परियोजना<Guid>, HashSet<परियोजना<Guid>>> प्रबंधक२ = new प्रबंधक<परियोजना<Guid>, HashSet<परियोजना<Guid>>>();

प्रबंधक१.प्रबंधित_इकाईयां.AddRange(new List<कंपनी<int>> {
new कंपनी<int>(1, "company1"),
new कंपनी<int>(2, "company2"),
new कंपनी<int>(3, "company3"),
new कंपनी<int>(4, "company4"),
new कंपनी<int>(5, "company5") });

प्रबंधक२.प्रबंधित_इकाईयां.Add(new परियोजना<Guid>(Guid.NewGuid(), "project1"));
प्रबंधक२.प्रबंधित_इकाईयां.Add(new परियोजना<Guid>(Guid.NewGuid(), "project2"));
प्रबंधक२.प्रबंधित_इकाईयां.Add(new परियोजना<Guid>(Guid.NewGuid(), "project3"));
प्रबंधक२.प्रबंधित_इकाईयां.Add(new परियोजना<Guid>(Guid.NewGuid(), "project4"));
प्रबंधक२.प्रबंधित_इकाईयां.Add(new परियोजना<Guid>(Guid.NewGuid(), "project5"));

//Select company where company id is in the Product's guid as string 0-o
var क्वेरी = प्रबंधक१.प्रबंधित_इकाईयां.Join(
प्रबंधक२.प्रबंधित_इकाईयां,
क => क.संख्या.ToString(),
क => क.संख्या.ToString(),
(क, ख) => ख.संख्या.ToString().Contains(क.संख्या.ToString()));

}
}

public class प्रबंधक<इकाई_प्रकार, सरणी_प्रकार>
where सरणी_प्रकार : new()
{
private सरणी_प्रकार _प्रबंधित_इकाईयां;
public सरणी_प्रकार प्रबंधित_इकाईयां
{
get { return _प्रबंधित_इकाईयां; }
}

public प्रबंधक()
{
_प्रबंधित_इकाईयां = new सरणी_प्रकार();
}
}

public class कंपनी<कंपनी_संख्या_प्रकार>
{
public कंपनी_संख्या_प्रकार संख्या { get; set; }
public string नाम { get; set; }
public कंपनी(कंपनी_संख्या_प्रकार _संख्या, string _नाम)
{
संख्या = _संख्या;
नाम = _नाम;
}
}

public class परियोजना<कंपनी_संख्या_प्रकार>
{
public कंपनी_संख्या_प्रकार संख्या { get; set; }
public string नाम { get; set; }

public परियोजना(कंपनी_संख्या_प्रकार _संख्या, string _नाम)
{
संख्या = _संख्या;
नाम = _नाम;
}
}
}


I know I know.. Mad Scientist at work :) But is stands to reason that Generics and crazy LINQ is always fun and allows getting more hindi then you could otherwise :)

Further:
  • SKTN - You have to watch his videos. I went LOL+ROLF
  • add en2hi@bot.talk.google.com to GTalks :D
Observations:
  • VS2008 is not complete in supporting Unicode unless the underlying OS is. So Kick you XP and pirate Win7 (Tooltips, Intellisense etc are just square blocks)
  • You can use the hindi transtation of numbers (१, २, ३..) as vars. That are still numbers :[
  • Go to Control panel>Language Ops>Add Hindi keyboard and enable the Language Bar. After that start>Accessories>Accessibility>OnScreen Keyboard. Who the hell owns a hindi keyboard anyways

Note: XP goes crazy with hindi file and folder names and no one want to set Hindi as the primary language. Vista and Win 7 are much better if you rally want to try this.

Thursday, May 07, 2009

Windows 7 RC1 - Ready to plunge in

Well it is that time again. Another new windows version is about to be unleashed upon us. So, be good little geeks and dive headon. Worry about the breathing gear later.


That is how it is always with windows, but there is a bit of hope this time. may be we can dare to have a good feeling..


Check out an article on engadget on this.

Personally I am interested in the Windows Media Center. i hope it has received a generous amount of jazzing up :)

Monday, July 28, 2008

Secure/Encrypted cookies in ASP.NET with System.Cryptography

In today's world one cant transmit a digital syllable without some kind of protective wrapper around it. Us Neos of the binary world have always struggled with proper cipher methods to do so.

In other words, beginners always have had difficulty in implementing a reliable yet flexible method for securing cookies. I have used the following code often and I am sure this will help anyone looking for a quick-fix solution to secure cookies.

The basic architecture is to create static methods to which you pass a cookie and get a encrypted version in return. It also conveniently retrieves the Algorithm to use as well as the key to encrypt/decrypt from the web.config file and can be adapted to retrieve/generate the key in other ways.

Step 1: Start off with our class.

using System.Security.Cryptography; //and other...

public class Security
{
//If you dont want ur methods to be static then use this and instantiate an object before use
//byte[] Key;
//string AlgorithmName;

public Security()
{
//If you dont want ur methods to be static then use this
//char[] chars = { ',' };
//string[] splits = ConfigurationManager.AppSettings["CookieSecurityKey"].Split(chars);
//AlgorithmName = splits[0];
//Key = new byte[Int32.Parse(splits[1])];// = KEY_64;
//for (int i = 2; i < Key.Length + 2; i++)
// Key[i - 2] = byte.Parse(splits[i].Trim());
}
...

You can store the key/algoritm name in the web.config like this:








Step 2: Create the basic methods that encode/decode a piece of string

public static string Encode(string value, Byte[] key, string AlgorithmName)
{
// Convert string data to byte array
byte[] ClearData = System.Text.Encoding.UTF8.GetBytes(value);

// Now create the algorithm from the provided name
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = key; //you can apply your own key mechs here
MemoryStream Target = new MemoryStream();

// Generate a random initialization vector (IV), helps to prevent brute-force
Algorithm.GenerateIV();
Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);

// Encrypt information
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(ClearData, 0, ClearData.Length);
cs.FlushFinalBlock();

// Convert the encrypted stream back to string
return Convert.ToBase64String(Target.GetBuffer(), 0, (int)Target.Length);
}

public static string Decode(string value, Byte[] key, string AlgorithmName)
{
// Convert string data to byte array
byte[] ClearData = Convert.FromBase64String(value);

// Create the algorithm
SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
Algorithm.Key = key;
MemoryStream Target = new MemoryStream();

// Read IV and initialize the algorithm with it
int ReadPos = 0;
byte[] IV = new byte[Algorithm.IV.Length];
Array.Copy(ClearData, IV, IV.Length);
Algorithm.IV = IV;
ReadPos += Algorithm.IV.Length;

// Decrypt information
CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(ClearData, ReadPos, ClearData.Length - ReadPos);
cs.FlushFinalBlock();

// Get the bytes from the memory stream and convert them to text
return System.Text.Encoding.UTF8.GetString(Target.ToArray());
}
Note: there methods are static so that you can use them directly from code without the additional line to create an object.

Step 3: Create the methods that encode/decode the cookie

public static HttpCookie EncodeCookie(HttpCookie cookie)
{
if (cookie == null) return null;

//get key and algorithm from web.config/appsettings
//Comment this section if you do now what this method to be static
char[] chars = { ',' };
string[] splits = ConfigurationManager.AppSettings["CookieEncodingKey"].Split(chars);
string AlgorithmName = splits[0];
byte[] Key = new byte[Int32.Parse(splits[1])];// = KEY_64;
for (int i = 2; i < Key.Length + 2; i++)
Key[i - 2] = byte.Parse(splits[i].Trim());

HttpCookie eCookie = new HttpCookie(cookie.Name);

for (int i = 0; i < cookie.Values.Count; i++)
{
string value = HttpContext.Current.Server.UrlEncode(Encode(cookie.Values[i], Key, AlgorithmName));
string name = HttpContext.Current.Server.UrlEncode(Encode(cookie.Values.GetKey(i), Key, AlgorithmName));
eCookie.Values.Set(name, value);
}
return eCookie;
}

public static HttpCookie DecodeCookie(HttpCookie cookie)
{
if (cookie == null) return null;

//Comment this section if you do now what this method to be static
char[] chars = { ',' };
string[] splits = ConfigurationManager.AppSettings["CookieEncodingKey"].Split(chars);
string AlgorithmName = splits[0];
byte[] Key = new byte[Int32.Parse(splits[1])];// = KEY_64;
for (int i = 2; i < Key.Length + 2; i++)
Key[i - 2] = byte.Parse(splits[i].Trim());

HttpCookie dCookie = new HttpCookie(cookie.Name);

for (int i = 0; i < cookie.Values.Count; i++)
{
string value = Decode(HttpContext.Current.Server.UrlDecode(cookie.Values[i]), Key, AlgorithmName);
string name = Decode(HttpContext.Current.Server.UrlDecode(cookie.Values.GetKey(i)), Key, AlgorithmName);
dCookie.Values.Set(name, value);
}
return dCookie;
}

At this point you have the basis setup and you can use the class in your code.

Encoding Example:

HttpCookie cookie = new HttpCookie("MySecureCookie");
cookie["ID"] = "39369a0d-975e-4456-9ade-3f04639fd309"; //recommended: use some unique value to later check for fraudulent cookies while retrieving
cookie["Name"] = username;
cookie["Email"] = email;

cookie = Security.EncodeCookie(cookie); //encode
cookie.Expires = DateTime.Now.AddDays(90);
Response.Cookies.Add(cookie);
...

Decoding Example:

HttpCookie cookie = context.Request.Cookies["MySecureCookie"];
cookie = Security.DecodeCookie(cookie); //decode

if (cookie["ID"] == "39369a0d-975e-4456-9ade-3f04639fd309") cookieChecksOut = true;
//process cookie
...

This code allows using a single generic implementation to use a variety of algorithms based on their merits and properties. I hope this will help a lot of beginners.