May 2010 C# Code Snippets

A snippet is a small section of text or source code that can be inserted into the code of a program. Snippets provide an easy way to implement commonly used code or functions into a larger section of code. Instead of rewriting the same code over and over again, a programmer can save the code as a snippet and simply drag and drop the snippet wherever it is needed. By using snippets, programmers and Web developers can also organize common code sections into categories, creating a cleaner development environment. Snippets used in software programming often contain one or more functions written in C#, VB.NET, Java, or any other programming language.

Generate MD5 Hash

Helper:

public static string GenerateMD5Hash(string password)
{
byte[] textBytes = System.Text.Encoding.Unicode.GetBytes(password);
try
{
System.Security.Cryptography.MD5CryptoServiceProvider cryptWrapper;
cryptWrapper = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash = cryptWrapper.ComputeHash(textBytes);
string ret = "";

foreach (byte a in hash)
{
ret += a.ToString("x2");
}

return ret.ToUpper(); ;
}
catch
{
throw;
}
}

Implementation:

GenerateMD5Hash("mystringvalue");

Retrieve MD5 Hash Value From A File

Helper:

public static string GetMD5HashValue(string pathName)
{
string strResult = "";
string strHashData = "";

byte[] arrbytHashValue;
System.IO.FileStream oFileStream = null;

System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher=
new System.Security.Cryptography.MD5CryptoServiceProvider();

try
{
oFileStream = GetFileStream(pathName);
arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);
oFileStream.Close();

strHashData = System.BitConverter.ToString(arrbytHashValue);
strHashData = strHashData.Replace("-", "");
strResult = strHashData;
}
catch(System.Exception ex)
{
throw;
}
return(strResult);
}

Implementation:

GetMD5HashValue(@"c:\temp\data.txt");

Get the name of the current page

Helper:

public static string GetCurrentPageName()
{
string path = HttpContext.Current.Request.Url.AbsolutePath;
FileInfo info = new FileInfo(path);
string pageName = info.Name;
return pageName;
}

Implementation:

GetCurrentPageName();

Get the physical application path

Helper:

public static string GetPhysicalApplicationPath(HttpContext context)
{
string _applicationPath = string.Empty;
_applicationPath = context.Request.PhysicalApplicationPath;
return _applicationPath;
}

Implementation:

GetPhysicalApplicationPath(ctx);

Get the application path

Helper:

public static string GetApplicationPath()
{
string _applicationPath = HttpContext.Current.Request.ApplicationPath.ToLower();
if (Convert.ToBoolean(string.Compare(_applicationPath, "/", true)))     //a site
_applicationPath = "/";
else if (!_applicationPath.EndsWith(@"/")) //a virtual
_applicationPath += @"/";

return _applicationPath;
}

Implementation:

GetApplicationPath();

Does the browser support javascript

Helper:

public static bool DoesBrowserSupportJavaScript()
{
Version ver = new Version();
if (IsHttpContext)
ver = HttpContext.Current.Request.Browser.EcmaScriptVersion;

if (ver.Major > 1)
return true;
return false;
}

Implementation:

DoesBrowserSupportJavaScript();

Find control recursively

Helper:

public static Control FindControlRecursive(Control ctrl, string id)
{
// Exit if this is the control we're looking for
if (ctrl.ID == id)
return ctrl;
else
{
// look in the hiearchy.
foreach (Control childCtrl in ctrl.Controls)
{
Control resCtrl = FindControlRecursive(childCtrl, id);
// Exit if we've found the result
if (resCtrl != null)
return resCtrl;
}
}
return null;
}

Implementation:

FindControlRecursive(txtBox, firstName);

The Microsoft Community Roundup

If you’re a Microsoft end user no matter if it is as a developer, consumer, or administrator then you may find this interesting. Are you looking for resources that can increase you knowledge or looking to find an answer to a question that you may have? If so, I will present a number of resources that you may or may not be aware of. While each resource may deal with a specific topic others may pertain to Microsoft products in general.

I work as a software engineer therefore my interest mainly resides within the area of development, but I will make every effort to add other topics as well. Should you have a suggestion, please contact me and I will get it added or leave a comment. It has been my experience that many experts in the field of Microsoft technologies are more than willing to help others. Remember, a community is a place to learn and interface with your peers.

Windows

Visual Studio .NET

Silverlight

SharePoint

MSDN

Office

Patterns and Practices

General Blogs and Communities

There you have it! Should you know of something I missed, please contact me or leave a comment.

April 2010 JQuery Goodness Roundup

Here it is April and that means it is time for another roundup of jQuery plugins that will greatly assist you in making short work of your development efforts while at the same time pleasing the end user. I have noticed that there are quite a few of new jQuery plugins out there and they really caught my attention as well as the proven older plugins that I have found useful. If you have a favorite plugin why not leave a comment and share wit the community?

TextBoxes and DropDowns

dropdown

  1. FlexBox (CodePlex)
  2. JQuery DropDown

Drag and Drop

drag drop panel

  1. JQuery List DragSort
  2. Table Drag and Drop JQuery plugin
  3. Collapsible Drag & Drop Panels Using jQuery
  4. JQuery Iconize Plugin

Menus

context menu

  1. ASP.NET Multi-Level Drop Down Menu
  2. QuickSand
  3. Horizontal Accordion
  4. Jeegoocontext
  5. jsTree
  6. jBreadCrumb

LightBox

lightbox

  1. JQuery LightBox
  2. prettyPhoto
  3. ThickBox

Animation

  1. Spiritely
  2. Page Curls
  3. S3 Slider

Charts and Graphs

  1. JQuery Visualize

Date and Time

date range picker

  1. jMonthCalendar
  2. Date Range Picker
  3. DateJs

Secure Code With The Microsoft Anti-Cross Site Scripting Library

Recently I attended a Security Development Lifecycle training course in Dallas, Texas and I must admit while I was aware of many vulnerabilities in web applications, I learned just how easy it is to do some real damage if software engineers don’t fully understand the implications they face when developing a web application. In fact, while I was researching statistics on this topic I ran across a statistic that stated applications today contain more security flaws themselves than the operating system that they run on. Now stop and think about this for a moment. Typically companies do everything in their power to patch the operating system, stand up firewalls, and generally control access. If a web application for example does not account for security unauthorized individuals many gain access or worst case scenario steal data that can be detrimental to a company should it fall into the wrong hands. Here are three areas that I believe you should focus on to get you started.

  1. Validate input: Validate input from all untrusted data sources. Proper input validation can eliminate the vast majority of software vulnerabilities.
  2. Enforce security policies: Create software architecture and design your software to implement and enforce these security policies.
  3. Enforce a secure coding standard: Develop a secure coding standard for your target development language and platform. Then ensure your team implements this standard.

Microsoft has really done a great job in the area of assisting software developers in the area of writing secure code in recent years and they obviously have been listening to the developer community. The Anti-Cross Site Scripting Library V3.1 is a wonderful product that any company or individual can easily incorporate into the development process to prevent cross site scripting which is a highly exploited aspect of web applications.

If you’re not familiar with Cross-Site Scripting (XSS) here is how Wikipedia defines this term: Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications that enables malicious attackers to inject client-side script into web pages viewed by other users. An exploited cross-site scripting vulnerability can be used by attackers to bypass access controls such as the same origin policy. Cross-site scripting carried out on websites were roughly 80% of all security vulnerabilities documented by Symantec as of 2007. Their impact may range from a petty nuisance to a significant security risk, depending on the sensitivity of the data handled by the vulnerable site, and the nature of any security mitigation implemented by the site’s owner.

So what is The Microsoft Anti-Cross Site Scripting Library V3.1 (Anti-XSS V3.1) exactly? It is an encoding library designed to help developers protect their ASP.NET web-based applications from XSS attacks. It differs from most encoding libraries in that it uses the white-listing technique sometimes referred to as the principle of inclusions to provide protection against XSS attacks. This approach works by first defining a valid or allowable set of characters, and encodes anything outside this set (invalid characters or potential attacks). The white-listing approach provides several advantages over other encoding schemes. New features in this version of the Microsoft Anti-Cross Site Scripting Library include:

  • An expanded white list that supports more languages
  • Performance improvements
  • Performance data sheets (in the online help)
  • Support for Shift_JIS encoding for mobile browsers
  • Security Runtime Engine (SRE) HTTP module
  • HTML Sanitization methods to strip dangerous HTML scripts

Once you have downloaded and installed this product all you need to to do is configure your application to employ this security product and you all set. For example the following demonstrates encoding the end user input:

protected void Button1_Click(object sender, EventArgs e)
{
// Read input
String Input = TextBox1.Text;

// Process input
...

// Encode untrusted input and write output
Response.Write(”The input you gave was” + Microsoft.Security.Application.AntiXss.HtmlEncode(Input));
}

You may be asking yourself is it really as simple as this? Well yes and no. XSS is just one aspect of vulnerabilities and if you recall from the 2007 Symantec Study 80% of weakness were found to be in cross site scripting attacks. I am not sure what the percentage is today but I can only assume that it is still high based upon the applications I have personally seen first hand. In fact , the OWASP Top Ten ranks XSS as the number two vulnerability second only to injection attacks.

  1. Injection
  2. Cross-Site Scripting (XSS)
  3. Broken Authentication and Session Management
  4. Insecure Direct Object References
  5. Cross-Site Request Forgery (CSRF)
  6. Security Misconfiguration
  7. Insecure Cryptographic Storage
  8. Failure to Restrict URL Access
  9. Insufficient Transport Layer Protection
  10. Unvalidated Redirects and Forwards