TURKISH BLOG   |  ABOUT ME  |  ARCHIVES  | DELETE LANGUAGE COOKIE

Enes TAYLAN

Mind Hegemony - Mood 1.0 - Total Control Edition

HEALTH MONITORING AND EXCEPTION HANDLING IN ASP.NET

clock June 27, 2009 07:11
Runtime exceptions and errors happen sometimes (or I should say always :) ), but end users don't need to know the details of them. Also showing internal details of the application may harm the security (gives hackers sensitive information). So websites should show user friendly error pages to users and save-log detailed technical information in an error message. To do so, we can configure web.config:

<customErrors mode="RemoteOnly" defaultRedirect="~/FriendlyErrorMessagePage.aspx">
    <error statusCode="404" redirect="~/PageNotFound.aspx" />
</customErrors>


In this example, for error "404" there is a specific page, and all other cases are addressed in "defaultRedirect" attribute of "customErrors". "RemoteOnly" means, when working in localhost, show the error page. But this is not enough. We should also have a system that saves technical details and inform the administrator about them. To take some action in "OnError" event in our code-behind files is a good option. A better approach is, rather than copying this code in every page, we can write a base page that inherits System.Web.UI.Page.
public class MyBasePage : System.Web.UI.Page
{
	protected override void OnError(EventArgs e)
	{
		//log the error-exception
	}

	//................
}
Another option is doing this in "Application_Error" event in "Global.asax.cs" :
void Application_Error (Object sender, EventArgs e)
{
	//log the error-exception
}
This approaches work but there is a full-scale mechanism in ASP.NET to get same functionality: instrumentation and health monitoring system. This system takes care of :

  • unhandled exceptions
  • lifetime exceptions (start of application, finish of application etc.)
  • audit events (failed or successful logins etc.)
  • .....
Instrumentation and health monitoring system is a framework and based on provider model design pattern. So we can log the details to SQL Server Database, the Windows Event Log, the WMI log, to mails or to Oracle RDMS by writing a specific provider for Oracle (by inheriting System.Web.Management.WebEventProvider).

Configuration setting of health monitoring is under <healthMonitoring> element of web.config

<healthMonitoring>
    <eventMappings>........</eventMappings>
    <providers>.................</providers>
    <rules>.......................</rules>
    <profiles>....................</profiles>
    <bufferModes>.............</bufferModes>
</healthMonitoring>


<eventMappings>........</eventMappings> registers the event classes so their types like:

<eventMappings>
    <add name="HeartBits" type="System.Web.Management.WebHeartbeatEvent,System.Web"  />
</eventMappings>


<providers>.................</providers> section registers providers:

<providers>
    <add name="SqlWebEventProvider" type="System.Web.Management.SqlWebEventProvider,System.Web" ConnectionStringName="localSqlServer" />
</providers>


<rules>.......................</rules> is the place we actually define which events to log, which registered provider and how often. Now an example that HeartBits events to be logged to Sql Server:

<rules>
    <add name="HeartBitEvents" eventName="HeartBits" provider="SqlWebEventProvider"
</rules>



HOW TO USE CACHE AND CACHE DEPENDENCY ?

clock June 21, 2009 04:28

Using cache is an easy way to increase efficiency in programs. By using cache techniques we can store the data in RAM that is normally in harddisk or another stuff whose access time is much bigger than RAM's. In this article, I will write a method that gets the subdirectory names in a directory and return them to caller. ( this method can be used, for example, to populate theme names in a dropdownlist so that user can select her preferred style. .NET cache classes are in System.Web.Cache hence don't forget import it. ( by using statement ) Another important thing about cache is: how much time the info should reside in cache? Because if it losses its validity after some time, it is just a garbage and may decrease the efficiency. If cache information is deleted earlier than it normally would be, we can't rely on the cache. Therefore, to solve this problem we have CacheDependency objects that enable us bind info to a file in system file hierarchy and say: "When this file is updated then delete this specific cache information. Now see the code:

 	public static string[] GetThemes()
        {
            if (HttpContext.Current.Cache["SiteThemes"] != null)
            {
		    //if there is already cache info then just use it
                return (string[])HttpContext.Current.Cache["SiteThemes"];
            }

            else //when cache is empty
            {
                string themesDirPath = HttpContext.Current.Server.MapPath("~/App_Themes");
		    //map virtual file location to full one

                string[] themes = Directory.GetDirectories(themesDirPath);
		    //using System.IO features get all directories in a specific one

                for (int i = 0; i < themes.Length; i++)
                {
                    themes[i] = Path.GetFileName(themes[i]);
                }

                CacheDependency dep = new CacheDependency(themesDirPath);
		    //define a dependency on the directory "themesDirPath"

                HttpContext.Current.Cache.Insert("SiteThemes", themes, dep);    
		    //Here we insert the "themes" string array with the cache key
		    //"SiteThemes" and say that if "dep" dependency object
		    //warns you delete this key - value pair from cache

		    
                return themes;
            }
        }

Here information is stored as key - value pairs. ( key is "SiteThemes" string and the value is "themes" array ) In this code snippet, when directory "App_Themes" is updated then "SiteThemes"-"themes" key - value pair also deleted. What we benefit from this code is: we don't read content of "App_Themes" every time (means many IO costs) instead read it only when the method is first invoked.



MICROSOFT IS PUTTING ITS POWER BEHIND SEARCH ENGINE BING

clock June 21, 2009 02:06

Steve BallmerThis week Thursday, Microsoft Corp. Ceo Steve Ballmer said, Microsoft is willing to invest in Internet search business up to 10% of its annual income. "Our shareholders, I told them we were willing to spend 5 to 10 percent of operating income for up to five years in this business, and we feel like we can get an economic return" said Ballmer in a business conference. Bing has grabbed 12.1% of US internet searches for the week June 8-1, up from June 1-5. However, Google has 65% share in the market. When this was reminded to Ballmer, he answered, "You don't go from 8 percent to 80. You have to be patient, we invested in Xbox for years and now it generates nice economic returns for us," he added, referring to the company's popular gaming console. Microsoft has operating $4.4 billion  in last quarter means that for a quarter $440 million and per year $1.8 billion to develop and advertise Bing. 

I always thought that why Microsoft hasn't done so much in internet area not just in search engine but in all internet related areas, because everything shifts to internet: software, advertise, information with cloud computing etc. And I see the answer now as Ballmer said "If we could have one do-over I would probably say I would start sooner on search," said Ballmer. "Sometimes the error you make is what you don't do and don't see. Our mistake wasn't that we didn't see the technology change coming, we didn't see the business change coming."  [Reuters]

And Google CEO Eric Schmidt' s ideas about Bing:



MULTI - TIER SOFTWARE DESIGN

clock June 20, 2009 23:35

Multi-tier or n-tier software design is a buzzword in recent years. To recap it in few words, it divides functionality, components, and code for a projects. There are generally 4 of them ( some people define 3 tiers not mentioning data store) multi-tier

1. Presentation Layer: This is the user interface. In this tier, the code defines what a user should see on the screen. To do so, it invokes the lower tier and get the data, shape and format it, maybe cast it considering its specific purpose and present data to user. 

2. Business Logic Layer (BLL): The code that takes the data from data access layer ( generally in the form of relational data ) and exposes it to the Presentation Layer in a more abstracted and intuitive way, hiding low level details. ( such as database schema, constraints) Also this tier grants input validation and ensures that the input is safe and consistent.

3. Data Access Layer: The code that takes of retrieving and manipulating raw data in the data store. It gives commands to data store ( to an RDMBS ) to create, read, update and delete information. The developer that prepares this layer should have knowledge about exactly all internal details of database: its constraints, columns - their names and data types and specific information about how RDMS works.In .NET environment this can be achieved by ADO.NET 

4. Data Store: This is where the data resides. This can be a RDMS, an XML file, a text file.

In small projects these tiers can be united, for example BLL and DAL can be implemented in a single class. However, in big projects that many developers work, multi - tier design with each tier is independent from the other ones is a very important and ease the work much.



WHICH ONE IS BETTER FOR SITE LAYOUT: "DIV" or "TABLE"

clock June 20, 2009 07:45
Sometimes developers use HTML tables to control the positioning of items to create a layout in webpage. This is a very common practice but not the best one. Also W3C discourages it by saying that <table> should be used to mark up tabular data such as sign up pages with many fields but not to create page layout. To create a layout <div> tags with "css" features should be used. These are why:
 
1. By using <div> and a separate stylesheet then we don't need to repeat this definition. This leads a site that is both faster to develop and easier to maintain.
 
2. Seperate .css files are cached by the browser but not html tables. So when we use <div> with .css files we get much faster loaded web sites. This is much more important in heavily loaded websites because sending less few bytes with thousands of users means much more efficient bandwidth usage.

3. By using <div> and separate stylesheet we can define multiple different themes and style sheets that users can select by considering preferences. These preferences can be colors, pictures and layout of <div> tags. (at top, at right etc.) Especially when changing position of some columns using <table> (i.e. exchanging positions of left and right column) is much more difficult than manipulating <div> tags.

4. For different screen resolutions, especially for PDA's to adapt the output for them is very easy by defining different stylesheets. Also hiding some content (i.e. some banner) by <div> is much easier than <table>
 


.NET IO - 2 ( Reading from and Writing to Files )

clock June 19, 2009 21:16
We are continuing from where we left in System.IO. (for the first article click) In .NET IO to write or read, we should use a stream or specific stream classes that extends abstract base class Stream. For example:

  • System.IO.FileStream
  • System.IO.MemoryStream
  • System.Net.Sockets.NetworkStream
  • System.IO.BufferedStream
In this article I'll use System.IO.FileStream to read from and write to a file. Let's look at this code:
 FileStream fs = new FileStream(Server.MapPath("example.txt"), FileMode.Open);
 //By using FileStream, we start to read the file. "FileMode.Open" means that this
 //file will be used just for reading not another operations. Other possible values are:
 //Append,Create,Truncate,CreateNew,OpenOrCreate 

byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length);
//we read the whole file by "from 0 to fs.length" 

foreach (byte k in data) 
{ 
    Response.Write(k.ToString()); 
} 
//and we send the result to the user 
When we run this example, we can get some meaningless results. The reason is "FileStream" gives us the result as "byte". If we don't want to transform these bytes to human-readable form, we should use "System.IO.StreamWriter" and "System.IO.StreamReader".
StreamWriter writer = new StreamWriter(File.Open(Server.MapPath("enes.txt"), FileMode.Open)); 
//file.open() -->> creates a filestream for streamwriter 
writer.Write("write to the file");
writer.Close(); 

////////////////////////////////////////////////////////// 

StreamReader reader = new StreamReader(File.Open(Server.MapPath("enes.txt"), FileMode.Open));
Label1.Text = reader.ReadLine(); 
reader.Close(); 
"System.IO.StreamWriter" and "System.IO.StreamReader" creates "System.IO.FileStream" themselves (so we don't need to create them)  "Label1.Text = reader.ReadLine(); " enables us to read file line by line. If we wanted to read whole file as a single chunk, we would write  "Label1.Text = reader.ReadToEnd(); " Besides these methods there are other static methods in System.IO that allows us carry out these operations easier:
 string k = File.ReadAllText(Server.MapPath("enes.txt")); 
and
 File.WriteAllText(@"C:\temp.txt",data); 


Tips and Tricks 2: HOW TO SWITCH MASTER PAGES AT RUNTIME

clock June 15, 2009 08:58
When designing user specific layout, besides themes and .css files we have also option of switching master pages. To do so we should write below code in PreInit event . ( this change can be occur just in PreInit, since after that, merging phase of content and master pages is already happened )
protected void Page_PreInit(object sender, EventArgs e)
{
     this.MasterPageFile = "~/otherMasterPage.master";
}


WHICH FEATURES A GOOD WEBSITE SHOULD HAVE?

clock June 13, 2009 03:35
Websites that are data-driven, content-based, real-world, have some shared features. This features are much more important than the past, because we have in the era of social media and competence is heavier. These features are:

1. An appealing user interface: Appearance is very important, because it is the first thing that a user face with. But interface doesn't mean just graphics. Also the site should be well-organized, reachable and easily accessible. The site must be able to provide a great user experience, means users can easily browse and interact. Another important thing is cross-browser compatibility, ensuring that the site looks and behaves fine from different platforms and browsers.

2. User loyalty: A successful content-based website requires users' loyalty so that they regularly visit the site. To do so, users can have the opportunity to write their own content, participate in polls and be informed about special events. This requires an authentication / authorization infrastructure so each user can have an identity, distinguishes him / her from other users. This infrastructure also grant and restrict access to different areas of the site.

3. Easily updatable: A mechanism that allows the content easily be updated: The site needs constant supply of fresh content to stay alive and vibrant. To have this constant stream of new content, editors or administrators should be able to update easily.

4. Newsletters: Not all users visit the site so that application should inform them about the new content by RSS and most importantly newsletters.
 
5. Getting feedback from users: What users like most and does not like? To get this feedback, users should have some kind of user-to-site communication.

6. Sociality: In the era of social media, user-to-user communication is very important. This also creates a community of loyal users, who come the site frequently to chat, discuss news and events, and ask about the content. To give users a feeling of membership will pay off in both in the short and long run.

7. Home page:
This is so important because after site grows and have big amount of information, it starts to contain non-related info about users. Everyone wants to see information about what he interested in. Hence, a mechanism should give the chance them to build their own home page.  


HOW TO DEVELOP A PROJECT, IN WHICH WAY?

clock June 13, 2009 02:19
In all programming projects, developers need a path to implement their projects. The most efficient path, development way can be achieved by defining corner stones. These corners are: problem, design and solution. With this clearly defined, separated, precisely and concisely understood path, development process can be quite easy and funny. So let’s look at these steps ( corner stones ) more closely:
 
1. Problem: Every project ( application ) comes from a need, a problem. This need can be a small need ( i.e. you may develop a diary program to organize your writings ) or can be a quite large project. ( you or your consumer needs an e-commerce store ) The point is to understand the need, the problem. In this Problem Stage developer tries to understand the question clearly, concisely and boldly. To reach this understanding, first of all, you should get the general statement of the problem. (i.e. this guy needs a news site ) Then he tries to detail the problem in the second stage, Design Stage. I can say that, Problem Stage is the most important stage. If you start wrongly, then you can get very silly solutions.
 
2. Design: This is the corner that you get a pen and a sheet of paper and start to understand business logic. For example, if the project is an e-commerce store, which type of store?, what admin needs?, what is the audience of this site, ordinary people or a specific group of people etc. Then you should design the interface in a general-high level. Most probably you will need a database design with its tables, constraints, security issues etc. Also classes and hierarchy between them should be written.

3. Solution: After first two stages, this part will be so quick and funny. By knowing the problem well and a good draft for its user interface, class hierarchies; just code the project. You have the manual, because.


COMPRESSING HTTP OUTPUT WITH AN HTTPMODULE

clock June 12, 2009 19:55
The communication between Server and Client is carried out via HTTP messages by sending necessary data. The workload of server and net speed is exactly how much time this messages requires to be sent. Therefore, to decrease message ( by using compressing algorithm and techniques ) size means higher speed and efficient bandwidth. Almost all new browsers can use "gzip" and "deflate" compression algorithms. ( they can decompress messages that comes from server) ASP.NET gives us compressing ability.

We will use "HttpModule" in this article. First create a Windows Class Library in C#.

Note: HttpModule' s are the controls that manipulates Request and Response messages. 



Name project as "CompressionModule" and with same name add a new class. Right-Click to the project, select "Add Reference" , browse "System.Web". Then write below code  :
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Web;  
  
namespace ZipModule  
{  
    //to get HttpModule capabilities implement "IHttpModule" interface
  
    public class CompressionModule : IHttpModule    
    {  
 
        #region IHttpModule Members  
  
        public void Dispose()  
        {  
            throw new NotImplementedException();  
        }  
  
        public void Init(HttpApplication context)  
        {  
            context.BeginRequest += new EventHandler(context_BeginRequest);  
        //besides default event handler we should write our custom one
        //context -->> current application that invokes our HttpModule
        }  
  
        void context_BeginRequest(object sender, EventArgs e)  
        {  
            HttpApplication app = (HttpApplication)sender;  
        //name this application as sender
  
            string encodings = app.Request.Headers.Get("Accept-Encoding");  
        //"Accept-Encoding" is the Http Header that informs us
        //whether the browser can use encoding algorithms
  
            if (encodings == null) //if it can't return
                return;  
  
            Stream s = app.Response.Filter;  
        //if can filter the response message
  
            encodings = encodings.ToLower();  
  
            if (encodings.Contains("gzip"))  
            {  
                app.Response.Filter = new GZipStream(s, CompressionMode.Compress);  
            //here is the core of the code
	//we zip the code here  
              
                app.Response.AppendHeader("Compression Tecnique", "gzip");  
            //we add a header to message so that we will be able
            //trace whether our module is working or not
          
                app.Context.Trace.Warn("GZIP Compression on");  
            }  
  
            else  
            {  
                app.Response.Filter = new DeflateStream(s, CompressionMode.Compress);  
            //if browser can't use "gzip" compress the message 
	//with "deflate"  
              
                app.Response.AppendHeader("Content-Encoding", "deflate");  
                app.Context.Trace.Warn("Deflate compression on");  
            }  
  
        }  
 
        #endregion  
    }  
}  
Build the project, copy the "ZipModule.dll" from "bin" directory. Add this .dll to your new website. Again like we did above right-click the website name and browse the "ZipModule.dll" and select it. To use this HttpModule we should configure "web.config" :
<httpModules>
    <add name="HttpCompressionModule" type="ZipModule.CompressionModule"/>
</httpModules>
<trace enabled="true"/>

By writing "<trace enabled="true"/>" we can trace our application and see exactly what happens in Request and Response messages. After making above configuration settings our HttpModule should work and compress the Http Messages. In browser url part, write "../Default.aspx/trace.axd". Click "View Details", if you see "Gzip compression on" ( like below snapshot ) then your HttpModule is working and you can send compressed Http Messages.  Congratulations.....
 


CISCO'S STRATEGY FOR FUTURE TRENDS

clock June 12, 2009 19:19

Cisco boss John Chambers told a conference that "video is the future and if you ask what excites me most, it's probably how video's going to change our lives - cisco logoboth personally and the way we work." Even Cisco predicts that video from small communication devices like cell phones will be the main e-mail technique. By using video in every aspect of the internet, internet traffic will reach 667 exabytes and 90% of that will be made up of video according the recent research. ( now internet size is about 500 exabyte - 1 exabyte is 1 million terabyte ) The traffic, equivalent of 10 billion DVDs worth of information, would cross the internet monthly said Cisco."If this prediction holds true, it would take more than a half a million years to watch all the online video"

What is Cisco?

Cisco Systems, Inc. is a multinational corporation with more than 66,000 employees and annual revenue of US$39 billion as of 2008. Headquartered in San Jose, California, it designs and sells networking and communications technology and services. According to 2008 data, Cisco net income of about 8 billion $. In Fortune 500 list, Cisco takes place as 57th.



FACEBOOK TRANSFERRED GREG BADROS FROM GOOGLE

clock June 12, 2009 18:49
Few days ago, Facebook transferred Greg Badros, a Google Senior Director of Engineering. As a man who graduated from Math and Computer Science simultaneously, Badros had been working in Google since 2003. He will be, like in Google, Director of Engineering in Facebook. What makes his transfer interesting is Badros was the team leader in several Google projects like "Google Calendar, Google Reader, Gmail team" and especially Google AdSense Team. This shows how much Facebook gives importance to online ad services in the times of people discussing whether social websites’ ad capabilities is more powerful than traditional search engine ad services. Moreover, this can be another big challenge for Google recently, after Microsoft's announcement of Bing Search Engine.
 
Here’s Facebook’s official statement :

    “Greg Badros has joined Facebook as a director of engineering, reporting to Mike Schroepfer. Greg is one of the most accomplished engineering talents at Google, and it’s wonderful that he has decided to bring these talents to Facebook and take on numerous responsibilities across the engineering organization.”


HOW TO MAINTAIN SCROLL POSITION AFTER PAGE REFRESH, POSTBACK?

clock June 12, 2009 08:51
In ASP.NET, after PagePostBack is done, to maintain the scroll position can be quite important in long web pages. ASP.NET gives us 3 methods to do this. They are:

       1. In Web.config :

               <pages maintainScrollPositionOnPostBack="true">

       2. In single Page :

              <%@ Page MaintainScrollPositionOnPostback="true" ...

       3. Programatically :

              Page.MaintainScrollPositionOnPostBack = true;