<?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; C#</title>
	<atom:link href="http://ekdd.co.il/category/c/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 href="http://msdn.microsoft.com/en-us/library/system.exception(VS.71).aspx" rel="nofollow" title="Exception class"  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 href="http://ekdd.co.il/howto-properly-connect-to-mssql-database/"title="Sqlconnection method"  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: Properly connect to MSSQL database</title>
		<link>http://ekdd.co.il/howto-properly-connect-to-mssql-database/</link>
		<comments>http://ekdd.co.il/howto-properly-connect-to-mssql-database/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 19:20:07 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[connection string]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=130</guid>
		<description><![CDATA[There are many ways you can connect to a database in ASP.NET, the way i’m going to explain here based on “try and error” during my development years. I will try to explain why i do each step and what errors i had in the past so you may prevent these in your web applications. [...]]]></description>
			<content:encoded><![CDATA[<p>There are many ways you can connect to a database in ASP.NET, the way i’m going to explain here based on “try and error” during my development years. I will try to explain why i do each step and what errors i had in the past so you may prevent these in your web applications. Experienced programmer should know each of these steps and may disagree so discussion is open to debate.</p>
<p><span id="more-130"></span></p>
<p><strong>What will you gain from using this technique ?</strong></p>
<ol>
<li>Organized in one place connection strings will prevent you from searching and replacing every time you change connection string or its name.</li>
<li>You will always have a connection closed and disposed from memory even if there was an error which prevented you from getting to the line where Sqlconnection is closed and disposed from memory.</li>
</ol>
<p><strong>Step one — Keep all connection string at one place<br />
</strong></p>
<p>Instead of hard coding every single place you connect to database you can set connection string value inside of web.config or a class. There is no rule where set connection string better in a class or web.config but any ASP.NET developer will first look at ConnectionStrings section of web.config so it would be better to keep connection strings where they belong to.</p>
<pre class="brush: xml">

&lt;connectionStrings&gt;
&lt;add name=&quot;Dismark&quot; connectionString=&quot;Data Source=.\sqlexpress;Initial Catalog=Dismark;Integrated Security=True;Pooling=False&quot; providerName=&quot;Sytem.Data.SqlClient&quot;/&gt;
&lt;add name=&quot;Support&quot; connectionString=&quot;Data Source=.\sqlexpress;Initial Catalog=Support;Integrated Security=True;Pooling=False&quot; providerName=&quot;Sytem.Data.SqlClient&quot;/&gt;
&lt;/connectionStrings&gt;
</pre>
<p>As you can see there are two database connection strings, it is important to name databases and give  connection string names according to what they represent. “Dismark” is an application name so i name the database and connection string the same name so in two month i won’t be needed to guess what “ConnectionString1” means. “Support” is a centralized database for costumer ticket support system because the client has few applications while it is much easier to work with centralized support ticket system rather have one per application. So each time you create an application for yourself or for a client ask yourself what whether are gonna be other applications or not because you can create external centralized Support, ErrorReports and Billing databases.</p>
<p><strong>Step two — Make connections easier to use by having a function to retrieve already opened SqlConnection.</strong></p>
<p>This step reduces amount of code you need to write each time you connect to database with your code. For example we will create a class inside of a App_Code folder named DB which will handle all our connections.</p>
<p>This is how your old code could look like</p>
<pre class="brush: c#">

using System;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Dismark&quot;].ConnectionString);
cn.Open();
// code goes here
cn.Close();
cn.Dispose();
}
}
</pre>
<p>Instead lets create a DB class with two functions, each function connects to specific database, opens a connection and returns to the caller.This way we will write less code each time we connect to database, it will be easier to change if for some reason we will change a database moved to another server or we will have to change connection string name.</p>
<pre class="brush: c#">

using System;
using System.Configuration;
using System.Data.SqlClient;

public class DB
{
public static SqlConnection connectToDismark()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Dismark&quot;].ConnectionString);
cn.Open();
return cn;
}
public static SqlConnection connectToSupport()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Support&quot;].ConnectionString);
cn.Open();
return cn;
}
}
</pre>
<p>This is a call to these functions from page where you connect to a database. As you can see there are less code to write and we don’t have to remember database’s exact name as Visual Studio’s intellisense helps us when we type DB class name.</p>
<pre class="brush: c#">
SqlConnection cn2 = DB.connectToDismark();
// code goes here
cn2.Close();
cn2.Dispose();
</pre>
<p><strong>Step 3 — Encapsulation of connection within using block<br />
</strong></p>
<p>As you see there are two methods remain, connection.Close() and connection.Dispose(). One obviously closes the connection to database and other one disposes it from memory. We need to keep in mind that sometimes we won’t reach those lines of code because of error of some kind (ie. bad input from user which cause an error to <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx" rel="nofollow" title="SqlCommand class"  target="_blank">SqlCommand </a>object). Which means connection will remain open until Sql Server closes it. Not good practice as server may have limit or still use resources to keep the connection alive, instead of that we can encapsulate connection within using block which will automatically close() and dispose() connection when we leave its scope. Lets see how its done.</p>
<pre class="brush: c#">
using (SqlConnection cn3 = DB.connectToDismark())
{
// code goes here
}
</pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx" rel="nofollow" title="SqlConnection Class"  target="_blank">Sqlconnection</a> class inherits from <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow" title="IDisposable Interface"  target="_blank">IDisposable</a> interface which allows to use it within using block, same goes for <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx" rel="nofollow" title="SqlDataReader Class"  target="_blank">SqlDataReader</a> class.</p>
<p>Much faster and secure isn’t it ?</p>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/howto-properly-connect-to-mssql-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HttpCombiner modifications for better usability</title>
		<link>http://ekdd.co.il/httpcombiner-modifications-for-better-usability/</link>
		<comments>http://ekdd.co.il/httpcombiner-modifications-for-better-usability/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 13:31:25 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[http handler]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=113</guid>
		<description><![CDATA[HttpCombiner is a HttpHandler allows you to gather all css and js files together which decreases amount of http requests made to server when user requests a page and also to cache the generated files, which makes you websites to load faster. You can download http handler from Microsoft’s website by clicking here and you [...]]]></description>
			<content:encoded><![CDATA[<p>HttpCombiner is a <a href="http://msdn.microsoft.com/en-us/library/f3ff8w4a%28VS.71%29.aspx" rel="nofollow" title="http handler explanation"  target="_blank">HttpHandler </a>allows you to gather all css and js files together which decreases amount of http requests made to server when user requests a page and also to cache the generated files, which makes you websites to load faster. You can download http handler from Microsoft’s website by <a href="http://code.msdn.microsoft.com/HttpCombiner" rel="nofollow" title="Http Handler"  target="_blank">clicking here</a> and you can read Omar’s article on how to implement the handler <a href="http://msmvps.com/blogs/omar/archive/2008/08/28/http-handler-to-combine-multiple-files-cache-and-deliver-compressed-output-for-faster-page-load.aspx" rel="nofollow" title="Omar's article on how to use Http handler"  target="_blank">here</a>. Original handler written by <a href="http://msmvps.com/blogs/omar/default.aspx" rel="nofollow" title="Omar Al Zabir's blog"  target="_blank">Omar Al Zabir</a>.</p>
<p>It took me few minutes to configure the handler to work, it is easy to use and well documented. So i advice you to read Omar’s post before continuing with modifications.</p>
<p><span id="more-113"></span></p>
<h2><span style="color: #ff0000;"><strong><span style="color: #000000;">What the problem with Omar’s http handler ?</span></strong></span></h2>
<ol>
<li><span style="color: #ff0000;"><span style="color: #000000;">needless number of paremeters which are passed to handler, instead of having 1 parameter ie. css or js , we got 3 parameters. Why to have file type and content type together when js extension clearly means “javascript/text” content type.</span></span></li>
<li>generated by handler output is cached which means old version will be used anytime you access the page which makes imposible to use handler during developement process when we constantly modify JS and CSS files. By default there is a parameter in query string call to handler “v” which stands for version but each change you make on files you will need to update the version number so there won’t be caching.</li>
<li>each JS or CSS file must be defined in web.config which goes against my dynamic thinking</li>
</ol>
<p>if you find these as faults in usability like i do continue reading further …</p>
<h2><strong>How do we fix those issues ?</strong></h2>
<p>First of lets get rid of parameters and just pass one that stands for file type (ie. css or js), second of all lets define folder within the application where all js and css files will be stored so we can loop though folder and dynamically get all files at once without defining each new file and last let’s define global parameter which tells handler whether it is production, development server or just a cache refresh to update website so we won’t directly deal with versioning.</p>
<p>I could rewrite the handler to work as i want it to but Omar did a great job with handler and all credit to him, while i don’t want to create “yet another HttpHandler” to combine css/js files.. My idea was to hack HttpCombiner as fast as i could so i could get to work with it without dealing with it’s design.</p>
<h2><strong>Implementation</strong></h2>
<p><strong><span style="color: #000000;">Step I — web.config</span></strong><strong><br />
</strong></p>
<p>let’s create two folders inside of our assets folder css and js, because handler already loads css you need to move all css files from your App_Theme/ThemeName folder to Assets/Css one and Js files just keep inside Assets/Js.</p>
<p><span style="text-decoration: underline;"> important note, from now on your CSS and JS files are virtually located on the root (where you place the HttpCombiner.ashx) and not inside real Assets/Foldername folder.</span></p>
<p>Once we have two folders and we understood where files gonna reside and where their virtual location will be, let’s tweak web.config file to work with new settings.</p>
<p><em><strong>old code</strong></em></p>
<pre class="brush: xml">
&lt;/appSettings&gt;
&lt;appSettings&gt;
&lt;add key=&quot;Set_Css&quot; value=&quot;~/App_Themes/Default/Css1.css,~/App_Themes/Default/Css2.css&quot;/&gt;
&lt;add key=&quot;Set_Javascript&quot; value=&quot;~/Javascripts/Js1.js,~/Javascripts/Js2.js,http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js&quot;/&gt;
&lt;/appSettings&gt;
</pre>
<p><em><strong>new code</strong></em></p>
<pre class="brush: xml">
&lt;appSettings&gt;
&lt;add key=&quot;css&quot; value=&quot;~/assets/css/&quot;/&gt;
&lt;add key=&quot;js&quot; value=&quot;~/assets/js/&quot;/&gt;
&lt;add key=&quot;refreshCombiner&quot; value=&quot;true&quot;/&gt;
&lt;/appSettings&gt;
</pre>
<p><strong><span style="color: #000000;">Step II — change of urls layout for handler calls</span></strong></p>
<p><strong><span style="color: #000000;">old urls</span></strong></p>
<pre class="brush: html">
&lt;link type=&quot;text/css&quot;  rel=&quot;Stylesheet&quot; href=&quot;HttpCombiner.ashx?s=Set_Css&amp;amp;t=text/css&amp;amp;v=1&quot; /&gt;
&lt;script type=&quot;text/javascript&quot;  src=&quot;HttpCombiner.ashx?s=Set_Javascript&amp;amp;t=type/javascript&amp;amp;v=2&quot; &gt;&lt;/script&gt;
</pre>
<p><strong><span style="color: #000000;">new urls</span></strong></p>
<pre class="brush: html">
&lt;link type=&quot;text/css&quot;  rel=&quot;stylesheet&quot; href=&quot;HttpCombiner.ashx?t=css&quot; /&gt;
&lt;script type=&quot;text/javascript&quot;  src=&quot;HttpCombiner.ashx?t=js&quot; &gt;&lt;/script&gt;
</pre>
<p><strong><span style="color: #000000;">Step III — modification of HttpCombiner.ashx<br />
</span></strong></p>
<p><strong><span style="color: #000000;">old code — lines 22–24<br />
</span></strong></p>
<pre class="brush: c#">

string setName = request[&quot;s&quot;] ?? string.Empty;
string contentType = request[&quot;t&quot;] ?? string.Empty;
string version = request[&quot;v&quot;] ?? string.Empty;
</pre>
<p><strong><span style="color: #000000;">new code<br />
</span></strong></p>
<pre class="brush: c#">

string setName = request[&quot;t&quot;] ?? string.Empty;
string contentType = (setName == &quot;js&quot;) ? &quot;text/javascript&quot; : &quot;text/css&quot;;

string version = &quot;1&quot;;
if (bool.Parse(ConfigurationManager.AppSettings[&quot;refreshCombiner&quot;]))
{
version = new Random().Next(1, 999999).ToString();
}
</pre>
<p><strong><span style="color: #000000;">old code — lines 47–56<br />
</span></strong></p>
<pre class="brush: c#">

string setDefinition =
System.Configuration.ConfigurationManager.AppSettings[setName] ?? &quot;&quot;;
string[] fileNames = setDefinition.Split(new char[] { &#039;,&#039; },
StringSplitOptions.RemoveEmptyEntries);

foreach (string fileName in fileNames)
{
byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
writer.Write(fileBytes, 0, fileBytes.Length);
}
</pre>
<p><strong><span style="color: #000000;">new code<br />
</span></strong></p>
<pre class="brush: c#">

string filesPath = ConfigurationManager.AppSettings[setName];
string[] fileEntries = Directory.GetFiles(HttpContext.Current.Server.MapPath(filesPath));
foreach (string fileName in fileEntries)
{
byte[] fileBytes = this.GetFileBytes(context, filesPath + fileName.Trim().Remove(0, fileName.LastIndexOf(&quot;\\&quot;)), encoding);
writer.Write(fileBytes, 0, fileBytes.Length);
}
</pre>
<p>Hope you enjoyed it !!!</p>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/httpcombiner-modifications-for-better-usability/feed/</wfw:commentRss>
		<slash:comments>1</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 href="http://www.developerfusion.com/" rel="nofollow" title="Developer Fusion"  target="_blank">Developer Fusion</a>, a <a href="http://www.developerfusion.com/tools/convert/vb-to-csharp/" rel="nofollow" title="c# vb converter"  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 href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow" title="asp.net page live cycle explanation"  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>
	</channel>
</rss>
