codetonics
codetonics
Code Tonics
65 posts
A Blog for C# programmer. Windows Forms, ASP.NET, WPF, WCF, WF, Windows Phone etc.
Don't wanna be here? Send us removal request.
codetonics · 12 years ago
Text
Recursively Copy folder contents to another in C#
The code snippet given below have a method CopyFolderContents() which will take two parameters "SourcePath" and "DestinationPath" and it will copy all the content in the directory "SourcePath" to "DestinationPath" recursively Code Snippet * private bool CopyFolderContents(string SourcePath, string DestinationPath) * { *    SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; *    DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\"; *    try *    { *       if (Directory.Exists(SourcePath)) *       { *          if (Directory.Exists(DestinationPath) == false) *          { *             Directory.CreateDirectory(DestinationPath); *          } * *          foreach (string files in Directory.GetFiles(SourcePath)) *          { *             FileInfo fileInfo = new FileInfo(files); *             fileInfo.CopyTo(string.Format(@"{0}\{1}", DestinationPath, fileInfo.Name), true); *          } * *          foreach (string drs in Directory.GetDirectories(SourcePath)) *          { *             DirectoryInfo directoryInfo = new DirectoryInfo(drs); *             if (CopyFolderContents(drs, DestinationPath + directoryInfo.Name) == false) *             { *                return false; *             } *          } *       } *       return true; *    } *    catch (Exception ex) *    { *       return false; *    } * } http://dlvr.it/4p9jr9
0 notes
codetonics · 12 years ago
Text
do while Loop in C#
The do statement conditionally executes an embedded statement one or more times. do-statement: do   embedded-statement   while   (   boolean-expression   )   ; A do statement is executed as follows: * Control is transferred to the embedded statement. * When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), the boolean-expression is evaluated. If the boolean expression yields true, control is transferred to the beginning of the do statement. * Otherwise, control is transferred to the end point of the do statement. Within the embedded statement of a do statement, a break statement (§8.9.1) may be used to transfer control to the end point of the do statement (thus ending iteration of the embedded statement), and a continue statement may be used to transfer control to the end point of the embedded statement. The embedded statement of a do statement is reachable if the do statement is reachable. The end point of a do statement is reachable if at least one of the following is true: * The do statement contains a reachable break statement that exits the do statement. * The end point of the embedded statement is reachable and the boolean expression does not have the constant value true. http://dlvr.it/4p9jm9
0 notes
codetonics · 12 years ago
Text
C# Language Release History
Details of all the C# version ever released till date. with highlight on some main features. C# Version Release Date Tool Feature 1.0 2002 Visual Studio .Net First release of .net 2.0 2005 Visual Studio 2005 Partial classes Support for generics Iterators Nullable syntax Anonymous methods Static class Volatile keyword 3.0 2008 Visual Studio 2008 Implicitly Typed Local Variables Extension Methods Lambda Expressions Type Inference Object and Collection Initializers Anonymous Types Automatically Implemented Properties Expression Trees 4.0 2010 Visual Studio 2010 Support for Covariance and Contravariance Optional parameters and named arguments Support for Dynamic and DLR Enhanced support for COM interop 5.0 2012 Visual Studio 2012 Async / Await Feature Support for caller information http://dlvr.it/4p8n5F
0 notes
codetonics · 12 years ago
Text
.Net Framework Release History
Ever found difficulty in tracking the .Net Framework realseases ? Don't worry this article gonna help you do exactly that. Tracking the release history of .Net Framework. I gonna update it as soon as new framework is released. .Net Version Release Date Tool Main Features 1.0 2002 Visual Studio .Net First release of .net 1.1 2003 Visual Studio 2003 Support for ASP.Net mobile controls Supports side-by-side execution Security Changes 2.0 2005 Visual Studio 2005 Generics (with generic collection) Nullable Types Support of IPv6 addresses in .net remoting Common Language Runtime 2.0 3.0 2006 – WCF (Communication framework) WPF (Presentation framework) WF (Workflow Foundation) 3.5 2008 Visual Studio 2008 LINQ Addin / Plugin Model (System.AddIn.Contract.dll) 4.0 2010 Visual Studio 2010 Parallel Computing Code Contracts Lazy Initialization Dynamic Language Runtime In-process side-by-side hosting Background garbage collection Covariance and Contravariance Common Language Runtime 4.0 4.5 2012 Visual Studio 2012 Enhanced regular expression support Default culture for application domain Zip compression Support of array with size more than 2GB Asynchronous file operation Improvement in parallel computing 4.5.1 2013 Visual Studio 2013 Ability to collect diagnostics information Ability to explicitly compact the large object heap (LOH) during garbage collection Additional performance improvements such as ASP.NET app suspension Multi-core JIT improvements http://dlvr.it/4p8n2n
0 notes
codetonics · 12 years ago
Text
Dropdown with all country names
The code given below is just a simple dropdown box / combobox with all the country names of the world. Simply copy and paste the code to get a dropdown box with all country names. Select Country Afghanistan Albania Algeria American Samoa Andorra Angola Anguilla Antarctica Antigua And Barbuda Argentina Armenia Aruba Australia Austria Azerbaijan Bahamas Bahrain Bangladesh Barbados Belarus Belgium Belize Benin Bermuda Bhutan Bolivia Bosnia And Herzegowina Botswana Bouvet Island Brazil British Indian Ocean Territory Brunei Darussalam Bulgaria Burkina Faso Burundi Cambodia Cameroon Canada Cape Verde Cayman Islands Central African Republic Chad Chile China Christmas Island Cocos (Keeling) Islands Colombia Comoros Congo Cook Islands Costa Rica Cote D'Ivoire Croatia (Local Name: Hrvatska) Cuba Cyprus Czech Republic Denmark Djibouti Dominica Dominican Republic East Timor Ecuador Egypt El Salvador Equatorial Guinea Eritrea Estonia Ethiopia Falkland Islands (Malvinas) Faroe Islands Fiji Finland France French Guiana French Polynesia French Southern Territories Gabon Gambia Georgia Germany Ghana Gibraltar Greece Greenland Grenada Guadeloupe Guam Guatemala Guinea Guinea-Bissau Guyana Haiti Heard And Mc Donald Islands Holy See (Vatican City State) Honduras Hong Kong Hungary Icel And India Indonesia Iran (Islamic Republic Of) Iraq Ireland Israel Italy Jamaica Japan Jordan Kazakhstan Kenya Kiribati Korea, Dem People'S Republic Korea, Republic Of Kuwait Kyrgyzstan Lao People'S Dem Republic Latvia Lebanon Lesotho Liberia Libyan Arab Jamahiriya Liechtenstein Lithuania Luxembourg Macau Macedonia Madagascar Malawi Malaysia Maldives Mali Malta Marshall Islands Martinique Mauritania Mauritius Mayotte Mexico Micronesia, Federated States Moldova, Republic Of Monaco Mongolia Montserrat Morocco Mozambique Myanmar Namibia Nauru Nepal Netherlands Netherlands Ant Illes New Caledonia New Zealand Nicaragua Niger Nigeria Niue Norfolk Island Northern Mariana Islands Norway Oman Pakistan Palau Panama Papua New Guinea Paraguay Peru Philippines Pitcairn Poland Portugal Puerto Rico Qatar Reunion Romania Russian Federation Rwanda Saint K Itts And Nevis Saint Lucia Saint Vincent, The Grenadines Samoa San Marino Sao Tome And Principe Saudi Arabia Senegal Seychelles Sierra Leone Singapore Slovakia (Slovak Republic) Slovenia Solomon Islands Somalia South Africa South Georgia , S Sandwich Is. Spain Sri Lanka St. Helena St. Pierre And Miquelon Sudan Suriname Svalbard, Jan Mayen Islands Sw Aziland Sweden Switzerland Syrian Arab Republic Taiwan Tajikistan Tanzania, United Republic Of Thailand Togo Tokelau Tonga Trinidad And Tobago Tunisia Turkey Turkmenistan Turks And Caicos Islands Tuvalu Uganda Ukraine United Arab Emirates United Kingdom United States United States Minor Is. Uruguay Uzbekistan Vanuatu Venezuela Viet Nam Virgin Islands (British) Virgin Islands (U.S.) Wallis And Futuna Islands Western Sahara Yemen Zaire Zambia Zimbabwe http://dlvr.it/4p7hVC
0 notes
codetonics · 12 years ago
Text
Change connection string from C#
Ever want to change the connection string of the database from C# code in your application than your are at right place. The below code snippet in C# exactly does that. Changing the connection string in your web.config or app.config file programmatically or with C# code. Code Snippet * private void UpdateConnectionString(string ConfigPath) * { *    XmlDocument xmlDocument = new XmlDocument(); *    xmlDocument.Load(ConfigPath); *    XmlNode parentNode = xmlDocument.DocumentElement; *    if (parentNode.Name == "connectionStrings") *    { *       foreach (XmlNode childNode in parentNode.ChildNodes) *       { *          if (childNode.Name == "add" && childNode.Attributes["name"].Value=="MySqlConnection") *          { *             string sqlConnectionString = childNode.Attributes["connectionString"].Value; *             SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(sqlConnectionString); *             sqlBuilder.InitialCatalog = "yourDatabaseName"; *             sqlBuilder.IntegratedSecurity = true; *             sqlBuilder.Password = ""; *             *             //Change any other attributes using the sqlBuilder object *             childNode.Attributes["connectionString"].Value = sqlBuilder.ConnectionString; *          } *       } *    } *    xmlDocument.Save(ConfigPath); * } http://dlvr.it/4p7hR7
0 notes
codetonics · 12 years ago
Text
Format date using Javascript
A Simple javascript function to format date. Pass a date as an argument and get formatted date. I needed a JavaScript date format function such as the Visual Basic Format function, in which you can pass a format string and get the formatted string back; my first approach was to issue a series of consecutive and "destructive" replace calls, but upon discovering that the 5.5 (or higher) version of JScript supported the use of a function as the replaceTextargument of the replace method, I got creative. Here's an example call of what I wanted: SomeDiv.innerText = (new Date()).format('dddd, mmmm dd, yyyy.'); This would display: Saturday, July 16, 2005 So in my first approach, I globally and case-insensitively replaced dddd with the corresponding string, which "destroyed" every occurrence, so that later in the code I could replace dd with the date number. This worked just fine, but I knew that by inspecting the format specifier for a match, I could skip the search of every format specifier; say I only want the month and the date; well, by switching upon the format specifier (or rather "datepart" specifier), the year replacement will never be issued. Get it? The fun part relies in the use of a function in the replaceText argument of the replace method; this way the $1 property as a function argument always represents the last match. Other considerations include the format or "datepart" specifiers: none other than yyyy will be parsed as the year; months and days have the usual three flavors of fullname (mmmm), three-letter (mmm) or numeric (mm); hours (hh) can be rectified to the 12-hour format with the a/p specifier, and minutes (nn) and seconds (ss) may also be specified. Javascript Function // a global month names array var gsMonthNames = new Array( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ); // a global day names array var gsDayNames = new Array( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ); // the date format prototype Date.prototype.format = function(f) { if (!this.valueOf()) return ' '; var d = this; return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi, function($1) { switch ($1.toLowerCase()) { case 'yyyy': return d.getFullYear(); case 'mmmm': return gsMonthNames[d.getMonth()]; case 'mmm': return gsMonthNames[d.getMonth()].substr(0, 3); case 'mm': return (d.getMonth() + 1).zf(2); case 'dddd': return gsDayNames[d.getDay()]; case 'ddd': return gsDayNames[d.getDay()].substr(0, 3); case 'dd': return d.getDate().zf(2); case 'hh': return ((h = d.getHours() % 12) ? h : 12).zf(2); case 'nn': return d.getMinutes().zf(2); case 'ss': return d.getSeconds().zf(2); case 'a/p': return d.getHours() < 12 ? 'a' : 'p'; } } ); } http://dlvr.it/4p6bnX
0 notes
codetonics · 12 years ago
Text
Convert HTML to PDF in C# using iTextSharp
You can use iTextSharp in a commercial application and it does not require your app to be released as open source. But it will not work with complex HTML pages and will give fairly good results with simple HTML pages. Specially, tables are not yet supported. iTextSharp-- http://itextsharpsl.codeplex.com/. Code Snippet * // create converter * HtmlToPdfConverter html2pdf = new HtmlToPdfConverter(); * // open new pdf file * html2pdf.Open(@"test"); * // start a chapter * html2pdf.AddChapter(@"Dummy Chapter"); * string html = ...; * // convert string * html2pdf.Run(html); * // add a new chapter * html2pdf.AddChapter(@"Boost page"); * // read web page * html2pdf.Run(new Uri(@"http://www.apple.com")); * // close and finish pdf file. * html2pdf.Close();   http://dlvr.it/4p6bhk
0 notes
codetonics · 12 years ago
Text
Convert HTML to PDF in C# using Spire.PDF
As far as I know, this is the simplest solution with high quality to convert any HTML file to PDF using C# and finally I chose this one. It supports to convert the complex HTML page with rich elements, such as HTTPS, CSS3, HTML5, JavaScript. But it is not free. You can have 1 month free trial on it. If you want to use it in commercial application, you need to purchase the license at the acceptable price. https://pdfapi.codeplex.com/ Code Snippet * //Create a pdf document * PdfDocument doc = new PdfDocument(); * String url = "Http://apple.com/" * doc.LoadFromHTML(url, false, true, true); * //Save pdf file * doc.SaveToFile("webpageaspdf.pdf"); * doc.Close(); * System.Diagnostics.Process.Start("webpageaspdf.pdf"); http://dlvr.it/4p5Lwg
0 notes
codetonics · 12 years ago
Text
CSS Selectors with examples
This Article is about CSS selector and how it woks. Following is explanation of most of the selector that is used in CSS. In the following first is css example and than html code on which it will work, so to try by yourself create html page and put the css as well as related Html and see the result. In most of the select I provided demo link where you can visit and see the result. In below post you might find some new CSS selector that are the part of new CSS3. All of the below examples and demo tried by me on latest Chrome version. .Class -: Select all the element with given class name sample css : Code Snippet * .MyIntro * { *   font:15px arial,sans-serif; *   color:red; * } sample html : Code Snippet * *     My name is Pranay Rana. *     I am working as Soft Engg. * #id -: Select all the element with given id name sample class : Code Snippet * #MyIntro { *     font: 15px arial,sans-serif; *     color: red; * } sample HTML : Code Snippet * *     My name is Pranay Rana. *     I am working as Soft Engg. * Point to Note : You can have more than one element having same classname in HTML page but you can have only one element with the ID. HTMLElement - Select all the html element which name is given. Sample CSS : Code Snippet * p { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. *     I am working as Soft Engg. * HtmlElement HtmlElemnt - Select all the html element which are in html element. Sample CSS : Code Snippet * div p { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. *      *         data *      * * I am working as Soft Engg. in this example all p element inside div get highlighted with read color, but p element outside div doesnt get affected. HtmlElement > HtmlElemnt - Select all the html element which are child of html element. Sample CSS : Code Snippet * div > p { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. *      *         data *      * * I am working as Soft Engg. in this example all p element which are child of div get highlighted with read color, but p element which are not child of div doesnt get affected. HtmlElement + HtmlElemnt - Select all the html element which are immediate after html element. Sample CSS : Code Snippet * div + p { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. * * I am working as Soft Engg. * data in this example p element which is immediate after div get highlighted with read color, in this example "I am working as Soft Engg." this text get highlighted. HtmlElement ~ HtmlElemnt - Select all the html element which are precedes html element. Sample CSS : Code Snippet * div ~ p { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. *      *         data *      * * I am working as Soft Engg. * My Demo Page. in this example p element which is precedes div get highlighted with read color, in this example "I am working as Soft Engg." and "My Demo Page." text get highlighted. [attribute] - Select all the html element which is having attribute. Sample CSS : Code Snippet * [data-name] { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. *      *         data *      * * I am working as Soft Engg. * My Demo Page. in this example any element which is having attribute "data-name"div get highlighted with red color, in this example "My name is Pranay Rana." and "My Demo Page." text get highlighted. [attribute = data] - Select all the html element which is having attribute value equal to data. Sample CSS : Code Snippet * [data-name = 'demo'] { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. *      *         data *      * * I am working as Soft Engg. * My Demo Page. in this example any element which is having attribute "data-name" and value = "demo" get highlighted with red color, in this example "My Demo Page." text get highlighted. [attribute ^= data] - Select all the html element where attribute value begins with data. Sample CSS : Code Snippet * [data-name ^= 'pra'] { *     font: 15px arial,sans-serif; *     color: red; * } So with the above html when apply this "My name is Pranjal Panchal." text is get highlighted because its "data-name" attribute value begining with "pra". [attribute $= data] - Select all the html element where attribute value end with data. Sample CSS : Code Snippet * [data-name ^= 'jal'] { *     font: 15px arial,sans-serif; *     color: red; * } So with the above html when apply this "My name is Pranjal Panchal." text is get highlighted because its "data-name" attribute value ending with "jal". [attribute *= data] - Select all the html element where attribute value contains data. Sample CSS : Code Snippet * [data-name *= 'panchal'] { *     font: 15px arial,sans-serif; *     color: red; * } So with the above html when apply this "My name is Pranjal Panchal." text is get highlighted because its "data-name" attribute value contains "pannchal". [attribute ~= data] - Select all the html element where attribute value contains word data. Sample CSS : Code Snippet * [data-name ~= 'page'] { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     My name is Pranay Rana. *      *         data *      * * I am working as Soft Engg. * My Demo Page. in this example any element where attribute "data-name" value contains word = "page" get highlighted with red color, in this example "My Demo Page." text get highlighted :first-child - Select first element (first child) of parent. Sample CSS : Code Snippet * li:first-child { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     item1 *     item2 *     item3 *     item4 * in this example "item1" element get highlighted with red color. :last-child - Select last element (last child) of parent. Sample CSS : Code Snippet * li:last-child { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     item1 *     item2 *     item3 *     item4 * in this example "item4" element get highlighted with red color. :nth-child(n) - Select all each element which n the child of parent. Sample CSS : Code Snippet * li:nth-child(2) { *     font: 15px arial,sans-serif; *     color: red; * } Sample HTML : Code Snippet * *     item1 *     item2 *     item3 *     item4 * in this example "second li" element get highlighted with red color, in this example "item2" text get highlighted. :empty - Select element which is empty i.e. donent have any child. Sample CSS : div:empty {   width:100px; height:20px; background:red; } Sample HTML :     pragraph 2     pragraph 3     pragraph 4 in this highlight all text in the document with red color. ::selection - highlight the text with the color selected. Sample CSS : ::selection {   background:green; } Sample HTML : pragraph 1        pragraph 2     pragraph 3     pragraph 4    in this highlight all text with green which get select in document. :not(HTMLElement) - it not apply the style to the HTMLElement specified. Sample CSS : :not(span) {   font:15px arial,sans-serif;   color:red; } span {   color:black; } Sample HTML :   pragraph 1   pragraph 2   pragraph 3   pragraph 4   span data   in this highlight all text which is in p element i.e. not apply style to span element. :enable - select to all enable element. :disable - select to all disable element. Sample CSS : :input[type="text"]:enabled { background:green; } input[type="text"]:disabled { background:red; } Sample HTML : Name: Country:    here name is get highlighted with red color and country box is get highlighted with green. http://dlvr.it/4p5LmM
0 notes
codetonics · 12 years ago
Text
Delegates in C#
A delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are objectoriented and type-safe. The following example declares and uses a delegate type named Function. Code Snippet * using System; * delegate double Function(double x); * class Multiplier * { *     double factor; *     public Multiplier(double factor) *     { *         this.factor = factor; *     } *     public double Multiply(double x) *     { *         return x * factor; *     } * } * class Test * { *     static double Square(double x) *     { *         return x * x; *     } *     static double[] Apply(double[] a, Function f) *     { *         double[] result = new double[a.Length]; *         for (int i = 0; i < a.Length; i++) result[i] = f(a[i]); *         return result; *     } *     static void Main() *     { *         double[] a = { 0.0, 0.5, 1.0 }; *         double[] squares = Apply(a, Square); *         double[] sines = Apply(a, Math.Sin); *         Multiplier m = new Multiplier(2.0); *         double[] doubles = Apply(a, m.Multiply); *     } * } An instance of the Function delegate type can reference any method that takes a double argument and returns a double value. The Apply method applies a given Function to the elements of a double[], returning a double[] with the results. In the Main method, Apply is used to apply three different functions to a double[]. A delegate can reference either a static method (such as Square or Math.Sin in the previous example) or an instance method (such as m.Multiply in the previous example). A delegate that references an instance method also references a particular object, and when the instance method is invoked through the delegate, that object becomes this in the invocation. Delegates can also be created using anonymous functions, which are “in-line methods” that are created on the fly. Anonymous functions can see the local variables of the surrounding methods. Thus the multiplier example above can be written more easily without using a Multiplier class: double[] doubles =  Apply(a, (double x) => x * 2.0); An interesting and useful property of a delegate is that it does not know or care about the class of the method it references; all that matters is that the referenced method has the same parameters and return type as the delegate. http://dlvr.it/4p444H
0 notes
codetonics · 12 years ago
Text
Finding Computer Name from C#
This C# code snippet obtains the NetBIOS and DNS computer names of the local computer. It is really a useful tip which you can implement in any desktop application to find the name of the computer on which it is running from your C# code. Useful to personalize  your application. Code Snippet * static string GetComputerName () * { *    string netBiosName = System.Environment.MachineName;    *    //return netBiosName; *    //Following method is deprecated *    //string dnsName = *    //System.Net.Dns.GetHostByName("LocalHost").HostName; *    string dnsName = System.Net.Dns.GetHostName(); *    return dnsName; * } http://dlvr.it/4p43yS
0 notes
codetonics · 12 years ago
Text
Difference Between var and dynamic
Variables declared with var are implicitly but statically typed. Variables declared with dynamic are dynamically typed. This capability was added to the CLR in order to support dynamic languages like Ruby and Python. This means that dynamic declarations are resolved at run-time, var declarations are resolved at compile-time. var dynamic 1. Introduced in C# 3.0 1. Introduced in C# 4.0 2. Statically typed – This means the type of variable declared is decided by the compiler at compile time. 2. Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time. 3. Need to initialize at the time of declaration. e.g., var str=”I am a string”; Looking at the value assigned to the variable str, the compiler will treat the variable str as string. 3. No need to initialize at the time of declaration. e.g., dynamic str; str=”I am a string”; //Works fine and compiles str=2; //Works fine and compiles 4. Errors are caught at compile time. Since the compiler knows about the type and the methods and properties of the type at the compile time itself 4. Errors are caught at runtime Since the compiler comes to about the type and the methods and properties of the type at the run time. 5. Visual Studio shows intellisense since the type of variable assigned is known to compiler. 5. Intellisense is not available since the type and its related methods and properties can be known at run time only e.g., var obj1; will  throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value. e.g., dynamic obj1; will compile; e.g. var obj1=1; will compile var obj1=” I am a string”; will throw error since the compiler has already decided that the type of obj1 is System.Int32 when the value 1 was assigned to it. Now assigning a string value to it violates the type safety. e.g. dynamic obj1=1; will compile and run dynamic obj1=” I am a string”; will compile and run since the compiler creates the type for obj1 as System.Int32 and then recreates the type as string when the value “I am a string” was assigned to it. This code will work fine.  http://dlvr.it/4p43tK
0 notes
codetonics · 12 years ago
Text
while Loop in C#
The while statement conditionally executes an embedded statement zero or more times. while-statement: while   (   boolean-expression   )   embedded-statement A while statement is executed as follows: * The boolean-expression is evaluated. * If the boolean expression yields true, control is transferred to the embedded statement. When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), control is transferred to the beginning of the while statement.  * If the boolean expression yields false, control is transferred to the end point of the while  statement.  Within the embedded statement of a while statement, a break statement may be used to transfer control to the end point of the while statement (thus ending iteration of the embedded statement), and a continue statement may be used to transfer control to the end point of the embedded statement (thus performing another iteration of the while statement). The embedded statement of a while statement is reachable if the while statement is reachable and the boolean expression does not have the constant value false. The end point of a while statement is reachable if at least one of the following is true: * The while statement contains a reachable break statement that exits the while statement. * The while statement is reachable and the boolean expression does not have the constant value true. http://dlvr.it/4p43ll
0 notes
codetonics · 12 years ago
Text
Convert HTML to PDF in C# using wkhtmltopdf
It is a simple shell utility created in C# to convert html to pdf using the webkit rendering engine, and it is free. But it has strange codes when converting HTML pages in GB2132-code to PDF. http://code.google.com/p/wkhtmltopdf/ Code Snippet * /// * /// Convert html to pdf document. * /// * ///URL address *   ///PDF save load * public static bool HtmlToPdf(string url, string path) * {         *             try *     { *        if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path)) *            return false;    *        Process p = new Process(); *        string str = System.Web.HttpContext.Current.Server.MapPath("wkhtmltopdf.exe"); *              *        if (!System.IO.File.Exists(str)) *            return false; * *        p.StartInfo.FileName = str; *        p.StartInfo.Arguments = " \"" + url + "\" " + path; *        p.StartInfo.UseShellExecute = false; *        p.StartInfo.RedirectStandardInput = true; *         p.StartInfo.RedirectStandardOutput = true; *         p.StartInfo.RedirectStandardError = true; *         p.StartInfo.CreateNoWindow = true; *         p.Start(); *         System.Threading.Thread.Sleep(500); *         return true; *     } *     catch (Exception ex) *     { *         HttpContext.Current.Response.Write(ex); *     } *     return false; * } http://dlvr.it/4p43ct
0 notes
codetonics · 12 years ago
Text
Keyboard Shortcuts for Visual Studio
Almost all the keyboard shortcuts available for Microsoft Visual Studio is listed below. Use it and show your expertise to your colleges. Happy Coding :-) Tons of Visual Studio Keyboard Shortcuts Class Diagram --- Num + ClassDiagram Expand Shift+Alt+B Edit ExpandCollapseBaseTypeList Ctrl+Del Edit Delete Del Edit RemovefromDiagram Enter View ViewCode Shift+Alt+L Edit NavigateToLollipop Num - ClassDiagram Collapse DataSet Editor --- Ins Data InsertColumn Ctrl+L Data Column Deployment Designer --- Shift+Alt+D Diagram RedrawConnection Shift+Alt+T Diagram RerouteConnection Global --- Ctrl+- View NavigateBackward Ctrl+Shift+- View NavigateForward Ctrl+. View ShowSmartTag Ctrl+/ Tools GoToCommandLine Ctrl+\, D View CodeDefinitionWindow Ctrl+\, E View ErrorList Ctrl+\, T View TaskList Ctrl+Shift+1 View BrowseNext Ctrl+Shift+2 View BrowsePrevious Ctrl+Shift+7 View ForwardBrowseContext Ctrl+Shift+8 View PopBrowseContext Ctrl+A Edit SelectAll Ctrl+Alt+A View CommandWindow Ctrl+Shift+A Project AddNewItem Shift+Alt+A Project AddExistingItem Ctrl+Alt+B Debug Breakpoints Ctrl+B Debug BreakatFunction Ctrl+Shift+B Build BuildSolution Alt+Bkspce Edit Undo Ctrl+Alt+Break Debug BreakAll Ctrl+Break Build Cancel Ctrl+Alt+C Debug CallStack Ctrl+Shift+C View ClassView Ctrl+Alt+D Debug Disassembly Ctrl+D Edit GoToFindCombo Shift+Alt+D Data ShowDataSources Shift+Del Edit Cut Ctrl+Alt+Down Arrow Window ShowEzMDIFileList Down Arrow Edit MoveControlDownGrid Shift+Down Arrow Edit SizeControlDownGrid Ctrl+Alt+E Debug Exceptions Ctrl+Shift+E View ResourceView Alt+Enter Diagram Properties Enter Edit ShowTileGrid Shift+Alt+Enter View FullScreen Esc Window ActivateDocumentWindow Shift+Esc Window CloseToolWindow Ctrl+F Edit Find Ctrl+Shift+F Edit FindinFiles Ctrl+Alt+F1 Help Contents Ctrl+F1 Help HowDoI F1 Help F1Help Shift+F1 Help WindowHelp Alt+F10 Debug ApplyCodeChanges Ctrl+Alt+F10 Debug StepOverCurrentProcess Ctrl+F10 Debug RunToCursor Ctrl+Shift+F10 Debug SetNextStatement F10 Debug StepOver Alt+F11 Tools MacrosIDE Ctrl+Alt+F11 Debug StepIntoCurrentProcess Ctrl+F11 Debug ToggleDisassembly Ctrl+Shift+Alt+F11 Debug StepOutCurrentProcess F11 Debug StepInto Shift+F11 Debug StepOut Alt+F12 Edit FindSymbol Ctrl+Alt+F12 View FindSymbolResults Ctrl+F12 Edit GoToDeclaration Ctrl+Shift+F12 View NextError F12 Edit GoToDefinition Shift+Alt+F12 Edit QuickFindSymbol Shift+F12 Edit FindAllReferences Ctrl+Alt+F2 Help Index Ctrl+F2 Window MovetoNavigationBar F2 View EditLabel Alt+F3, S Edit StopSearch Ctrl+Alt+F3 Help Search Ctrl+F3 Edit FindNextSelected Ctrl+Shift+F3 Edit FindPreviousSelected F3 Edit FindNext Shift+Alt+F3 Help SearchResults Shift+F3 Edit FindPrevious Ctrl+F4 Window CloseDocumentWindow F4 View PropertiesWindow Shift+F4 View PropertyPages Alt+F5 Data StepInto Ctrl+Alt+F5 Data Execute Ctrl+F5 Debug StartWithoutDebugging Ctrl+Shift+F5 Debug Restart F5 Debug Start Shift+Alt+F5 Debug StartWithApplicationVerifier Shift+F5 Debug StopDebugging Alt+F6 Window NextPane Ctrl+F6 Window NextDocumentWindow Ctrl+Shift+F6 Window PreviousDocumentWindow F6 Window NextSplitPane Shift+Alt+F6 Window PreviousPane Shift+F6 Window PreviousSplitPane Alt+F7 Window NextToolWindowNav Ctrl+F7 Build Compile F7 View ToggleDesigner Shift+Alt+F7 Window PreviousToolWindowNav Alt+F8 View MacroExplorer F8 Edit GoToNextLocation Shift+F8 Edit GoToPrevLocation Alt+F9, A DebuggerContextMenus BreakpointsWindow Alt+F9, D DebuggerContextMenus BreakpointsWindow Alt+F9, S DebuggerContextMenus BreakpointsWindow Ctrl+F9 Debug EnableBreakpoint Ctrl+Shift+F9 Debug DeleteAllBreakpoints F9 Debug ToggleBreakpoint Shift+F9 Debug QuickWatch Ctrl+Alt+G Debug Registers Ctrl+G Edit GoTo Ctrl+Shift+G Edit OpenFile Ctrl+Alt+H Debug Threads Ctrl+H Edit Replace Ctrl+Shift+H Edit ReplaceinFiles Ctrl+Alt+I Debug Immediate Ctrl+Alt+Ins Project Override Ctrl+Ins Edit Copy Ctrl+Shift+Ins Edit CycleClipboardRing Shift+Ins Edit Paste Ctrl+Alt+J View ObjectBrowser Ctrl+K, Ctrl+B Tools CodeSnippetsManager Ctrl+K, Ctrl+F NewFolder Ctrl+K, Ctrl+M Edit GenerateMethodStub Ctrl+K, Ctrl+N Edit NextBookmark Ctrl+K, Ctrl+P Edit PreviousBookmark Ctrl+K, Ctrl+R View ObjectBrowserGoToSearchCombo Ctrl+K, Ctrl+S Edit SurroundWith Ctrl+K, Ctrl+V View ClassViewGoToSearchCombo Ctrl+K, Ctrl+W View BookmarkWindow Ctrl+K, Ctrl+X Edit InsertSnippet Ctrl+Shift+K, Ctrl+Shift+N Edit NextBookmarkInFolder Ctrl+Shift+K, Ctrl+Shift+P Edit PreviousBookmarkInFolder Ctrl+Alt+L View SolutionExplorer Alt+Left Arrow View Backward Left Arrow Edit MoveControlLeftGrid Shift+Left Arrow Edit SizeControlLeftGrid Ctrl+Alt+M, 1 Debug Memory1 Ctrl+Alt+M, 2 Debug Memory2 Ctrl+Alt+M, 3 Debug Memory3 Ctrl+Alt+M, 4 Debug Memory4 Ctrl+Alt+N Debug ScriptExplorer Ctrl+N File NewFile Ctrl+Shift+N File NewProject Alt+Num * Debug ShowNextStatement Ctrl+Alt+O View Output Ctrl+O File OpenFile Ctrl+Shift+O File OpenProject Ctrl+Alt+P Tools AttachtoProcess Ctrl+P File Print Ctrl+Shift+P Tools RunTemporaryMacro Ctrl+PgDn Window NextTab Ctrl+Q Data RunSelection Ctrl+Alt+R View WebBrowser Ctrl+R, Ctrl+E Refactor EncapsulateField Ctrl+R, Ctrl+I Refactor ExtractInterface Ctrl+R, Ctrl+M Refactor ExtractMethod Ctrl+R, Ctrl+O Refactor ReorderParameters Ctrl+R, Ctrl+P Refactor PromoteLocalVariable Ctrl+R, Ctrl+R Refactor Rename Ctrl+R, Ctrl+V Refactor RemoveParameters Ctrl+Shift+R Tools RecordTemporaryMacro Alt+Right Arrow View Forward Right Arrow Edit MoveControlRightGrid Shift+Right Arrow Edit SizeControlRightGrid Ctrl+Alt+S View ServerExplorer Ctrl+S File SaveSelectedItems Ctrl+Shift+S File SaveAll Ctrl+Alt+T View DocumentOutline Ctrl+Shift+Tab Window PreviousDocumentWindowNav Ctrl+Tab Window NextDocumentWindowNav Shift+Tab Edit SelectPreviousControl Tab Edit SelectNextControl Ctrl+Alt+U Debug Modules Shift+Up Arrow Edit SizeControlUpGrid Up Arrow Edit MoveControlUpGrid Ctrl+Alt+V, A Debug Autos Ctrl+Alt+V, L Debug Locals Ctrl+Alt+W, 1 Debug Watch Ctrl+Alt+W, 2 Debug Watch2 Ctrl+Alt+W, 3 Debug Watch3 Ctrl+Alt+W, 4 Debug Watch4 Ctrl+Shift+W File ViewinBrowser Ctrl+Alt+X View Toolbox Ctrl+Shift+X Test StartSelectedTestProjectwithoutDebugger Shift+Alt+X Test StartSelectedTestProjectwithDebugger Ctrl+Alt+Z Debug Processes Ctrl+Shift+Z Edit Redo HTML Editor Design View --- Ctrl+B Format Bold Ctrl+Alt+Down Arrow Layout InsertRowBelow Shift+F7 View ViewMarkup Ctrl+I Format Italic Ctrl+L Format ConverttoHyperlink Ctrl+Shift+L Format InsertBookmark Ctrl+Alt+Left Arrow Layout InsertColumntotheLeft Ctrl+M, Ctrl+C Project AddContentPage Ctrl+M, Ctrl+M View EditMaster Ctrl+Alt+Q View NonVisualControls Ctrl+Q View VisibleBorders Ctrl+Shift+Q View Details Ctrl+Alt+Right Arrow Layout InsertColumntotheRight Ctrl+U Format Underline Ctrl+Alt+Up Arrow Layout InsertRowAbove HTML Editor Source View --- Ctrl+Shift+. View AutoCloseTagOverride Shift+F7 View ViewDesigner Ctrl+PgDn View NextView Ctrl+PgUp Window PreviousTab Managed Resources Editor --- Ctrl+1 Resources Strings Ctrl+2 Resources Images Ctrl+3 Resources Icons Ctrl+4 Resources Audio Ctrl+5 Resources Files Ctrl+6 Resources Other Del Edit Remove Report Designer --- Ctrl+Alt+D View Datasets Ctrl+Down Arrow Edit MoveControlDown Ctrl+Shift+Down Arrow Edit SizeControlDown Down Arrow Edit LineDown Shift+Down Arrow Edit LineDownExtend Enter Edit BreakLine Ctrl+Left Arrow Edit MoveControlLeft Ctrl+Shift+Left Arrow Edit SizeControlLeft Left Arrow Edit CharLeft Shift+Left Arrow Edit CharLeftExtend Ctrl+Right Arrow Edit MoveControlRight Ctrl+Shift+Right Arrow Edit SizeControlRight Right Arrow Edit CharRight Shift+Right Arrow Edit CharRightExtend Shift+Tab Edit TabLeft Tab Edit InsertTab Ctrl+Shift+Up Arrow Edit SizeControlUp Ctrl+Up Arrow Edit MoveControlUp Shift+Up Arrow Edit LineUpExtend Up Arrow Edit LineUp Settings Designer --- Ctrl+Del Edit RemoveRow Esc Edit SelectionCancel F2 Edit EditCell Text Editor --- Alt+, Edit DecreaseFilterLevel Alt+. Edit IncreaseFilterLevel Ctrl+] Edit GotoBrace Ctrl+Shift+] Edit GotoBraceExtend Ctrl+= Edit SelectToLastGoBack Bkspce Edit DeleteBackwards Ctrl+Bkspce Edit WordDeleteToStart Ctrl+Shift+Alt+C Edit CopyParameterTip Ctrl+Del Edit WordDeleteToEnd Ctrl+Down Arrow Edit ScrollLineDown Shift+Alt+Down Arrow Edit LineDownExtendColumn Ctrl+E, Ctrl+W Edit ToggleWordWrap End Edit LineEnd Shift+Alt+End Edit LineEndExtendColumn Shift+End Edit LineEndExtend Ctrl+Enter Edit LineOpenAbove Ctrl+Shift+Enter Edit LineOpenBelow Home Edit LineStart Shift+Alt+Home Edit LineStartExtendColumn Shift+Home Edit LineStartExtend Ctrl+I Edit IncrementalSearch Ctrl+Shift+I Edit ReverseIncrementalSearch Ins Edit OvertypeMode Ctrl+J Edit ListMembers Ctrl+K, Ctrl+\ Edit DeleteHorizontalWhiteSpace Ctrl+K, Ctrl+A Edit SwapAnchor Ctrl+K, Ctrl+C Edit CommentSelection Ctrl+K, Ctrl+D Edit FormatDocument Ctrl+K, Ctrl+F Edit FormatSelection Ctrl+K, Ctrl+H Edit ToggleTaskListShortcut Ctrl+K, Ctrl+I Edit QuickInfo Ctrl+K, Ctrl+K Edit ToggleBookmark Ctrl+K, Ctrl+L Edit ClearBookmarks Ctrl+K, Ctrl+U Edit UncommentSelection Ctrl+L Edit LineCut Ctrl+Shift+L Edit LineDelete Ctrl+Left Arrow Edit WordPrevious Ctrl+Shift+Alt+Left Arrow Edit WordPreviousExtendColumn Ctrl+Shift+Left Arrow Edit WordPreviousExtend Shift+Alt+Left Arrow Edit CharLeftExtendColumn Ctrl+M, Ctrl+H Edit HideSelection Ctrl+M, Ctrl+L Edit ToggleAllOutlining Ctrl+M, Ctrl+M Edit ToggleOutliningExpansion Ctrl+M, Ctrl+O Edit CollapsetoDefinitions Ctrl+M, Ctrl+P Edit StopOutlining Ctrl+M, Ctrl+T Edit CollapseTag Ctrl+M, Ctrl+U Edit StopHidingCurrent Ctrl+Shift+Alt+P Edit PasteParameterTip Ctrl+PgDn Edit ViewBottom Ctrl+Shift+PgDn Edit ViewBottomExtend PgDn Edit PageDown Shift+PgDn Edit PageDownExtend Ctrl+PgUp Edit ViewTop Ctrl+Shift+PgUp Edit ViewTopExtend PgUp Edit PageUp Shift+PgUp Edit PageUpExtend Ctrl+R, Ctrl+W Edit ViewWhiteSpace Ctrl+Right Arrow Edit WordNext Ctrl+Shift+Alt+Right Arrow Edit WordNextExtendColumn Ctrl+Shift+Right Arrow Edit WordNextExtend Shift+Alt+Right Arrow Edit CharRightExtendColumn Ctrl+Shift+Space Edit ParameterInfo Ctrl+Space Edit CompleteWord Ctrl+Shift+T Edit WordTranspose Ctrl+T Edit CharTranspose Shift+Alt+T Edit LineTranspose Ctrl+Shift+U Edit MakeUppercase Ctrl+U Edit MakeLowercase Ctrl+Up Arrow Edit ScrollLineUp Shift+Alt+Up Arrow Edit LineUpExtendColumn Ctrl+W Edit SelectCurrentWord VC Accelerator Editor --- Ins Edit NewAccelerator Ctrl+W Edit NextKeyTyped VC Dialog Editor --- Ctrl+B Format ButtonBottom Ctrl+D Format TabOrder Ctrl+Shift+Down Arrow Format AlignBottoms Shift+F7 Format SizetoContent Ctrl+F9 Format CenterVertical Ctrl+Shift+F9 Format CenterHorizontal F9 Format AlignMiddles Shift+F9 Format AlignCenters Ctrl+G Format ToggleGuides Ctrl+Left Arrow Edit ScrollColumnLeft Ctrl+Shift+Left Arrow Format AlignLefts Ctrl+M Format CheckMnemonics Ctrl+R Format ButtonRight Alt+Right Arrow Format SpaceAcross Ctrl+Right Arrow Edit ScrollColumnRight Ctrl+Shift+Right Arrow Format AlignRights Ctrl+T Format TestDialog Alt+Up Arrow Format SpaceDown Ctrl+Shift+Up Arrow Format AlignTops VC Image Editor --- Ctrl+- Image SmallerBrush Ctrl+Shift+, Image ZoomOut Ctrl+. Image SmallBrush Ctrl+Shift+. Image ZoomIn Ctrl+[ Image PreviousColor Ctrl+Shift+[ Image PreviousRightColor Ctrl+] Image NextColor Ctrl+Shift+] Image NextRightColor Ctrl+= Image LargerBrush Ctrl+A Image AirbrushTool Ctrl+B Image BrushTool Ctrl+F Image FillTool Ctrl+H Image FlipHorizontal Ctrl+Shift+H Image Rotate90Degrees Shift+Alt+H Image FlipVertical Ctrl+I Image PencilTool Ctrl+Shift+I Image EraseTool Ins Image NewImageType Ctrl+J Image DrawOpaque Ctrl+L Image LineTool Ctrl+M Image MagnificationTool Ctrl+Shift+M Image Magnify Alt+P Image EllipseTool Ctrl+Shift+Alt+P Image FilledEllipseTool Shift+Alt+P Image OutlinedEllipseTool Alt+R Image RectangleTool Ctrl+Shift+Alt+R Image FilledRectangleTool Shift+Alt+R Image OutlinedRectangleTool Ctrl+Alt+S Image ShowGrid Ctrl+Shift+Alt+S Image ShowTileGrid Shift+Alt+S Image RectangleSelectionTool Ctrl+T Image TextTool Ctrl+Shift+U Image CopyandOutlineSelection Ctrl+U Image UseSelectionasBrush Alt+W Image RoundedRectangleTool Ctrl+Shift+Alt+W Image FilledRoundedRectangleTool Shift+Alt+W Image OutlinedRoundedRectangleTool VC String Editor --- Ins Edit NewString View Designer --- Ctrl+1 QueryDesigner Diagram Ctrl+2 QueryDesigner Criteria Ctrl+3 QueryDesigner SQL Ctrl+4 QueryDesigner Results Ctrl+G QueryDesigner GotoRow Ctrl+Shift+J QueryDesigner JoinMode Ctrl+R QueryDesigner ExecuteSQL Ctrl+T QueryDesigner CancelRetrievingData WebBrowser --- Alt+Down Arrow Help Nexttopic Alt+Up Arrow Help Previoustopic Windows Forms Designer --- End Edit DocumentEnd Shift+End Edit DocumentEndExtend Home Edit DocumentStart Shift+Home Edit DocumentStartExtend XML Editor Schema View --- Ctrl+- Schema Collapse Ctrl+= Schema Expand http://dlvr.it/4p2p1c
1 note · View note
codetonics · 12 years ago
Text
Writing Registry from C#
This example adds the value pair, "Name" and "Isabella", to the current user's registry, under the key "Names". Code Snippet * Microsoft.Win32.RegistryKey key; * key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names"); * key.SetValue("Name", "Isabella"); * key.Close(); Steps to follow : * Copy the code and paste it into the Main method of a console application. * Replace the Names parameter with the name of a key that exists directly under the   HKEY_CURRENT_USER node of the registry. * Replace the Name parameter with the name of a value that exists directly under the Names node. It is more secure to write data to the user folder — Microsoft.Win32.Registry.CurrentUser — rather than to the local computer — Microsoft.Win32.Registry.LocalMachine. http://dlvr.it/4p2nzr
0 notes