Naming a variable in C# and Best Practices

C# requires the programmer to use names from letters chosen from a through zA through Z, and numbers are chosen from 0 through 9.

Best practise to for naming a variable is to use :

  1. Camel Case. First word in variable name is in small letter and Second word in variable name is capital letter. Example : rollNumber
  2. Use relevant names to explain the variable use instead of names like x , y and z. Example : candidateName

Reserved Characters and Escape Values in API Call URLs

Use the Escape values to replace reserved characters as augmented value in API Call URLs :
 

Reserved character Escape value
slash (/) %2F
question mark (?) %3F
ampersand (&) %26
semicolon (;) %3B
colon (:) %3A
commercial at sign (@) %40
comma (,) %2C
dollar sign ($) %24
equals sign (=) %3D
space ( ) %20
percent sign (%) %25
quotation marks (“) %22
plus sign (+) %2B
hash (#) %23
asterisk (*) %2A
less-than sign (<) %3C
greater-than sign (>) %3E
left brace ({) %7B
right brace (}) %7D
vertical bar (|) %7C
left square bracket ([) %5B
right square bracket (]) %5D
circumflex (^) %5E
backslash () %5C
accent grave (`) %60
left parenthesis (() %28
right parenthesis ()) %29

New Features of VB.NET and C# languages in 2005 version

New Features of VB.NET and C# languages in 2005 version

VB.NET C#
Visual Basic 2005 has many new and improved language features — such as inheritance, interfaces, overriding, shared members, and overloading — that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. This language has following new features,

  1. Continue Statement, which immediately skips to the next iteration of a Do, For, or While loop.
  2. IsNot operator, which you can avoid using the Not and Is operators in an awkward order.
  3. 3. Using...End. Using statement block ensures disposal of a system resource when your code leaves the block for any reason.
4.  Public Sub setbigbold( _
5.      ByVal c As Control)
6.  Using nf As New _
7.    System.Drawing.Font("Arial",_
8.    12.0F, FontStyle.Bold)
9.    c.Font = nf
10.  c.Text = "This is" &_
11.  "12-point Arial bold"
12.End Using
End Sub
  1. Explicit Zero Lower Bound on an Array, Visual Basic now permits an array declaration to specify the lower bound (0) of each dimension along with the upper bound.
  2. Unsigned Types, Visual Basic now supports unsigned integer data types (UShort, UInteger, and ULong) as well as the signed type SByte.
  3. Operator Overloading, Visual Basic now allows you to define a standard operator (such as +, &, Not, or Mod) on a class or structure you have defined.
  4. Partial Types, to separate generated code from your authored code into separate source files.
  5. Visual Basic now supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A corresponding type argument specifies at compilation time the data type of one of the elements in the generic type.
  6. Custom Events. You can declare custom events by using the Custom keyword as a modifier for the Event statement. In a custom event, you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the event.
  7. Compiler Checking Options, The /nowarn and /warnaserror options provide more control over how warnings are handled. Each one of these compiler options now takes a list of warning IDs as an optional parameter, to specify to which warnings the option applies.
  8. There are eight new command-line compiler options:
    1. The /codepage option specifies which codepage to use when opening source files.
    2. The /doc option generates an XML documentation file based on comments within your code.
    3. The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft.
    4. The /filealign option specifies the size of sections in your output file.
    5. The /noconfig option causes the compiler to ignore the Vbc.rsp file.
    6. The /nostdlib option prevents the import of mscorlib.dll, which defines the entire System namespace.
    7. The /platform option specifies the processor to be targeted by the output file, in those situations where it is necessary to explicitly specify it.
    8. The /unify option suppresses warnings resulting from a mismatch between the versions of directly and indirectly referenced assemblies.
With the release of Visual Studio 2005, the C# language has been updated to version 2.0. This language has following new features:

  1. Generics types are added to the language to enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generic types can differ only by arity. Parameters can also be forced to be specific types.
  2. Iterators make it easier to dictate how a for each loop will iterate over a collection’s contents.
3.  // Iterator Example
4.  public class NumChar
5.  {
6.  string[] saNum = { 
7.    "One", "Two", "Three", 
8.    "Four", "Five", "Six", 
9.    "Seven", "Eight", "Nine", 
10.  "Zero"};
11.public 
12. System.Collections.IEnumerator 
13. GetEnumerator()
14.{
15.foreach (string num in saNum)
16.yield return num;
17.}
18.}
19.// Create an instance of 
20.// the collection class
21.NumChar oNumChar = new NumChar();
22.// Iterate through it with foreach
23.foreach (string num in oNumChar)
24.Console.WriteLine(num);
  1. Partial type definitions allow a single type, such as a class, to be split into multiple files. The Visual Studio designer uses this feature to separate its generated code from user code.
  2. Nullable types allow a variable to contain a value that is undefined.
  3. Anonymous Method is now possible to pass a block of code as a parameter. Anywhere a delegate is expected, a code block can be used instead: There is no need to define a new method.
28.button1.Click += 
29. delegate { MessageBox.Show( 
 "Click!") };
  1. . The namespace alias qualifier (::) provides more control over accessing namespace members. The global :: alias allows to access the root namespace that may be hidden by an entity in your code.
  2. Static classes are a safe and convenient way of declaring a class containing static methods that cannot be instantiated. In C# v1.2 you would have defined the class constructor as private to prevent the class being instantiated.
  3. 8. There are eight new compiler options:
    1. /langversion option: Can be used to specify compatibility with a specific version of the language.
    2. /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 architectures.
    3. #pragma warning: Used to disable and enable individual warnings in code.
    4. /linkresource option: Contains additional options.
    5. /errorreport option: Can be used to report internal compiler errors to Microsoft over the Internet.
    6. /keycontainer and /keyfile: Support specifying cryptographic keys.

C# 3.0 New Features

C# 3.0 New Features

1. Implicit typing of local variables, which permits the types of local variables to be inferred from the expressions used to initialize them
2. Extension methods, which make it possible to extend existing types and constructed types with additional methods, outside their definitions
3. Lambda expressions, an evolution of anonymous methods that provide improved type inference and conversions to both delegate types and expression trees
4. Object initializers, which ease construction and initialization of objects
5. Anonymous types, which are tuple types automatically inferred and created from object initializers
6. Implicit typing of arrays, which is a form of array creation and initialization together where the element type of the array is inferred from the initializer
7. Query expressions, which provide a language-integrated syntax for queries that is similar to relational and hierarchical query languages, such as SQL and XQuery

ASP.NET , C# – Configuring to use XML to display error and validation message

ASP.NET , C# – Configuring to use XML to display error and validation message

Step 1 – Add XML file to store error and validation message.
              Below is sample of ErrorMessage.xml :
<?xml version=1.0 encoding=utf-8 ?>
<appSettings>
<add key=NoMatchingRecord value=No Matching Records Found/>
<appSettings>                  

Below is sample of ValidationMessage.xml :

<?xml version=”1.0″ encoding=”utf-8″ ?>
<appSettings>

 <add key=”EndDateGreaterthanStartDate” value=”End Date should be greater than Start Date”/>
</appSettings>

If more error or validation message need to be added then add it to ErrorMessage.xml or ValidationMessage.xml with key and value pair. Also , make sure key is unique and not repeated in XML file. You can also add more XML files if needed

Step 2 – Add below key in appSettings section of Web.config file
<appSettings>
  <add key=”ErrorMessage” value=”D:ConfigErrorMessage.xml”></add>
  <add key=”ValidationMessage” value=”D:ConfigValidationMessage.xml”></add>
 </appSettings>

Above keys are added which contains path of XML file as  key value

Step 3 – Add a Class file and name it to CustomMessage.cs . Add below code in Custom Message.cs

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;
using System.Xml;
////// <summary> Summary description for CustomMessage/// </summary>
public class CustomMessage{
System.Xml.XmlDocument doc;

{
}
public CustomMessage(String FileName)
{
doc = new XmlDocument();
doc.Load(FileName);
}

/// <summary>/// To get value from XML file at specified location./// </summary>/// <param name=”TagName”></param>/// <returns></returns>

public string GetMessageValue(string TagName)
    {
        string ConstString = string.Empty;
        try
        {
            //Get Connection path from XML file

            XmlNodeList elemList = doc.GetElementsByTagName(“add”);
            for (int i = 0; i < elemList.Count; i++)
            {
                string KeyName = elemList[i].Attributes[“key”].Value;
                if (KeyName == TagName)
                {
                    ConstString = elemList[i].Attributes[“value”].Value;
                }
            }
        }
        catch (Exception ex)
        {
        }
        return ConstString;
    }

}

CustomMessage class contains a public constructor which accepts FileName as input paramter and load the XML file into XMLDocument.

CustomMessage class also contains a method GetMessageValue which takes key as input parameter and returns value of key.

Step 4 – Final step is to consume the CustomMessage class to display appropriate message. Below is code in calling aspx or cs file :

string errorFile = ConfigurationManager.AppSettings.Get(“ErrorMessage”).ToString();
CustomMessage objCustomMessage = new CustomMessage(errorFile);

this.lblError.Text = objCustomMessage.GetMessageValue(“NoMatchingRecord”);

Line 1 is used to get path of ErrorMessage.xml
Line 2 is used to call Custom message class constructor to load XML file into XMLDocument
Line 3 is used to get value of error message key by passing key to CustomMessage method GetMessageValue

string validationFile = ConfigurationManager.AppSettings.Get(“ValidationMessage”).ToString();
CustomMessage objCustomMessage = new CustomMessage(validationFile);this.lblValidation.Text = objCustomMessage.GetMessageValue(“EndDateGreaterthanStartDate”);  

 Line 1 is used to get path of ValidationMessage.xml
 Line 2 is used to call Custom message class constructor to load XML file into XMLDocument
 Line 3 is used to get value of validation message key by passing key to CustomMessage method GetMessageValue

Programming with word in C# : Replace bookmark with actual values

Programming with word in C#  : Replace bookmark with actual values

Step 1 : Add a bookmark to work document ( for example StudentLetter.doc )

  1. Click where you want to insert a bookmark.
  2. On the Insert tab, in the Links group, click Bookmark.
  3. Under Bookmark name, type a name. For example StudentName 
  4. Click Add.

Step 2 : Create a C# project and Add reference to Microsoft Word Object Library

  1. Start Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET.
  2. On the File menu, click New, and then click Project. Under Project Types, click Visual C# Projects, and then click Windows Application under Templates. Form1 is created by default.

    Note In Visual Studio 2005, click Visual C# instead of Visual C# Projects.

  3. Add a reference to Microsoft Word Object Library. To do this, follow these steps:
  4. On the Project menu, click Add Reference.
  5. On the COM tab, locate Microsoft Word Object Library, and then click Select.

Step 3 : Create instance of the Word application

Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

Step 4 : Initialize  all the parameters

object fileName = @”C:TemplateStudentLetter.doc”;
object confirmConversions = Type.Missing;
object readOnly = Type.Missing;
object addToRecentFiles = Type.Missing; o
bject passwordDoc = Type.Missing;
object passwordTemplate = Type.Missing;
object revert = Type.Missing;
object writepwdoc = Type.Missing;
object writepwTemplate = Type.Missing;
object format = Type.Missing;
object encoding = Type.Missing;
object visible = Type.Missing;
object openRepair = Type.Missing;
object docDirection = Type.Missing;
object notEncoding = Type.Missing;
object xmlTransform = Type.Missing;

Step 5 : Create instance of document by passing above paramters

Microsoft.Office.Interop.Word .document doc = wordApp.Documents.Open(
ref fileName, ref confirmConversions, ref readOnly, ref addToRecentFiles,
ref passwordDoc, ref passwordTemplate, ref revert, ref writepwdoc,
ref writepwTemplate, ref format, ref encoding, ref visible, ref openRepair,
ref docDirection, ref notEncoding, ref xmlTransform);
 
Step 6 : Create to Common method to find a bookmark . If the bookmark exists replace it with text.
 
private void ReplaceBookmarkText ( 
Microsoft.Office.Interop.Word .document doc,
string bookmarkName,
string text)
{
if ( doc.Bookmarks.Exists(bookmarkName) )
{
Object name = bookmarkName;
Microsoft.Office.Interop.Word.Range range =
doc.Bookmarks.get_Item( ref name ).Range;

range.Text = text;
object newRange = range;
doc.Bookmarks.Add(bookmarkName, ref newRange);
}
}
 
 

 Step 7 : Call the common method ReplaceBookmarkText to replace bookmark StudentName with actual value i.e studentName

ReplaceBookmarkText(doc, “StudentName”, studentName);

Sharepoint List : Lists.UpdateListItems Method from C# Code

Lists.UpdateListItems Method is used to add, delete, or update the specified items in a list on the sharepoint site.  

It is part of web service : http://<Site>/_vti_bin/Lists.asmx

Step 1:

Add Web Reference to http://<Site>/_vti_bin/Lists.asmx to C# project

Step 2 :

Build a CAML Query using C# code . Refer the code below :

StringBuilder camlQuery = new StringBuilder();
 camlQuery.Append(“<Method ID=’1′ Cmd=’New’>”);
 camlQuery.Append(string.Format(“<Field Name=ID>{0}</Field>”, “12345”);
 camlQuery.Append(string.Format(“<Field Name=’Name’>{0}</Field>”, “Santosh”));
 camlQuery.Append(string.Format(“<Field Name=’Role’>{0}</Field>”, “Manager”));
 camlQuery.Append(“</Method>”);

Note : Make sure Field Name refers to internal name of the field

Step 3 :

Call UpdateListItem method using the below code :

XmlNode ndReturn;
XmlNode ndUpdateStatus;
string listName = “EmployeeList” ; // Set correct list name to update or insert
list.Url = “https://sharepointserver/_vti_bin/lists.asmx“; //Provide correct url of List Web service
ndReturn = list.GetListAndView(listName, “”);
XmlDocument xmlDocQuery = new System.Xml.XmlDocument();
System.Xml.XmlElement elBatch = xmlDocQuery.CreateElement(“Batch”);
elBatch.SetAttribute(“ListVersion”, “1”);
elBatch.SetAttribute(“ViewName”, ndReturn.ChildNodes[1].Attributes[“Name”].Value);
elBatch.InnerXml = CAMLQuery; // Set the CAMLQuery formed in Step 2
ndUpdateStatus = list.UpdateListItems(ndReturn.ChildNodes[0].Attributes[“Name”].Value, elBatch);
               
Step 4 :

Check whether list was inseted or not using below C# code.
if ( ndUpdateStatus  != null )
{
if (ndUpdateStatus.ChildNodes[0] != null)
                {
                    if (ndUpdateStatus.ChildNodes[0].InnerText == “0x00000000”)
                    {
                        // UpdateListItem success               
                     }
                     else
                    {
                         // UpdateListItem failure
                    }
                }
else
               {
                     // UpdateListItem failure
                }
}
else
{
// UpdateListItem failure
}

Lists.UpdateListItems Method is successful if return from this method has ndUpdateStatus.ChildNodes[0].InnerText == “0x00000000”)

Hope this article is useful for people integrating C# code with Sharepoint List. Please mail me your feedback at : contactus@alltechnicalfaqs.com

C# Partial Methods

C# Partial Methods

Partial methods can be defined in one part of a type declaration and implemented in another. The implementation is optional; if no part implements the partial method, the partial method declaration and all calls to it are removed from the type declaration resulting from the combination of the parts.

Partial methods cannot define access modifiers, but are implicitly private. Their return type must be void, and their parameters cannot have the out modifier. The identifier partial is recognized as a special keyword in a method declaration only if it appears right before the void type; otherwise it can be used as a normal identifier. A partial method cannot explicitly implement interface methods.

There are two kinds of partial method declarations: If the body of the method declaration is a semicolon, the declaration is said to be a defining partial method declaration. If the body is given as a block, the declaration is said to be an implementing partial method declaration. Across the parts of a type declaration there can be only one defining partial method declaration with a given signature, and there can be only one implementing partial method declaration with a given signature. If an implementing partial method declaration is given, a corresponding defining partial method declaration must exist, and the declarations must match as specified in the following:

• The declarations must have the same modifiers (although not necessarily in the same order), method name, number of type parameters and number of parameters.

• Corresponding parameters in the declarations must have the same modifiers (although not necessarily in the same order) and the same types (modulo differences in type parameter names).

• Corresponding type parameters in the declarations must have the same constraints (modulo differences in type parameter names).

An implementing partial method declaration can appear in the same part as the corresponding defining partial method declaration.

Only a defining partial method participates in overload resolution. Thus, whether or not an implementing declaration is given, invocation expressions may resolve to invocations of the partial method. Because a partial method always returns void, such invocation expressions will always be expression statements. Furthermore, because a partial method is implicitly private, such statements will always occur within one of the parts of the type declaration within which the partial method is declared.

If no part of a partial type declaration contains an implementing declaration for a given partial method, any expression statement invoking it is simply removed from the combined type declaration. Thus the invocation expression, including any constituent expressions, has no effect at runtime. The partial method itself is also removed and will not be a member of the combined type declaration.

If an implementing declaration exist for a given partial method, the invocations of the partial methods are retained. The partial method gives rise to a method declaration similar to the implementing partial method declaration except for the following:

• The partial modifier is not included

• The attributes in the resulting method declaration are the combined attributes of the defining and the implementing partial method declaration in unspecified order. Duplicates are not removed.

• The attributes on the parameters of the resulting method declaration are the combined attributes of the corresponding parameters of the defining and the implementing partial method declaration in unspecified order. Duplicates are not removed.

If a defining declaration but not an implementing declaration is given for a partial method M, the following restrictions apply:

• It is a compile time error to create a delegate to method (§7.5.10.5).

• It is a compile time error to refer to M inside an anonymous function that is converted to an expression tree type (§6.5.2).

• Expressions occurring as part of an invocation of M do not affect the definite assignment state (§5.3), which can potentially lead to compile time errors.

• M cannot be the entry point for an application (§3.1).

Partial methods are useful for allowing one part of a type declaration to customize the behavior of another part, e.g., one that is generated by a tool. Consider the following partial class declaration:

partial class Customer

{

string name;

public string Name {

get { return name; }

set {

OnNameChanging(value);

name = value;

OnNameChanged();

}

}

partial void OnNameChanging(string newName);

partial void OnNameChanged();

}

If this class is compiled without any other parts, the defining partial method declarations and their invocations will be removed, and the resulting combined class declaration will be equivalent to the following:

class Customer

{

string name;

public string Name {

get { return name; }

set { name = value; }

}

}

Assume that another part is given, however, which provides implementing declarations of the partial methods:

partial class Customer

{

partial void OnNameChanging(string newName)

{

Console.WriteLine(“Changing “ + name + “ to “ + newName);

}

partial void OnNameChanged()

{

Console.WriteLine(“Changed to “ + name);

}

}

Then the resulting combined class declaration will be equivalent to the following:

class Customer

{

string name;

public string Name {

get { return name; }

set {

OnNameChanging(value);

name = value;

OnNameChanged();

}

}

void OnNameChanging(string newName)

{

Console.WriteLine(“Changing “ + name + “ to “ + newName);

}

void OnNameChanged()

{

Console.WriteLine(“Changed to “ + name);

}

}


 

Reference : C# Specification Document

Articles

Convert Uploaded file to Base64String in C#

We will go through steps to convert a uploaded file to Base64String in C#.

Add a File Upload control to aspx page( for example with ID = CntlFileUpload )
Add a button to aspx page

Add the below code to convert uploaded file to Base64String in Button click event

protected void Button1_Click(object sender, EventArgs e)

{

HttpPostedFile postedFile = this.CntlFileUpload.PostedFile;

Byte[] fileBytes = new Byte[postedFile.ContentLength];

postedFile.InputStream.Read(fileBytes, 0, postedFile.ContentLength);

string base64string = Convert.ToBase64String(fileBytes);

}

Please let me know if this is helpful.

C# 3.0 language enhancements

The C# 3.0 language enhancements consist of:

Anonymous types – are types which are automatically inferred and created from object initializers
Implicitly typed local variables – This permits the type of local variables to be inferred from the expressions used to initialize them.
Auto-implemented properties – This is used to automate the process of creating properties.
Implicitly typed arrays – This is used for array creation and initialization that infers the element type of the array from an array initializer.
Extension methods – This makes it possible to extend existing types and constructed types with additional methods.
Lambda expressions – an evolution of anonymous methods that concisely improves type inference and conversions to both delegate types and expression trees.
Expression trees, which permit lambda expressions to be represented as data (expression trees) instead of as code (delegates).
Object and collection initializers, which you can use to conveniently specify values for one or more fields or properties for a newly created object, combining creation and initialization into a single step.
Query expressions, which provide a language-integrated syntax for queries that is similar to relational and hierarchical query languages such as SQL and XQuery.
.