DCSIMG
Michael Neiter's Blog
Patterns for Parallel Programming Document
19 December 10 01:00 PM | Michael Neiter | 2 comment(s)

Understanding and Applying Parallel Patterns with the .NET Framework 4

Overview:

This document provides a detailed and in-depth tour of support in the Microsoft® .NET Framework 4 for parallel programming. This includes an examination of common parallel patterns and how they’re implemented without and with this new support in the .NET Framework, as well as covering best practices for developing parallel components utilizing parallel patterns.

Stephen Toub
Parallel Computing Platform

Download:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=86B3D32B-AD26-4BB8-A3AE-C1637026C3EE

תגים:, , , ,
Running ADPlus on a Windows Server 2008
16 December 10 07:28 AM | Michael Neiter | 2 comment(s)

What does ADPlus do?
ADPlus is console-based Microsoft Visual Basic script. It automates the Microsoft CDB debugger to produce memory dumps and log files that contain debug output from one or more processes.

The following are the three steps to run ADPlus command:

1. Open a command prompt as an administrator.

as an Administrator

Note: The reason I wrote this post is because without running the command as an administrator you can’t create a dump file. It took me some time to figure out why I could not create a dump file. I want to believe this post will save some time for others.

2. Move to the folder.

cd C:\Program Files\Debugging Tools for Windows (x64)

or

cd C:\Program Files\Debugging Tools for Windows (x86)

3. Execute command.

Adplus -hang -pn "process Name" -o "output directory"

or

Adplus -crash-pn "process Name" -o "output directory"

Summary:

Create a dump file is the first step in the process of analysis and understanding of the application. ADPlus is one of the tools that gives the possibility to create a dump file.

Download and Install Debugging Tools for Windows:

http://www.microsoft.com/whdc/devtools/debugging/default.mspx

Reference:
http://support.microsoft.com/kb/286350

http://msdn.microsoft.com/en-us/library/ff537953(v=VS.85).aspx

How To Create Forms Authentication Cookies
31 May 09 02:00 PM | Michael Neiter | 3 comment(s)

What is Forms Authentication Cookies:

Forms authentication cookie is the container for forms authentication ticket. The ticket is passed as the value of the forms authentication cookie with each request and is used by forms authentication, on the server, to identify an authenticated user.

IIS Authentication:

ASP.NET authentication is a two-step process. First, Internet Information Services (IIS) authenticates the user and creates a Windows token to represent the user. IIS determines the authentication mode that it should use for a particular application by looking at IIS metabase settings. If IIS is configured to use anonymous authentication, a token for the IUSR_MACHINE account is generated and used to represent the anonymous user. IIS-then passes the token to ASP.NET.

Second, ASP.NET performs its own authentication. The authentication method used is specified by the mode attribute of the authentication element. The following authentication configuration specifies that ASP.NET uses the FormsAuthenticationModule class.

Example:

The following example shows how to create a custom FormsAuthenticationTicket.

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, //The version number of the ticket. 
    username, //The user name associated with the ticket. 
    DateTime.Now, //The local date and time at which the ticket was issued. 
    DateTime.Now.AddMinutes(30), //The local date and time at which the ticket expires. 
    isPersistent, //true if the ticket will be stored in a persistent cookie (saved across browser sessions); otherwise, false. If the ticket is stored in the URL, this value is ignored.
    userData, //The user-specific data to be stored with the ticket.
    FormsAuthentication.FormsCookiePath //The path for the ticket when stored in a cookie. 
    );
    
    // Encrypt the ticket.
    string encTicket = FormsAuthentication.Encrypt(ticket);
    
    // Create the cookie.
    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

ASP.NET Forms Authentication:

ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication with the forms element.

<authentication mode="Forms">
    <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH">
    </forms>
</authentication>

Authorization Configuration:

In IIS, anonymous access is enabled for all applications that use forms authentication. The UrlAuthorizationModule class is used to help ensure that only authenticated users can access a page.

<authorization>
    <deny users="?"/>
</authorization>

Web Farm Scenarios:

In a Web farm, you cannot guarantee which server will handle successive requests. If a user is authenticated on one server and the next request goes to another server, the authentication ticket will fail the validation and require the user to re-authenticate.

The validationKey and decryptionKey attributes in the machineKey element are used for hashing and encryption of the forms authentication ticket. The default value for these attributes is AutoGenerate.IsolateApps. The keys are auto-generated for each application, and they are different on each server. Therefore, authentication tickets that are encrypted on one computer cannot be decrypted and verified on another computer in a Web farm, or in another application on the same Web server.  

Reference:

http://msdn.microsoft.com/en-us/library/aa480476.aspx

http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx

http://support.microsoft.com/kb/910443

 

How to measure elapsed time in C# with Stopwatch class
01 April 09 10:00 AM | Michael Neiter | with no comments

In this post I will discuss how to measure elapsed time in C# with Stopwatch class.

What is a Stopwatch:

Stopwatch class provides a set of methods and properties that you can use to accurately measure elapsed time.

In a simple scenario we call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

Stopwatch class depends on the hardware available in your computer and implements the high-resolution performance counter API functions of Windows.

Example:

The following example shows how to create Stopwatch object, call the Start method,  call the Stop method, call the Reset method and then to check the elapsed time using the Elapsed property.

Stopwatch sw = new Stopwatch();

sw.Start();

// Do something here

sw.Stop();

Console.WriteLine("Time elapsed: {0}ms", sw.Elapsed.TotalMilliseconds.ToString());

sw.Reset();

sw.Start();

// Do something here 

sw.Stop();

Console.WriteLine("Time elapsed: {0}ms", sw.Elapsed.TotalMilliseconds.ToString());

Console.ReadLine();
 
Summary:
 
Stopwatch class is an effective tool to use when performing diagnostics or benchmarks on an application.

Reference:
 
How to Get Data from Resource Files in ASP.NET 2.0
29 March 09 11:30 PM | Michael Neiter | 2 comment(s)

In this post I will present how to access data from resource files in an ASP.NET 2.0 web application.

Example:

The following code creates ResourceManager object and loads data from a resource file.
ResourceManager myResourceManager;
ResourceSet rs;

Assembly vResAssembly = Assembly.Load(new AssemblyName(AssemblyName));
 myResourceManager = new ResourceManager(baseName, vResAssembly);

rs = myResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
 
The following code shows how to convert ResourceManager object to list of items.
rs = DataAccesss.GetResourceData(resourceName);

Dictionary<object, object> dict = new Dictionary<object, object>();

/*  populate dictionary */
IDictionaryEnumerator en = rs.GetEnumerator();
while (en.MoveNext())
{
    dict.Add(en.Key, en.Value);
}

List<KeyValuePair<object, object>> summaryList = new List<KeyValuePair<object, object>>();
summaryList.AddRange(dict);

The following code shows a DropDownList bound to a list of items.

<asp:DropDownList ID="ddlCountry" runat="server" CssClass="Fill1" DataTextField="Value"
    DataValueField="Key" AutoPostBack="True" DataSourceID="ObjectDataSourceCountry">
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSourceCountry" runat="server" TypeName="BusinessLogic"
    SelectMethod="GetResourceData">
    <SelectParameters>
        <asp:Parameter Name="resourceName" Type="String" DefaultValue="Resources.CountryList" />
    </SelectParameters>
</asp:ObjectDataSource>
 
Summary:

This isn't very prevalent, but sometimes we need to get data from the resource files and this is a way I chose to implement it.

Download:

The code is attached as a zip file. For download Click Here.

Cross Browser Copy To the Clipboard with JavaScript and Flash
26 March 09 10:30 AM | Michael Neiter | 4 comment(s)

When we want to copy text to the clipboard in the browser Internet Explorer, then the copyToClipboard function uses the window.clipboardData.setData function to set the clipboard data. Otherwise, the browser creates an embedded flash object, and adds the data to flash using a parameter.

 Example:

The following code present easy way to copy text from textarea to the clipboard using JavaScript and Flash object.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Cross Browser Copy To Clipboard</title>

    <script type="text/javascript" language="javascript">
   1:  
   2:         function copyToClipboard(text2copy) {
   3:             if (window.clipboardData) {
   4:                 window.clipboardData.setData("Text", text2copy);
   5:             } else {
   6:                 var flashcopier = 'flashcopier';
   7:                 if (!document.getElementById(flashcopier)) {
   8:                     var divholder = document.createElement('div');
   9:                     divholder.id = flashcopier;
  10:                     document.body.appendChild(divholder);
  11:                 }
  12:                 document.getElementById(flashcopier).innerHTML = '';
  13:                 var divinfo = '<embed src="clipboard.swf" mce_src="clipboard.swf" FlashVars="clipboard=' + escape(text2copy) + '" width="30" height="30" type="application/x-shockwave-flash"></embed>';
  14:                 document.getElementById(flashcopier).innerHTML = divinfo;
  15:             }
  16:         }
  17:     
</script> </head> <body> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td> <textarea id="txtInput" rows="4" cols="50" id="txtInput">Copy and paste the text.</textarea> </td> <td> &nbsp; </td> <td> <a href="BLOCKED SCRIPTcopyToClipboard(document.getElementById('txtInput').value);">Copy text</a> </td> </tr> </table> </body> </html>

Summary:

This is a possible cross-brouser solution for performing copy to clipboard. I believe this is quite common problem web developers need to cope with. It's 'dirty' but it's efficient and it works. I'll be happy to receive other possible solution suggestions for this problem.

Download:

The code is attached as a zip file. For download Click Here.

How to Compress and Decompress using GzipStream object in C#
24 March 09 11:00 AM | Michael Neiter | 6 comment(s)

Below is the implementation of the compress and decompress methods using GzipStream class.

Example:

The method shows how to compress a text.

public static string Compress(string text)

{

byte[] buffer = Encoding.UTF8.GetBytes(text);

MemoryStream ms = new MemoryStream();

using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))

{

zip.Write(buffer, 0, buffer.Length);

}



ms.Position = 0;

MemoryStream outStream = new MemoryStream();



byte[] compressed = new byte[ms.Length];

ms.Read(compressed, 0, compressed.Length);



byte[] gzBuffer = new byte[compressed.Length + 4];

System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);

System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);

return Convert.ToBase64String(gzBuffer);

}


The method shows how to decompress a text that has been previously compressed.

public static string Decompress(string compressedText)

{

byte[] gzBuffer = Convert.FromBase64String(compressedText);

using (MemoryStream ms = new MemoryStream())

{

int msgLength = BitConverter.ToInt32(gzBuffer, 0);

ms.Write(gzBuffer, 4, gzBuffer.Length - 4);



byte[] buffer = new byte[msgLength];



ms.Position = 0;

using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))

{

zip.Read(buffer, 0, buffer.Length);

}



return Encoding.UTF8.GetString(buffer);

}

}


Note:

You can choose any type of encoding you need (UTF8, Unicode, etc.).

How to Encoding and Decoding Base64 strings in C#
22 March 09 10:15 AM | Michael Neiter | 5 comment(s)
In this post I’ll show how to encodes and decodes Base64 strings.

Example:

The method shows how to create a Base64 encoded string from a plain text.

/// <summary>
/// The method create a Base64 encoded string from a normal string.
/// </summary>
/// <param name="toEncode">The String containing the characters to encode.</param>
/// <returns>The Base64 encoded string.</returns>
public static string EncodeTo64(string toEncode)
{

    byte[] toEncodeAsBytes

          = System.Text.Encoding.Unicode.GetBytes(toEncode);

    string returnValue

          = System.Convert.ToBase64String(toEncodeAsBytes);

    return returnValue;

}

The method shows how to decode a Base64 encoded string to a plain text.

/// <summary>
/// The method to Decode your Base64 strings.
/// </summary>
/// <param name="encodedData">The String containing the characters to decode.</param>
/// <returns>A String containing the results of decoding the specified sequence of bytes.</returns>
public static string DecodeFrom64(string encodedData)
{

    byte[] encodedDataAsBytes

        = System.Convert.FromBase64String(encodedData);

    string returnValue =

       System.Text.Encoding.Unicode.GetString(encodedDataAsBytes);

    return returnValue;

}

Note:

You can choose any type of encoding you need (UTF8, Unicode, etc.).

How to create Web Request from .NET applications.
19 March 09 10:45 AM | Michael Neiter | 2 comment(s)
Sometimes we need to access external resources on the Web from our applications.
One way to do it is to create WebRequest instances through the WebRequest.Create method.
 
Example:
 
The following example demonstrates how to create web request and retrieve the results .
 
// Create a request for the URL.         
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.        
string responseFromServer = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();

Note:

After you are finished with a WebResponse object, you must close it by calling the Close method. If you do not close either the response or the stream, your application can run out of connections to the server and become unable to process additional requests.

When create web request it is important to place the code in a Try and Catch block, because some exceptions are expected (timeout, etc.).

Summary:

In this post we saw how to create web request and retrieve the results from .NET applications.

Reference:

 
 
 
Implement the ICallbackEventHandler in ASP.NET 2.0
17 March 09 10:25 AM | Michael Neiter | 2 comment(s)

What is ICallbackEventHandler

ASP.NET 2.0 introduced an interface named ICallbackEventHandler (System.Web.UI.ICallbackEventHandler) to allow asynchronous communication with the server. Unlike Postback, in Callback only user defined information is sent to the server. Instead of using Postback to post the page, ICallbackEventHandler uses the DoCallback event to send user defined data to server, and return a String to client; on the client-side JavaScript can then manipulate the string. In total we have to use four functions for the implementating ICallbackEventHandler; two client side functions (in javascript) and two server side functions.

Components of Client Callbacks

Creating an ASP.NET page that programmatically implements client callbacks is similar to creating any ASP.NET page, with a few these differences. The page's server code must perform the following tasks:

  • Implement the ICallbackEventHandler interface. You can add this interface declaration to any ASP.NET Web page.

  • Provide an implementation for the RaiseCallbackEvent method. This method will be invoked to perform the callback on the server.

  • Provide an implementation for the GetCallbackResult method. This method will return the callback result to the client.

In addition, the page must contain three client script functions that perform the following actions:

  • One function calls a helper method that performs the actual request to the server. In this function, you can perform custom logic to prepare the event arguments first. You can send a string as a parameter to the server-side callback event handler.

  • Another function receives (is called by) the result from the server code that processed the callback event, accepting a string that represents the results. This is referred to as the client callback function.

  • A third function is the helper function that performs the actual request to the server. This function is generated automatically by ASP.NET when you generate a reference to this function by using the GetCallbackEventReference method in server code.

Both client callbacks and postbacks are requests for the originating page. Therefore, client callbacks and postbacks are recorded in Web server logs as a page request.

Example:

The following server code implement the ICallbackEventHandler interface.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //
        string sbReference = ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");

        string cbScript = String.Empty;

        // check if the script is already registered or not 

        if (!ClientScript.IsClientScriptBlockRegistered("CallServer"))
        {

            cbScript = @" function CallServer(arg,context) { " + sbReference + "}";

            ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);

        }
    }

    #region ICallbackEventHandler Members

    public string GetCallbackResult()
    {
        try
        {
            // Returns the results of a callback event to the client.

            string dateString = DateTime.Now.ToString();

            return dateString;
        }
        catch (Exception)
        {

            return string.Empty;

        }

    }

    public void RaiseCallbackEvent(string eventArgument)
    {
        if (!String.IsNullOrEmpty(eventArgument))
        {

            // Processes a callback event on the server using the event
            // argument from the client.

        }
        else
        {

            // Set a flag so that the GetCallbackResult is not called. 

        }
    }

    #endregion
}

The client code contains the following javascript block.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Client Callbacks</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <script language="javascript" type="text/javascript">
   1:  
   2:  
   3:             setTimeout ( "CallServer('','');", 5000 );
   4:  
   5:             function ReceiveServerData(rValue) 
   6:             {    
   7:                 alert("Date from server: " + rValue)
   8:             }
   9:  
  10:     
</script> </div> </form> </body> </html>

 Summary:

This post demonstrated easy way to implement client callbacks functionality into ASP.NET 2.0 applications.

Download:

The code is attached as a zip file and is available for download Click Here.

 References:

http://msdn.microsoft.com/en-us/library/ms178208.aspx

How to access members of a form or a class from another thread.
15 March 09 11:26 AM | Michael Neiter | with no comments

One way to solve this is to call the Invoke method of a control with a delegate.

Example:

if (this.InvokeRequired)
{
    this.Invoke(delegate
    {
        // Here you can access to your form or class members.
    });
}