Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Color Picker

Posted by ramanisandeep on November 6, 2009

There are lots of way show color picker on web site. Today I was search for such color picker which I want to use it in one of my website.

I have searched a lot of color picker that can be useful, so here I m writing about it.

ColorPicker AJAX Extender

ColorPicker is an ASP.NET AJAX extender that can be attached to any ASP.NET TextBox control. It provides client-side color-picking functionality with UI in a popup control. You can interact with the ColorPicker by clicking on a colored area to set a color. It requires a binary reference to the ASP.NET AJAX Control Toolkit.

ColorPicker extender is multi-browser compatible: it works with IE 6/7/8, Firefox, Safari and Goggle Chrome. ColorPicker is built on top of ASP.NET AJAX Control Toolkit and internally utilizes a Popup extender. ColorPicker is compatible with the UpdatePanel: can be placed inside the UpdatePanel.

ColorPicker is included in Ajax Control Toolkit since Release 30512. For those who use previous release of Ajax Control Toolkit this ColorPicker project will continue to evolve and stay in sync with the Ajax Control Toolkit.

Read more…

Color Picker using javascript

This widget is used to select a color, in hexadecimal #RRGGBB form. It uses a color "swatch" to display the standard 216-color web-safe palette. The user can then click on a color to select it.

This script is very simple to implement, and can add a lot of style to your page that requires color values!

Because of the size of the table, this color picker may be slow on lower-end machines. Consider your target users when deciding whether or not it operates fast enough.

Read more…

Posted in ASP.NET 2.0, ASP.NET 3.5, ASP.NET Ajax, JavaScript | Tagged: , , | Leave a Comment »

Moving Values Between Select Boxes

Posted by ramanisandeep on November 2, 2009

These functions allowed you to do commonly-requested actions with select boxes.

For example, you can easily pass values between two select boxes. This makes a nice Windows-style interface for choosing components, adding and removing items from a list, etc. Options are re-ordered as they are added and removed from the lists.

Several other functions are included in the source that are not in the examples. This includes copying items in lists instead of moving them, copying/moving all items, and automatically selecting all items in a list.

read more

Other related articles 

Posted in JQuery, JavaScript | Tagged: , , | Leave a Comment »

Beginning with Digital Signatures in .NET Framework

Posted by ramanisandeep on November 2, 2009

This article explains how to get started with digital signatures, using X509 certificates in .NET.

The purpose of digital signatures is to identify data in a way that cannot easily be faked.  Phishing, infected software and illegal contents published by unknown subjects can be prevented with digital signatures. Digital signatures will allow data and digital documents to be used as if they were signed paper. Browsers are now able to recognize X.509 certificates and know which Certificate Authorities are trusted. The X.509 system has grown to be the standard format for public key certificates, and is therefore the best way of proving that a document comes from the source it claims to come from.

This article will introduce X509 certificates, explain a little about the asymmetric cryptography that is at their heart, and end by describing how to use and manage these certificates within the .NET Framework classes.

Asymmetric Cryptography and Digital Signatures

Digital signatures are created using asymmetric cryptography, the approach on which digital signatures are based. Asymmetric Cryptography is distinguished by having two different keys, a private key to encrypt messages and a public key to decrypt them. The cryptographic private key K0 (a suitable array of bytes) is used with an appropriate algorithm to  transform the initial human-readable message into a different message that is encrypted.

A second public cryptographic key K1, which is related to the private one, is used to change the encrypted message back to its original decrypted form via a second related algorithm.

With this mechanism, your recipient is sure that the message that she/he received is your message, because only you hold the private key that is related to the public, shared, key. You digitally ‘sign’ your message.

In practice, you will hash the message beforehand (with hash algorithm such as MD5 or SHA1), obtaining the hashed message M1. Then you will encrypt M1 with your private key K0, digitally signing your message, and, finally, you will send your message M, the encrypted hash M1 (the signature) and the public key K1 to your recipient. Your recipient will compute the hash of your message M and will compare it with the decrypted value of M1. If the two hashes matches, the signature is valid.

You will notice that the signature is obtained by encrypting the hash of a message, rather than  the message itself. This is done for performance reasons.  Asymmetric cryptography is a slow process and the time required to encrypt, or decrypt, a message is directly related to the message length.  You can make better use of the processor by reducing the amount of data to be processed. Sometimes, a very large (in bytes) message, can be reduced, by hashing it, to a much smaller hashed message. It is more convenient to transmit a the bulk of the data as clear text and just attach less than a hundred encrypted bytes attached to it than to encrypt the entire message and send it in the encrypted form.

Asymmetric key encryption by itself is not enough because it is necessary to trust the public key received. An attacker can deceive you by signing a message with his private key and send you a digitally confirmed message with its (related) public key, whilst  pretending he is someone  else.

The public-key infrastructure (PKI) avoids this by utilizing a third-party entity, called Certification Authority that, under its responsibility, binds a public key to its owner. The binding occurs when the Certification Authority digitally sign a message that contains the public key and the identity of its owner. A digital certificate is obtained.

Read more

Posted in .Net Framework | Tagged: , , | Leave a Comment »

.NET Challenge – for or foreach?

Posted by ramanisandeep on November 2, 2009

Question:

for should be used instead of foreach to iterate over collections in performance-critical loops.

Answer: True

foreach uses an enumerator which can sometimes be slower than the simple iteration of a variable in a for loop. Enumerators, such as those contained in the .NET Framework, have both managed heap and virtual function overhead. The amount of overhead depends on the collection used and the version of the .NET Framework. As always, the best way to determine the overhead between techniques is to run a performance test and compare.

To illustrate the performance impact, 10 strings were concatenated 100 times using the techniques outlined below. 

Running against .NET Framework 3.5 using an ArrayList, a generic List and a LinkedList with 5,000 strings, the following results were obtained using Ants Performance Profiler 5:

Wall Clock Time (ms) Loop Structure (5,000 strings)
25.003 for LinkedList<string>
0.037 foreach LinkedList<string>
0.039 for ArrayList
0.053 foreach ArrayList
0.019 for List<string>
0.034 foreach List<string>

 

Except for the LinkedList, the for loop is faster.

The for loop is thought by many developers to be less readable and maintainable than foreach. Using foreach also makes it possible to iterate across anything that’s IEnumerable, allowing for the creation of more general algorithms and the use of "yield" to build custom collections.

It is normally good practice to code for clarity rather than micro-optimization.

Reference : Rad-gate

Posted in ASP.NET 2.0, ASP.NET 3.5, C# 2.0, C# 3.0 | Tagged: , , , , | Leave a Comment »

Multiple File Upload using JQuery

Posted by ramanisandeep on October 28, 2009

Introduction

In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.

I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.

Download the Following Files

Namespace used

using System.Security.Cryptography;
using System.Text;
using System.IO;

Step 1: Include the jQuery Files needed on the page.

Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:

<head id="Head1" runat="server">
    <title>Multiple File Upload using JQuery</title>
    <script src="Scripts/jquery-1.3.2.js"
        type="text/javascript">
    </script>
    <script src="Scripts/jquery.MultiFile.js"
        type="text/javascript">
    </script>
</head>

Step 2: Add File Upload Control & Button on the Page.

 

<asp:FileUpload ID="FileUpload1" runat="server"
         class="multi" accept="gif|jpeg|bmp|png|jpg"
         maxlength="5" />
        <br />
        <asp:Button ID="btnUpload" runat="server"
        Text="Upload All" OnClick="btnUpload_Click" />
        <br />
        <asp:Label ID="lblMsg" runat="server" Text="">\
        </asp:Label>

 
class=”multi” is used to specify that user can select multiple files.
 

maxlength property specify that user can upload maximum 5 files not more than that.

accept property used to restrict user to upload only certain type of file only.

Step 3: Double click on Upload Button & Write the code that is used to upload files.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ServerSideValidation() == true)
        {
            string SavePath, Msg = null;

            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
                        + GetUniqueKey() + GetFileExtension(hpf.FileName);
                    hpf.SaveAs(Server.MapPath(SavePath));
                    //SavePath can be saved in DB.
                    Msg += GetFileName(hpf.FileName.ToString()) + " , ";
                }
            }
            lblMsg.Text = Msg + " Uploaded Successfully.";
        }
    }

Step 4: Write the private function which helps to Upload files.

This function helps to extract file extension from the fileName.

private string GetFileExtension(string FileName)
   {
       char saperator = ‘.’;
       string[] temp = FileName.Split(saperator);

       return "." + temp[1].ToString();
   }

This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.

private string GetUniqueKey()
    {
        int maxSize = 8;
        char[] chars = new char[62];
        string a;

        a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        chars = a.ToCharArray();

        int size = maxSize;
        byte[] data = new byte[1];

        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

        crypto.GetNonZeroBytes(data);
        size = maxSize;
        data = new byte[size];
        crypto.GetNonZeroBytes(data);
        StringBuilder result = new StringBuilder(size);

        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length - 1)]);
        }

        return result.ToString();
    }

This function help to get Filename from the filepath.

   private string GetFileName(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Name;
    }

Step 5: Add Server Side Validation Code

This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.

Validation rules like whether file type is correct or not, file size is valid or not.

If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.

private bool ServerSideValidation()
    {
        string errorMsg = string.Empty , temp=null;
        bool errorFlag = true;

        // Get the HttpFileCollection
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                temp = ValidateImage(hpf);
                if(temp != null)
                {
                    errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
                    temp = null;
                }
            }
        }

        if (errorMsg != "")
        {
            lblMsg.Text = errorMsg;
            errorFlag = false;
        }
        return errorFlag;
    }

This function used to check file type & file size. If file is invalid than it will return error message.

private string ValidateImage(HttpPostedFile myFile)
    {
        string msg = null;       
        int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
        //Check Length of File is Valid or Not.
        if (myFile.ContentLength > FileMaxSize)
        {
            msg = msg + "File Size is Too Large.";
        }
        //Check File Type is Valid or Not.       
        if (!IsValidFile(myFile.FileName))
        {                    
            msg = msg + "Invalid File Type.";
        }
        return msg;
    }

This function is used to check whether the file that user want to upload is valid file type or not.

    private bool IsValidFile(string filePath)
    {
        bool isValid = false;

        string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };

        for (int i = 0; i < fileExtensions.Length; i++)
        {
            if (filePath.Contains(fileExtensions[i]))
            {
                isValid = true;
            }
        }
        return isValid;
    }

Conclusion:

This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.

Hope this will help !!!
Jay Ganesh

 

Posted in ASP.NET 2.0, JQuery | Tagged: , , , , | 1 Comment »

ASTreeView – A Powerful ASP.Net TreeView Control

Posted by ramanisandeep on October 23, 2009

ASTreeView is a powerful treeview with drag drop, ajax loading, context menu, xml import/export, checkbox, selection, add/editing/deleting nodes with ajax.

ASTreeView is developed on .NET framework 2.0. Demo project is a Visual Studio 2005 project.

ASTreeView is FREE! That means you can use it anywhere!

for more detail : click here

Posted in ASP.NET 2.0, ASP.NET Ajax | Tagged: , , | Leave a Comment »

Happy Diwali

Posted by ramanisandeep on October 15, 2009

Hi Readers,

Happy Diwali to all the readers of this blog & have a great time with your dear ones !!!

happy_diwali_big1

Celebrate your Diwali with Shree Ganesh’s Aarti :

Jai Ganesha Jai Ganesha Jai Ganesha Deva
Maata Jaaki Parvati Pitaa Mahadeva
Ladoowan Ka Bhog Lage Sant Karen Sevaa
Jai Ganesh Deva
Eka Dant Dayavant Chaar Bhujadhari
Maathe Par Tilak Sohe Muse Ki Sawaari
Paan Chadhe Phool Chadhe Aur Chadhe Mevaa
Jai Ganesh Deva
Andhe Ko Aankh Det Kohin Ko Kaaya
Banjhan Ko Putra Det Nirdhan Ko Maaya
Surya Shama Sharan Aaye Safal Kijye Sevaa
Jai Ganesh Deva

Jay Ganesh !!!

Posted in Mics | Tagged: | Leave a Comment »

Ebook : 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls

Posted by ramanisandeep on October 14, 2009

hi readers ,

here is a very useful book that explore the jQuery usage with ASP.NET Controls. This is very handy book for the web developer who uses jQuery along with ASP.NET.

It helps to enhance your web experience & better understand how/where/when to use jQuery with ASP.NET Controls.

read more : here

read the content : here

Posted in ASP.NET 2.0, ASP.NET 3.5, JQuery | Tagged: , , , | Leave a Comment »

Watch the Video of Luke Hoban & Luca Bolognese

Posted by ramanisandeep on October 14, 2009

Linq to SQL by Luca Bolognese

Luca Bolognese is the Principal Program Manager Lead on the C# team. His talk on LINQ to SQL endows developers with the knowledge necessary to wield the tools that drive data driven application development under C# 3.0. A consummate speaker, Luca skillfully guides his audience through the elements that comprise LINQ to SQL development.

watch the video here

An In-Depth Look at C# 3.0 by Luke Hoban

Luke Hoban was the PM who drove the development of LINQ to Objects, and the man who created the now famous implementation of a ray tracer in a single, very long, LINQ query expression. He is now focusing his efforts on F#. By listening to his talk on C# 3.0 features you will get a chance to see a detailed and specific analysis of how LINQ works. Listening to him give this talk marked a turning point in my understanding of LINQ. For the first time I understood how the team folded extension methods and query expressions together to create the marvelously supple and deceptively simple syntax that we know as LINQ.

watch the video here

Posted in ASP.NET 3.5, C# 3.0 | Tagged: , , | Leave a Comment »

What is httpHandler & httpModule?

Posted by ramanisandeep on September 24, 2009

httpHandler – Extenstion Based Preprocessor :

ASP.NET HTTP handler is the process that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

httpModule – Event based Preprocessor :

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

When to use HTTP handlers:

  • RSS feeds: To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
  • Image server:   If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler’s response.

When to use HTTP modules:

  • Security:   Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
  • Statistics and logging:   Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
  • Custom headers or footers:   Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.

Main Features:

  • The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.
    The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.
  • Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.
  • Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change.
  • Modules can subscribe to a variety of request-pipeline notifications. Modules can receive notification of events of the HttpApplication object.

Built-in HTTP Handlers in ASP.NET

  • ASP.NET page handler (*.aspx): The default HTTP handler for all ASP.NET pages.
  • Web service handler (*.asmx): The default HTTP handler for Web service pages created as .asmx files in ASP.NET.
  • Generic Web handler (*.ashx): The default HTTP handler for all Web handlers that do not have a UI and that include the @ WebHandler directive.
  • Trace handler (trace.axd): A handler that displays current page trace information.

Reference:

I have taken the content & compiled from here.

Other Useful Articles are:

  1. The Two Interceptors: HttpModule and HttpHandlers – Click here
  2. Displaying images in ASP.NET using HttpHandlers – Click here

Posted in ASP.NET 2.0, C# 2.0 | Tagged: , , , , | Leave a Comment »