Wednesday, July 27, 2011

Understanding Paths in ASP.NET

There are more than 30 methods in ASP.NET classes that deal with paths and/or URLs. Many developers coming from traditional ASP tend to stick with the methods they know from ASP (which are still there), but there are many other useful methods that can save you a lot of time and headache. Fritz Onion covers the details of managing paths and URLs in ASP.NET, looking at everything from virtual to physical path mapping to root path reference syntax.
A quick scan of the classes in the System.Web.* hierarchy reveals more than 30 methods that deal with paths and/or URLs. In this article, I will cover the more commonly used path and URL functions in ASP.NET—presenting
what they do, how they work, and when to use them.
The best way to understand what each of these functions and properties do is
to try them out and review the results. I have prepared a page that makes calls
to the most commonly used path functions and properties in ASP.NET, which you
can download from

http://staff.develop.com/onion/pathsample.zip.
I recommend that you download this file, unzip it, and place the contents in a
virtual directory on a machine with ASP.NET installed. Try to access the
pathsample.aspx page from a browser, inspect the results, and refer to
your running page as you read the rest of this article.
In case you're not near a suitably equipped computer to run the page,
Table 1 shows the results of running the test page. This page was run and
expressions were all evaluated in the context of a page called
client.aspx, responding to a request made to the following URL
http://localhost/informit/subdir/pathsample.aspx/extra.
The physical directory on the Web server corresponding to this virtual directory
mapping was c:\mywebdirs\informit\subdir, and the top-level virtual
directory for this application was called informit and was located at
c:\mywebdirs\informit.

Table 1 Path Functions in ASP.NET and Their Results


Expression

Evaluation

this.TemplateSourceDirectory


/informit/subdir

Request.MapPath("log.txt")

c:\mywebdirs\informit\subdir\log.txt

this.MapPathSecure("log.txt")

c:\mywebdirs\informit\subdir\log.txt

Request.Path


/informit/subdir/pathsample.aspx/extra

Request.FilePath

/informit/subdir/pathsample.aspx

Request.CurrentExecutionFilePath

/informit/subdir/pathsample.aspx

Request.PathInfo

/extra


Request.PhysicalPath

c:\mywebdirs\informit\subdir\pathsample.aspx

Request.PhysicalApplicationPath

c:\mywebdirs\informit\

Request.ApplicationPath

/informit


Request.Url

http://localhost/informit/subdir/client.aspx/extra

Request.RawUrl

/informit/subdir/pathsample.aspx/extra


Response.ApplyAppPathModifier("foo.aspx")

/informit/subdir/foo.aspx

this.ResolveUrl("~/client.aspx")


/informit/pathsample.aspx


Path Mapping

We start by looking at one of the most commonly used path methods in ASP.NET:
MapPath. This useful function converts a virtual path into its
corresponding physical path and is typically used to read or modify physical
files on the server in the context of a Web request. It is available through the
HttpRequest object, and for backward compatibility with classic ASP, it
is also available through the HttpServerUtility object (accessed via
the HttpContext or Page Server property). As an example
of its use, suppose you wanted to write an entry into a log file when a page was
accessed. Assuming that the log file is named log.txt and is located in
the same directory as the .aspx page that is accessing it, you could write to
the file with the following code:

// within a method of the Page class
string logfile = Request.MapPath("log.txt");
using (StreamWriter sw = File.AppendText(logfile))
{
 sw.WriteLine("I was here at {0}", DateTime.Now);
}
Notice in Table 1 that the call to MapPath with a string of
log.txt resulted in the complete path
c:\mywebdirs\informit\subdir\log.txt corresponding to the physical
location of the virtual directory accessed in the request. In general, any time
you call MapPath, it prefixes the string you pass in with the complete
physical directory path to the current directory to which the request was
dispatched. This is useful any time you need to access a physical file on disk
that is placed in the same directory as your page, particularly for things such
as loading XML files, writing to log files, and performing file
manipulation.

Be aware that any time you access the file system from within an ASP.NET
application, you are operating under the restrictive rights associated with the
ASPNET account (or, in Windows Server 2003, NETWORK SERVICE). This account is
specially created for ASP.NET on your machine, and by default is granted only
User privileges. In a typical installation, this means that you cannot
modify existing or create new files from within an ASP.NET page. If you find
yourself wanting to use MapPath to modify or create files, the best
solution is to grant the ASP.NET account write and modify
privileges to that one subdirectory.
There is an additional function for performing virtual to physical path
mapping in ASP.NET called MapPathSecure. This method, also of the
HttpRequest class, differs only in the fact that it makes a File I/O
security demand as you request the translation, but it is used internally in
many of the ASP.NET methods. This demand is not the same as requesting whether
the account has privileges to write to a file, but rather whether the code that
is currently being executed has sufficient trust to perform file I/O (done
through a code access security or CAS check). Most of the time, your ASP.NET
code will be running with full privileges, so this function will always succeed.
It is possible, however, in ASP.NET 1.1 to specify a lower trust level at which
to run your application using the trust element in your configuration
file (or more likely, for some third-party host environment to run your
application at a lower level of trust). If this is a possibility for you, then
it may make sense to call MapPathSecure instead of MapPath, as
it will trigger a code access security exception sooner rather than later,
giving your more flexibility in dealing with the failure.

There are two other potentially useful properties available in the
Request object: PhysicalPath and
PhysicalApplicationPath. The former is the complete physical path to
the endpoint that was requested, and the latter is the complete physical path to
the root of the application.

Monday, July 18, 2011

How to build your own C# Autodialer

How to build your own C# Autodialer



Let me start with a short background story. One day, one of my oldest friends (who is a professional business man) came to me (the developer) for advice. He had a specific idea to boost his business: he wanted to install an Autodialer software. He asked for my expert opinion about how this could be done. That time I had a lot of work so I didn't have the time to come up with something brand new and write him a program. But I really wanted to help him, so in my freetime I was searching for a convenient solution. I've found it. We've done it. The business is on the wing ever since. My friend gave his approval to publish his story and the method he chose. I've thought this could be useful for many people and for many company.
The key to build an Autodialer, and also to the great success, was a software development kit. It has a sample program to have a look at its facilities. Here's how you configurate it, after downloading, extracting, and opening it:

Right click on MainForm.cs file and select View Code option (Figure 1).

Search for MainForm_Load method. You can find the configuration of the autodialer within this method.
1.       ///   
2.       /// Occurs when the user loads the form.  
3.       ///   
4.       ///   
5.       ///   
6.       void MainForm_Load(object sender, EventArgs e)  
7.       {  
8.           #region DataBinding  
9.           // See later  
10.                              #endregion  
11.                        
12.                              #region Configuration  
13.                         
14.                              autodialer = new Autodialer(GetLocalIP().ToString(), 5060, 5080, 5060, @"..\..\Resources\autodialer-example.wav");  
15.                              autodialer.ProcessingCompleted += autodialer_ProcessingCompleted;  
16.                              autodialer.PhoneLineStateChanged += autodialer_PhoneLineStateChanged;  
17.                         
18.                              var sipAccount = new SIPAccount(true, "oz890", "oz890", "oz890", "oz890", "192.168.91.212", 5060);  
19.                              autodialer.CreateAndRegisterPhoneLine(sipAccount);  
20.                              #endregion  
21.                        
22.                              #region Copyright  
23.                       // Implementation.  
24.                              #endregion  
25.                         
26.                          }  
Parameters for the autodialer:
1.    public Autodialer(string localIPAddress,   
2.                    int minPort,   
3.                    int maxPort,   
4.                    int localSIPPort,   
5.                    string wavPath)  
Parameters:
6.    localIPAddress:
This is the local IP address of the computer. If there are more network cards, then you need to enter the IP address of that network card here, with which you connect to the PBX or to the VoIP service provider.
7.    minPort:
This is the minimum port that can be used.
8.    maxPort:
This is the maximum port that can be used.
9.    localSIPPort:
This is the port reserved for SIP. SIP messages will be listened to via this port.
10.                       wavPath: This is the path for the audio file that will be played during the calls.
The SIP account includes information with which you can register in the PBX or the VoIP service provider successfully.

Parameters for SIP account:
1.    public SIPAccount(  
2.        bool registrationRequired,   
3.        string displayName,  
4.        string userName,   
5.        string registerName,   
6.        string registerPassword,   
7.        string domainServerHost,   
8.        int domainServerPort)  
Parameters:
9.    registrationRequired
The registration to the PBX is required. Please note that if you do not register in the PBX, you will only be able to make calls but you will not be able to receive calls.
10.                       displayName
This name will be displayed for the the called party during the calls.
11.                       userName
This is the username will be used during calls.
12.                       registerName
This is the name used for registration.
13.                       registerPassword
This password is needed for registration and for authentication during calls.
14.                       domainServerHost
This is the IP address or domain name of the PBX.
15.                       domainServerPort
This is the port number of the PBX.
After configuration, click on Build button in Visual Studio or click F5 on your keypad.

Now you see, that building an Autodialer isn't necessarily a hard thing. You only have to find the appropriate help. Here you can find the sample program for this sdk:
http://www.voip-sip-sdk.com/p_130-how-to-build-an-autodialer-in-c-using-the-ozeki-voip-sip-softphone-source-code-voip.html

Thursday, July 14, 2011

Creating SqlParameters Best Practices


This article summarizes some nice ways to create SqlParameter arrays.  When we use SqlHelper, or even without SqlHelper when we use SqlCommands directly, and we want to pass an array of SqlParameters to the function.  The method I will discuss does not require you to hard-code the number of elements, nor does it require you to create a temporary list of some sort, but it requires you to have all the values up front that you want to insert into the list.
There are several ways to create this array.
  1. One is to hardcode the number of parameters as follows:
    1.SqlParameter array SqlParameter[] sqlParams = new SqlParameter[5];
  2. An evolution of this is to use an ArrayList
    ArrayList sqlParams = new ArrayList();

    Then add the parameters using sqlParams.Add(…) to add them
    Then the final step is to use sqlParams.ToArray() and pass that to your SqlHelper.
  3. Another evolution would be to use a Generic list of SqlParameters
    System.Collections.Generic.List sqlParams = new  System.Collections.Generic.List();
  4. But in my opinion the BEST way of creating your SqlParameter array is as follows: C# Example:

    Vb.Net Example:



     You can even use conditionals such as if your questionCode is null you want to insert a null (C# example):
    4.

    SqlParameter[] sqlParams = new SqlParameter[] {
         new SqlParameter("@username", strUserName) ,
         new SqlParameter("@password", strPassword)
      };
    
      Dim params As SqlParameter() = { _
         New SqlParameter("@CenterID", centerID), _
         New SqlParameter("@TypeID", typeID) _
      }
    
    SqlParameter[] sqlParams = new SqlParameter[] {
      new SqlParameter("@Required", required),
      questionCode == null ? new SqlParameter("@Code", DBNull.Value) : new SqlParameter("@Code", questionCode)
    };

    Update Aug7’09 – Not specifying the DB type of the parameter will actually be slower than manually specifying the parameter sql types (ie int, varchar, etc). However, I find the tradeoff for convenience to be worth a slight loss of speed. This also allows you to change the parameter type in the stored procedure (say from datetime to string), without having to also update it here.

Wednesday, July 13, 2011

C# Coding Standards Series – Naming Conventions

Terminology and Definitions for Naming Conventions:
Camel Case (camelCase): The first letter of the word is lower case and then each first letter of the part of the word is upper case;
Pascal Case (PascalCase): The first letter of the word is upper case and then each first letter of the part of the word is upper case;
Underscode Prefix (_underscore): The word begins with underscore char and for the rest of the word use camelCase rule;

General Rules

1. Use Pascal Case for Class names:
Ex:
1
public class HelloWorld { ... };
2. Use Pascal Case for Method names:
Ex:
1
public void SayHello(string name) { ... };
3. Use Camel Case for variables and method parameters:
Ex:
1
2
3
4
5
6
7
int totalCount = 0;
 
void SayHello(string name)
{
     string fullMessage = "Hello " + name;
     //...
}
4. Avoid all upper case or all lower case names;
5. Do not use Hungarian notation:
Example of Hungarian Notation:
string m_sName; (the prefix m_ means that is a member variable and s means that is a string data type);
6. Avoid abbreviations longer than 5 characters;
7. Avoid using abbreviations unless the full name is excessive:
Ex:
Good: string address;             Not good: string addr;
8. Use meaningfull, descriptive words for naming variables;
9. Try to prefix Boolean variables with “Can”, “Is” or “Has”;
10. Do not use Underscore Prefix for local variables names;
11. All member variables must use Underscore Prefix so that they can be identified from other local variables names;
12. Avoid naming conflicts with existing .NET Framework namespaces or types;
13. Do not include the parent class name within a property name:
Ex: Good: Customer.Name;               Not good: Customer.CustomerName;
14. When defining a root namespace, use a Product, a Company or a Developer name as the root:
Ex: NorthwindApplication.Utilities;
15. Use Pascal Case for file names;
16. Method name should tell you what it does;
17. A method should do only “one job”. Do not combine multiple jobs in one method even if those jobs have very few lines of code.
Ex:
1
2
3
4
protected void SaveCustomerName(string customerName)
{
   //code here...
}

Naming Conventions for ASP.NET Controls

In general, naming ASP.NET controls is made using Camel Case naming convention, where the prefix of the name is the abbreviation of the control type name.
Abbreviation ASP.NET Control
STANDARD CONTROLS
btn Button
cb CheckBox
cbl CheckBoxList
ddl DropDownList
fu FileUpload
hdn HiddenField
lnk Hyperlink
img Image
ibtn(btn) ImageButton
lbl Label
lbtn(btn) LinkButton
lb ListBox
lit Literal
mv MultiView
pnl Panel
ph PlaceHolder
rb RadioButton
rbl RadioButtonList
tbl Table
txt TextBox
v View
DATA CONTROLS
dtl DataList
dp DataPager
dtv DetailsView
ets EntityDataSource
fv FormView
gv GridView
lds LinqDataSource
lv ListView
ods ObjectDataSource
qe QueryExtender
rpt Repeater
smd SiteMapDataSource
sds SqlDataSource
xds XmlDataSource
VALIDATION CONTROLS
cpv CompareValidator
ctv CustomValidator
rv RangeValidator
rev RegularExpressionValidator
rfv RequiredFieldValidator
vs ValidationSummary
Please share your opinion about this post by commenting below.

(hide this) .net Naming Conventions and Programming Standards - Best Practices

This article is the single most popular bit of content from my old site and blog, bar none. While I think books such as the .NET Framework Design Guidelines by Krzystof Cwalina and Brad Abrams do a better job explaining all the standards, I've kept this page up for quick reference and to support the schools and individuals currently using it.

Common .NET Naming Conventions

These are the industry-accepted standard naming conventions for C# and VB.NET programs. For additional information, please see the MSDN help documentation and the book referenced above. While individual naming conventions at organizations may vary (Microsoft only suggests conventions for public and protected items), the list below is quickly becoming the de-facto standard in the industry. Please note the absence of Hungarian Notation. These naming standards should find their way into all of your .NET development, including ASP.NET Web applications, WPF, Silverlight and Windows Forms applications.
Note that while this document predates the online and printed standards documentation from Microsoft, everything below which indicates it is based on .NET library standards is consistent with that documentation and Brad's book. In areas where Microsoft has not provided guidance (Microsoft generally doesn't care what you do in private/non-exposed code. In fact, they aren't even consistent in their internal code in the .NET framework), de facto standards have emerged, and I have captured them here.
The "ux" naming convention for controls is something I have added and found to be helpful in Windows Forms, but not so much in Silverlight and WPF. It is not based on any official standards, but instead based upon a multitude of projects by my teams and others, as well as on-line discussions on the topic. While I strongly recommend that you follow Microsoft guidelines when present, I encourage you to try out the items marked as extensions below and see how they work for you before committing to them.
Type Standard / Convention Example
Namespaces Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores. Use CompanyName.TechnologyName as root. If you don't have a company, use your domain name or your own initials. Note that any acronyms of three or more letters should be pascal case (Xml instead of XML) instead of all caps.
Why: This convention is consistent with the .NET Framework and is easy to read.
AppliedIS.TimeCard.BusinessRules
IrritatedVowel.Controllers
PeteBrown.DotNetTraining.InheritanceDemo PeteBrown.DotNetTraining.Xml
Assemblies Standard Based Upon Microsoft .NET Library Standards
If the assembly contains a single name space, or has an entire self-contained root namespace, name the assembly the same name as the namespace.
Why: This convention is consistent with the .NET Framework and is easy to read. More importantly, however, it keeps your assembly names and namespaces lined up, making it really easy to figure out what is any particular assembly, and what assembly you need to reference for any given class.
AppliedIS.TimeCard.BusinessRules.dll
IrritatedVowel.Controllers.dll
Classes and Structs Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores or leading "C" or "cls". Classes may begin with an "I" only if the letter following the I is not capitalized, otherwise it looks like an Interface. Classes should not have the same name as the namespace in which they reside. Any acronyms of three or more letters should be pascal case, not all caps. Try to avoid abbreviations, and try to always use nouns.
Why: This convention is consistent with the .NET Framework and is easy to read.
Widget
InstanceManager
XmlDocument
MainForm
DocumentForm
HeaderControl
CustomerListDataSet (typed dataset)
Collection Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Collection to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
WidgetCollection
Delegate Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Delegate to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
WidgetCallbackDelegate
Exception Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Exception to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
InvalidTransactionException
Attribute Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Attribute to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
WebServiceAttribute
Interfaces Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but start the name with "I" and capitalize the letter following the "I"
Why: This convention is consistent with the .NET Framework and is easy to read. It also distinguishes classes from interfaces, where (unlike in VB6) are truly different beings. This avoid name collisions as well, as it is quite common to have IFoo and a class named Foo that implements IFoo.
IWidget
Enumerations Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions. Do not add "Enum" to the end of the enumeration name. If the enumeration represents a set of bitwise flags, end the name with a plural.
Why: This convention is consistent with the .NET Framework and is easy to read.
SearchOptions (bitwise flags)
AcceptRejectRule (normal enum)
Functions and Subs Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores except in the event handlers. Try to avoid abbreviations. Many programmers have a nasty habit of overly abbreviating everything. This should be discouraged. We're not designing license plates or being charged by the letter :)
Functions and subs must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET
Why: This convention is consistent with the .NET Framework and is easy to read.
VB: Public Sub DoSomething(...)
C#: public void DoSomething(...)
Properties and Public * Member Variables Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores. Try to avoid abbreviations. Members must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.
Why: This convention is consistent with the .NET Framework and is easy to read.
VB: Public Property RecordId As Integer
C#: public int RecordId
Parameters Standard Based Upon Microsoft .NET Library Standards
Camel Case. Try to avoid abbreviations. Parameters must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.
Why: This convention is consistent with the .NET Framework and is easy to read.
VB: ByRef recordId As Integer
C#: ref int recordId
Procedure-Level Variables Standard Based Upon De facto Industry-Accepted Practices
Camel Case
Why: This convention is consistent with the .NET Framework and is easy to read. It also avoids naming collisions with class-level variables (see below)
VB: Dim recordId As Integer
C#: int recordId ;
Class-Level Private and Protected Variables Standard Based Upon De facto Industry-Accepted Practices
Camel Case with Leading Underscore. In VB.NET, always indicate "Protected" or "Private", do not use "Dim". Use of "m_" is discouraged, as is use of a variable name that differs from the property by only case, especially with protected variables as that violates compliance, and will make your life a pain if you program in VB.NET, as you would have to name your members something different from the accessor/mutator properties.
Of all the items here, the leading underscore is really the only controversial one. I personally prefer it over straight underscore-less camel case for my private variables so that I don't have to qualify variable names with "this." to distinguish from parameters in constructors or elsewhere where I likely will have a naming collision. With VB.NET's case insensitivity, this is even more important as your accessor properties will usually have the same name as your private member variables except for the underscore.
As far as m_ goes, it is really just about aesthetics. I (and many others) find m_ ugly, as it looks like there is a hole in the variable name. It's almost offensive. I used to use it in VB6 all the time, but that was only because variables could not have a leading underscore. I couldn't be happier to see it go away.
Microsoft recommends against the m_ (and the straight _) even though they did both in their code. Also, prefixing with a straight "m" is right out. Of course, since they code mainly in C#, they can have private members that differ only in case from the properties. VB folks have to do something else. Rather than try and come up with language-by-language special cases, I recommend the leading underscore for all languages that will support it.
If I want my class to be fully CLS-compliant, I could leave off the prefix on any C# protected member variables. In practice, however, I never worry about this as I keep all potentially protected member variables private, and supply protected accessors and mutators instead.
Why: In a nutshell, this convention is simple (one character), easy to read (your eye is not distracted by other leading characters), and successfully avoids naming collisions with procedure-level variables and class-level properties.
VB: Private _recordId As Integer
C#: private int _recordId ;
Controls on Forms An Extension to the Standards
May 2009 update
Note that I still consider this useful in many respects, especially for intellisense grouping, but have backed away from using this in recent projects, specifically Silverlight and WPF. I still use an appropriate classification suffix such as Field or Label (but not an actual control type) so that I can differentiate between, say, the last name field and the label for it.
Examples would be LastNameField, LastNameLabel, NextPageNavigation, PreviousPageNavigation. The classifications you pick will need to make sense to you, and also allow for signficiant flexibility for the designer of the UI to change the control type in Xaml without you having to change the name in the storyboards (runtime checked), code behind (compile-time checked), and control lookups in code behind (runtime checked).
I backed away simply because it didn't look right in generated member variables in my applications, or in the x:Name properties in Xaml. It was a code smell issue, albeit a minor one.
Note also that in Silverlight and WPF, I only name controls which need to be named because they are used in the code behind or are referred to from a storyboard or relative binding. The name is the primary contract between the code and the visual design, and you want to keep that contract as small as possible.
Note that I have seen the "ux" prefix in example code on the net, and from Microsoft. Some folks still find it useful. You'll need to make that decision for yourself.
I do not use the ux prefix when working in XAML-based uI, like Silverlight and WPF.

Original Information from 2002
In recent projects (since 2002 or so), I have taken to a single prefix for all my UI controls. I typically use "ux" (I used to use "ui", but it wasn't set apart well in intellisense). "ux" comes from my usual design abbreviations where it means "User eXperience", which has also since become a popular acronym. I have found this to be extremely helpful in that I get the desired grouping in the intellisense even better than if I use "txt", "lbl" etc. It also allows you to change combo boxes to text boxes etc. without having to change the names - something that happens often during initial prototyping, or when programming using highly iterative agile/xp methodologies.
Why: This convention avoids problems with changing control types (textboxes to drop-down lists, or simple text box to some uber textbox, or text box to date picker, for example), and groups the items together in intellisense. It is also much shorter than most Hungarian conventions, and definitely shorter and less type-dependent than appending the control type to the end of the variable name. I will use generic suffixes which allow me enough freedom to change them around.
"ux" prefix
uxUserIdField, uxHeaderLabel, uxPatientDateOfBirthField, uxSubmitCommand

no "ux" prefix
LastNameField, LastNameLabel, SubmitCommand, NextPageNavigation
Constants Standard Based Upon Microsoft .NET Library Standards
Same naming conventions as public/private member variables or procedure variables of the same scope. If exposed publicly from a class, use PascalCase. If private to a function/sub, use camelCase..
Do not use SCREAMING_CAPS
Why: This convention is consistent with the .NET Framework and is easy to read. A sizable section of the Framework Design Guidelines is dedicated to why they chose not to go the SCREAMING_CAPS route. Using SCREAMING_CAPS also exposes more of the implementation than is necessary. Why should a consumer need to know if you have an enum, or (perhaps because they are strings) a class exposing public constants? In the end, you often want to treat them the same way, and black-box the implementation. This convention satisfies that criteria.
SomeClass.SomePublicConstant
localConstant
_privateClassScopedConstant
* Public class-level variables are universally frowned upon. It is considered to be a much better practice to use property procedures (accessors and mutators) to provide read and/or write access to a private member variable. If you must expose a member variable to other classes using "Public", follow the property naming conventions, but don't complain if your guilty conscience keeps you up at night ;-).
You Can find the standards for publicly exposed classes/properties etc at MSDN . If you want to run a tool to validate your code for public standards and required practices, download FXCop or use the analysis tools in Visual Studio.

Why Hungarian Has Fallen Out of Favor with .NET

With his simple question in my guestbook, Andrew Coupe inspired me to write this little blurb here explaining why I feel that Hungarian Notation has outlived its usefulness. If you're sticking to Hungarian Notation in .NET, waffling, or just plain curious - read on.
True Hungarian Notation is a naming convention invented by Charles Simonyi from Microsoft back in the 70s. (For more information on its origins, see this funny article) Back in the day, one of the more promising versions of Hungarian Notation was used in a way that indicated the purpose or logical type of the variables rather than the language-specific type. For example, instead of indicating something was an int, it would be specified that it was an Id or a Quantity. When Hungarian was used this way, it was very useful, especially in languages where variable names were limited in length.
Shortly after the notation started being used, developers came up with standard language-specific data-type based prefixes. I remember when I worked in C/C++, we had things such as "rgsz" meaning an array of zero-terminated strings (rg is short for"reference to a graph" - an array in C/C++). This was useful for a while, but the prefixes became unwieldy in both in length and in understanding the permutations and combinations; you ended up with things not too far from rgszxyzpdqOrderNo. Think that's a stretch? Imagine what the name of a variable that contained a long pointer to an array of arrays of long pointers to some particular structure looked like when you mapped out the full prefix. Yes, we really did have the occassional variable like that in our programs, especially the database engine I worked on.
Then along came Visual Basic. This great rapid application development tool introduced a lot of programmers to Windows programming. Many them were brand new to programming, and gave their variables meaningless or less than helpful, and almost always inconsistent names. In response to this influx of bad code, good VB developers started to use two different variations of the Hungarian naming conventions. One was a traditional "as many letters as needed" set with prefixes such as "s" for String, "i" for Integer, and sometimes things like "arrl" for an array of longs. The second school standardized on three letters for all prefixes "str" for String, and "int" for Integer being two examples.
Some people took the conventions to extremes, and did silly things like prefix database table names with "tbl", stored procedures with "P", VB classes with "C" or "cls", and function names with the Hungarian for their return type. That was and is still just pure silliness, IMHO. I do, however, think that "I" in front of an interface is important as interfaces need to be treated very differently from classes.
During this time, VB4 and eventually VB5 and VB6 came out. VB4 introduced classes and some object-oriented language features to these developers. Developers needed to remember to use "Set" when assigning object variables, and had to remember to set them to "Nothing" when they were done with them. To assist in remembering to do this, developers would prefix all their object variables with "obj" or "o". Typical code around this time was nothing but a ton of variables with names like objResults and oHenry. It looked just a bit odd, and wasn't particularly helpful.
Those of us who worked a lot with COM objects in Visual Basic realized that the prefixes made no sense in public interfaces. In fact, they looked plain awful. Many of us adopted conventions that stated that anything exposed via COM would not have any prefixes whatsoever. That included parameters, functions, classes, etc. This was inline with what Microsoft and most 3rd-party vendors did with all the COM libraries and ActiveX controls they provided.
At the same time, those of us working on large projects noticed a definite laziness on the part of some other programmers (you know who you are! ) when it came to updating the variable prefixes when they changed a variable from, say, an Integer to a Long. This caused far more confusion than was worth. When coupled with the huge multi-page lists of "all the prefixes" for every possible type you could think of, Hungarian started to get in the way more than it helped.
Along comes .NET and just about everything is an object or can be boxed as such, and everything public is exposed to other languages - languages which may not use the same names for the variables we use (this was the same issue we had when writing for COM). If I want to know a variable's type, I can hover over it with the mouse in the VS.NET IDE. If I want to know a variable's use, I simply look at the well-worded variable name.
Now, rather than memorizing lists of prefixes, or prefixing everything with "obj", programmers are able to concentrate on the purpose of the variable rather than the underlying type. This alone has increased programmer productivity by removing the requirement to perform that mental prefix lookup - which for some of us was like a SQL Server full-table scan .
Since the .NET languages were a reasonably clean break from the old versions, it made sense for Microsoft and .NET developers to also change the expected naming conventions at the same time. They knew the adoption of the new conventions would be more likely (and less painful) with the platform shift.
.NET variables and types can have extremely long names, names that can describe the purpose of a variable rather than the underlying type. We don't have to pack as much meaning as possible into just a few letters. Control-space makes typing the long names completely painless, and the long names really assist in understanding and documentation.
Some people still stick to the old Hungarian notation, but those are the hold-outs. Sharing code with them becomes frustrating as the conventions have to be all modified when you do so. If everyone follows the Microsoft-recommended .NET conventions, information exchange and collaboration becomes much easier :-) If you are one of these hold-outs, and have good reasons for sticking to Hungarian, I'd love to hear from you via the contact link at the bottom of this page.
UI controls are something that are still in flux when it comes to conventions. The reason Hungarian is still often used for them is to ensure they are grouped in intellisense. Hungarian is definitely not perfect for this, but it works.

Resources - ASP.Net Coding Standards

Adopting a common coding standard across your web applications

Note: These standards assume C# but are just as applicable to VB etc. All these standards stay as close as possible to those recommended by Microsoft.
The Microsoft's Design Guidelines for Class Library Developers (MSDN site) is a useful set of guidelines which all ASP.Net developers should take a look at. In particular, those new to C# coding should see the naming conventions section, including capitalisation conventions (Pascal vs camel etc) and when to use nouns, verbs etc for naming of identifiers. It is interesting to note that Microsoft are moving away from the hungarian style of notation in .Net (I think based on the premise that everything is an object anyway in the framework and identifier names should be based on semantics not types).
Although Microsoft's guidelines are an excellent guide, I created this standards page, as I could not find a one-stop summary of standards I could follow quickly when building ASP.Net web applications - Microsoft's are not exactly a quick reference guide! Also, they do not target ASP.Net specifics (e.g. Web Control naming).

Naming and Capitalisation

Below summarises the naming recommendations for identifiers in .Net. Pascal casing is used mainly (ie capitalise first letter of each word) with camel casing (capitalise each word except for the first one) being used in certain circumstances.
Identifier Case Examples Additional Notes Detailed Info
Class Pascal Person, BankVault, SMSMessage, Dept Class names should be based on "objects" or "real things" and should generally be nouns.
MSDN site - more details
Method Pascal GetDetails, UpdateStore Methods should use verbs or verb phrases.
 
Parameter camel personName, bankCode  
MSDN site - more details
Interface Pascal with "I" prefix IDisposable One of the few times when prefixing is adopted.
MSDN site - more details
Property
Associated private member variable
Pascal
_camelCase
ForeColor, BackColor
_foreColor, _backColor
Use underscore camel casing for the private member variables, but keep the names the same as associated property accessors.
MSDN site - more details
Exception Class Pascal with "Exception" suffix WebException, SMSException  
 
Event Pascal plus optional "EventHandler" suffix where relevant btnSubmit_Click, Painting, Click, Clicked, MyEventHandler VS uses underscores to separate an object from its event. Be careful with tense (pre/past), e.g. a Close event that can be canceled should have a Closing event and a Closed event. MS also recommend adding the "EventHandler" suffix where thought needed.
MSDN site - more details
Note that acronym parts of phrases may be all in uppercase (e.g. SMSMessage) where relevant.
User interface objects (text boxes, drop down lists etc) are treated as a special case and discussed in the next section.

User Interface Objects and Controls

The Microsoft .Net guidelines do not go into detail on the naming of user interface objects (again probably because they are only objects after all), but one approach that is well adopted is the use of the "control type" prefix convention (similar to hungarian style often used in VB, C++ etc). Although this should not be used for indicating variable types, it is useful for user interface controls as it makes it explicitly clear where user interface elements are in your code.
Some samples are below for ASP.Net web form controls:
Control Prefix Example
Label lbl lblSurname
TextBox txt txtSurname
DataGrid dg dgResults
Button btn btnSave
ImageButton ibtn ibtnSave
Hyperlink lnk lnkHomePage
DropDownList ddl ddlCompany
ListBox lst lstCompany
DataList dlst dlstAddress
Repeater rep repSection
Checkbox chk chkMailList
CheckBoxList chk chkAddress
RadioButton rdo rdoSex
RadioButtonList rdo rdoAgeGroup
Image img imgLogo
Panel pan panSection
PlaceHolder plh plhHeader
Calender cal calMyDate
Adrotator adr adrBanner
Table tbl tblResults
[All] Validators val valCreditCardNumber
ValidationSummary vals valsErrors
     

Namespaces

All namespace should use Pascal casing and be prefixed with your company (and department if you wish). See examples below:
Sample "project level" namespaces:
YourCompany.YourDept.YourProject
Visualize.Blog

Generic reusable routines, classes etc which will be used across projects, can sit at the 'company' or 'dept' level, for example:
Visualize.Utils

Commenting Code

Code should be commented where necessary and C# XML commenting tags used, to aid VS intellisense, object browsing and on-line documentation generation if needed. Example: some sample C# source is given below for a method in an SMS tool I developed recently:
///

/// SendSMSMessage sends a text message to a valid mobile number
///

/// Mobile number to send to in format +44 1234 112233
/// Message itself, max 160 chars
/// Message result string from gateway
public string SendSMSMessage(string mobileNo,string message)
{

// rest of code here...
Full details of more XML tags can be found in the Visual Studio.Net on-line help.

Internal Coding Guidelines

Table of Contents

1. Introduction.......................................................................................................................................... 1

2. Style Guidelines.................................................................................................................................... 2

2.1 Tabs & Indenting................................................................................................................................ 2

2.2 Bracing............................................................................................................................................... 2

2.3 Commenting........................................................................................................................................ 2

2.3.1 Documentation Comments............................................................................................................. 2

2.3.2 Comment Style............................................................................................................................. 3

2.4 Spacing............................................................................................................................................... 3

2.5 Naming............................................................................................................................................... 4

2.6 Naming Conventions............................................................................................................................ 4

2.6.1 Interop Classes............................................................................................................................. 4

2.7 File Organization................................................................................................................................. 5


1. Introduction

First, read the .NET Framework Design Guidelines. Almost all naming conventions, casing rules, etc., are spelled out in this document. Unlike the Design Guidelines document, you should treat this document as a set of suggested guidelines. These generally do not effect the customer view so they are not required.
2. Style Guidelines
2.1 Tabs & Indenting

Tab characters (\0x09) should not be used in code. All indentation should be done with 4 space characters.
2.2 Bracing

Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:

if (someExpression)
{
DoSomething();
}
else
{
DoSomethingElse();
}

“case” statements should be indented from the switch statement like this:

switch (someExpression)
{

case 0:
DoSomething();
break;

case 1:
DoSomethingElse();
break;

case 2:
{
int n = 1;
DoAnotherThing(n);
}
break;
}

Braces should never be considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability.
for (int i=0; i<100; i++) { DoSomething(i); } 


2.3 Single line statements Single line statements can have braces that begin and end on the same line. public class Foo { int bar; public int Bar { get { return bar; } set { bar = value; } } } It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required. 

2.4 Commenting Comments should be used to describe intention, algorithmic overview, and/or logical flow. It would be ideal, if from reading the comments alone, someone other than the author could understand a function’s intended behavior and general operation. While there are no minimum comment requirements and certainly some very small routines need no commenting at all, it is hoped that most routines will have comments reflecting the programmer’s intent and approach. 

2.4.1 Copyright notice Each file should start with a copyright notice. To avoid errors in doc comment builds, you don’t want to use triple-slash doc comments, but using XML makes the comments easy to replace in the future. Final text will vary by product (you should contact legal for the exact text), but should be similar to: //----------------------------------------------------------------------- //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------
2.4.2 Documentation Comments

All methods should use XML doc comments. For internal dev comments, the tag should be used.

public class Foo
{

///

Public stuff about the method
/// What a neat parameter!/// Cool internal stuff!
///
public void MyMethod(int bar) { … }

}

However, it is common that you would want to move the XML documentation to an external file – for that, use the tag.

public class Foo
{

///
///
public void MyMethod(int bar) { … }

}

UNDONE§ there is a big doc with all the comment tags we should be using… where is that?
2.4.3 Comment Style

The // (two slashes) style of comment tags should be used in most situations. Where ever possible, place comments above the code instead of beside it. Here are some examples:

// This is required for WebClient to work through the proxy
GlobalProxySelection.Select = new WebProxy("http://itgproxy");

// Create object to access Internet resources
//
WebClient myClient = new WebClient();

Comments can be placed at the end of a line when space allows:

public class SomethingUseful
{
private int itemHash; // instance member
private static bool hasDoneSomething; // static member
}
2.5 Spacing

Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:

Do use a single space after a comma between function arguments.
Right: Console.In.Read(myChar, 0, 1);
Wrong: Console.In.Read(myChar,0,1);
Do not use a space after the parenthesis and function arguments
Right: CreateFoo(myChar, 0, 1)
Wrong: CreateFoo( myChar, 0, 1 )
Do not use spaces between a function name and parenthesis.
Right: CreateFoo()
Wrong: CreateFoo ()
Do not use spaces inside brackets.
Right: x = dataArray[index];
Wrong: x = dataArray[ index ];
Do use a single space before flow control statements
Right: while (x == y)
Wrong: while(x==y)
Do use a single space before and after comparison operators
Right: if (x == y)
Wrong: if (x==y)

2.6 Naming

Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of these include:

Do not use Hungarian notation
Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use “this.” in C# and “Me.” in VB.NET.
Do use camelCasing for member variables
Do use camelCasing for parameters
Do use camelCasing for local variables
Do use PascalCasing for function, property, event, and class names
Do prefix interfaces names with “I”
Do not prefix enums, classes, or delegates with any letter

The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to produce a consistent source code appearance. In addition a goal is to have clean readable source. Code legibility should be a primary goal.


2.7 Naming Conventions
2.7.1 Interop Classes


Classes that are there for interop wrappers (DllImport statements) should follow the naming convention below:

NativeMethods – No suppress unmanaged code attribute, these are methods that can be used anywhere because a stack walk will be performed.
UnsafeNativeMethods – Has suppress unmanaged code attribute. These methods are potentially dangerous and any caller of these methods must do a full security review to ensure that the usage is safe and protected as no stack walk will be performed.
SafeNativeMethods – Has suppress unmanaged code attribute. These methods are safe and can be used fairly safely and the caller isn’t needed to do full security reviews even though no stack walk will be performed.

class NativeMethods
{
private NativeMethods() {}


[DllImport(“user32”)]
internal static extern void FormatHardDrive(string driveName);
}

[SuppressUnmanagedCode]
class UnsafeNativeMethods
{
private UnsafeNativeMethods() {}

[DllImport(“user32”)]
internal static extern void CreateFile(string fileName);
}

[SuppressUnmanagedCode]
class SafeNativeMethods
{
private SafeNativeMethods() {}

[DllImport(“user32”)]
internal static extern void MessageBox(string text);
}

All interop classes must be private, and all methods must be internal. In addition a private constructor should be provided to prevent instantiation.


2.8 File Organization


Source files should contain only one public type, although multiple internal classes are allowed
Source files should be given the name of the public class in the file
Directory names should follow the namespace for the class

For example, I would expect to find the public class “System.Windows.Forms.Control” in “System\Windows\Forms\Control.cs”…

Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)
Using statements should be inside the namespace declaration.

namespace MyNamespace
{

using System;

public class MyClass : IFoo
{

// fields
int foo;

// constructors
public MyClass() { … }

// properties
public int Foo { get { … } set { … } }

// events
public event EventHandler FooChanged { add { … } remove { … } }

// methods
void DoSomething() { … }
void FindSomethind() { … }

//private interface implementations
void IFoo.DoSomething() { DoSomething(); }

// nested types
class NestedType { … }

}

}

Friday, July 8, 2011

Different ways for setting Connection Strings in Asp.net / Various ways to use Connection Strings

There are various ways to declare and use connections strings like Web.config file, Application variables,Hardcoded strings, components etc.

There are many ways where we can keep the connection strings in web.config file , as it is completely safe.One cant access the web.config file by request from fronend/browser.It is been avoided using IIS.But there can be the case that if the user gets the direct access to Server and can able to see the files and more info.In this case we can use Encryption & descryption facility provided by .Net.

1) First of all & simple is use Connection string using in Web.config we can access the same in code behind C# as follows

string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

quite easy to use !!!!

2) we can also store connectionstrings into .you need to add an AppSettings section, like this one:we can access the same in code behind C# as follows
string connstring = ConfigurationManager.AppSettings["ConnectionString"];

3) You can keep Connection Settings in web.config file with the protection of Encryption & descryption of particular sections.Then read it in your program and decrypt it before Editing. Check out the encryption/decryption APIs in .net.
e.g. IF we want to encrpt “connectionStrings> section then do the following/write following at command prompt of visual studio-
aspnet_regiis -pe “connectionStrings” -app “/YourApplicationName

The -pe option and the string “connectionStrings” to encrypt the connectionStrings element of the Web.config file for your application.
The -app option and the name of your application.

open web.config then and check the encryption completed !!!

For decryption of the same file
aspnet_regiis -pd “connectionStrings” -app “/YourApplicationName
Detail Reference

4) If we are having multiple connection strings then we can declare them in web.config and for accessing them easily & securily we can create one static class file in App_Code folder. I am explaining it with one sample example.

In the Web.Config -





Static Class file under App_Code e.g. ConnectionSettings.cs -

public static class ConnectionSettings
{
public static string ConnectionString
{
get
{

// code for accessing the connection string from web.config we can do it directly or using any other method //depends upon needs
string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

return conn;
}
}

}

Then we can able to access connection string settings as ConnectionSettings.ConnectionString

5) we can also read the connection string in Global.asax and store it in a applictaion level variable. and then we can read connection string from application variable so accessing web.config multiple times while accessing DB can be avoided.
Detail Reference

6)Also Last but not least I read recently that we can also create Dll with all Data Connection and run dotfuscator for more security if we are going to put connection settings part at client side.

There can be many more ways to use it …