Friday, December 26, 2008

Password Encryption using SHA256+SALT

Heare I created the C# method for to return the encrypted password where I used SHA256 + SALT

public static string sha256encrypt(string phrase,string UserName)
{
string salt = CreateSalt(UserName);
string saltAndPwd = String.Concat(phrase, salt);
UTF8Encoding encoder = new UTF8Encoding();
SHA256Managed sha256hasher = new SHA256Managed();
byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(saltAndPwd));
string hashedPwd = String.Concat(byteArrayToString(hashedDataBytes), salt);
return hashedPwd;
}

public static string byteArrayToString(byte[] inputArray)
{
StringBuilder output = new StringBuilder("");
for (int i = 0; i < inputArray.Length; i++)
{
output.Append(inputArray[i].ToString("X2"));
}
return output.ToString();
}

Heare I taken Username, converted to a byte array, then XORed the bytes together. I took the xored result as the seed to my random number generator. Then I used the result of the PRG as my salt.

private static string CreateSalt(string UserName)
{
string username = UserName;
byte[] userBytes; string salt;
userBytes = ASCIIEncoding.ASCII.GetBytes(username);
long XORED = 0x00; foreach (int x in userBytes)
XORED = XORED ^ x;
Random rand = new Random(Convert.ToInt32(XORED));
salt = rand.Next().ToString();
salt += rand.Next().ToString();
salt += rand.Next().ToString();
salt += rand.Next().ToString();
return salt;
}

Hope it helps!!!!

Tuesday, May 20, 2008

Definitions

Application - refers to an assembly that has an entry point (§10.1). When an application is run, a new application domain is created. Several different instantiations of an application may exist on the same machine at the same time, and each has its own application domain.

Application domain - an entity that enables application isolation by acting as a container for application state. An application domain acts as a container and boundary for the types defined in the application and the class libraries it uses. Types loaded into one application domain are distinct from the same type loaded into another application domain, and instances of objects are not directly shared between application domains. For instance, each application domain has its own copy of static variables for these types, and a static constructor for a type is run at most once per application domain. Implementations are free to provide implementation-specific policy or mechanisms for the creation and destruction of application domains.

Argument - an expression in the comma-separated list bounded by the parentheses in a method or instance constructor call expression. It is also known as an actual argument.


Assembly - refers to one or more files that are output by the compiler as a result of program compilation. An assembly is a configured set of loadable code modules and other resources that together implement a unit of functionality. An assembly may contain types, the executable code used to implement these types, and references to other assemblies. The physical representation of an assembly is not defined by this specification. Essentially, an assembly is the output of the compiler.


Behavior, undefined - behavior, upon use of a nonportable or erroneous construct or of erroneous data, for which this International Standard imposes no requirements. [Possible handling of undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message)].

Class library - refers to an assembly that can be used by other assemblies. Use of a class library does not cause the creation of a new application domain. Instead, a class library is loaded into the application domain that uses it. For instance, when an application uses a class library, that class library is loaded into the application domain for that application. If an application uses a class library A that itself uses a classlibrary B, then both A and B are loaded into the application domain for the application.

Diagnostic message - a message belonging to an implementation-defined subset of the implementations output messages.

Namespace - a logical organizational system that provides a way of presenting program elements that are exposed to other programs.

Parameter - a variable declared as part of a method, instance constructor, or indexer definition, which acquires a value on entry to that method. It is also known as formal parameter.
Program . refers to one or more source files that are presented to the compiler. Essentially, a program is the input to the compiler.

Unsafe code - code that is permitted to perform such lower-level operations as declaring and operating on pointers, performing conversions between pointers and integral types, and taking the address of variables. Such operations provide functionality such as permitting interfacing with the underlying operating system, accessing a memory-mapped device, or implementing a time-critical algorithm.

Wednesday, May 14, 2008

10 Tips to Improve LINQ to SQL Application Performance

1 – Turn off ObjectTrackingEnabled Property of Data Context If Not Necessary
If you are trying only to retrieve data as read only, and not modifying anything, you don’t need object tracking. So turn it off using it like in the example below:using (NorthwindDataContext context = new NorthwindDataContext())
{
context.ObjectTrackingEnabled = false;
}



This will allow you to turn off the unnecessary identity management of the objects – hence Data Context will not have to store them because it will be sure that there will be no change statements to generate.
2 – Do NOT Dump All Your DB Objects into One Single DataContext
DataContext represents a single unit of work, not all your database. If you have several database objects that are not connected, or they are not used at all (log tables, objects used by batch processes,etc..). These objects just unnecessarily consume space in the memory hence increasing the identity management and object tracking costs in CUD engine of the DataContext.
Instead think of separating your workspace into several DataContexts where each one represents a single unit of work associated with it. You can still configure them to use the same connection via its constructors to not to loose the benefit of connection pooling.
3 – Use CompiledQuery Wherever Needed
When creating and executing your query, there are several steps for generating the appropriate SQL from the expression, just to name some important of them:
Create expression tree
Convert it to SQL
Run the query
Retrieve the data
Convert it to the objects
As you may notice, when you are using the same query over and over, hence first and second steps are just wasting time. This is where this tiny class in System.Data.Linq namespace achieves a lot. With CompiledQuery, you compile your query once and store it somewhere for later usage. This is achieved by static CompiledQuery.Compile method.
Below is a Code Snippet for an example usage:Func> func =
CompiledQuery.Compile>
((NorthwindDataContext context) => context.Categories.
Where(cat => cat.Products.Count > 5));



And now, “func” is my compiled query. It will only be compiled once when it is first run. We can now store it in a static utility class as follows :///
/// Utility class to store compiled queries
///

public static class QueriesUtility
{
///
/// Gets the query that returns categories with more than five products.
///

/// The query containing categories with more than five products.
public static Func>
GetCategoriesWithMoreThanFiveProducts
{
get
{
Func> func =
CompiledQuery.Compile>
((NorthwindDataContext context) => context.Categories.
Where(cat => cat.Products.Count > 5));
return func;
}
}
}



And we can use this compiled query (since it is now a nothing but a strongly typed function for us) very easily as follows:using (NorthwindDataContext context = new NorthwindDataContext())
{
QueriesUtility.GetCategoriesWithMoreThanFiveProducts(context);
}



Storing and using it in this way also reduces the cost of doing a virtual call that’s done each time you access the collection – actually it is decreased to 1 call. If you don’t call the query don’t worry about compilation too, since it will be compiled whenever the query is first executed.
4 – Filter Data Down to What You Need Using DataLoadOptions.AssociateWith
When we retrieve data with Load or LoadWith we are assuming that we want to retrieve all the associated data those are bound with the primary key (and object id). But in most cases we likely need additional filtering to this. Here is where DataLoadOptions.AssociateWith generic method comes very handy. This method takes the criteria to load the data as a parameter and applies it to the query – so you get only the data that you need.
The following code below associates and retrieves the categories only with continuing products:using (NorthwindDataContext context = new NorthwindDataContext())
{
DataLoadOptions options = new DataLoadOptions();
options.AssociateWith(cat=> cat.Products.Where(prod => !prod.Discontinued));
context.LoadOptions = options;
}



5 – Turn Optimistic Concurrency Off Unless You Need It
LINQ to SQL comes with out of the box Optimistic Concurrency support with SQL timestamp columns which are mapped to Binary type. You can turn this feature on and off in both mapping file and attributes for the properties. If your application can afford running on “last update wins” basis, then doing an extra update check is just a waste.
UpdateCheck.Never is used to turn optimistic concurrency off in LINQ to SQL.
Here is an example of turning optimistic concurrency off implemented as attribute level mapping:[Column(Storage=“_Description”, DbType=“NText”,
UpdateCheck=UpdateCheck.Never)]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged(“Description”);
this.OnDescriptionChanged();
}
}
}



6 – Constantly Monitor Queries Generated by the DataContext and Analyze the Data You Retrieve
As your query is generated on the fly, there is this possibility that you may not be aware of additional columns or extra data that is retrieved behind the scenes. Use Data Context’s Log property to be able to see what SQL are being run by the Data Context. An example is as follows:using (NorthwindDataContext context = new NorthwindDataContext())
{
context.Log = Console.Out;
}



Using this snippet while debugging you can see the generated SQL statements in the Output Window in Visual Studio and spot performance leaks by analyzing them. Don’t forget to comment that line out for production systems as it may create a bit of an overhead. (Wouldn’t it be great if this was configurable in the config file?)
To see your DLINQ expressions in a SQL statement manner one can use SQL Query Visualizer which needs to be installed separately from Visual Studio 2008.
7 – Avoid Unnecessary Attaches to Tables in the Context

Since Object Tracking is a great mechanism, nothing comes for free. When you Attach an object to your context, you mean that this object was disconnected for a while and now you now want to get it back in the game. DataContext then marks it as an object that potentially will change - and this is just fine when you really intent to do that.
But there might be some circumstances that aren’t very obvious, and may lead you to attach objects that arent changed. One of such cases is doing an AttachAll for collections and not checking if the object is changed or not. For a better performance, you should check that if you are attaching ONLY the objects in the collection those are changed.
I will provide a sample code for this soon.
8 – Be Careful of Entity Identity Management Overhead
During working with a non-read only context, the objects are still being tracked – so be aware that non intuitive scenarios this can cause while you proceed. Consider the following DLINQ code:using (NorthwindDataContext context = new NorthwindDataContext())
{
var a = from c in context.Categories
select c;
}



Very plain, basic DLINQ isn’t it? That’s true; there doesn’t seem any bad thing in the above code. Now let’s see the code below:using (NorthwindDataContext context = new NorthwindDataContext())
{
var a = from c in context.Categories
select new Category
{
CategoryID = c.CategoryID,
CategoryName = c.CategoryName,
Description = c.Description
};
}



The intuition is to expect that the second query will work slower than the first one, which is WRONG. It is actually much faster than the first one.
The reason for this is in the first query, for each row the objects need to be stored, since there is a possibility that you still can change them. But in the 2nd one, you are throwing that object away and creating a new one, which is more efficient.
9 – Retrieve Only the Number of Records You Need
When you are binding to a data grid, and doing paging – consider the easy to use methods that LINQ to SQL provides. These are mainly Take and Skip methods. The code snippet involves a method which retrieves enough products for a ListView with paging enabled:///
/// Gets the products page by page.
///

/// Index of the starting page.
/// Size of the page.
/// The list of products in the specified page
private IList GetProducts(int startingPageIndex, int pageSize)
{
using (NorthwindDataContext context = new NorthwindDataContext())
{
return context.Products
.Take(pageSize)
.Skip(startingPageIndex * pageSize)
.ToList();
}
}



10 – Don’t Misuse CompiledQuery
I can hear you saying “What? Are you kiddin’ me? How can such a class like this be misused?”
Well, as it applies to all optimization LINQ to SQL is no exception: