<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>eugene.K &#187; ASP.NET</title>
	<atom:link href="http://ekdd.co.il/tag/asp-net/feed/" rel="self" type="application/rss+xml" />
	<link>http://ekdd.co.il</link>
	<description>web developer to web developers</description>
	<lastBuildDate>Tue, 22 Sep 2009 06:05:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>HOWTO: Log website errors using exceptions in ASP.NET</title>
		<link>http://ekdd.co.il/log-errors-in-asp-do-net/</link>
		<comments>http://ekdd.co.il/log-errors-in-asp-do-net/#comments</comments>
		<pubDate>Mon, 21 Sep 2009 14:00:04 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[exceptions]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=98</guid>
		<description><![CDATA[Defensive programming  (ie. checking object for null before having an action on it) can be a great tool but do we always can prevent all the errors especially when it comes to user inputs or web servers that not always reliable. When application is up and running there are not many ways we can find [...]]]></description>
			<content:encoded><![CDATA[<p>Defensive programming<strong> </strong> (ie. checking object for null before having an action on it) can be a great tool but do we always can prevent all the errors especially when it comes to user inputs or web servers that not always reliable. When application is up and running there are not many ways we can find out that some user had an error unless the error is global so application goes down. Of course if we have an access to Windows Event Viewer on the server we can check it daily but in my honest opinion Event Viewer is quite hard to use.  Instead of that we can write our own ErrorLogger. So each time user or server have a bug we will have a nice report on that. For error tracking we will use .NET built in <a title="Exception class" href="http://msdn.microsoft.com/en-us/library/system.exception(VS.71).aspx" target="_blank">Exception class</a> and Try and Catch block.</p>
<p><span id="more-98"></span></p>
<h2><span style="color: #000000;"><span style="text-decoration: underline;">part I — setting up database</span></span></h2>
<p>Create a database with name ErrorLog inside of it create a table in database called Errors with following fields errorID, userID, userIP, errorPage, errorName, errorStack, errorDate and isRead.</p>
<pre class="brush: sql">

CREATE TABLE [dbo].[Errors](
[errorID] [int] IDENTITY(1,1) NOT NULL,
[userID] [int] NOT NULL,
[userIP] [varchar](14) NOT NULL,
[errorPage] [nvarchar](200) NOT NULL,
[errorName] [nvarchar](100) NOT NULL,
[errorStack] [nvarchar](max) NOT NULL,
[errorDate] [smalldatetime] NOT NULL,
[isRead] [bit] NOT NULL,
CONSTRAINT [PK_Errors] PRIMARY KEY CLUSTERED
(
[errorID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
</pre>
<p><em>userID </em>will be stored in case you have user logged in ( or any other tracking parameter ie. user Guid), otherwise you can save zero value. Ability to know what user had an error can help you to debug the application. <em>userIP </em>field useful to know whether it is the same user accessed resource with error in case there was no <em>userID </em>provided. <em>errorPage</em> is useful because sometimes there is no indication in Exception’s stack where an error appeared so saving it could be a good idea also in case you have one error logging system for multiple websites this way you will save time understanding where it was or to review an error log at any website. <em>errorName</em> is a short name of the exception that mostly not descriptive enough to debug but useful for short indication or error category needs. <em>errorStack </em>field<em> </em>will be used to store everything from <em>Exception.ToString(). errorDate </em>obviously for sorting and timing issues and <em>isRead </em>is useful in cases when you don’t delete errors but just hide them from viewing.</p>
<p>Next lets write a stored procedure “LogError” which will insert an error to database, code is quite straightforward.</p>
<pre class="brush: sql">

CREATE PROCEDURE dbo.LogError
@userID int,
@userIP VarChar(14),
@errorPage NVarChar(200),
@errorName NVarChar(100),
@errorStack NVarChar(max)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Errors VALUES (@userID,@userIP,@errorPage,@errorName,@errorStack,getdate(),0)
END
GO
</pre>
<h2><span style="color: #000000;"><span style="text-decoration: underline;">part II — the code</span></span></h2>
<p>We got two options “lazy way” and the “proper way”. The “lazy way” is to capture an error as it appears from <em>global.asax Application_Error() </em>method which i will show you in a few but it is important to understand that the “lazy way” won’t give you much as flexibility as “proper” one simply because you will just log <span style="text-decoration: underline;">some of errors</span> without the ability to inform user of what really happened. Catching an error from global.asax is a global method which will act the same for any kind of error from any kind of page while “proper way” will allow you to have conditional logic so for x error application will redirect z page and y error will redirect somewhere else and show user friend message  (ie. if not logged in user tries to get to page that requires <em>userID </em>stored in session or cookie you would like him to be redirected to login page, to show him user friendly message and then to log an error which could be caused by wrong account confirmation mail you have sent SO IT IS IMPORTANT TO LOG ANY ACTION). This way you will know for sure where, why and how.</p>
<h3 style="font-size: 1.17em;"><span style="color: #999999;"><span style="color: #000000;">The “lazy method”</span></span></h3>
<p>Code pretty much speaks for itself but here some explanation. First we get an <em>Exception </em>from <em>Server.GetLastError()</em> object then we connect to database, with “LogError” stored procedure</p>
<p>*** “Lazy method” suitable for those who already have an online application when architectural changes in its design will create needless bugs. Even though  “proper method” has much wider flexibility than just logging errors, so next time you start another project consider using the proper one but to use it on live application is not such a good idea.</p>
<p>Add this piece of code to<strong><span style="color: #000000;"> </span></strong> <strong>Application_Error()</strong> method of<strong> global.asax</strong>.</p>
<pre class="brush: c#">

Exception currentError = Server.GetLastError().GetBaseException();
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Errors&quot;].ConnectionString))
{
cn.Open();
SqlCommand com = new SqlCommand(&quot;InsertError&quot;,cn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(&quot;@userID&quot;, SqlDbType.Int).Value = Users.getUserID();
com.Parameters.Add(&quot;@userIP&quot;, SqlDbType.VarChar,14).Value = Users.getUserIP();
com.Parameters.Add(&quot;@errorPage&quot;, SqlDbType.NVarChar,200).Value = Request.Url.ToString();
com.Parameters.Add(&quot;@errorName&quot;, SqlDbType.NVarChar,100).Value = error.Name;
com.Parameters.Add(&quot;@errorStack&quot;, SqlDbType.NVarChar).Value = error.ToString();
try
{
com.ExecuteNonQuery();
Server.ClearError();
Response.Redirect(&quot;~/errorpage.aspx&quot;);
}
catch (Exception)
{
}
}
</pre>
<p>This is not a good idea to use empty catch block but we have no choice and nowhere to log this error, think of situation when your application database in one place and ErrorLog on another, by having try and catch block in there we protect user from being thrown from application when ErrorLog database will fail. So we won’t track an error but user will continue to browse our application.</p>
<p><strong>The “proper method”</strong></p>
<p>Lets create a class inside our App_Code folder caller Errors. Add a method in it caller logError. This method it wrapped by try and catch block so we will avoid Exception in case we could not be able to establish connection to Errors database or any other connection error like transaction deadlock. Thanks to Shuaib Rameh for pointing out this mistake.</p>
<pre class="brush: c#">
try {
public static void logError(Exception ex)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Errors&quot;].ConnectionString))
{
SqlCommand com = new SqlCommand(&quot;LogError&quot;, cn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(&quot;@userID&quot;, SqlDbType.Int).Value = Users.getUserID();
com.Parameters.Add(&quot;@userIP&quot;, SqlDbType.VarChar,14).Value = Users.getUserIP();
com.Parameters.Add(&quot;@errorPage&quot;, SqlDbType.NVarChar,200).Value = Request.Url.ToString();
com.Parameters.Add(&quot;@errorName&quot;, SqlDbType.NVarChar,100).Value = ex.Name;
com.Parameters.Add(&quot;@errorStack&quot;, SqlDbType.NVarChar).Value = ex.ToString();
com.ExecuteNonQuery();
}
}
}
catch(Exception)
{
}
</pre>
<p>Method is similar to one we added to Application_Error handler inside of global.asax with with difference we pass Exception as parameter and use its values to track an error. Now lets see how to use this method and what its flexibility will allow us to do.</p>
<pre class="brush: c#">

public static bool isUserEmailExists(string userEmail)
{
bool isEmailExists = false;
try
{
using (SqlConnection cn = DB.connectMainapplicationDataBase())
{
SqlCommand com = new SqlCommand(&quot;IsUserEmailExists&quot;, cn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(&quot;@userEmail&quot;, SqlDbType.VarChar, 50).Value = userEmail;
using (SqlDataReader reader = com.ExecuteReader())
{
if (reader.HasRows)
{
isEmailExists = true;
}
}
}
}
catch (Exception ex)
{
Errors.logError(ex);
}
return isEmailExists;
}
</pre>
<p>This a sample method in which we check whether user’s email exists in our database ie. for password recovery needs or registration. Connection is wrapped up with try-catch block and on Exception we track it down with a method we create inside of Errors class. We can redirect or do what ever we want but error will be logged. Connection here is made with using block for more information about it read  <a title="Sqlconnection method" href="http://ekdd.co.il/howto-properly-connect-to-mssql-database/" target="_self">HOWTO: Properly connect to MSSQL database</a> .</p>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/log-errors-in-asp-do-net/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>HOWTO: Use C# and VB in the same project</title>
		<link>http://ekdd.co.il/howto-use-c-and-vb-in-the-same-project/</link>
		<comments>http://ekdd.co.il/howto-use-c-and-vb-in-the-same-project/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 17:00:20 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=84</guid>
		<description><![CDATA[You will get a compilation error if you will place  C# and VB code along in App_Code directory. This little code snippet for web.config gives your compliper an ability to distinguish between languages.  Some of you could ask, i use X language why should i start an application with native support for few ? Real [...]]]></description>
			<content:encoded><![CDATA[<p><strong>You</strong> will get a compilation error if you will place  C# and VB code along in <em>App_Code </em>directory. This little code snippet for web.config gives your compliper an ability to distinguish between languages.  Some of you could ask, i use X language why should i start an application with native support for few ? Real life example explains why would you do that.</p>
<p><span id="more-84"></span></p>
<p><strong>real life example:</strong></p>
<p>I had to work on a project large part of which was written in VB, i do understand VB but i feel much more comfortable with C#.  I could use great tool by <a title="Developer Fusion" href="http://www.developerfusion.com/" target="_blank">Developer Fusion</a>, a <a title="c# vb converter" href="http://www.developerfusion.com/tools/convert/vb-to-csharp/" target="_blank">.NET Code Converter</a> but it was much easier to keep the old code and just have new one written in my native language.  This way i could utilize already written code inVB.</p>
<p>Important note, if you using VB in multi language project please write your functions as strict as possible to avoid possible compliation issues while use a combination of functions from both App_Code dirs.</p>
<p><strong>code:</strong></p>
<p><strong> </strong>Create two new folders inside of <em>App_Code </em>folder, CS for C# code and VB obviously for VB code.  Folder names are not important as used only as identifiers for web.config attributes in code below.</p>
<pre class="brush: xml">

&lt;compilation&gt;

&lt;codeSubDirectories&gt;

&lt;add directoryName=&quot;CS&quot; /&gt;

&lt;add directoryName=&quot;VB&quot; /&gt;

&lt;/codeSubDirectories&gt;

&lt;/compilation&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/howto-use-c-and-vb-in-the-same-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HOWTO: Access Session outside of the page’s live cycle</title>
		<link>http://ekdd.co.il/access-session-out-of-page/</link>
		<comments>http://ekdd.co.il/access-session-out-of-page/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 16:43:48 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[session]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=73</guid>
		<description><![CDATA[You cannot access Session object or any other object which resides in page’s life cycle from out of the scope functions .This follow OOP rules but sometimes complicate development process when you need to access session from external source. In this example i will examine the way i use at any project to hack OOP [...]]]></description>
			<content:encoded><![CDATA[<p>You cannot access Session object or any other object which resides in <a title="asp.net page live cycle explanation" href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" target="_blank">page’s life cycle</a> from out of the scope functions .This follow OOP rules but sometimes complicate development process when you need to access session from external source. In this example i will examine the way i use at any project to hack OOP for my needs. Maybe there is a better solution but this is the best i’ve found so far.</p>
<p><span id="more-73"></span></p>
<p><strong>real life example:</strong></p>
<p>There was a website that used <em>userID </em>stored in the session in order to retrieve information about logged user. All fine because most of the time access to session object comes from within page life cycle ( ie.<em>Page_Load</em>) itself but it has certain complication when it comes to using functions whether these are on the same page but outside of page life cycle scope or inside of <em>App_Code</em> directory.</p>
<p>Why would i access session outside of the page’s life cycle ? Simply because anytime website requests an  <em>userID </em>i need to check session for null in case user lost session or never logged in. Another reason could be architectural change in the application that won’t use <em>userID </em>stored in the session but in object of some kind. So much more elegant solution will be to use external function that does all the job for me. Gets an <em>userID </em>in case there is one and if not gets n0ne can be used in conditional logic for example to redirect an user to login page.</p>
<p>So i’ve created a private function to get an <em>userID </em>and if <em>redirectToLogin </em>variable is <em>TRUE </em>then it redirects. Second private functions retrieves the real <em>userID </em>by accessing current context <em>HttpContext.Current. </em>Same way you can access anything from your page life cycle’s context ( <em>ie.Request </em>and <em>Response) </em>which i use in redirection <em>redirectToLoginPage </em>method. Most important is to understand that this kind of programming gives you flexibility in the future (ie. if you change your login page name or will start storing whole user details in <em>session </em>as<em> User object</em>, this way you will just need to change one function that will access <em>User </em>object stored in session rather searching and modifying every place <em>userID </em>session variable was stored.)</p>
<p><strong>code:</strong></p>
<pre class="brush: c#">

public static int getUserID(bool redirectToLogin)
{
int userID = getUserID();
if (redirectToLogin &amp;amp;&amp;amp; userID == 0)
{
redirectToLoginPage();
}
return userID;
}

private static int getUserID()
{
int userID = 0;
if (HttpContext.Current.Session[&quot;userID&quot;] != null)
{
userID = Convert.ToInt32(HttpContext.Current.Session[&quot;userID&quot;]);
}
return userID;
}

private static void redirectToLoginPage()
{
HttpContext.Current.Response.Redirect(&quot;~/login.aspx&quot;);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/access-session-out-of-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HOWTO: Limit Viewstate length</title>
		<link>http://ekdd.co.il/limit-viewstate-length/</link>
		<comments>http://ekdd.co.il/limit-viewstate-length/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 16:00:23 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[viewstate]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=4</guid>
		<description><![CDATA[In some occasions browsers may block or truncate  generated viewstate due to it’s length. This short tweak may solve the issue  by dividing the viewstate to independent hidden fields based on the number you provide as value. In this example maxPageStateFieldLength set to 50 this means when viewstate get beyond 50 characters it will be [...]]]></description>
			<content:encoded><![CDATA[<p><strong>In</strong> some occasions browsers may block or truncate  generated viewstate due to it’s length. This short tweak may solve the issue  by dividing the viewstate to independent hidden fields based on the number you provide as value. In this example <em>maxPageStateFieldLength</em> set to<em> 50</em> this means when viewstate get beyond 50 characters it will be broken to different hidden fields holding viewstate’s value</p>
<p><span id="more-4"></span></p>
<p><strong>code :</strong></p>
<pre class="brush: xml">

&lt;system.web&gt;
&lt;pages maxPageStateFieldLength=&quot;50&quot;&gt;
&lt;controls /&gt;
&lt;/pages&gt;
&lt;/system.web&gt;
</pre>
<p>* put this code as <em>&lt;pages&gt;</em> attribute inside of <em>&lt;web.section&gt;</em> section in web.config</p>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/limit-viewstate-length/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
