Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Monday, September 19, 2011

throw vs throw ex: C# .NET Exceptions

There are a couple options to raise an exception again after it has been caught. One option is to raise the exception again by using the "throw exception" keyword like below:

try
{
   ...//code that encounters an exception
}
catch (Exception ex)
{
   ...//exception handling code
   throw ex; //raise the exception again
}

The disadvantage in this way is that the original context of the exception is lost. There is no longer a meaningful call stack attached to the exception because it will contain the latest context from the newly added throw. If you plan to throw the exception in this matter you should wrap the original exception into another new more high level (application) exception. The new exception would add more high level info about the original exception.


The second option is to use the throw keyword alone with out passing the actual exception variable. This tells the .NET framework to throw the original exception without updating its context like below:

try
{
   ...//code that encounters an exception
}
catch (Exception e)
{
   ...//exception handling code
   throw; //notice the exception e is omitted
}

This way should be used when the exception is trivial enough and the code is too small to require wrapping into another exception. Again the advantage here is that you maintain the original call stack so that any user of this code can track the cause of the exception.

It's worth noting that Java is different in this aspect and using "throw ex" in Java will retain the original stack trace.


Sunday, March 29, 2009

C# .NET Default Access Modifiers

It's good to refresh what the default access modifiers are in C#. Default access modifiers could explain why you can't see something you declared when expect to see it and vice versa.

First let's quickly review all the access modifiers in C#.
private: Can be accessed by members of the same class only.
protected: Can be accessed by members of the same class plus members of derived classes only.
internal: Can be accessed by all that is in the same assembly regardless of what class they are in. But can only be accessed from the same assembly.
public: Can be accessed by everything.

The general rule is that the default access modifier is as secured as possible for the declaration context. This does not mean that everything is private by default because private does not make sense for everything. So here is the breakdown.

Data types: class, struct, enum
For data types such as classes the most strict reasonable access modifier is internal. And that is exactly the default modifier. So when declaring a new class it is internal by default so that it can be accessed by other classes in the same assembly. It does not make sense for a class to be private by default because it would inaccessible.

Members: variables, methods
For member variables and methods which are inside a certain data type from the list above, the most restrictive reasonable modifier is private and that is it. Any time a member is declared with no access modifier, it is private by default.

Monday, March 16, 2009

Inline ASP.NET Tags Differences <%#, <%, <%=, <%$, <%--, <%@

It gets confusing at times when figuring out which ASP.NET tag is best to use. Moreover, it is good to know the settle difference between a couple of the similar tags. One might think that for example the "<%#" tag and "<%=" are the same for certain cases and can be used interchangeably. Actually they are different and in most cases only one of them would work unless some code change is done. So here is a summary of the tag attributes and the differences amongst them:

<% ... %>


This tag is used to insert code into an ASP.NET page usually with a .aspx extension. One of the most common use of this tag is conditional statements where you can choose to display certain content only when a condition is met.

<% if(isLoggedIn){ %>
Hello user
<% } else { %>
Please login
<% } %>

For more info:
http://msdn.microsoft.com/en-us/library/ms178135(vs.80).aspx

<%# ... %>


This tag is used with data binding. It can be used with DataBinder.Eval() or DataBinder.Bind() or just with any protected or public member as shown in the example. The trick about this tag is that it must be used inside a server-side element (with runat="server"). Also the DataBind() method of that element must be called at some point. However, certain ASP.NET elements automatically call their DataBind() method in their PreRender() methods. So there is no need to is explicitly call their DataBind() methods. Such elements are GridView, DetailsView, and FormView.

<div id="div1" runat="server">
Hello <%# userName %>
</div>


In the code behind:

protected void Page_Load(object sender, EventArgs e)
{
div1.DataBind();
}

For more info:
http://msdn2.microsoft.com/en-us/library/ms178366.aspx

<%= ... %>


This tag is similar to the above tag in the sense that it is used to evaluate the value of a protected or public member variable. The tag evaluates the ToString() method of the variable used and displays it. The nice thing about this tag is that it does not need to be inside a server-side element and its parent element does not even need to have a name.

<div>
Hello <%= userName %>
</div>

For more info:
http://msdn.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx

<%$ ... %>


This tag is used to evaluate expressions in a configuration file. It is usually used for connection strings but it can be used with AppSettings and other configurations.

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT * FROM [Employees]"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>">
</asp:SqlDataSource>

For more info:
http://msdn.microsoft.com/en-us/library/d5bd1tad.aspx

<%@ ... %>


This is usually used at top of a page as a directive to register controls or import a library.

<%@ Register TagPrefix="uc" Namespace="MyCustomUserControl" %>

For more info:
http://msdn.microsoft.com/en-us/library/xz702w3e(VS.80).aspx


<%-- ... --%>


This tag allows you to add server-side comments which would never show in the HTML output. This is different from using an HTML comment (<! -->) because HTML comments do get rendered in the outputted HTML.

<%-- this is a comment --%>

For more info:
http://msdn.microsoft.com/en-us/library/4acf8afk.aspx

That should be a good summary but there is obviously more to some of tags.

Friday, November 7, 2008

ASP .NET Connection Strings in Web.config File

ASP .NET offers an elegant way to store data source connection creditentials. Connection strings should be stored in a .config file, commonly and by default the Web.config file.

Firstly, what are connection strings? Connection strings are strings of text that contain information about a data source used in the code for data access. Information contained in a connection string includes the data source name, data source address, security mode, login creditentials, and the data source type.

There are a couple reasons why the Web.config file is a good place to store connection. One, ASP .NET is automatically configured to never display a file with a .config extension. So you can assume a level of security when storing login information in the Web.config. In addition, ASP .NET can be configured to encrypt the Web.config file, which would add more security. Nonetheless, you can be assured that any web request to a .config file would result in an error. Secondly, using Web.config allows a central way to manage information without requiring digging into the code nor code modification.

Below are examples of how connection strings would be used:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 <connectionStrings>
  <add name="connectionName" connectionString="Data Source=serverName;
  Initial Catalog=databaseName;User Id=username;Password=password;"
  providerName="System.Data.SqlClient"/>
</connectionStrings>
...
</configuration>



To retrieve the above connection string in C# code:

string connStr = ConfigurationManager.ConnectionStrings["connectionName"];



To use the connection string directly in an ASP .NET page:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:connectionName %>"
  SelectCommand="SELECT * FROM [Employees]" />