Posts

Generate random string using c#

Hi, Today am blogging a simple concept related to generating a random sring. In realtime it will be used mainly for generating captcha, random password, Temporary objects etc. Here we can send the string length expected. Also You can modify he complexity. Its a simple code and easily understandble. Here is the code snippet. /// /// Creates the random string based on the length provided /// /// Length of the password. /// public static string generateRandomString(int PasswordLength) { string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"; Random randNum = new Random(); char[] chars = new char[PasswordLength]; int allowedCharCount = _allowedChars.Length; for (int i = 0; i < PasswordLength; i++) { chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())]; } return new string(chars); } hope it helps you. Regards, Pavan N

Finding file size in bytes on serverside using c#

Hi, This requirement will come mainly while doing I/O operations (in my opinion it is obviously one of tedious taks carried by server). Here am showing you the snippet of code to find out the number of bytes of a file. here am using this code to validate the size of the file on server side. Which is a common requirement while doing file uploads. Here is the snippet. private static long GetFileSizeOnDisk(string filelocation) { FileInfo info = new FileInfo(file); uint dummy, sectorsPerCluster, bytesPerSector; int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy); if (result == 0) throw new Win32Exception(); uint clusterSize = sectorsPerCluster * bytesPerSector; uint hosize; uint losize = GetCompressedFileSizeW(file, out hosize); long size; size = (long)hosize Thanks & Regards, Pavan N

Number to String conversion

Hi, Generally in finance or banking or this kind of requirement is needed. Its more or less a common thing to convert a number to a string. I used this to convert currency to words format. Here is the snippet. /// /// Numbers to text. /// /// The value. /// public string NumberToText(int value) { string[] num0to10 = new string[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" }; string[] num11to20 = new string[] { "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty" }; string[] num20to100 = new string[] { "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety...

Download file using WCF REST services

Hi, Generally we used to download a file using a handlers and sending parameters as a querystring (lets say download.ashx). Here few cases we might need to impersonate the user also. It purely depends on environment. Here is a sample code snippet just for reference. if (extension.Trim() == ".pdf") { context.Response.Clear(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", "attachment;filename=" + queryFile + ".pdf"); context.Response.BinaryWrite(System.IO.File.ReadAllBytes(file)); } But instead of that we can download a file as a stream using a WCF REST service too. Here is the code snippet for declaration in interface .. /// <summary> /// To fetch documents /// </summary> /// <param name="filePath">Represent text of filepath</param> /// <param name="fileName">Represents text of filename...

Validate domain user using c#

Hi, Here am sharing code related to validate a domain user againsta active directory. This is well used for implementing authentication and authorization in asp.net or windows application. the call should be sent a [domainname]\[username] and [password] public int VerifyUser(string userName, string password) { try { string domainName = string.Empty; string domainUserName = string.Empty; string[] tempString = null; string[] delimiter = new string[] { @"\" }; tempString = userName.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); if ((tempString.Length == 0) || (tempString.Length == 1)) { return 1; } domainName = tempString[0]; domainUserName = tempString[1]; LDAP.Domain_Authentication imperson = new LDAP.Domain_Authentication(domainUserName, password, domainName); if (imperson.IsValid()) { return 2; } return 3; } catch (Exception ex) { return -1; } } And the LDAP class i...

server side printing / PDF conversions using c# and asp.net/wcf service

Hi All, I know its a tough task to search this kind of  requirement . As i did same and endup with a solution like using Crystal reports for printing on network printer. And a WKHTML library to convert html pages to either images or PDF. There inturn i can convert TIFF files to PDF using Ghostscript(If you need this code please drop a comment). Now coming to this server side network printing. At first we need to have a following things Visual studio Crystal reports for Visual studio WKHTMLTOPDF/WKHTMLTOIMAGE A proper permissions on a folder where we are going to store our images or PDF files etc which need to be sent to a printer And the code flow is first i will scale the image to a standard size with the following code  prepare a HTML file having image tag with SRC as the image file which needs to be printed then i will call WKHTMLTOIMAGE library  to convert public static Image ScaleImage(Image image, int maxWidth, int maxHeight) { ...

Part– II : Coding standards

These are the main checklist I used to follow in day to day code development and maintenance. Hope this might help some of you new people. If there is any mistakes/typo please do not hesitate to comment. Coz these are my personal views and opinions 1. Need to avoid unnecessary comments especially while releasing a build 2. Reduce as much lines of code as possible 3. if a variable is used only once then declare it locally if possible 4. Follow the naming conventions especially in DB layer. This helps a lot I promise :) 5. Method name should tell what it does. Do not use miss-leading names. If the method name is obvious, there is no need of documentation explaining what the method does 6. Make a note or summary at top of the page if the code was developed my multiple persons. it helps to track when and which kind of development started 7. Make sure that the required input values gets logged while logging the error message in catch block 8. Avoid ...