Sunday, February 15, 2009

Two most exciting features in VS-10 to me


Modern computers have seen explosive growth in the number of processors and cores available for systems running on them. by conceive it as contemplation Microsoft’s Parallel Computing Platform (PCP) is providing tools enabling developers to leverage this power in an efficient, maintainable, and scalable manner. Parallel Extensions to the .NET Framework brings several important concepts into this toolset: imperative and task parallelism via the Task Parallel Library (TPL), and Parallel LINQ (PLINQ), which gives developers a declarative way to deal with data parallelism.


Parallelize a long running service

Consider the following conventional code which takes almost 50 sec to execute…

private static void Ex1Task2_StandardForEach()
{
foreach (Employee employee in employeeData)
{
Console.WriteLine("Starting process for employee id {0}",
employee.EmployeeID);
decimal span =
PayrollServices.GetPayrollDeduction(employee);
Console.WriteLine("Completed process for employee id {0}",
employee.EmployeeID);
Console.WriteLine();
}
}

But now with MS blessings, exerting the parallel processing technique we can significantly reduce the execution time.

private static void Ex1Task2_ParallelForEach()
{
Parallel.ForEach(employeeData, ed =>
{
Console.WriteLine("Starting process for employee id {0}",
ed.EmployeeID);
decimal span = PayrollServices.GetPayrollDeduction(ed);
Console.WriteLine("Completed process for employee id {0}",
ed.EmployeeID);
Console.WriteLine();
});
}

It takes less than half execution time compare to previous code………

Use the ParallelEnumerable class’ Extension methods to parallelize LINQ (PLINQ)

private static void Ex4Task2_Extensions()
{
var q = employeeData.
Where(x => x.EmployeeID % 2 == 0).OrderBy(x => x.EmployeeID)
.Select(x => PayrollServices.GetEmployeeInfo(x))
.ToList();

foreach (var e in q)
{
Console.WriteLine(e);
}
}

This conventional LINQ takes almost 50 secs to be executed.

To parallelize this LINQ query just add AsParallel() to the query’s data source, like so:
private static void Ex4Task2_ConvertToParallelExtensions()
{
var q = employeeData.AsParallel()
.Where(x => x.EmployeeID % 2 == 0).OrderBy(x => x.EmployeeID)
.Select(x => PayrollServices.GetEmployeeInfo(x))
.ToList();

foreach (var e in q)
{
Console.WriteLine(e);
}
}


Compare to previous, it takes less than half of execution time. Amazing!!!!!

Number 2 is….


Microsoft Distributed Caching Service

Microsoft Distributed Caching Service (code named “Velocity”) provides a means to store data in an in-memory cache for later retrieval, eliminating the need to get the data from the disc or data store. This can significantly increase the performance of your application. Additionally, Velocity supports caching on a cluster of services, which can increase your application’s scalability

Download the Velocity Community Technology Preview installation package MicrosoftDistributedCache.msi from http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&displaylang=en


we have to install and used Microsoft Distributed Caching Service (“Velocity”) to cache resources and speed up access to data retrieval.
we can access the cache via its API and can configure a web site to use Velocity to store its session state.



ASP.NET Application Performance Tips

By applying these general solutions, we can gain significant performance improvement. Then we can do page specific optimization to improve speed further.


• Turn on IIS Gzip compression. http://msmvps.com/blogs/omar/archive/2006/08/10/iis-6-compression-quickest-and-effective-way-to-do-it-for-asp-net-compression.aspx
• Turn on IIS Static file expiration: http://msmvps.com/blogs/omar/archive/2007/11/29/making-best-use-of-cache-for-high-performance-website.aspx
• Defer JS loading after visible content for faster perceived speed and combine multiple JS into one: http://www.codeproject.com/KB/aspnet/fastload.aspx
• Apply these 10 techniques for better server and client speed: http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx
• Combine small CSS into one common CSS. Ensure one page links to maximum two or three CSS.
• Use CSS Sprite technique to combine multiple icons into one sprite. You can get significant site load performance improvement by using this technique. http://css-tricks.com/css-sprites-what-they-are-why-theyre-cool-and-how-to-use-them/
• Use YUI Compressor to minify CSS files after you deploy on production. It will significantly reduce CSS file size.
• Use YUI Compressor to minify JS files after you deploy on production. It will significantly reduce JS file size.
• Improve hardware on server:
o Add more RAM – at least 4 GB
o Add more CPU – at least Dual Core Xeon
o Add better disk – must be SCSI 15K RPM
o Split database into two physical disks – MDF in one disk and LDF in another disk

•Trim whitespace from ASP.NET pages
•Use JQuery for its lightness instead of MS Ajax




Saturday, February 14, 2009

Achieve Denial of Service (DOS) attacks

The Article is an understanding from Omar Al Zabir (C# MVP) book’s on ASP.NET.
Web services are the most attractive target for cyber-terrorists as a naughty Coder can easily bring down a server by repeatedly calling a web service which does expensive work.


Consider the following masterpiece, which is enough to jeopardize your site.


for( int i = 0; i < 100000; i ++ )
{
WebClient client = new WebClient();
client.DownloadString("Your Service URL");
}


So what would be the salvation process.The trick that has been used here is an inexpensive way to remember how many requests are coming from a particular IP. When the number of request exceeds the melting point, deny further request for some duartion. The idea is to remember caller’s IP in Asp.net Cache and maintain a count of request per IP. When the count exceeds a predefined limit, reject further request for some specific duration like 15 mins. After 15 mins, again allow requests from that IP.


Here is a class named ActionValidator which maintains a count of specific actions like First Visit, Revisit, Asynchrnous postbacks etc. It checks whether the count for such specific action for a specific IP exceeds the melting point or not.


public static class ActionValidator {

private const int DURATION = 15; // 15 min period

public enum ActionTypeEnum
{ FirstVisit = 100, // The most expensive one, choose the valu wisely.
ReVisit = 1000, // Welcome to revisit as many times as user likes
Postback = 5000, // post bact count
}
}


A static method named IsValid does the check. It returns true if the request limit is not passed, false if the request needs to be denied.

public static bool IsValid( ActionTypeEnum actionType )
{
HttpContext context = HttpContext.Current;
if( context.Request.Browser.Crawler ) return false;
string key = actionType.ToString() + context.Request.UserHostAddress;
HitInfo hit = (HitInfo)(context.Cache[key] ?? new HitInfo());

if( hit.Hits > (int)actionType ) return false;
else hit.Hits ++;

if( hit.Hits == 1 )
context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(DURATION), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);

return true;

}


The cache key is built with a combination of action type and client IP address. First it checks if there’s any entry for the action and the client IP in Cache or not. If not, start the count and store remember the count for the IP in cache for the specific duration. The absolute expiration on cache item ensures after the duration, the cache item will be cleared and the count will restart. When there’s already an entry in the cache, get the last hit count, and check if the limit is exceeded or not. If not exceeded, increase the counter. There is no need to store the updated value in the cache again by doing: Cache[url]=hit; because the hit object is by reference and changing it means it gets changed in the cache as well.

private class HitInfo
{
public int Hits;
private DateTime _ExpiresAt = DateTime.Now.AddMinutes(DURATION);
public DateTime ExpiresAt { get { return _ExpiresAt; } set { _ExpiresAt = value; } }
}


The usage is very simple:

protected override void OnInit(EventArgs e)
{
base.OnInit(e);

// Check if revisit is valid or not
if( !base.IsPostBack )
{
// Block cookie less visit attempts
if( Profile.IsFirstVisit )
{
if( !ActionValidator.IsValid(ActionValidator.ActionTypeEnum.FirstVisit) Response.End();
}
else
{
if( !ActionValidator.IsValid(ActionValidator.ActionTypeEnum.ReVisit) ) Response.End();
}
}
else
{
// Limit number of postbacks
if( !ActionValidator.IsValid(ActionValidator.ActionTypeEnum.Postback) Response.End();
}
}

Thanks Omar Al Zabir for making us aware about such threat.

ASP.NET Cookies

Creating cookies with ASP.NET is simple and straight forward. The System.Web namespace offers a class called HttpCookie to create cookies. A Cookie is a small text file that the browser creates and stores on the hard drive of your machine. Cookie is just one or more pieces of information stored as text strings. A Web server sends you a cookie and the browser stores it. The browser then returns the cookie to the server the next time the page is referenced.

The following code demonstrates the creation of cookies.

protected void CreateCookie_Click(object sender, EventArgs e){

HttpCookie newCookie= new HttpCookie("Books");
newCookie.Values.Add("Name", TextBox1.Text);
newCookie.Values.Add("FavBook", RadioButtonList1.SelectedItem.Text);
newCookie.Expires = Convert.ToDateTime("12/31/2009");
Response.Cookies.Add(newCookie);
Label3.Text = "Cookie Created";
Select.Visible = false;
TextBox1.Visible = false;
Label1.Visible = false;
Label2.Visible = false;
RadioButtonList1.Visible = false;
}


To ensure that the cookie stays on the user's hard drive for a while we set it's date using the HttpCookie object's Expires property. To get this cookie sent back to the browser and stored on the hard drive we used the Response object.


Retriving the cookie

The code below demonstrates how to retrieve a cookie and display information to the user based on his preferences.
protected void RetrieveCookie_Click(object sender, EventArgs e){

Label3.visible=false;
Label4.Text = "Hello" +" "+ Request.Cookies["Books"]["Name"] + "."+
"We have a new book for you:";
if(Request.Cookies["Books"]["FavBook"] == "VB")
Label5.text="XYZ VB Book";
else if( Request.Cookies["Books"]["FavBook"] == "C#")
Label5.text="ABC C# Book";
else
Label5.text="Arif's ASP Book";
}


The path to the location on the hard drive where cookies are stored is C:\Documents and Settings\Administrator\Cookies.

Tuesday, December 30, 2008

It’s a gigantic business plan, behind a noble purpose





If we paint the set-up, it’s like above, Click on to see full image….


Do u node your agreement that not a slogan but a sagacious slogan can change an entire business…


I am software professional but always cherish the intention to be a business man that’s why a bit perturbed for how can i move? I dream about plenty of substances that would help me to make my motto turn into reality. However it will be determined by almighty and time will say where my destiny will be destined but here at least I can express myself in few words..

I always prefer ideas and know-how on ongoing technology. Genetic Engineering is most probably the most frontier engineering practice in recent time and lots of stuffs are evolving around us, what we need just to pick up one from those and cogitate. Somebody can say don’t build your castle where it is not suppose to be…but I shall say at least let’s take a confrontation by simulating the rate of success. I love to do programming in my notebook as it’s like playing game but now and then try to come out from the circles periphery to do some cerebral task on something else. As a result of the fact, let me share with you a business plot today…may be a pharmaceuticals business entrepreneur can do best in this regard.


I beg your pardon as I will slightly deviate from my laconic preamble at here. let’s focus on an ethical issue.. Should we take insulin, those are coming from pork’s pancreas??? Is there any other measure on our hands as pork is strictly prohibited for the Muslim Community? We know that in case of severe diabetes patient the pancreas stops the supply of necessary protein (Insulin) thus arise huge complexity into some parts of human body. In this scenario insulin is the life saver. Here, a bit details for general audience…



Protein is very important chemical substance for living creature and Insulin is a very small protein. Insulin as a molecule from living creature consists of 777 number of atoms. The ratio is like below..



Carbon – 254
Hydrogen – 377
Nitrogen - 65
Oxygen – 75
Sulpher - 06

i.e. C254H377N65O75S6



In production environment, by means of awesome sophisticated genetic engineering process, with exerting Recombinant DNA craft we can produce Insulin. We can define the process of Recombinant DNA as by cutting a piece from a projected place of a DNA molecule of a cell then separating it and putting it into another projected place of a DNA molecule, thus we can get a new DNA molecule which can be tagged as Recombinant DNA. Basically the process of making Insulin is an area where we can push a Recombinant DNA into Bacteria by plasmid. Plasmid plays a very responsible role in Genetic Engineering. However In case of manufacturing Recombinant DNA, it is used as an environment where with the help of this medium we can enter the external DNA(here DNA from animal) into carrier DNA(i.e. from E-Coli Bacteria).




There are 51 Amino Acid units from 17 kind of different Amino Acid in Insulin. The pivotal function of Amino Acid is to produce protein hence various kind of Amino Acid form a Protein by clinching each other on different fashion. In a protein molecule, bond among two Amino Acids is defined as peptide bond so a protein quintessentially consists of many active polypeptide bonds. For Insulin there are two polypeptide chain which are tagged as A-Chain (A structure of 26 Amino Acid) and B-Chain (A structure of 31 Amino Acid). In Industry level by superseding 30th Amino Acid (Alanin) of B-Chain of Pork‘s Insulin, almost 99% human compatible insulin can be formulate. The sequence of Amino acid into Insulin among human and animal is pretty much similar.




Here I got the idea as pork’s insulin is different from human insulin at 1 place whereas the animals like cow’s insulin are different compare to human at 3 places but the sequence of amino acid is better than pork’s insulin. So here it would be a huge replacement or transition in case of making human insulin from Halal (pure) animal rather than pork’s pancreas.




In western society Pork can be there first preference but for Muslim community there is a replacement or an alternative, which we should go for. We want to make 100% halal Insulin and here is about the selection of slogan that I have told before. It would be a huge hit as we are biased toward halal things. In this regard somebody should setup pharmaceuticals that will have target production of halal insulin taken into contemplation the issue of halal and haram (prohibited) for the muslim community in the world.




Dear readers vote for this article and comment as it’s transcendent to me.

Tuesday, December 23, 2008

Be a bit cautious before believe an Anthropologist otherwise it may be your big blunder

I am a famous Hollywood director let’s say Steven Spielberg(seems like a jerk but don’t chuckle as day dreaming never comes true!!!), the mastermind of the plot, going to make a movie on how Arab’s quintessentially buy fame from western’s as they are blessed with lot of wealth except wisdom. I am going to make a request to audience please don’t bring the prehistoric contribution of the nation on science & technology and take a side of them as those are already fading out like dim light…



Okay the story (it’s a bogus boo tale and has no bond with reality) is about… UAE has decided to buy little fame from US and given bribe to his counterpart to get some eminence in invention industry so that their name can get wide spread around the world in the book of elite. The US then thought how they can manage a scenario for UAE so that they don’t let them get frustrated. Eventually they have decided they will sell distinction on gigantic invention of human kind history i.e. on hand held cell phone device so that they can increase the settling score as well as spill out more oil from them. They didn’t delay and sent a team of anthropologists to the desert of Dubai to find out the invention history of cell phone. I have forgot to mention one thing that the time of the plot u have to consider 100 years onward from now and have to take into contemplation that the invention history of the cell phone has already been wipped out or somehow got missed from the record. Now a query can confront that why they sent the team to the desert why not somewhere else…well the USA is tricky enough, as all of us know the cell phone primarily consist of plastic and silicon and the plastic is basically oil(from Hydro-Carbon sense), while silicon is Silicon-Di-Oxide(So2) or silica.



Therefore, the Dubai desert was a perfect choice cuz of its richness on oil and silica, though the cell phone basically came from Silicon Valley, Northern California. By the way the Anthropologist Team went, dug the desert and got an antic piece of hand set, which made them to infer that the origin of cell phone discovery was UAE instead of USA. They had discovered the first cell phone in the history, since Dubai is famous for Silica and Oil and the cell phone is made of it, thus they came up with a finding on the basis of so called data collection. How charismatic!!! Everything is predefined.




Once I was hanging out with some of my friends, they were discussing about a controversial issue on first landing on the moon between US and Russia. The Russian supporter were proclaiming about the fluttering of US flag in the breeze on the chest of moon. They said how it’s possible as all of us know there is no wind or Nitrogen/Oxygen like gas there…however my standing was on the side of US and my point was as any substance’s mass on the moon is 1/6 than the earth, therefore it’s an usual scenario for any substance tend to be upward, where a man feels there almost near zero weight(no g effect).



beg ur pardon as I was distracted, however my intention here is not to blame Arab or any country but dig out some fact about so called anthropologist and their stupid remarks now and then they make by showing some extremely vulnerable ground. So dear guyz, be a bit suspicious ahead of making your conscious decision on Anthropologist as they are not driven by themselves but by some mighty power acting behind the screen.

Wednesday, November 19, 2008

Prophet’s meet with Almighty, Back to high school physics & My Analysis



The first pillar of the Islam is belief, regardless of how potent logic works behind the screen. Although Islam doesn’t require any inquisition, I am going to postmortem of a huge event from scientific point of view as I have stated first that it’s just an analysis, nothing else. If my analysis proof false it doesn’t mean that the incident was a fable. It’s a Universal truth and has a very significant impact on human being. However, let’s come to the spot; we are familiar with the theory of relativity and Gallelio’s transformation if we have bit knowledge of school physics.

There are two laws..

i. T = 〖 t〗_0 / √ (1- v^2/c^2)
ii. L = 〖 l〗_0 * √( 1- v^2/c^2)


Here the first law deals with the time and the second law deals with the length or space. Now I am going to introduce with the signs that has been used in laws, the T indicate here the actual time or real time and the 〖 t〗_0 indicates the relative time.

The L indicates here the actual length or the real length and 〖 l〗_0 indicates the relative length. And v is the real velocity; c (3 *〖 10〗^8 m/sec) is the velocity of light, which is constant. Now I am going to show you guys, how the distance between two points or two places can be null or 0 using above laws.

Take into consideration that you are enough futuristic and driving a Ford or a Ferrari at velocity 3 *〖 10〗^8 m/sec , i.e. u have achieved the velocity of light in case of your car (though it’s really tough for a man made machine). Now what result brings the first law if you can gain the 3 * 〖 10〗^8 m/sec magnitude, if we put the magnitude in first law then the calculation becomes v=3 *〖 10〗^8 m/sec and
c=3 *〖 10〗^8 m/sec , i.e.v^2=c^2 we can easily omit the v & c and there remains 1. One minus one becomes zero and root over zero equals to zero. The rest is 〖 t〗_0, as we know something divided by zero (〖 t〗_(0 )/ 0) becomes infinity so we can gain the output is infinity from first equation. So, T = ∞ or infinity.



Let’s check the second law. I have to say here these laws are interrelated. In case of 2nd law if we put the magnitude 3 *〖 10〗^8 m/sec here too, the calculation becomes v=c, omit it then remain one minus one i.e. zero, root over zero equals to zero and something (〖 l〗_0 * 0) multiply zero equals to zero. So the output is zero.

So, L = 0 or zero.



Now corollary goes on, somehow if we can achieve the velocity of light then there will have no distance between two places and the time will become infinity, you can assume something infinity is no value. As we have said earlier 〖 l〗_0 is the relative length and L is the real length between two points, we can easily diminish the real length at light speed. So at light speed if you go from somewhere to elsewhere, time is stopped or of no value and the length is equal to zero. That means your single existence can be at two places simultaneously. (It sounds like magic!!!)




Dear brothers as we know we have a sublime night called “Shab-e-Meraj”, on that happening, prophet went to meet with Almighty Allah sobhanataAla by arriving ‘Borak’ a transport, with an angel and brought the most important customs to exercise for the peace of human being. A lot of events happened there which usually takes time and an interesting as well as exciting thing was there were no or a very few time difference on the earth.


So I want to up my index finger to those skeptics who has any doubt or want any scientific proof about the most valuable event of our prophet as well as human being. Moreover that was not just an event that was the change that convey the messages to whole human being how we should configure our daily life…


May Allah bless all.

IHttp Handler Creation & Caching

We want to create a page on our site returning an XML file to the visitor.

There are lots of suggestions creating a regular ASPX page (say rss.aspx) and in Page_Load use Response.Write to return the XML. Example:



public class RSS : System.Web.UI.Page
{

private void Page_Load(object sender, System.EventArgs e)
{
Response.ContentType = "text/xml";
Response.ContentEncoding = Encoding.UTF8;

string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string

Response.Write( sXml );
Response.End();
}
}


This will indeed work, and since it is a regular page you have great options to improve performance just with some page declarations at the top of the rss.aspx file:


Now what's wrong with it? Well, basically nothing, but it is a fact that our page class (RSS) inherits from System.Web.UI.Page and that page handler is indented for serving aspx pages (i.e WebForms) and includes a lot of overhead not needed for just serving a simple XML file.


So, There are other solutions. You can create your own page handlers, and you can even map your own file extentions to your handlers, for example you could invent your own file extention called .myspecialrss. Now you can (with some configurations settings in IIS/web.config) map all requests to whatever.myspecialrss to your own special file handler. However, needing to do some configurations are never fun to do - if even possible in a shared hosting scenario, therefore Microsoft has kindly given us a special filetype .ASHX which maps to the ASP.NET engine.

Now what we are going to is is create a file - rss.ashx - which when called returns the same XML as in the example above. If you have forgotten why - the ashx handler doesn't give us all that overhead as a .aspx request does.

So, start off by creating rss.ashx




Yes, thats correct, just one single line. It says the class for our Webhandler is called Arif.RSSHandler, so we will now create that class. To put it simple - what happens is that when the request for rss.ashx comes to the ASP.NET engine it reads the rss.ashx file, sees that the class is Arif.RSSHandler and therefore instantiates an object of that class.

Now lets have a look at the handler class:


RSSHandler.cs

namespace Arif
{
using System;
using System.IO;
using System.Web;


public class RSSHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;

string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string

context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Write( sXml );
}

public bool IsReusable
{
get { return true; }
}

}

}


And there you have it. Looks pretty much like the first code we created, doesn't it? As for caching, you can solve it by accessing the Cache object from your code, see the context.Response.Cache calls.

Read XML using LINQ

Read XML using LINQ in ASP.NET

Here we have created a xml file containing a software various modules License Keys and reading the xml file according to settings using LINQ.


// Source sample

void WriteXML(string keyId)
{
try
{
//pick whatever filename with .xml extension
string filename = "c:\\License.xml";

XmlDocument xmlDoc = new XmlDocument();

try
{
xmlDoc.Load(filename);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filename,
System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml",
"version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("RootMenu");
//If WriteProcessingInstruction is used as above,
//Do not use WriteEndElement() here
//xmlWriter.WriteEndElement();
//it will cause the to be
xmlWriter.Close();
xmlDoc.Load(filename);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement childNode = xmlDoc.CreateElement("Menus");
XmlElement childNode2 = xmlDoc.CreateElement("Menu");


root.AppendChild(childNode);

childNode.SetAttribute("name", plainText);
childNode.SetAttribute("KeyId", keyId);
childNode.AppendChild(childNode2);

childNode.SetAttribute("AccessValue",cipherText);

xmlDoc.Save(filename);
}
catch (Exception ex)
{
throw ex;
}
}




Here we are reading the xml file…

public bool LicenseKeyRight(string cipherText, string KeyID)//cipher text is the

//encrypted string
{
XDocument feedXML;
if (cipherText != String.Empty)
{

if (File.Exists(HttpContext.Current.Server.MapPath("License.xml")))
{
feedXML =
XDocument.Load(HttpContext.Current.Server.MapPath("License.xml"));
}

var feeds = from menu in feedXML.Descendants("Menu")
select new
{
Menus = menu.Parent.Attribute("name").Value,
AccessValue=
menu.Parent.Attribute("AccessValue").Value,
KeyId = menu.Parent.Attribute("KeyId").Value
};

string str = "";

foreach (var Property in feeds)
{
if (String.Compare(str, Property.Menus) != 0)
{
if ((String.Compare(Property.Menus, cipherText) == 0)
&& (String.Compare(KeyID, Property.KeyId)==0))
{

plainText= “”; // here we decrypt the encrypted
//string
if (String.Compare(plainText, cipherText) == 0)
{
return true;
}
}

}
str = Property.Menus;
}

}
return false;
}

CLR Integration/ Call a .net user defined function from SQL server Stored Proc

how we do CLR Integration with SQL....

Here is a sample illustrating the actions…

DECLARE @MailBody varchar(max)
SET @MailBody=dbo.GetAlertForTimesheetUpdate(@Id)

--Here dbo.GetAlertForTimesheetUpdate() is an SQL server programmability
--user defined function, calling from a stored procedure…

Lets see the function like..

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER FUNCTION [dbo].[GetAlertForTimesheetUpdate](@Id [int])
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS EXTERNAL NAME [TP.Automation].[TP.Automation.Facade].[GetAlertForTimesheetUpdate]

The above function will be autogenerated when we will build and deploy our .net project..

Lets see the code block in c# in our .net project..

//Add namespace
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

[return: SqlFacet(MaxSize = -1)]
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static string GetAlertForTimesheetUpdate(int Id)
{
string Report = string.Empty;


string strHeader = @"”; // build some html
string Report= “”; // build some html
string GetReportFooter = “”; // build some html

return strHeader + Report + GetReportFooter;
}

So here it is… enjo..o..y…

Automatic Project deployment using CruiseControl.Net















































































Sunday, October 12, 2008

floating pop up notification bar

Here is a sample function to show a floating pop up notification bar in ASP.NET…….
take a page, put an updatepanel and add a label into it, inject rest of the stuff into label, eventuallyCall the function against a button click event.

// call MiscUtil. ShowMessage(lbl,”hello”,false);

Public class MiscUtil
{

public static void ShowMessage(Label label, string message, bool isError)
{
string strInterval = string.Empty;
if (message == string.Empty) return;
try
{
AlwaysVisibleControlExtender avce = new AlwaysVisibleControlExtender();
avce.TargetControlID = label.ID;
avce.ScrollEffectDuration = .1f;
label.Parent.Controls.Add(avce);
label.ForeColor = System.Drawing.Color.Black;

label.Text = "PADDING: 5PX;\ STYLE="\" DIVPARENT\>";label.Text += "ALIGN: LEFT;\>";
label.Text += "[Photo]/ />";label.Text += " " + "" + message + "";label.Text += "";label.Text += "ALIGN: RIGHT; PADDING-RIGHT: 10PX; WHITE-SPACE: NOWRAP\ STYLE="\">";
label.Text += " onclick=\"javascript:hideMeClick('" + label.ClientID + "')\"title=\"Hide Me\">Hide Me";
label.Text += "";
strInterval =ConfigurationManager.AppSettings["AlertInterval"].ToString();//get the time to show the notification
ScriptManager.RegisterClientScriptBlock(label,typeof(MiscUtil), "MiscUtil","window.setTimeout(function(){hideMeClick('" + label.ClientID+ "');}, '" + strInterval + "')", true);

if (isError)
{
label.ForeColor = System.Drawing.Color.Red;label.Font.Bold = true;
}
label.CssClass = "CommonAlertMessage";
}
catch (Exception ex)
{
label.ForeColor = System.Drawing.Color.DodgerBlue;label.Text = message;
if (isError)
{
label.ForeColor = System.Drawing.Color.Red;label.Font.Bold = true;
}
}

}
}


// Here is the script codefunction


hideMeClick(ctlId)
{
document.getElementById(ctlId).style.display = 'none';
}

Wednesday, September 17, 2008

Text Encryption & Decryption

Source sample :


// static fields


string plainText = string.Empty; // original plaintext

string passPhrase = "Passport"; // can be any string
string saltValue = "s@ltValue"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5" SHA1
int passwordIterations = 2; // can be any number
string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
int keySize = 256; // can be 192 or 128

public static string cipherText = string.Empty;


// calling methods

cipherText = RijndaelSimple.Encrypt(plainText,
passPhrase,
saltValue,
hashAlgorithm,
passwordIterations,
initVector,
keySize);


plainText = RijndaelSimple.Decrypt(cipherText,
passPhrase,
saltValue,
hashAlgorithm,
passwordIterations,
initVector,
keySize);


//……………………………………………………………………………………………………………..

// the class



public class RijndaelSimple
{
///
/// Encrypts specified plaintext using Rijndael symmetric key algorithm
/// and returns a base64-encoded result.
///
///
/// Plaintext value to be encrypted.
///
///
/// Passphrase from which a pseudo-random password will be derived. The
/// derived password will be used to generate the encryption key.
/// Passphrase can be any string. In this example we assume that this
/// passphrase is an ASCII string.
///
///
/// Salt value used along with passphrase to generate password. Salt can
/// be any string. In this example we assume that salt is an ASCII string.
///
///
/// Hash algorithm used to generate password. Allowed values are: "MD5" and
/// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
///
///
/// Number of iterations used to generate password. One or two iterations
/// should be enough.
///
///
/// Initialization vector (or IV). This value is required to encrypt the
/// first block of plaintext data. For RijndaelManaged class IV must be
/// exactly 16 ASCII characters long.
///
///
/// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
/// Longer keys are more secure than shorter keys.
///
///
/// Encrypted value formatted as a base64-encoded string.
///
public static string Encrypt(string plainText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
// Convert strings into byte arrays.
// Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

// First, we must create a password, from which the key will be derived.
// This password will be generated from the specified passphrase and
// salt value. The password will be created using the specified hash
// algorithm. Password creation can be done in several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);

// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);

// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();

// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;

// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);

// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream();

// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

// Finish encrypting.
cryptoStream.FlushFinalBlock();

// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memoryStream.ToArray();

// Close both streams.
memoryStream.Close();
cryptoStream.Close();

// Convert encrypted data into a base64-encoded string.
string cipherText = Convert.ToBase64String(cipherTextBytes);

// Return encrypted string.
return cipherText;
}

///
/// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
///
///
/// Base64-formatted ciphertext value.
///
///
/// Passphrase from which a pseudo-random password will be derived. The
/// derived password will be used to generate the encryption key.
/// Passphrase can be any string. In this example we assume that this
/// passphrase is an ASCII string.
///
///
/// Salt value used along with passphrase to generate password. Salt can
/// be any string. In this example we assume that salt is an ASCII string.
///
///
/// Hash algorithm used to generate password. Allowed values are: "MD5" and
/// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
///
///
/// Number of iterations used to generate password. One or two iterations
/// should be enough.
///
///
/// Initialization vector (or IV). This value is required to encrypt the
/// first block of plaintext data. For RijndaelManaged class IV must be
/// exactly 16 ASCII characters long.
///
///
/// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
/// Longer keys are more secure than shorter keys.
///
///
/// Decrypted string value.
///
///
/// Most of the logic in this function is similar to the Encrypt
/// logic. In order for decryption to work, all parameters of this function
/// - except cipherText value - must match the corresponding parameters of
/// the Encrypt function which was called to generate the
/// ciphertext.
///
public static string Decrypt(string cipherText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
// Convert strings defining encryption key characteristics into byte
// arrays. Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

// First, we must create a password, from which the key will be
// derived. This password will be generated from the specified
// passphrase and salt value. The password will be created using
// the specified hash algorithm. Password creation can be done in
// several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);

// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);

// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();

// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;

// Generate decryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);

// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

// Define cryptographic stream (always use Read mode for encryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor,
CryptoStreamMode.Read);

// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold ciphertext;
// plaintext is never longer than ciphertext.
byte[] plainTextBytes = new byte[cipherTextBytes.Length];

// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
0,
plainTextBytes.Length);

// Close both streams.
memoryStream.Close();
cryptoStream.Close();

// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
string plainText = Encoding.UTF8.GetString(plainTextBytes,
0,
decryptedByteCount);

// Return decrypted string.
return plainText;
}
}

Object encryption & decryption

Here is a sample for a object encryption and decryption

Source sample :

// property

[DataMember]
public byte[] ChangedObject
{
get;
set;
}


// code
private static Hashtable hashTableAr = null;
hashTableAr = new Hashtable();
// Key and object’s value
hashTableAr.Add("CellPhone", memberArchiveInfo.CellPhone);
hashTableAr.Add("CurrentCity", memberArchiveInfo.CurrentCity);
// fill the object
MemberChangeArchive memberChangeArchive = new
MemberChangeArchive();
memberChangeArchive.ChangedObject = ObjectEncrypter.Encrypt(
hashTableAr);
// Add into memory
Facade.AddMemberChangeArchive(memberChangeArchive);

///
Retrieve from memory
Hashtable hashTablememberChangeArchive = new Hashtable();

hashTablememberChangeArchive = ObjectEncrypter.Decrypt(
memberChangeArchive.ChangedObject);

// get original value
hashTablememberChangeArchive["CurrentCity "].ToString();

//…
/// the class


public static class ObjectEncrypter
{
#region Public Methods

[DebuggerStepThrough()]
public static byte[] Encrypt(Text plain) where Text : class
{
if (!plain.GetType().IsSerializable)
{
throw new SerializationException("Object is not
serializable.");
}

using (MemoryStream ms = new MemoryStream())
{
using (SymmetricAlgorithm crypto =
CreateSymmetricAlgorithm())
{
using (CryptoStream cs = new CryptoStream(ms,
crypto.CreateEncryptor(), CryptoStreamMode.Write))
{
(new BinaryFormatter()).Serialize(cs, plain);

cs.FlushFinalBlock();

using (KeyedHashAlgorithm hash =
CreateHashAlgorithm())
{
hash.Key = crypto.Key;
ms.Seek(0, SeekOrigin.Begin);
hash.ComputeHash(ms);
ms.Write(hash.Hash, 0, hash.Hash.Length);
}
}
}

return ms.ToArray();
}
}

[DebuggerStepThrough()]
public static Text Decrypt(byte[] cipher) where Text : class
{
using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm())
{
using (KeyedHashAlgorithm hash = CreateHashAlgorithm())
{
hash.Key = crypto.Key;

int hashSizeInBytes = (hash.HashSize / 8);

byte[] data = new byte[cipher.Length - hashSizeInBytes];

Buffer.BlockCopy(cipher, 0, data, 0, data.Length);

byte[] DAC = new byte[hashSizeInBytes];

Buffer.BlockCopy(cipher, data.Length, DAC, 0,
DAC.Length);

hash.ComputeHash(data, 0, data.Length);

if (!CompareByteArray(hash.Hash, DAC))
{
throw new CryptographicException("Object hash does
not match!");
}

using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms,
crypto.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
ms.Seek(0, SeekOrigin.Begin);

return (new BinaryFormatter()).Deserialize(ms) as
Text;
}
}
}
}
}

[DebuggerStepThrough()]
public static string OurEncrypt(string input)
{
string s1 =
Convert.ToBase64String(
System.Text.Encoding.Unicode.GetBytes(input));

return s1;
}

[DebuggerStepThrough()]
public static string OurDecrypt(string input)
{
string s2 =
System.Text.Encoding.Unicode.GetString(
Convert.FromBase64String(input));

return s2;
}

#endregion

#region Helper Methods

[DebuggerStepThrough()]
private static SymmetricAlgorithm CreateSymmetricAlgorithm()
{
SymmetricAlgorithm crypto = new RijndaelManaged();

crypto.Mode = CipherMode.CBC;
crypto.Padding = PaddingMode.PKCS7;

crypto.Key = new byte[] { 4, 93, 171, 3, 85, 23, 41, 34, 216, 14,
78, 156, 78, 3, 103, 154, 9, 150, 65, 54, 226, 95, 68, 79, 159,
36, 246, 57, 177, 107, 116, 8 };
crypto.IV = new byte[] { 56, 2, 86, 234, 139, 10, 67, 10, 223,
210, 0, 19, 87, 21, 142, 100 };

return crypto;
}

[DebuggerStepThrough()]
private static KeyedHashAlgorithm CreateHashAlgorithm()
{
return HMACSHA1.Create();
}

[DebuggerStepThrough()]
private static bool CompareByteArray(byte[] array1, byte[] array2)
{
if (array1.Length != array2.Length)
{
return false;
}

for (int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}

return true;
}

#endregion

public static System.Collections.IDictionary Decrypt1(object p)
{
throw new Exception("The method or operation is not
implemented.");
}
}

Date Difference

One very essential function for developers to find date, month & year difference between two dates.

the parameters here are respectively end date & start date..


public static string FindDateDiffFrmEndtoStart(DateTime dtEndDate, DateTime dtStartDate)
{
string result;
int[] arr = { 31, 28, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int Year, Day, Month, StartYear, EndYear, StartDay, EndDay, StartMonth, EndMonth;

StartYear = dtStartDate.Year;
EndYear = dtEndDate.Year;
StartMonth = dtStartDate.Month;
EndMonth = dtEndDate.Month;
string[] Startday = dtStartDate.ToShortDateString().Split('/');
string[] Endnday = dtEndDate.ToShortDateString().Split('/');
StartDay = (int)Convert.ToInt16(Startday[1]);
EndDay = (int)Convert.ToInt16(Endnday[1]);

if (EndDay < StartDay)
{
if (EndMonth == 1)
EndDay += arr[EndMonth - 1];
else if (EndMonth == 2)
{
if (DateTime.IsLeapYear(EndYear))
EndDay += arr[EndMonth];
else
EndDay += arr[EndMonth - 1];
}
else
EndDay += arr[EndMonth];

EndMonth--;
}

if (EndMonth < StartMonth)
{
EndMonth += 12;
EndYear--;
}

Year = EndYear - StartYear;
Month = EndMonth - StartMonth;
Day = EndDay - StartDay;

result = (Year > 0 ? Year.ToString() + " Year(s) " : string.Empty) + (Month > 0 ? Month.ToString() + " Month(s) " : string.Empty) + (Day > 0 ? Day.ToString() + " Day(s)" : string.Empty);

return result;
}

Some Usefull functions for my fellow friends

How to Get The Words for a Given Number

By using this sample code in an IIS Server, we can have a Web Service that will convert a given number into its equivalent in words. For example, if you need a code that converts a total amount such as $43.25 into words such as forty-three dollars and twenty-five cents, you can use this Web Service.
Here is the sample code for the same.

<%@ WebService Language="VB" Class="NumberToWords" %>
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Diagnostics
Imports System.Web
Imports System.Web.Services
Imports Microsoft.VisualBasic
Public Class NumberToWords
Inherits System.Web.Services.WebService
EnableSession:=False)> _
Public Function getWords(myNumber AS String) As String
getWords = SpellNumber(myNumber)
End Function
'Main Function
Private Function SpellNumber(MyNumber As String)
Dim Dollars, Cents, Temp
Dim DecimalPlace, Count
Dim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amount
MyNumber = Convert.ToString(MyNumber)
' Position of decimal place 0 if none
DecimalPlace = InStr(MyNumber, ".")
'Convert cents and set MyNumber to dollar amount
If DecimalPlace > 0 Then
Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
"00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1
Loop
Select Case Dollars
Case ""
Dollars = "zero Dollars"
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars & " Dollars"
End Select
Select Case Cents
Case ""
Cents = " and zero Cents"
Case "One"
Cents = " and One Cent"
Case Else
Cents = " and " & Cents & " Cents"
End Select
SpellNumber = Dollars & Cents
End Function
'Converts a number from 100-999 into text
Private Function GetHundreds(MyNumber As String)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
'Convert the hundreds place
If Mid(MyNumber, 1, 1) <> "0" Then
Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
End If
'Convert the tens and ones place
If Mid(MyNumber, 2, 1) <> "0" Then
Result = Result & GetTens(Mid(MyNumber, 2))
Else
Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function
'Converts a number from 10 to 99 into text
Private Function GetTens(TensText As String)
Dim Result As String
Result = "" 'null out the temporary function value
If Val(Left(TensText, 1)) = 1 Then ' If value between 10-19
Select Case Val(TensText)
Case 10: Result = "Ten"
Case 11: Result = "Eleven"
Case 12: Result = "Twelve"
Case 13: Result = "Thirteen"
Case 14: Result = "Fourteen"
Case 15: Result = "Fifteen"
Case 16: Result = "Sixteen"
Case 17: Result = "Seventeen"
Case 18: Result = "Eighteen"
Case 19: Result = "Nineteen"
Case Else
End Select
Else ' If value between 20-99
Select Case Val(Left(TensText, 1))
Case 2: Result = "Twenty "
Case 3: Result = "Thirty "
Case 4: Result = "Forty "
Case 5: Result = "Fifty "
Case 6: Result = "Sixty "
Case 7: Result = "Seventy "
Case 8: Result = "Eighty "
Case 9: Result = "Ninety "
Case Else
End Select
Result = Result & GetDigit(Right(TensText, 1))
'Retrieve ones place
End If
GetTens = Result
End Function
'Converts a number from 1 to 9 into text
Private Function GetDigit(Digit As String)
Select Case Val(Digit)
Case 1: GetDigit = "One"
Case 2: GetDigit = "Two"
Case 3: GetDigit = "Three"
Case 4: GetDigit = "Four"
Case 5: GetDigit = "Five"
Case 6: GetDigit = "Six"
Case 7: GetDigit = "Seven"
Case 8: GetDigit = "Eight"
Case 9: GetDigit = "Nine"
Case Else: GetDigit = ""
End Select
End Function
End Class