Total Pageviews

Wednesday, July 1, 2009

True Random and Unique AlphaNumeric Number Generator

public string GetRandomUniqueAlphaNumericCode(int length, bool lowerCase) { 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)]); } strCode = (result.ToString()).ToUpper(); bool flag = false; for (int i = 0; i < strCode.Length; i++) { if (char.IsDigit(strCode, i)) { flag = true; } } if (flag == false) { GetRandomUniqueAlphaNumericCode(); } return strCode; } here strCode is static class variable. this will generate random and unique alphanumeric string.

Forums for Microsoft .NET developers

Hi begginers to Microsoft.NET world, here a list of forums and educational sites where you can post your queries and get ur answers from professionals. this may help you to increase your knowledge and also help if u stuck with some issues…become a regular member(its free) so that source code access is easy ….and also contibute wen u have enough greymatter to solve complex issues of .NET. Comment on this post and add more forums which i might have missed …..

www.eggheadcafe.com

www.c-sharpcorner.com

www.vbdotnetheaven.com

www.dotnetheaven.com

forums.asp.net

www.codeproject.com

www.eggheadcafe.com

www.4guysfromrolla.com

www.aspalliance.com

www.devasp.net

DotNetCommunity

www.w3schools.com

Tuesday, June 30, 2009

Find out the Binary, ASCII and Character of a Given String in SQL Server

When you are storing data inside fields like ‘address’, there are bound to be unusual characters in it which make way due to poor validation rules. A good way to look for them is to convert your string to varbinary.

Here’s the query:

DECLARE @MyAddress varchar(35)
SET @MyAddress = 'CANTB RY EA%T P.O.Box 55343'

DECLARE    @BIN AS VARBINARY(100)
SET    @BIN = convert(varbinary(100),@MyAddress)

SELECT    SUBSTRING(@BIN, Number, 1) AS Binary,
ASCII(SUBSTRING(@BIN, Number, 1)) AS ASCII,
CHAR(ASCII(SUBSTRING(@BIN, Number, 1))) AS Character
FROM    master..spt_values
WHERE    Type = 'p'
AND Number BETWEEN 1 AND DATALENGTH(@BIN)

Monday, June 29, 2009

Using JavaScript for Validation of Different Date Formats in Asp.NET Web Form

Most often asp.net web applications need to validate date in a form. It is not that easy to play with different format of dates at different places. Mostly the mm/dd/yyyy (alternatively, mm-dd-yyyy) format of date is used. But we may need to go dd/mm/yyyy (alternatively, dd-mm-yyyy) also, and yyyy/mm/dd (alternatively, yyyy-mm-dd) format is no exception too. This article will discuss how to validate date in all these formats using simple yet powerful javascript code snippet.
Date of Purchase: <asp:textbox id="txtPurchaseDate" runat="server"></asp:TextBox><br /><cc1:calendarextender id="CalendarExtenderTo" format="dd-MM-yyyy" targetcontrolid="txtPurchaseDate" popupbuttonid="imgCalendarTo" runat="server"></cc1:CalendarExtender><br /><img id="imgCalendar" runat="server" src="SmallCalendar.gif" border="0" /><br /><asp:button id="btnSubmit" runat="server" text="Submit" onclientclick="ValidateForm();"> Remember, we need ajax enabled page to use the calendar extender. Note that I have set the format in the calendarextender to dd-MM-yyyy. This will put the date in the targetcontrol (here, txtPurchaseDate) in dd-mm-yyyy format. On client click of the button btnSubmit, the javascript function ValidateForm() will validate the date in the textbox. If it is not in dd-mm-yyyy format, a message will be alerted as in the figures above. Here are the functions Validateform() and validateInputDate(). function ValidateForm() { if(document.getElementById("txtPurchaseDate")) { if(validateInputDate(document.getElementById("txtPurchaseDate").value)==false) { alert("Please input purchase date in the format dd-mm-yyyy."); return false; } } } //Validates date in the format dd-mm-yyyy (e.g. 19-10-2009) function validateInputDate(dateString){ if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\-.](0[1-9]1[012])[\-.](1920)[0-9]{2})$/)) { return true; } else { return false; } } //Validates date in the format dd/mm/yyyy (e.g. 19/10/2009) function validateInputDate(dateString){ if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\/.](0[1-9]1[012])[\/.](1920)[0-9]{2})$/)) { return true; } else { return false; } } //Validates date in the format dd-mm-yyyy or dd/mm/yyyy (e.g. 19-10-2009 or 19/10/2009) function validateInputDate(dateString){ if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\- \/.](0[1-9]1[012])[\- \/.](1920)[0-9]{2})$/)) { return true; } else { return false; } } // Validates date in the format mm/dd/yyyy (e.g. 10/19/2009) function validateInputDate(dateString){ if (dateString.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/)) { return true; } else { return false; } } // Validates date in the format yyyy-mm-dd or yyyy/mm/dd (e.g. 2009-10-19 or 2009/10/19) function validateInputDate(dateString){ if (dateString.match(/^(?:(1920)[0-9]{2})[\- \/.](0[1-9]1[012])[\- \/.](0[1-9][12][0-9]3[01])$/)) { return true; } else { return false; } } // Validates date in the format yyyy-mm-dd (e.g. 2009-10-19) function validateInputDate(dateString){ if (dateString.match(/^(?:(1920)[0-9]{2})[\-.](0[1-9]1[012])[\-.](0[1-9][12][0-9]3[01])$/)) { return true; } else { return false; } } // Validates date in the format yyyy/mm/dd (e.g. 2009/10/19) function validateInputDate(dateString){ if (dateString.match(/^(?:(1920)[0-9]{2})[\/.](0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])$/)) { return true; } else { return false; } }

22 Visual Studio Short Keys and 6 Short-cut Ways to Custom Jobs: A List of Tips and Tric

Efficient programmers use short keys in IDE like Visual Studio. This saves time and in many cases makes the work run faster also. I also love short keys. They are smart! And there also go some tricks that help make your visual studio days a party! I have listed here some short cuts and some tips with the hope that this will be helpful to you all. Visual Studio Short-cuts 1. Ctrl+F5 to run the website without debugging. F5 only will run the website in debugging mode. 2. Stop Debugging: Shift+F5 3. Restart Debugging: Ctrl+Shift+F5 4. Break All: Ctrl+Alt+Break 5. F11 to debug line by line downwards from the toggle point. This works with F10 also. In fact you can see F10 assigned for this task. See Debug menu in the visual studio. 6. F9 to toggle a break point. 7. To delete all the break points at once: Ctrl+Shift+F9. If you only wish to disable the break points you can go down the Debug menu. 8. Ctrl+S to save the current document. Ctrl+Shift+S to save all the documents at once. 9. Print a document directly from the visual studio? Press Ctrl+P. This will bring the print dialog. 10. Ctrl+F to find a text. A find dialog will be displayed. Then you are left with a number of options. 11. Ctrl+H or Ctrl+Shift+H for find and replace. 12. Ctrl+G to go to the specific line number in the current document. 13. Open the web browser right from within the visual studio? Press Ctrl+Alt+R. 14. Irritated switching back and forth the design view and code behind page of a file? Use F7 to navigate back and forth the files of a page. 15. Press F4 to view the properties window for a control from the design page. 16. To view the server explorer: Ctrl+Alt+S 17. To view the solution explorer: Ctrl+Alt+L 18. To view the output window: Ctrl+Alt+O 19. To view the toolbox: Ctrl+Alt+X 20. Press Shift+Alt+Enter to view/undo full screen. 21. Press Ctrl+O to open a document from the project folder. 22. Ctrl+F11 to view disassembly: the machine level code! Visual Studio Tips 1. To view the start page, navigate View->Other Windows->Start Page 2. To initiate the start page to display feed from a website, Tools->Options->Startup. Choose show start page at start from the combo fox. Input the start page news channel rss feed. Click Ok. 3. To display line numbers in the documents, Tools->Options->Text Editor. Now click the editor you need to display number in. Check Line Numbers at the right side of the window. 4. Initiate the home page for the web browser [opened by pressing Ctrl+Alt+R]? Follow Tools->Options->Environment->Web Brower. Set the home page and optionally the search page from the right side of the window. 5. Know the class name or method name but confused the right namespace? Right click the class name or method name and click Resolve; you will see the reference you need to add. Click the reference. It will be added for the page. 6. Using find window and clicking Find button each time to go to next match? Leave the trend. Just press F3 to go to next match!! Shortcuts are the small but useful ladders of programming. You can use them to go up and down, left and right or south and north. I would like to heartily welcome to share your tips and tricks that you have learned from your dedicated play around with the visual studio. All the tips and shortcuts I have listed above are tested and learned from visual studio 2005. They may or may not work in visual studio 2008 and later versions. You can specify the compatibility of your trick that you are posting as comment in this article. Thank you very much. Happy Programming!

Friday, June 26, 2009

How to detect browser using JavaScript

var isIE = false; var isFF = false; var isOP = false; var isSafari = false; function DetectBrowser() { var val = navigator.userAgent.toLowerCase(); if(val.indexOf("firefox") > -1) { isFF = true; } else if(val.indexOf("opera") > -1) { isOP = true; } else if(val.indexOf("msie") > -1) { isIE = true; } else if(val.indexOf("safari") > -1) { isIE = true; } }

Thursday, June 25, 2009

Generating Unique Keys in .Net

Introduction :
I have few applications where I need to create some unique IDs. GUIDs are great as they give Globally Unique identifier but they are big. I mean if you want to issue unique number in your application which you want to give as Booking Number or any reference number then GUIDs is obviously not a solution. Therefore, I need some simple Id which is unique too. For example when I send a request to my Credit Card Processor there’s an ID that correlates my invoice with the transaction at the provider. A GUID isn’t what I’d want here.
But one relatively simple solution is to create sequential ID which will be of appropriate size as well as it will guarantee uniqueness. Very Good and Simple solution!!! Isn’t it !! My answer would be NO !! Because it is security threat for your website. In case of Web Application where you can Retrieve your Order or Booking Details by just giving Order Reference number, you can easily BruteForce Sequential Reference numbers to retrieve records.
In this article I will discuss some of techniques.
Using DateTime and HashCode:
Using DateTime for generating unique keys is very common practice. I have remixed this approach by inducing HashCode in it also. Like
DateTime.Now.ToString().GetHashCode().ToString(”x”);
It will give you some key like 496bffe0. At the first glance it seems to be satisfied Unique key as its using current time and hashing to generate key but GetHashCode() doesn’t procduce unique code everytime. Althought Microsoft is using Double Hashing algorithms with N Number of collision resolving double hash function but during my experimentation I found lot of collisions.
Using GUIDs and HashCode:
So then I tried
Guid.NewGuid().ToString().GetHashCode().ToString(”x”);
It gives key something like 649cf2e3.Somehow I don’t think that this string representation at least is unique… 38 characters represented as 8? Ok 32 bits, but still it’s 8 digits and characters limited to hex values and yes my doubt got right as I wrote program which generated 100,000 keys and checked it for collisions and found several keys duplicated.
Using RNGCryptoServiceProvider and Character Masking :
The .net Framwork provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers. Although I can use this class to generate unique number in some sense but it is also not collision less. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only. So, I used this class along with some character masking to generate unique key of fixed length.
Below is code sample:


 private string GetUniqueKey()
        {
            int maxSize = 8;
            int minSize = 5;
            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();
        }

Analysis shows that RNGCrypto with Character Masking is best method to generate Unique keys.

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...