Wednesday, December 8, 2010
Friday, November 19, 2010
Tower Of Hanoi
#include<conio.h>
#include<math.h>
{
if(x==1)
{
printf("Move Disk From %c to %c\n",from,to);
}
else
{
hanoi(x-1,from,aux,to);
printf("Move Disk From %c to %c\n",from,to);
hanoi(x-1,aux,to,from);
}
}
void main()
{
int disk;
int moves;
clrscr();
printf("Enter the number of disks you want to play with:");
scanf("%d",&disk);
moves=pow(2,disk)-1;
printf("\nThe No of moves required is=%d \n",moves);
hanoi(disk,'A','C','B');
getch();
}
Thursday, November 18, 2010
Law of simplicity
in mind the next time you set out to design an application, a website, or even
improve your daily life. They are The Laws of Simplicity
and were conceived by John Maeda, an artist and noted computer scientist from
the MIT Media Lab. He compiled them in a short, 100-page book (and posted them
on his website as well). I found them in a back issue of Wired
magazine, in an article that applied them in
a critique some new gadget. I have since found that they increasingly
influence my own analysis of UIs and websites, and occassionally
use them as the basis for discussions with clients to keep a design
session on track.
The Laws are:
1. Reduce – The simplest way to achieve simplicity is through
thoughtful reduction of functionality.
2. Organize – Organization makes a system of many appear fewer.
3. Time – Savings in time feel like simplicity.
4. Learn – Knowledge makes everything simpler.
5. Differences – Simplicity and complexity need each other.
6. Context – What lies in the periphery of simplicity is de?nitely not peripheral.
7. Emotion – More emotions are better than less.
8. Trust – In simplicity we trust.
9. Failure – Some things can never be made simple.
10. The One – Simplicity is about subtracting the obvious, and adding the
meaningful.
You can find a more detailed explanation of each law on his site
guidelines for asp.net development
<!–
ASP.NET Development
guidelines
<!--[if !supportLists]-->·
<!--[endif]-->Guidelines
for ASP.NET AJAX
Performance Improvement
Among the 95% of the .NET developers that said they are
using some flavor of Ajax either in production, development or prototype, the
most used AJAX Framework is ASP.NET AJAX, with 73,7%, followed by the Ajax
Control Toolkit which is used by almost half of the .NET developer that are
using Ajax.
However ASP.NET AJAX model is showing performance problem.
The web application developed in ASP.NET AJAX makes the site slow down.
So following are the few of guideline which will help you
out to improve performance of ASP.NET AJAX application. This will basically
apply to the ASP.NET AJAX version 1.0 final release.
- Use HttpWatch to check the network traffic.
- This is one of important tool using which you can check the data returned by
the server. There is dedicated tool available for this. Moreover to that
you can also utilize Firebux extension of firefox to watch network
traffic. The dedicated tool is available for the download from following
URL: http://www.httpwatch.com/download/.This is a limited feature version.
- This is one of important tool using which you can check the data returned by
- Use "ScriptReferenceProfile" to show Javascript reference
- ScriptReferenceProfiler is an open source tool on CodePlex, for analysis the JavaScript
references of ASP.NET AJAX, we can simply add the following code to our
page in order to show the JavaScript references imported by
ScriptManager.<microsoft:scriptreferenceprofiler runat="server">
- ScriptReferenceProfiler is an open source tool on CodePlex, for analysis the JavaScript
</microsoft:scriptreferenceprofiler>
You can obtain it from the following URL
Reference: http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=13356
- Web.Config Optimization
- To have optimized web.config file our application, all we need to do is to
have a compression and caching is enabled in web.config file for the
ASP.NET AJAX Includes. You can use the following code in web.config file
to enable compression & caching for AJAX includes.<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="true" enableCaching="true"/>
</scripting>
</system.web.extensions>
Also check before and after result of before and after of enabling
caching & compression in network traffic.Now this is limited to the compression and caching for AJAX includes. In our site we also
generally have many other script files included. There can also be no. of
different CSS files, JS files etc. We can also compress them so that It make fewer request in bytes.Basically there is no any method available in ASP.NET which allows the
compression of JS & CSS files. We need to do it manually and
reference those compressed file in our application.One very key important point to consider is related to change management
of those files. Once you have compressed file in place and referenced in
your different pages, If your JS file or CSS
file need to have any modification, then you again have to recompress it
from newer version.So this method should be adopted for such scripts or CSS which are less
frequently changed.There are different tools available which allows your script and CSS file
compression. Following are the different methods which can be used for
this purpose.1) Yahoo compresser (http://yui.2clics.net/)
2) http://www.vlead.in/resources/tools/minify-javascript/index.php
(The best one which I utilized)
- To have optimized web.config file our application, all we need to do is to
- Optimization of ScriptManager
- The ScriptManager control manages client script for AJAX-enabled ASP.NET Web
pages. By default, the ScriptManager control registers the script for the
Microsoft AJAX Library with the page. This enables client script to use
the type system extensions and to support features such as partial-page
rendering and Web-service calls. Following, we need to setting
the property of ScriptManager to optimize the performance of ASP.NET
AJAX.
- The ScriptManager control manages client script for AJAX-enabled ASP.NET Web
<!--[if !supportLists]-->·
<!--[endif]-->Set "scriptMode" to Release.
for e.g.
<asp:ScriptManager ID="ScriptManager1″
runat="server" ScriptMode="Release">
</asp:ScriptManager>
Moreover to this set "debug" mode in "compilation" section of web.config file
to false.
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
<!--[if !supportLists]-->·
<!--[endif]-->Disable partial page rendering
If we using the UpdatePanel in the page, we must set this property to true,
conversely, if the UpdatePanel is not using in our page, it would be better
that we set the EnablePartialRendering to false.
For e.g.
<asp:ScriptManager ID="ScriptManager1″ runat="server"
EnablePartialRendering="false">
</asp:ScriptManager>
- Move All Script Tags After Body Content
- ASP.NET ScriptManager control has a property "LoadScriptsBeforeUI", when set to
false, should load all AJAX
framework scripts after the content of the page. But it does not
effectively push down all scripts after the content. Some framework
scripts, extender scripts and other scripts registered by Ajax Control
Toolkit still load before the page content loads.
- ASP.NET ScriptManager control has a property "LoadScriptsBeforeUI", when set to
So these are the basic general guidelines which can be
followed one by one to have an improved ASP.NET AJAX response.
<!--[if !supportLists]-->·
<!--[endif]-->Guideline
for ASP.NET Application Performance
Following, I will demonstrate some of important guideline
for the improvement of ASP.NET application. These guidelines should be
implemented carefully by taking into consideration of development needs. It is
not necessary to have all following steps followed.
- Removing unnecessary HTTP MODUES from site.
- There are several ASP.NET default HttpModules which
sit in the request pipeline and intercept each and every request.For example, if you aren't using Membership and Profile provider, you
don't need "FormsAuthentication" module. If you aren't using Windows
Authentication for your users, you don't need "WindowsAuthentication".We can remove those unnecessary references of HTTP modules from
web.config using <remove> tag.Generally following are the HTTP modules which are not generally used in
our current development architecture.<remove name="WindowsAuthentication" />
<remove name="PassportAuthentication" />
<remove name="AnonymousIdentification" />
<remove name="UrlAuthorization" />
<remove name="FileAuthorization" />
- There are several ASP.NET default HttpModules which
- Removing or compressing "VIEWSTATE" from page
- We can override few of method of default System.Web.UI.Page class of .net
framework.Use the following file and include it in your project's APP_CODE.
Inherits rest of all your pages from this page instead of regular System.Web.UI.Page
class.Ref: BasePage.vb
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
- We can override few of method of default System.Web.UI.Page class of .net
- Use caching for pages which changes less frequently
- There are several ways to use the cache; we'll focus on the easiest tricks to
get you started, then point you toward some resources that will help you
tackle more advanced ways to utilize the cache.The simplest solution is to use the OutputCache directive on your pages
or user controls.
- There are several ways to use the cache; we'll focus on the easiest tricks to
- Disable VIEWSTATE for pages where no Grid related functionality.
- One should set the VIEWSTATE disabled in those pages where there is no grid
level manipulation. When we have a simple page with no complex logic, it
should be disabled.Moreover to that set the following pages which are not security
sensitive.1) EnableViewStateMac="false"
2) ViewStateEncryptionMode="never"
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
- One should set the VIEWSTATE disabled in those pages where there is no grid
- Use classical ASP type of page for normal pages.
- Another important point is to use a classical ASP type of pages which are simple.
Those pages which do not have any complex display should be developed
like normal ASP pages. Please check the following referenced page for
this similar purpose.these are such files which do not have underlying code behind file
attached to it.We can also utilize the feature of "include" file method which is there
in classical ASP.
- Another important point is to use a classical ASP type of pages which are simple.
<!--[if !supportLists]-->·
<!--[endif]-->Guidelines
for structuring ASP.NET Application
In the following, I will demonstrate the basic guidelines
for the structuring of any web application.
See these guidelines are generally be best suitable for SEO
oriented sites. It can also be adopted for general site also keeping
requirement in mind.
These guidelines are prepared keeping modularized
development in mind. So there are no such tricks that by following them you
will be able to better structure your site. One should do the do modularized
development in their programming also to achieve this.
- Use dedicated folders for JS & CSS files.In a site generally there are different JS & CSS files for different
functionality. These JS & CSS files should be accordingly structure
inside your website. Please take a look at the following example for the
better illustration of this method.Say for e.g. in a site few pages have functionality to display a jQuery
zoom light box when anyone click on the image of product.So following should be the structure of JS & CSS files.
In this example, assume there are also few global JS & CSS. So I will
also demonstrate the purpose of integrating them in site.Root
|___js
| |___lightbox
| |___lightbox.js
|____|___global
|____jquery-1.2.6.min.js
|____common.js
|___css
| |___lighbox
| |___ lighbox.css
|________global
|____global.css
This modularization can also be used to
differentiate CSS & JS for each page of site.Modularization is also not limited to the CSS & JS files, one can
follow same modularization concept across different type of files also
like XML content, flash content, image folders etc.<!--[if !supportLineBreakNewLine]-->
<!--[endif]--> - Use proper naming conversion in CSS files.
- Care full design of CSS classes and attributes provide better traceability. As
you just shown above that the CSS & JS can be modularized. We should
also use proper naming convention in those CSS file. If you follow these
conventions, you can easily identify respective class.Say for e.g.
you set naming abbreviation of respective CSS as per below.
1) global.css
= glb2) lightbox.css = lg
so now you can have following CSS class/section defined in respective css
files.like in global.css
glb-main
{
}
.glb-title
{
color: #7D3D0D;
font-family: Arial;
font-size: 20px;
font-weight: normal;
text-decoration: none;
clear: both;
}
in the same way, you can also different class in lighbox.css
.lg-dvtop
{
width: 100%;
margin: 20px 10px 10px 10px;
}
.lg-content
{
width: 700px;
height: 600px;
}
- Care full design of CSS classes and attributes provide better traceability. As
- Configure
APP_CODE to have two sub directories. Each sub directory can be used for
different language. It is generally like following.APP_CODE
|___VB|___CS
Respective programming files should be placed in respective folders. Also
make sure to configure code sub directory in web.config also.
<!--[if !supportLists]-->·
<!--[endif]-->Guidelines
before final release of site
Following, there are some important and necessary checks
that web-sites should be checked against before the official launch.
- Favicon
- A favicon icon the tab or window in which your website is open in the
user's browser. It is also saved with the bookmark so that users can
easily identify pages from your website.for e.g.
<link href="images/fav_icon.ico" rel="icon"
type="image/Jpeg" />
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
- A favicon icon the tab or window in which your website is open in the
- Title & Meta data
- Your page title is the most important element for SEO and is also important so
that users know what's on the page. Make sure it changes on every page
and relates to that page's content.Also one should make sure that related meta data
details are also get placed in every pages and are changes as it should
be to different pages.
- Your page title is the most important element for SEO and is also important so
- Cross-Browser Check
- The most popular browsers to check are Internet Explorer 6, 7 and 8, Firefox
3, Safari 3. Following are the few methods used to do cross browser check1) XecoCode (http://www.xenocode.com/browsers/)
2) IETester (http://www.my-debugbar.com/wiki/IETester/HomePage)
3) Browser shot (http://browsershots.org/)
- The most popular browsers to check are Internet Explorer 6, 7 and 8, Firefox
- Links
- Don't just assume all your links work. Click on them. You may often forget to
add "http://" to links to external websites. There may be case when some
URL rewriting related prefix or postfix would be forgotten.
- Don't just assume all your links work. Click on them. You may often forget to
Getting dig into SQL CLR
SQL CLR is a new SQL Server feature that allows you to embed logic written in C#, VB.Net, and other managed code into the body of T-SQL objects like stored procedures, functions, triggers, aggregates and types. Client applications interact with these resulting routines like they are written in native T-SQL. Internally, things like string manipulations and complex calculations become easier to program because you are no longer restricted to using T-SQL and now have access to structured .Net languages and the reuse of base class libraries. Externally, the logic you create is wrapped in T-SQL prototypes so that the client application is not aware of the implementation details. This is advantageous because you can employ SQL CLR where you need it without rearchitecting your existing client code.
With SQL CLR, you are also freed from the constraint of logic that applies only within the context of the database. You can with appropriate permissions write logic to read and write to file systems, use logic contained in external COM or .Net DLLs. These capabilities are exciting and concerning, especially in the historical context of new feature overuse. To help you use this new feature appropriately, we want to make sure that you understand how it integrates with SQL Server and where this feature may be heading. In this chapter, we'll give you this type of overview. We'll spend the rest of the book explaining these concepts using real-world SQL CLR examples that you can use today.
Let's go through step by step for your first introduction on sql clr.
The first step in creating a stored procedure (or any database object) is to create a SQL Server project in Visual Studio:
- From the File menu, create a new project
- In the New Project Dialog, select and expand a language node in the Project Types area
- Select the Database node
- Select the SQL Server Project template
- Click OK and you are done
Next you will be promted of of creating sql connection to connect to sql server. But wait, before that your datebase and server need to be configured to run/host SQL CLR.
If you dont know how to do that just run the following code in your query window
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
Creating your first user defined CLR function
- Open an existing SQL Server Project, or create a new one. From the Project menu, select Add New Item.
- Select User Defined Function
- Type a Name for the new user defined function.
- Add code to run when the function is executed.
- In the following code snippet, i have written a custom user defined SQL CLR function which convert the european anccented characters into regular english character.
[Code]public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction( DataAccess = DataAccessKind.None, Name = "fnReplaceAccentedCharacters", IsDeterministic = true)] public static SqlString fnReplaceAccentedCharacters(SqlString inputString)
{
SqlString xReturnValue="";
Int16 a;
String[,] xCharGroup ={{"à", "a"}, {"â", "a"}, {"ä", "a"}, {"é", "e"}, {"è", "e"}, {"ê", "e"}, {"ë", "e"}, {"î", "i"}, {"ï", "i"}, {"ô", "o"}, {"ö", "o"}, {"û", "u"}, {"ü", "u"}, {"ù", "u"}, {"ç", "c"}, {"", "oe"}, {"", "oe"}, {" ", "-"}};
for (a = 0; a < xCharGroup.GetLongLength(0); a++)
inputString = ((String)inputString).Replace(xCharGroup[a, 0], xCharGroup[a, 1]);
return (xReturnValue=inputString);
}
};[/code]
Once the code is ready, you can build and deploy the code to the database by pressing 'F5′.
To test the deployment, there is a file in your project called test.sql. In this file, you can add script calls to the obects you just created. For example, to call the function created above, enter: Select dbo.fnReplaceAccentedCharacters('des objets de très grande qualité, originaux, épurés,')
That's it. If the stored procedure was written correctly, you will now see this item in list of functions in your management stuidio. However, you'll see the object has a lock icon next to it, as shown below. This is because the object is not editable outside of the Visual Studio project.
Monday, November 15, 2010
Software engineering fundamental
To understand the necessity for web engineering, we must pause briefly to look back at the recent history of computing. This history will help us to understand the problems that started to become obvious in the late sixties and early seventies, and the solutions that have led to the creation of the field of software & web engineering. These problems were referred to by some as "The software Crisis," so named for the symptoms of the problem. The situation might also been called "The Complexity Barrier," so named for the primary cause of the problems. Some refer to the software crisis in the past tense. The crisis is far from over, but thanks to the development of many new techniques that are now included under the title of software engineering, we have made and are continuing to make progress.
Although the topic I have written on is about very tiresome, even thought the importance of web/software engineering is very essential in all parts development life cycle. It's all about making your development process more sophisticated and well documented.
Let me first of all outline you the agenda which I am going to explain in this article.
- Nature of web/software project
- Engineering approach
- Software/web process
- A process steps
- Characteristics of a good process
- Role of waterfull model in the development
- Project planning
Next we will examine the different engineering approach that we can apply on our development process. Generally we understand the engineering is of field civil, mechanical, architectural etc. But engineering approaches can also be used in the development process to make it more simpler.
Then after we will take a look at the different software engineering process models available. We will then define the a practical software process steps and then we will also examine the characteristics of a good software process.
Nature of web/software project
We encounter may software or web application in the our day to day life. It may be of different domain, it may be simple, it can a large enterprise portal or can be a scientific for purpose.
Typically the nature of a software system can be:
- Ubiquitous, used in variety of area
Business, engineering etc.
- It can be simple to complex, internal or public, one location centric or distributed, real time, information purpose, help desk etc.
- Effort intensive
- High cost
- Continuous and log development
- User requirements frequently changes
- Risk of failure that can be performance issue, unable to accept response of user, maintainability of project etc.
Personally I feel that in most of development of either a web based project or enterprise application, the user's continues changing requirement never ends. In any project, the end user is the one who is going to give final review. Software engineers do make requirement engineering, but the due to many factor user's requirement keep on changing. Those factory may be managerial, market competition, changing in the government laws, marketing strategy etc. Because of these the user's requirement get changed.
Sometime everything goes well but when the final outcome of software/web project get released, it does not satisfy the user. The performance may not be upto the mark. The end user is not concern with the technical issue involved in development. They only concern for the quick and accurate output.
So these are the few hurdles that any software engineer or manager face in his past experience life.
So when can we say that software is successful:
- Software project have not always been successful.
- When do we consider a project is successful
- Development completed
- It is useful
- It is usable
- It is used
- Development completed
- Software should be cost effective & maintainable
- Schedule slippage
- Cost goes over
- Does not fulfill user's requirement
- Poor quality
Now let's consider that what are the reasons that lead to such failure.
- Unplanned development
- The milestones and deliverables are not identified
- User requirement changing/poor understanding user's requirement.
- No review control
- Technically the team is not matured
- Unsuccessful planning of cost by user & developer.
Let's think that you are a smart developer who plan for all his work before he actually going to implement. Then in that case the if the deliverables or milestones are not defined, we would not be able to judges the progress of development. Milestones/deliverables are most important in the development cycle. They tells about the progress of development. It help you to identify set up next goal in development.
Requirement engineering is one of the most crucial part in development life cycle. It is always been hard to identify and model user's requirement. If the user's requirement is not identified properly then the development can't proceed further.
Constant review or control is also important part of development. The inspection and review is heart in the quality assurance. The development need to be monitored by the supervisor so that we can actually come to know how the development is going.
The developer need to be constantly updated with the latest tools and technology. Sometime the company have the projects, but they do not have such experienced or skilled resource, due to which they postpone their effort in getting such projects. Nowadays the technology is keep on changing. So many tools and technology are emerging which can really solve your many development issues. The open source platform is one of the great example. There are thousand of scripts and tools are available over the internet that a developer can learn and implement. The developer need to be in touch with different community sites and build up their knowledge bank.
So these is what I want to tell about why we engineer the web/software. If we want to overcome those issue we really need to implement those software engineering and development process in our development.
So you will say that this is the end of my talk. No, I further want to tell you something regarding the engineering terms. After reading that much, you are really free to go by leaving your seat J.
"Engineering" a solution:
According to the definition given by the professor Sarda(IIT Bombay) a engineering is: To design, develop an artifact that meets specification efficiently, cost-effective and ensure quality.
Why the other engineering projects are successful than the software?
So to understand the reason of that, lets first go through what a large engineering project is made up of.
- Involve different type of peoples
Building project: civil engineers, electrical engineer, architects, workers etc.
- Continuous supervision for the quality assurance.
On site supervisor
- Many deliverables: architecture plan, model, structure diagrams, electric cabling etc.
- Standards need to be followed
- Steps and milestone are defined, reviewed and we proceed further. So the visibility of development is important aspect.
I will make you introduce with rest of discussion in my next series of articles.
So have a good time and have a productive coding.
DIWALI - story behing this festival
Also known as Deepawali and Deepotsav, this is the final day of the Hindu year.
Origin
Mankind is forever steeped in the misery of ãdhi (mental agony), vyãdhi (physical sufferings) and upãdhi (pain from external elements).
On the day when man is liberated from these, it becomes the day of Diwali, of bliss for him.
There are five stories celebrating this day:
- Shri Krishna vanquished Narkasur, releasing people from misery.
- Pruthu Raja extracted goodness from the earth.
- During the Samudra Manthan, Lakshmiji emerged from the ocean.
- The Pandavas returned from their forest exile.
- Shri Ramchandra returned to Ayodhya after his victory over Ravan in Lanka.
Rituals The Bhavishyottar Puran (140–14–29) cites details of how to celebrate Diwali from early morning.
- To augur success, those involved in trade and business do pujan of their new ledgers, known as Chopda Pujan (also known as Sharda Pujan).
- People light divas in their homes every evening.
- During Diwali it is a tradition in Hindu homes for the womenfolk to decorate a rangoli at the entrance or near the doorway, after washing the floor. A rangoli is an intricate and artistic design, using coloured powders. It represents an auspicious welcome for Lakshmiji, who visits people during Diwali to grant wealth.
- People forgive and forget misdeeds of the past year and resolve to spend the coming year in peace, harmony, purity and to earn lakshmi by observing dharma.
- On this the darkest (moonless) day of the month, people light divas symbolically, praying to Paramatma for inner enlightenment.
- Diwali is a festival to resolve personal discord and familial conflict, to increase love, unity and harmony in the family and society.
- Finally, since we are graced by the infinite love of God and his holy Sadhu, we should feel fulfilled and contented, known as purnakampanu. Therefore we should endeavour to consolidate our dharma, gnan, vairagya and bhakti, to further receive their benediction.
Sunday, November 14, 2010
.Net 3.5, C#, VB.Net Language Improvement: Automatic Properties, Object initializers, Collection Initializers, Lambda expression, Anonymous type.
The new .net 3.5 has significant improved features. This feature makes the .net programming concept more sophisticated. You will now be able to write less code and build more dynamic application using those.
From all of them what the most I like is the LINQ, which allow you to query over variety of objects.
LINQ is all about queries, they returns a set of matching objects, a single object, or a subset of fields from an object or set of objects. In LINQ, this returned set of objects is called a sequence.
Basically LINQ comes in variety of flavors' like following:
- LINQ to Objects
- LINQ to XML
- LINQ to Dataset
- LINQ to SQL
- LINQ to Entities
Well there is a detailed discussion on LINQ further in this article. Let me first make you guys introduce to the language improvements in .net 3.5. In fact I believe that these new improvements are essential to learn before we actually get dig into the LINQ J.
To summarize quickly, here are the list of new language feature that are shipped with .Net 3.5.
- Automatic properties
- Object initializers, Collection initializers
- Anonymous types
- Extension methods
- Query Expression
Well if you are the C# developer, I believe you will really love to have such significant improvement. Because these features puts extra wing on your programming skill.
The important is not that you learn the latest technology of .Net 3.5 like WCF, WPF, Silverlight etc. These are the core part of basic programming. Its like you should be knowing the if syntax of C programming language before you actually write your first "Hello word" program J
So let's go through each of them step by step and try to understand what they are and how it can help the developer to create rich internet/desktop application.
- Automatic Property
Before I explain you the concept of "automatic property in .net 3.5, can you guys first please try to go through the following code?
public
class
MShoppingCart
{
private
int _cartId;
public
int CartId
{
get { return _cartId; }
set { _cartId = value; }
}
private
int _customerid;
public
int Customerid
{
get { return _customerid; }
set { _customerid = value; }
}
private
int _billingaddressid;
public
int Billingaddressid
{
get { return _billingaddressid; }
set { _billingaddressid = value; }
}
private
int _shippingaddressid;
public
int Shippingaddressid
{
get { return _shippingaddressid; }
set { _shippingaddressid = value; }
}
private
MShippingCartItem _cartitem;
public
MShippingCartItem Cartitem
{
get { return _cartitem; }
set { _cartitem = value; }
}
}
Most of the time we are used to write such model classes. This are the most basic and popular mechanism in returning a wrapper classes. The basic purpose of writing such getter/setter property is to hide the actual private member of our classes. It has been the standard pattern to access the private method of any classes. Well you may arise with a question that why do we actually need to write such getter/setter properties. Can't we simply expose the private member? Well the answer is YES, but I would request you to remember the fundamental of object oriented programming. J
Anyway there are basically two reason of not doing so. Following are this:
- You won't be easily able to bind those private variable to controls
- You will not be able to modify them into property later on.
The first point is quite understandable, what do you mean by the second one? Well, say for e.g. if you need to add any business logic or validation logic when assigning value to any private variable then? You will not be able to do that.
So what if we need not to write even the private variables? Exited, yes the new version of .Net 3.5 allows you have such facility. The concept is called automatic property. All you have to do is to write the getter/setter property. You need not to worry about the private member of that property. The compiler will decide and prepare base private member for you on the fly.
See the example in the following.
public
class
MShoppingCart
{
public
int CartId
{
get;
set;
}
public
int Customerid
{
get;
set;
}
public
int Billingaddressid
{
get;
set;
}
public
int Shippingaddressid
{
get;
set;
}
private
MShippingCartItem _cartitem;
public
MShippingCartItem Cartitem
{
get;
set;
}
}
Now it this case when the compiler will encounter this properties while compiling your code, it will automatically expose the private variable for each of property with its associated type. For e.g. compiler automatically assume and expose the _cartid private variable of integer type. Using advantage of this is we need not to worry about the underlying private variable. In future we can add any sort of validation logic in this property.
- Object initialization, collection initialization
I would like to explain this concept by taking the example of automatic property so that I maintain the continuity for you to understand. Say for e.g. when we want to use the "shopping cart" class that we created earlier. What we do is write following code.
MShoppingCart cart = new
MShoppingCart();
cart.CartId = 1;
cart.Customerid = 1001111;
cart.Shippingaddressid = 2333;
cart.Billingaddressid = 2232;
With the feature supported by the .net framework 3.5, you can take advantage of what is called "syntactic sugar", and that is object initializers.
Using object initializers, you can write the same code given above, in following way.
MShoppingCart cart = new
MShoppingCart {CartId =1, Customerid=1001111, Billingaddressid=2232, Shippingaddressid =23333 };
So it allows you to pass the value of all property at the time of initializing the object.
In fact it not only allow to initialize object's property in this way, you can also have nested initialization of object within any object.
To demonstrate you, see the following example.
MShoppingCart cart = new
MShoppingCart { CartId = 1, Customerid = 1001111, Billingaddressid = 2232, Shippingaddressid = 23333, Cartitem = new
MShippingCartItem { } };
If you see in the highlighted (underlined) part of above code, you can clearly see that the child object can also be initialized in the same way.
As if the new object initialization enhancements were not enough, someone at Microsoft must have said, "What about collections?" Collection initialization allows you to specify the initialization values for a collection, just like you would do for an object, as long as the collection implements the
System.Collections.Generic.ICollection<T> interface.
List<string> presidents = new
List<string> { "Name 1″, "Name 2″, "Name 3″ };
foreach (string president in presidents)
{
Console.WriteLine(president);
}
- Anonymous types
What is anonymous type?
Well, we have been familiar till date with different types. They are either custom classes or any of .net's build in type. So what is actually the anonymous type is. The answer is that the "Anonymous type" has no type defined to it. It has no type name. Though there should be at least one type name associated in .Net. In anonymous type, the type name is specified by the developer doing the programming. It is the compiler which will identify the type to associate with the declaration of any anonymous type.
There is also another significant different in anonymous type is that it is called immutable. The definition of immutable type is that the one that is declared and initialized once. It can't be altered later on. So anonymous type has the same characteristic. Once you declared and initialized, you can't alter the anonymous type afterward.
This is also why anonymous types have been introduced. They allow us to create a type on the fly and therefore return only certain values of a given named type. This is very handy when only a subset of properties is needed, properties are joined together or even objects are joined together.
class
Program
{
static
void Main(string[] args)
{
// create a list of carts with dummy data.
List<MShoppingCart> carts = new
List<MShoppingCart>();
carts.Add(new
MShoppingCart { CartId=101, Customerid=1001, Billingaddressid=20, Shippingaddressid =30});
carts.Add(new
MShoppingCart { CartId = 102, Customerid = 1002, Billingaddressid = 22, Shippingaddressid = 33 });
carts.Add(new
MShoppingCart { CartId=103, Customerid=1003, Billingaddressid=23, Shippingaddressid =34});
// query the cart collection to collect cart with id of 101
var result = from c in carts
where c.CartId >= 101
// put the result in a anonymous type
select
new { c.Billingaddressid };
// loop over the result.
foreach (var item in result)
{
// print out the name of the item.
Console.WriteLine(item.Billingaddressid );
}
}
}
Anonymous type are mostly used when working with the LINQ. It is utilized highly while querying to your data in LINQ. It is irrespective which flavor of LINQ you are using.
Although the anonymous type can be used in your own code also. It is especially useful when we want to combine different variables into one.
Se for e.g. following example:
// create an anonymous type instance with a name.
var anonymousType = new
{
Name = name,
Age = age,
Nationality = nationality
};
// print the name to the console.
Console.WriteLine(anonymousType.Name);
Though the real time use of anonymous type Is when you use it with the LINQ. I need to write a separate article to demonstrate you actual usage LINQ. J
- Extension methods
An extension method is a static method of a static class that you can call as though it were an instance method of a different class.
To make you understand the extension method, let me first re cape the class level methods (static methods) and instance methods. The primary different between these two is that the instance method can also be access by initializing object of any class. It can't be invoked by using class name only. The exact opposite of that is class method. You can only call static class method using the name of class only. You can't access them using the instance of same class.
I am not gonna give you any example for the above explanation as I expect from you guys that you are familiar with the different I explained.
Extension method is a way of extending existing classes for whatever additional functionality. Let me demonstrate you that by example.
namespace ExtensionMethods
{
public
static
class
StringExtensionMethods
{
public
static
bool IsNumeric(this
string str)
{
try
{
int i = int.Parse(str);
return
true;
}
catch
{
}
return
false;
}
}
}
In the above given example, almost everything seems to be similar what we are used to in normal programming. But, the difference is clearly seen. You should be able to notice that in the "IsNumeric" static method parameter are passed using this keyword. This keyword tells the compiler what you are going to extend for particular given type. So in this example it tells you that it extends the existing string class.
See for e.g. how to use the extension method.
string s = "someValue";
bool bs = s.IsNumeric();
// bs is false;
string i = "7″;
bool bi = i.IsNumeric();
// bi is true;
- Query Expression
One of the conveniences that the C# language provides is the foreach statement. When you use foreach, the compiler translates it into a loop with calls to and MoveNext. The simplicity the foreach statement provides for enumerating through arrays and collections has made it very popular and often used.
One of the features of LINQ that seems to attract developers is the SQL-like syntax available for LINQ queries. The first few LINQ examples in the first chapter of this book use this syntax. This syntax is provided via the new C# 3.0 language enhancement known as query expressions. Query expressions allow LINQ queries to be expressed in nearly SQL form. To perform a LINQ query, it is not required to use query expressions. The alternative is to use standard C# dot notation, calling methods on objects and classes.
Although it is occupy a dedicated book for detail understanding of query expression with LINQ. Just to summarize you, here is the example that shows you what actually query expression does.
For e.g.
string[] names = {
"Adams", "Arthur", "Buchanan", "Bush", "Carter", "Cleveland",
"Clinton", "Coolidge", "Eisenhower", "Fillmore", "Ford", "Garfield",
"Grant", "Harding", "Harrison", "Hayes", "Hoover", "Jackson",
"Jefferson", "Johnson", "Kennedy", "Lincoln", "Madison", "McKinley",
"Monroe", "Nixon", "Pierce", "Polk", "Reagan", "Roosevelt", "Taft",
"Taylor", "Truman", "Tyler", "Van Buren", "Washington", "Wilson"};
IEnumerable<string> sequence = from n in names
where n.Length < 6
select n;
foreach (string name in sequence)
{
Console.WriteLine("{0}", name);
}
Though query expression can be used by two different way. 1) is using dot notation and 2) is using expression syntax.
Hope I could make you understand what are the new improvements in the newer version of .net 3.5.
Once you are aware and familiar with this feature, you are ready to get dig into dip into the word of .net 3.5 for all new existing experience in developing rich internet/enterprise application.
Debate - Asp.net vs. PHP
It has been a debate from long time that who is faster, asp.net or php?
So many times I have heard php guyes claim that php is so much faster than Asp.Net and that Asp.Net is clunky and slow.
I have collected few of important resource to make it very clear.
See basically both the development are different like two side of coin. Each of it have its own purpose to choose for your development need. It highly depend how is your requirement.
Any way check from here to get more detail on this debate.
http://bit.ly/4Fdqa9
http://bit.ly/QMgQy
http://misfitgeek.com/blog/aspnet/php-versus-asp-net-ndash-windows-versus-linux-ndash-who-rsquo-s-the-fastest/
Cheers
Combine/Compress/Minify JavaScript, CSS in Asp.net
Combine/Compress/Minify JavaScript, CSS in Asp.net
Introduction:
When we design and develop the website, the performance is in the core of development. The system you are developing must produce the result with high speed. For the web development perspective, website load performance is very essential thing to take care of. You need good working layout, easy layout and easy navigation.
Here with this article I m not going to talk about of all the aspects of web application performance improvements. But I am specifically targeting the topic when it comes to the CSS and JavaScript faster loading in the client browser. In fact Google is also counting the speed of your website site when indexing to your website.
The goal was to improve overall performance on the client side. At the same time, it will show how we can force a client side script to be coached at the browser, so that in subsequent visit, it will take those scripts from the cache. This becomes increasingly important when using AJAX techniques within an application that introduce new features and functionality.
First of all I will outline the requirements and essential steps that this project is made of. So that if you want to implement the same in your development, it become easy for you to set up project.
To download complete project, click here
Setup:
To begin with, we will have following list of files to be created in the development studio.
- 2 XML files, first one to hold source of JS files for each page and second to hold CSS files for each page.
- A generic class that implement IHttpHandler, that will be used to delivery combined and compressed JavaScript/CSS at the client.
- And at last your .ASPX file that will be used to serve combined and compressed Javascript/CSS at client side.
Step by Step Implementation:
Now let's get dig into the actual development. To summarize, let's say we have a page default.aspx that has following no. of JavaScript files and CSS files. Think of these file that we wanted to combine them and deliver at one go at the client browser.
- jquery.js
- script-file-1.js
- style-1.css
- style-2.css
As you can see, we have 2 different JavaScript file & 2 CSS files. So what basically we will do in the next is to create a utility which can combine given JavaScript and compress it, then send it to client browser. Next the same process will be done for the CSS. Both the CSS files will be combined and compressed and send to client browser.
Now it's time to take a look at into actual stuff that does this underlying work.
First of all we will create a CS class file that will hold the programming stuffs.
So perform the following steps to create & configure that CS class file.
- Create CS class file with the name ScriptCombiner.cs and put the following code in that.
public
class
ScriptCombiner : IHttpHandler
{
private
readonly
static
TimeSpan CACHE_DURATION = TimeSpan.FromDays(1);
private
HttpContext context;
public
void ProcessRequest(HttpContext context)
{
}
public
bool IsReusable
{
get { return
true; }
}
}
As you can see, we are implementing the IHttpHandler interface.
You can write custom HTTP handlers to process specific, predefined types of HTTP requests in any Common Language Specification (CLS) compliant language. Executable code defined in the HttpHandler classes, rather than conventional ASP or ASP.NET Web pages, responds to these specific requests. HTTP handlers give you a means of interacting with the low-level request and response services of the IIS Web server and provide functionality much like ISAPI extensions but with a simpler programming model.
We are also implementing IsReusable properly as it is compulsory to implement as a part of inheritance of IHttpHandler interface.
Now, let's put the nuts & bolts inside the ProcessRequest function. I will also explain you the step by step each execution that is inside this function.
- We will also create another CS class file that is used to compress JavaScript. That file is named as "JavaScriptMinifier.cs". Please take a look at the attached project solution file. As it is contain long lines of code, I can't put it here.
- Complete your class file with following functions.
public
void ProcessRequest(HttpContext context)
{
string xStrType, xStrSet, xStrVer, xStrpagecode;
Boolean xBlnCanCompress;
this.context = context;
HttpRequest request = context.Request;
xStrType = (!String.IsNullOrEmpty(request["type"])) ? request["type"] : null;
xStrSet = (!String.IsNullOrEmpty(request["s"])) ? request["s"] : null;
xStrVer = (!String.IsNullOrEmpty(request["v"])) ? request["v"] : null;
xStrpagecode = (!String.IsNullOrEmpty(request["pcode"])) ? request["pcode"] : null;
//first check if client browser can support compressions
xBlnCanCompress = CanClientGZip(request);
using (MemoryStream memStream = new
MemoryStream(8092))
{
Stream writer;
//if browser is supporing GZip compression then create a new object using ICSharpCode.SharpZipLib.GZip
//library which allow the compressed respose to send to client
if (xBlnCanCompress)
writer = (new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(memStream));
else
writer = memStream;
using (writer)
{
//now its time to read all the script/css files into a StringBuilder object.
StringBuilder combinedSource = new
StringBuilder();
foreach (string file in GetFileNames(xStrSet, xStrpagecode, xStrType))
combinedSource.Append(System.IO.File.ReadAllText(context.Server.MapPath(file), Encoding.UTF8));
//Upto now we have combined all css/javascript based on request.
//its now time to remove extra white spaces and other unwanted characters from respose.
//compression will take place now.
string minified;
//use the YUI Javascript/CSS minifier to compress all js files
if (xStrType == "js")
minified = combinedSource.ToString();
else
minified = CompressCSS(combinedSource.ToString());
// Send minfied string to output stream
byte[] bt = Encoding.UTF8.GetBytes(minified);
writer.Write(bt, 0, bt.Length);
}
//cache the respose so that in next request it can be reused
byte[] responseBytes = memStream.ToArray();
//context.Cache.Insert(GetCacheKey(xStrSet, xStrType, xStrVer, xBlnCanCompress), responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration, CACHE_DURATION);
// Generate the response
this.WriteBytes(responseBytes, xBlnCanCompress, xStrType);
}
}
private
bool CanClientGZip(HttpRequest request)
{
string acceptEncoding = request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(acceptEncoding) &&
(acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
return
true;
return
false;
}
// helper method that return an array of file names inside the text file stored in App_Data folder
private
static
string[] GetFileNames(string setName, string pagecode, string type)
{
System.Xml.XPath.XPathDocument doc2;
System.Xml.XPath.XPathNavigator navigator;
System.Xml.XPath.XPathNodeIterator iterator;
System.Collections.Generic.List<string> scripts = new System.Collections.Generic.List<string>();
string key;
if (type == "js")
key = "scriptfile";
else
key = "cssfile";
if (System.Web.HttpContext.Current.Cache[key] != null)
{
doc2 = (System.Xml.XPath.XPathDocument)System.Web.HttpContext.Current.Cache[key];
}
else
{
string filename;
filename = System.Web.HttpContext.Current.Server.MapPath(String.Format("~/App_Data/{0}.xml", setName));
doc2 = new System.Xml.XPath.XPathDocument(filename);
System.Web.HttpContext.Current.Cache.Insert(key, doc2, new System.Web.Caching.CacheDependency(filename), DateTime.Now.AddMinutes(60), TimeSpan.Zero);
}
navigator = doc2.CreateNavigator();
if (type == "js")
iterator = navigator.Select("/scripts/page[@pagecode='" + pagecode + "']/script");
else
iterator = navigator.Select("/styles/page[@pagecode='" + pagecode + "']/style");
while (iterator.MoveNext())
scripts.Add(iterator.Current.InnerXml);
return scripts.ToArray();
}
private
string GetCacheKey(string type, string setName, string version, bool cancompress)
{
return
"HttpCombiner." + setName + "." + type + "." + version + "." + cancompress;
}
private
void WriteBytes(byte[] bytes, bool isCompressed, string type)
{
HttpResponse response = context.Response;
response.AppendHeader("Content-Length", bytes.Length.ToString());
if (type == "js")
response.ContentType = "application/x-javascript";
else
response.ContentType = "text/css";
if (isCompressed)
response.AppendHeader("Content-Encoding", "gzip");
else
response.AppendHeader("Content-Encoding", "utf-8″);
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
context.Response.Cache.SetMaxAge(CACHE_DURATION);
response.ContentEncoding = Encoding.Unicode;
response.OutputStream.Write(bytes, 0, bytes.Length);
response.Flush();
}
public
static
string GetScriptTag(string setname, string pageid, string type, string ver)
{
string result = "";
if (type == "js")
result += String.Format("<script type=\"text/javascript\" src=\"/" + Web.Utility.Functions.GetURLPrefix() + "ScriptCombiner.axd?s={0}&v={1}&type=js&pcode={2}\"></script>", setname, ver, pageid);
else
result += String.Format("<link link href=\"ScriptCombiner.axd?s={0}&v={1}&type=css&pcode={2}\" rel=\"stylesheet\" type=\"text/css\"/>", setname, ver, pageid);
return result;
}
public
static
string CompressCSS(string body)
{
body = Regex.Replace(body, "/\\*.+?\\*/", "", RegexOptions.Singleline);
body = body.Replace(" ", string.Empty);
body = body.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, string.Empty);
body = body.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
body = body.Replace(Environment.NewLine, string.Empty);
body = body.Replace("\\t", string.Empty);
body = body.Replace(" {", "{");
body = body.Replace(" :", ":");
body = body.Replace(": ", ":");
body = body.Replace(", ", ",");
body = body.Replace("; ", ";");
body = body.Replace(";}", "}");
body = Regex.Replace(body, "/\\*[^\\*]*\\*+([^/\\*]*\\*+)*/", "$1″);
body = Regex.Replace(body, "(?<=[>])\\s{2,}(?=[<])|(?<=[>])\\s{2,}(?= )|(?<=&ndsp;)\\s{2,}(?=[<])", string.Empty);
return body;
}
You are now almost done with 50% of work for your project.
Now let's take a look at the few of important execution steps that are in this function.
First of all we are declaring four different string variables:
string xStrType, xStrSet, xStrVer, xStrpagecode;
They will be used to get the Querystring passed in to this handler. This is utilized later on the code.
Moving next, you will find these function call:
//first check if client browser can support compressions
xBlnCanCompress = CanClientGZip(request);
This is basically to check does client browser support GZip compression.
Gzip compression, otherwise known as content encoding, is a publicly defined way to compress textual content transferred from web servers to browsers. HTTP compression uses public domain compression algorithms, like gzip and compress, to compress XHTML, JavaScript, CSS, and other text files at the server. This standards-based method of delivering compressed content is built into HTTP 1.1, and most modern browsers that support HTTP 1.1 support ZLIB inflation of deflated documents. In other words, they can decompress compressed files automatically, which saves time and bandwidth.
In the next step it is preparing the stream object used to hold the response output. We will not take dipper look into that code. As I expect that the a beginning developer even must be able know about next few line of code. J
Let's move to the line of code:
//now its time to read all the script/css files into a StringBuilder object.
StringBuilder combinedSource = new
StringBuilder();
foreach (string file in GetFileNames(xStrSet, xStrpagecode, xStrType))
combinedSource.Append(System.IO.File.ReadAllText(context.Server.MapPath(file), Encoding.UTF8));
As you can see in the foreach loop, it is calling to method GetFileNames, by passing 3 different parameters. Here this is also core and important part of this project. Let me outline you first what this function basically do. This function will read to the "script.xml" file that hold content of script file that we want to load. Please look inside the attached project solution to understand it better. The function will read xml file and return array of string object containing JavaScript files to read.
In the subsequent line of code, it iterate through each file name and read it. Each content of read file is placed inside a StringBuilder object.
Please take look at the code inside the GetFileNames function to understand what is actually happening inside it. It fetches the JavaScript/CSS based on the parameter passed. And return either the JavaScript file name array or CSS file name array.
So now we have a combined script/CSS with us. It's a time to minify JavaScript/CSS now.
Following line of code will minify respective JavaScript/CSS based on type of client script requested.
//use the YUI Javascript/CSS minifier to compress all js files
if (xStrType == "js")
{
JavaScriptMinifier minifier = new
JavaScriptMinifier();
minified = minifier.Minify(combinedSource.ToString());
}
else
{
minified = CompressCSS(combinedSource.ToString());
}
The JavaScriptMinifier has been created in the 2nd step. Please refer to the attached solution project for more detail regarding this class file. I have adopted this class file from one of the article
You will also see function CompressCSS that is used to compress CSS file. The compressor of CSS file is done through just few regular expression. JavaScript compression has different algorithm.
After that it is calling to WriteBytes function that will prepare the combined & compressed JavaScript & CSS response and send it to the client.
Hurray as part of implementation we are done.
Now it's time to check that in action. You can run the project attached here with and check it In live action.
To download complete project, click here
Let's compare the result of two different pages. The first one is with the compressed JavaScript & CSS. The second one is with the normal JavaScript & CSS. We will also see the difference in load time and size of content received.
Response time with compressed JavaScript & CSS.
Response time without compressed JavaScript & CSS.
As you can see from given statistics
With Combined & Compressed JavaScript and CSS ..
Total request: 3
Response size: 16.3 KB
Without Combined & Compressed JavaScript and CSS ..
Total request: 5
Response size: 96 KB
You can clearly see the difference between these two request.
To get more idea open and run the project yourself. That will give you better idea.
Hope you will find it very useful.
Happy coding . J