http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx
Here you can see ternary operator returns one of the two values based on the condition. See following example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Blogging
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Response.Write("Page is not postback");
}
for (int i = 1; i <= 20; i++)
{
Response.Write(i.ToString());
}
}
}
}
Now I want to hide the following Page.IsPostBack part via right click Outlining –> Hide Selection
Recently in one the project we require to check whether page is secure or not as we are going to open a new popup window from that page and that why we need to pass https protocol if we have that page secure. I have search lots of things on internet and I have found following ways of finding whether page is secure or not in ASP.NET or JavaScript.
In ASP.NET There are two way of doing it. Either we can use current request to check whether it is secured or not or we can use server variables to check whether it it secure or not just like following.
HttpContext.Current.Request.IsSecureConnectionHere in above code If this returns true then Page is secured otherwise it is not Or you can use following server variable to check the protocol.
Request.ServerVariables["SERVER_PROTOCOL"];In JavaScript you can document.location.protocol to check whether page is secure or not. Just like following.
document.location.protocol=='https:'So you can see its very easy to check whether page is secure or not. Hope you liked it… Stay tuned for more..
While developing a windows service using Linq-To-SQL i was in need of something that will intersect the two list and return a list with the result. After searching on net i have found three great use full operators in Linq Union,Except and Intersect. Here are explanation of each operator.
Union Operator: Union operator will combine elements of both entity and return result as third new entities.
Except Operator: Except operator will remove elements of first entities which elements are there in second entities and will return as third new entities.
Intersect Operator: As name suggest it will return common elements of both entities and return result as new entities.
Let’s take a simple console application as a example where i have used two string array and applied the three operator one by one and print the result using Console.Writeline. Here is the code for that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] a = { "a", "b", "c", "d" };
string[] b = { "d","e","f","g"};
var UnResult = a.Union(b);
Console.WriteLine("Union Result");
foreach (string s in UnResult)
{
Console.WriteLine(s);
}
var ExResult = a.Except(b);
Console.WriteLine("Except Result");
foreach (string s in ExResult)
{
Console.WriteLine(s);
}
var InResult = a.Intersect(b);
Console.WriteLine("Intersect Result");
foreach (string s in InResult)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}
Hope this will help you..
In ASP.NET controls used in to the user controls are generate Client Id which unique for the control and If you have so many user controls hierarchy then you will have very long client id like ‘ctl00_CPH_ctl02_BM_userLogin_UserName’.It will increase the Kilo Bytes of html rendered in the browsers. Label control is the control which is used to display text and its render as span tag in the html render by the browser. So in such type of scenario if you have so many label controls then your html is going to increase very much. And overall it will decrease the your application performance.
In asp.net 4.0 we can manage the Client Id via different options i have already posted over here. But for asp.net 3.5 and lower version we have to write our own code for doing that there are two options either we have to create a our own custom control inherited from label which override the ClientID generated by system or we can use the span tag instead of label control because ultimately label control will be rendered as span tag in browser.
We having same scenario in the one of the project we are having so many label controls in one of the form in our page. So it is going to kill our application because rendered HTML will be heavy. So we have decided to use span tag. Now you guys are having questions that how we can manage span text from the server side we have used static string variables for to manage the text of span. Let’s create a simple example to understand how its works.
We have created a static string which will contain the text for the label. We are assigning text in page_load event of page or control then we have used that static string directly in html in between span tag which will have same style sheet as label control. Following is code for that.
protected static string UserName;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//asssign text here for first time
UserName = "User Name";
}
}
<span class="label"><%=UserName%></span>That’s it will render span tag in your browser with same look as label and there will not be any id generated for this span tag and ultimately your html rendered in browser will have less Kilo Bytes. We able to reduce 10 to 12 KB bytes of our page via this technique. Hope this will help you too..
Singleton pattern is very popular pattern used by programmer. The idea behind the singleton pattern is to have only one instance of a class at any time. This kind of pattern is very useful for for heavy resources like Linq Data Context etc. It is also useful in multithreaded application where different thread of application try to crate instance of one class but it should be thread safe. It can be also useful for global resources and state objects. In singleton class there are two things required. One static variable which hold the instance of class and other is a static method which will return the instance of singleton class. Here is the example of singleton class
public class MySingleTon
{
private static MySingleTon mySingleTonInstance = new MySingleTon();
private MySingleTon()
{
//private constructor
}
public static MySingleTon GetInstace()
{
return mySingleTonInstance;
}
}
MySingleTon objSingleTon = MySingleTon.GetInstace();The above example is not thread safe so it may be possible that different thread can create different instance of classes. To make above singleton class thread safe we need to change code like following.
public class MySingleTon
{
private static MySingleTon mySingleTonInstance = new MySingleTon();
private MySingleTon()
{
//private constructor
}
public static MySingleTon GetInstace()
{
lock (typeof(MySingleTon))
{
if (mySingleTonInstance == null)
{
mySingleTonInstance = new MySingleTon();
}
return mySingleTonInstance;
}
}
}
While taking interviews for Microsoft.NET i often ask about indexer classes in C#.NET and i found that most of people are unable to give answer that how we can create a indexer class in C#.NET. We know the array in C#.NET and each element in array can be accessed by index same way for indexer class a object was class can be accessed by index. Its very easy to create a indexer class in C#. First lets looks some points related to indexer class in C#.
Let’s create simple indexer class with single parameter and for string type.
public class MyIndexer
{
private string[] MyIndexerData;
private int SizeOfIndexer;
//declaring cursor to assing size of indexer
public MyIndexer(int sizeOfIndex)
{
this.SizeOfIndexer = sizeOfIndex;
MyIndexerData = new string[SizeOfIndexer];
}
public string this[int Position]
{
get
{
return MyIndexerData[Position];
}
set
{
MyIndexerData[Position] = value;
}
}
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int indexSize=5;
MyIndexer objMyIndexer = new MyIndexer(indexSize);
for (int i = 0; i < indexSize; i++)
{
objMyIndexer[i] = i.ToString();
Console.WriteLine("Indexer Object Value-[{0}]: {1}",
i, objMyIndexer[i]);
}
Console.ReadKey();
}
}
}
Technorati Tags: Indexer,C#,Array
In C# we are having automatic properties since C# 3.5 framework but now with Microsoft.NET 4.0 Framework VB.NET 10.0 version we are also having automatic properties for VB.NET Also.
Like in C# we can define automatic like following.
Public string TestProperty
{
get;
set;
}
Public Property TestProperty As String
I am loving more and more visual studio 2010 for some of the cool things. One of the new feature i have found in visual studio 2010 is the selected text. In the earlier version of visual studio 2010 when we select tax then its not maintaining the highlighted code but with visual studio 2010 it is maintain the colored syntax. Isn't that cool?. We can still know that what we are selecting. Like following.
As we all know we any web page on the internet is state less. We have to write our own mechanism to maintain state between httprequest and httpresponse. Asp.net has great features called viewstate to maintain state during page postback. It will store the element state in hidden variables with _VIEWSTATE. It will look like below.
If you are having large amount of controls then you will have larger viewstate on the page and it will increase your html kb as well as your performance. So to increase the performance of our application we need to store this viewstate in other place. ASP.NET 2.0 has nice new class called SessionPagePersister which will store the viewstate in the session. You just need to override the PageStatePersister property in your page and your viewstate will be on the page.
Here is the code.
If you are having so many pages then you have to write that cod manually Instead of doing this you can use inheritance features of C#.NET to write the code in just one way and then inherit your page from that class. Following is the code for that. You can create a class called MyPage that class into all the pages here is the code for class MyPage .
and Then inherit the class in your page like following.
So that's it that way you can increase your application performance via maintaining the viewstate in session. Happy Codding..
In asp.net 3.5 there is one good features called extension method now you can extend your functionality without modifying existing classes. Extension method allow developers to add own functionality to any existing classes. You don't need to create subclass or don't need to recompile existing classes and still you can extend that class with extension methods. Let's create an example to extend existing string classes to convert a simple string to bold html string.
So now our extension method is ready. Following the sample code to use this extension method.public static class MyExtensions{public static string ConvertToBold(this string mystring){System.Text.StringBuilder myBoldString =new System.Text.StringBuilder(string.Empty);myBoldString.Append("<strong>");myBoldString.Append(mystring);myBoldString.Append("</strong>");return myBoldString.ToString();}}
While running application you can out like below.protected void Page_Load(object sender, EventArgs e){string helloWorld = "Hello World";Response.Write(helloWorld.ConvertToBold());}
Microsoft SQL Server are one of the popular RDBMS(Relational Database Management System) all over world. Before some time Microsoft has launched the new version of SQL Server 2008. SQL Server 2008 provides the highest levels of security, reliability, and scalability for your business-critical applications. . Following are the some of new features of SQL Server 2008.
and many more features are there. It's great rdbms to use in your future projects. Please visit following link to explore above features in great details.
http://www.microsoft.com/sqlserver/2008/en/us/whats-new.aspx
You can download SQL server 2008 Express database for free from following link.
When asp.net page loaded in to browser there are lots of white spaces between tags and in tags that will increase your html kb. For example if your page around 300 kb then it will take 3 second to load on 100 kbps internet connection and in dial up connection it will still take time. So if you want to load your site fast on dial up internet connection then you need to decrease html kb as much you can and removing white spaces from the html will be good idea for that.
Following is the code for the page on which you want to remove white spaces from the html. It will decrease your html kb by 30 percentage.
private static readonly Regex REGEX_FOR_TAGS = new Regex(@">s+<", RegexOptions.Compiled);
private static readonly Regex REGEX_FOR_BREAKS = new Regex(@">[\s]*<",
RegexOptions.Compiled);protected override void Render(HtmlTextWriter writer){using (HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter())){base.Render(writer);string htmlkb = writer.InnerWriter.ToString();htmlkb = REGEX_FOR_TAGS.Replace(htmlkb, "> <");htmlkb= REGEX_FOR_BREAKS .Replace(htmlkb, "><");writer.Write(html.Trim());}}
Here in the above code there are two regular expression one for white space in tag and another for whitespace between tag and by just overriding the render event of event you can replace the whitespace.
Happy Coding...
Technorati Tags: HTMLKb,ASP.NET,Whitespace,Performance
Client Id is used to store the id of a server control in client side. ASP.NET Engine creates a very long client id to unique identify each element on the same page. If you are having so many inner controls hierarchy then asp.net will generate very long client id like “ctl00_Ctl001_ctl02_BM_Login_btnSave” here i i have used control name like ctrl00,ctr001,bm etc. If you are having long control name then it will more longer then this. This will increase html kilobytes for the pages and if you are having so many server controls in the page then it will take time to load in browser and will decrease performance of application . To overcome this problem we have to override existing asp.net controls like textbox,label etc and then you have override client id from server side with server side id. Now with asp.net 4.0 you can control client id generated by .net framework. In asp.net 4.0 there is one another property called ClientIdMode which will control the behavior of client id generated by .net framework. Like following.
<asp:Button ID="btnSave" runat="server" ClientIDMode="[Mode]" />
There are four types of different mode for ClientIdMode property.
Instead of this you should use.string alertScript = "javascript:alert('Alter From asp.net page')";ClientScript.RegisterStartupScript(typeof(Page),"alertscript", alertScript);
This will work. Happy coding..string alertScript = "javascript: alert('This is aler from asp.net page')";ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript,true);
Microsoft Silvelight 2.0 has been great success for the Microsoft. There lots of rich user friendly animated application is designed with Microsoft Silvelight 2.0. Now with Microsoft has added some new features to Silverlight 3.0. It includes major media enhancement,allowing web applications to view on desktop, Graphic improvement for 3D Support, GPU Acceleration and H-264 Support etc. Following is new feature list for silvelight 3.0
There are many more features. To know more about him please visit following link. http://silverlight.net/getstarted/silverlight3/default.aspx
If you have any question then you can ask here in silverlight community.http://silverlight.net/Community/
You can get started with silvelight 3.0 with following. Its will be great help and tools available on following link. http://silverlight.net/GetStarted/
With C# 2.0 Microsoft has added partial keyword in C#. So what is partial keyword used for. Lets go through the partial keyword in greater detail.
First and foremost use of the partial keyword is the you can declare one class or method with more then one declaration and at the compilation time it will have one complete class.So now you can declare a class more then one file at the compile time it will be treated as one class.
For example this is one class
//first file Patial Classpublic class partial PartialClass{public void First(){//First function}
}
Here is the another class
Now at the compile time it will be treat as single class like following.public class partial PartialClass{public void Second(){// Logic...}}
Same way you can use partial method it will treated as one method as compile time. Partial method will only available with C# 3.0. It will not be available to C# 2.0.public class PartialClass{public void First(){// Logic...}public void Second(){// Logic...}}
Practical Usage Of Partial Class:
There are lots of way where partial class is useful like many developer can work on same class via creating different files. There are lost of code generators available in market so you can extend the class functionality via marking them partial. Partial class can also be used for the manage code in separate files instead of creating large files. With C# 3.5 linq to sql designer uses this concept to split custom behaviors outside mapping class.
There lots of ORM(Object Relational Mapper) is available now like entity framework,nhibernate, linq, dlinq but i choose subsonic 3.0 for my next application which will be a question answer site for the following reason
And another great news is that Rob Conery is hired by the Microsoft and subsonic will official ORM for ASP.net Applications.
You can download subsonic 3.0 from here.
http://www.subsonicproject.com/Download
Happy Coding..
For every enterprise level application the key to make that application success is the responsiveness of application. ASP.NET also offers great deal of the features for developing web based enterprise application but some times due to avoiding best practice to write application the performance of application performance of application is not so fast as it should be. Here are the some use full suggestion to make your application super fast.
That’s it!!…..Happy Programming..