Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Confirmation dialog box in Code Behind using C#( C-Sharp ) in ASP.NET

You can call a confirmation dialog box from code behind using c#. Copy follow the code in respective files.

Copy this is HTML

<p>
<asp:Button id="btnSave" runat="server" Text="Save and Update 'RFFM'" OnClientClick="return UpdateRFFM();" />
</p>

Copy this in C# code behind.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Text;
using ADI.Web;

namespace SIS
{
public partial class update_sis : System.Web.UI.Page
{
SqlCommand cmd;
SqlParameter pm;
string strForm = "";
StringBuilder sb;
string strError = "";
int UpdateStatus = -1;
string strEmailTemplate = "";

protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
Response.Cache.SetCacheability(HttpCacheability.NoCache);

if (Request["form_name"] == null)
{
Response.Write("");
Response.End();
}
strForm = Utils.ToStringNullSafe(Request["form_name"]);
sb = new StringBuilder();

if (Session["ApplicationId"] == null)
{
Response.Write("Bad Request...");
Response.End();
}

int ApplicationId = int.Parse(Session["ApplicationId"].ToString());

switch (strForm)
{
case "rffm_create_user":
if (Session["email"] == null)
{
Response.Write("Bad Request");
Response.End();
}
Session["errmsg"] = "";
try
{
cmd = new SqlCommand("usp_SIS_PutUser");

// output parameter
pm = new SqlParameter("@UpdateStatus", SqlDbType.Int);
pm.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pm);

// input parameters
cmd.Parameters.Add("Id", SqlDbType.Int).Value = 0;
cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50).Value = Session["Email"].ToString();

string strPassword = System.Guid.NewGuid().ToString().Substring(0, 8);

cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = Utils.base64Encode(strPassword);
cmd.Parameters.Add("@Active", SqlDbType.Bit).Value = false;
int ClubId = int.Parse(Session["ClubId"].ToString());
if (ClubId > 0)
{
cmd.Parameters.Add("@Group_Id", SqlDbType.Int).Value = 31;
cmd.Parameters.Add("@Club_Id", SqlDbType.Int).Value = ClubId;
cmd.Parameters.Add("@NonClub_Id", SqlDbType.Int).Value = (object)DBNull.Value;
}
else
{
cmd.Parameters.Add("@Group_Id", SqlDbType.Int).Value = 32;
cmd.Parameters.Add("@Club_Id", SqlDbType.Int).Value = (object)DBNull.Value;
cmd.Parameters.Add("@NonClub_Id", SqlDbType.Int).Value = int.Parse(Session["Non_ClubId"].ToString());
}

Utils.executeSP(cmd);
Session.Remove("emil");
strError = "";

if (Session["errmsg"].ToString() != "") 
strError = "-1" + Session["errmsg"].ToString();

if (strError == "")
{
int UpdateStatus = int.Parse(cmd.Parameters["@UpdateStatus"].Value.ToString());
if (UpdateStatus < 0)
strError = "-1There was a problem when creating new user. Please contact Admin";
else
{
// send email
strEmailTemplate = Utils.ReadTemplate("newuser.txt");
strError = "00" + SIS_Site.SendEmail(UpdateStatus, strEmailTemplate);
}
}
} catch (Exception ex) {
strError = "-1" + ex.Message;
}
break;
case "rffm_SendVerificationEmail":
// send email
if (Session["UserId"] == null)
{
Response.Write("Bad Request");
Response.End();
}
strError = "";
strEmailTemplate = Utils.ReadTemplate("newuser.txt");
strError = "00" + SIS_Site.SendEmail(int.Parse(Session["UserId"].ToString()), strEmailTemplate);
Session.Remove("UserId");
break;
case "rffm_UserSetupVerify":
strError = "";
try
{
cmd = new SqlCommand("usp_SIS_UserSetupVerify");

// output parameter
pm = new SqlParameter("@UpdateStatus", SqlDbType.Int);
pm.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pm);

SqlParameter pm2 = new SqlParameter("@EMail", SqlDbType.VarChar, 500);
pm2.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pm2);

SqlParameter pm3 = new SqlParameter("@Updatetext", SqlDbType.VarChar, 200);
pm3.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pm3);

SqlParameter pm4 = new SqlParameter("@UserId", SqlDbType.Int);
pm4.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pm4);

// input parameters
cmd.Parameters.Add("@ApplicationId", SqlDbType.Int).Value = ApplicationId;

Utils.executeSP(cmd);

if (Session["errmsg"] != null)
strError = Session["errmsg"].ToString();

if (strError == "")
{
UpdateStatus = int.Parse(cmd.Parameters["@UpdateStatus"].Value.ToString());
if (UpdateStatus < 0)
strError = "There was an error when processing your request";
}

Session["email"] = cmd.Parameters["@EMail"].Value.ToString();
Session["UserId"] = cmd.Parameters["@UserId"].Value.ToString();
Session["Updatetext"] = cmd.Parameters["@Updatetext"].Value.ToString();

switch (UpdateStatus)
{
case 1:
strError = "1";
break;
case 2:
strError = "2";
break;
case 3:
strError = "3";
break;
case 4:
strError = Session["Updatetext"].ToString();
break;
case 5:
strError = "5" + Session["Updatetext"].ToString();
break;
default:
break;
}
}
catch (Exception ex)
{
strError = ex.Message;
}
break;

case "rffm":
Session["current_tab"] = "rffm";
try
{
cmd = new SqlCommand("usp_SIS_PutProjectProfile");

// output parameter
pm = new SqlParameter("@UpdateStatus", SqlDbType.Int);
pm.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pm);

// input parameters
cmd.Parameters.Add("@ApplicationId", SqlDbType.Int).Value = ApplicationId;
cmd.Parameters.Add("@LastSavedBy", SqlDbType.VarChar, 50).Value = Session["user"].ToString();

cmd.Parameters.Add("@FeasibilityStudyDocument", SqlDbType.VarChar, 8000).Value = Request["FeasibilityStudy"];
cmd.Parameters.Add("@PlanningPermissionNotRequired", SqlDbType.VarChar, 8000).Value = Request["PlanningPermissionNotRequired"];
cmd.Parameters.Add("@Sustainable", SqlDbType.VarChar, 8000).Value = Request["Sustainable"];

string strRDMRecommendation = Request["RDMRecommendation"];
cmd.Parameters.Add("@RDMRecommendation", SqlDbType.VarChar, 8000).Value = (strRDMRecommendation == null) ? (object)DBNull.Value : strRDMRecommendation;

cmd.Parameters.Add("@Risk", SqlDbType.VarChar, 10).Value = Request["Risk"];
cmd.Parameters.Add("@Region", SqlDbType.VarChar, 50).Value = Request["Region"];
cmd.Parameters.Add("@RDMName", SqlDbType.VarChar, 50).Value = Session["user"].ToString();
cmd.Parameters.Add("@RDMReviewDate", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("@DesignAndPlanningPermission", SqlDbType.VarChar, 8000).Value = Request["DesignAndPlanningPermission"];
cmd.Parameters.Add("@RecommendationOfProjectNeedAgainstSDA", SqlDbType.VarChar, 8000).Value = Request["RecommendationOfProjectNeedAgainstSportsDevelopmentActivity"];
cmd.Parameters.Add("@ValueForMoneyAssessment", SqlDbType.VarChar, 8000).Value = Request["ValueForMoneyAssessment"];
cmd.Parameters.Add("@ActionId", SqlDbType.Int).Value = int.Parse(Request["ActionId"].ToString());
cmd.Parameters.Add("@ActionNotes", SqlDbType.VarChar, 500).Value = "RFFM";

Utils.executeSP(cmd);

if (Session["errmsg"] != null)
strError = Session["errmsg"].ToString();

if (strError == "")
{
UpdateStatus = int.Parse(cmd.Parameters["@UpdateStatus"].Value.ToString());
if (UpdateStatus < 0)
strError = "There was an error when processing your request";
else
Session["current_tab"] = "";
}
}
catch (Exception ex)
{
strError = ex.Message;
}
break;

case "check_session":
if (Session["ApplicationId"] != null)
{
string hfID = Request["hf_ApplicationId"].ToString();
string sfID = Session["ApplicationId"].ToString();

if (hfID != sfID)
{
strError = "-1";
}
}
break;
default:
strError = "Bad request";
break;

}

Response.Write(strError);
}
}
} 
 
 
 
Copy this in Javascript file

function UpdateRFFM()
{
var msg;
var status_code;
var rffmAction = $(".rffmAction").val();
var Risk = $(".ddlRisk").val();
var Region = $(".ddlRegion").val();
var strError = "";

if (rffmAction == "151") {
if (Risk == "")
strError = strError + "Please select a Risk\n";
if (Region == "")
strError = strError + "Please select a Region\n";                
}

if (strError != "") {
alert(strError);
return false;
}

var reply = false;

if (rffmAction == "151") {
$.post(getFullPath("update_sis.aspx"), 
{form_name: 'rffm_UserSetupVerify'}, function(data) {
if (data.length > 0)
status_code = data.substring(0, 1);
else
status_code = '';

switch(status_code) {
case '0':
UpdateRFFM_Normal();
break;
case '1':
$.post(getFullPath("update_sis.aspx"),
{form_name: 'rffm_create_user'}, function(data) {
status_code = data.substring(0, 2);
msg = data.substring(2);
if (status_code == "-1") 
alert(msg);
else {
alert('created new user account\n\n' + msg);
UpdateRFFM_Normal();
}                                    
});
break;
case '2':
UpdateRFFM_Normal();
break;
case '3':
$.post(getFullPath("update_sis.aspx"),
{form_name: 'rffm_SendVerificationEmail'}, function(data) {
status_code = data.substring(0, 2);
msg = data.substring(2);
if (status_code == "-1") 
alert(msg);
else {
alert('verification email sent\n\n' + msg);
UpdateRFFM_Normal();
}
});
break;
case '4':
alert(data);
break;
case '5':
msg = data.substring(1);
if (confirm(msg) == true) {
$.post(getFullPath("update_sis.aspx"),
{form_name: 'rffm_SendVerificationEmail'}, function(data) {
status_code = data.substring(0, 2);
msg = data.substring(2);
if (status_code == "-1") 
alert(msg);
else 
alert('verification email was sent\n\n' + msg);
UpdateRFFM_Normal();
});
}
break;                                                                                                
default:
alert(data);
break;
}
});
} else
UpdateRFFM_Normal();

return reply;
}
function UpdateRFFM_Normal() {
var reply = false;         
$.post(getFullPath("update_sis.aspx"), {form_name: 'rffm',
FeasibilityStudy: $(".FeasibilityStudy").val(),
PlanningPermissionNotRequired: $(".PlanningPermissionNotRequired").val(),
Sustainable: $(".Sustainable").val(),
RDMRecommendation: $(".RDMRecommendation").val(),
Risk: $(".ddlRisk").val(),
Region: $(".ddlRegion").val(),
DesignAndPlanningPermission: $(".DesignAndPlanningPermission").val(),
RecommendationOfProjectNeedAgainstSportsDevelopmentActivity: $(".RecommendationOfProjectNeedAgainstSportsDevelopmentActivity").val(),
ValueForMoneyAssessment: $(".ValueForMoneyAssessment").val(),
ActionNotes: $(".ActionNotes").val(),
ActionId: $(".rffmAction").val()
}, function(data) {
if (data.length > 0) {
alert(data);
return false;
} else {
window.location = getFullPath("application_form.aspx");
return false;
}
});
}

Hello, World! in C# 2010

You can learn to create classes in the C# language. Consider the following code example, which define a class:

using System;
public class Hello
{
public static void Main(string[] args)
{
System.Console.WriteLine("Hello, World!\n");
}
}

Output: Hello, World!

The preceding class declaration provides a method Main() that will display the message "Hello, World!" on your screen.

Leap Year program using C# or CSharp.

The following code checks whether the year entered by the user is a Leap Year. If the condition specified in the if statement is true, the statements in the if block are executed. And if the condition specified in the if statement is false , the statement in the else block are executed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int Year;
Console.WriteLine("Enter the year: ");
Year = Convert.ToInt32(Console.ReadLine());
if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 == 0))
{
Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
}
else
{
Console.WriteLine("The Year you have entered is not a Leap Year {0}.", Year);
}
Console.ReadLine();
}
}
}

Output:

How to create Session Timeout alert box and Redirect to Login.aspx page in ASP.NET

ASP.NET allows you to save values by using session state, which is an instance of the System.Web.SessionState.HttpSessionState class, for each active Web Application session. If different users are using your application, each user session will have a different session state. You can use session state to accomplish the following tasks:
  1. Uniquely identify browser or client-device requests and map them to an individual session instance on the server.
  2. Store session-sepcific data on the server for user across multiple browser or client-device requests within the same session.
  3. Raise appropriate session management events. In addition, you can write application code that make use of these event.
So, here is how you can redirect a user who's session time is out. Copy the JavaScript and HTML code in you application.





Copy this HTML code in your application.

Factorial of a number in C#(CSharp)

The following is an example of the factorial number. It is also recursive method. Have a look:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
public int factorial(int n)
{
int result;
if (n == 1)
return 1;
else
{
result = factorial(n - 1) * n;
return result;
}
}
static void Main(string[] args)
{
Program obj = new Program();
Console.WriteLine("Factorial of 3 is " + obj.factorial(3));
Console.WriteLine("Factorial of 4 is " + obj.factorial(4));
Console.WriteLine("Factorial of 5 is " + obj.factorial(5));

Console.ReadLine();
}
}
}

Output:

Factorial

C# Program to perform Addition, Subtraction, Multipilcation and Division operation.

The following program perform mathematical operation such as Addition, Subtraction, Multipilcation and Division operation.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
int Number1, Number2;
char option;
int Result;

public void Number()
{
Console.WriteLine("Enter the First Number:");
Number1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the Second Number:");
Number2 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Main Menu");
Console.WriteLine("1. Addition");
Console.WriteLine("2. Subtraction");
Console.WriteLine("3. Multiplication");
Console.WriteLine("4. Division");

Console.WriteLine("Enter the Operation you want to perform");
option = Convert.ToChar(Console.ReadLine());

switch (option)
{
case '1':
Result = Number1 + Number2;
Console.WriteLine("The result of Addition is:{0}", Result);
break;
case '2':
Result = Number1 - Number2;
Console.WriteLine("The result of Subtraction is:{0}", Result);
break;
case '3':
Result = Number1 * Number2;
Console.WriteLine("The result of Multiplication is:{0}", Result);
break;
case '4':
Result = Number1 / Number2;
Console.WriteLine("The result of Division is:{0}", Result);
break;
default:
Console.WriteLine("Invalid Option");
break;
}
Console.ReadLine();
}

static void Main(string[] args)
{
Program objProgram = new Program();
objProgram.Number();            
}
}
} 

Output:

Creating a Sample C# program using Classes and objects.

A C# program can be written by using Visual Studio or any editor. Consider the following code, which declares the Car class and creates the object MyCar of the same class:

using System;
class Car
{
//Following are the Member variables of a class.
string Engine;
int NoOfWheels;
//Following are the Member function of a class.
public void AcceptDetails()
{
Console.WriteLine("Enter the Engin Model");
Engine = Console.ReadLine();
Console.WriteLine("Enter the number of Wheels");
NoOfWheels = Convert.ToInt32(Console.ReadLine());
}

public void DisplayDetails()
{
Console.WriteLine("The Engine Model is:{0}", Engine);
Console.WriteLine("The number of Wheels are:{0}", NoOfWheels);
}

//Class used to instantiate the Car Class.
class ExecuteClass
{
public static void Main(string[] args)
{
Car MyCar = new Car();
MyCar.AcceptDetails();
MyCar.DisplayDetails);

Console.ReadLine();
}
}

Output:
Enter the Engine Model
800CC
Enter the number of Wheels
4
The Engine Model is: 800CC
The number of Wheels are: 4

Fibonacci Series Using C#(CSharp)

Following program generates the Fibonacci series up to 200.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{       
static void Main(string[] args)
{
int number1, number2;
number1 = 0;
number2 = 1;

Console.WriteLine("{0}", number1);
while (number2 < 200)
{
Console.WriteLine("{0}", number2);
number2 = number2 + number1;
number1 = number2 - number1;
}

Console.ReadLine();

}
}
}

Output

Fibonacci Series

How can I bind Data in ASP.NET GridView?

You can easy bind data in ASP.NET. You don't even need to write a single line of code for that. You only need to follow the steps:

1. Fire-up Microsoft Visual Studio IDE. Navigate to File - New -Project. You will find New Project dialog box open. Now select appropriate language from Project Type, Select ASP.NET Web Application from Templates enter name of the project and set the location for it.

Data Binding in ASP.NET Step-1
2. Once you open a new project you will get some default files in Visual Studio Solution Explorer. Open Default.aspx in Design Mode and Add a GridView control from the Toolbox to the Design surface as shown in image below.

Data Binding in ASP.NET Step-2

3. You will find a smart tag on top of the GridView Control, click that. You will see GridView Task window. Click on Choose Data Source Drop Down Control and Select >




Data Binding in ASP.NET Step-3
4. Once you select that you will get Choose a Data Source Type screen, Select DataBase and click Next.


Data Binding in ASP.NET Step-4
5. Now click New Connection button and Select Microsoft SQL Server and Click Continue button and then Click Next button.



Data Binding in ASP.NET Step-5
6. You need to select your SQL Server Database name in Server Name location. Once you select  the name that will populate all the database in Select or enter a database name: field. Select one database and Click on Test Connection button at you bottom. You will get a confirmation that Test Connection Succeeded. Click OK button twice.



Data Binding in ASP.NET Step-6
7. Now click Next button two time. You will get the following image. Select the table and then the column as shown in image below. Click Next

Data Binding in ASP.NET Step-7
8. You will get the Test Query screen. Now you have the query  just click Test Query button to check you query. To test you query is correct or not. Then Click Finish button.

Data Binding in ASP.NET Step-8
9. Now Run you application in Visual Studio to see the output.

Data Binding in ASP.NET Step-9

How to make your Web Application Performance Faster?

Hi, following are the most important thinks to note for Web Application performance:

1. Make fewer HTTP requests
              Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads. Some ways to reduce the number of components include: combine files, combine multiple scripts into one script, combine multiple CSS files into one style sheet, and use CSS Sprites and image maps.

2. Content Delivery Network (CDN)
            User proximity to web servers impacts response times. Deploying content across multiple geographically dispersed servers helps users perceive that pages are loading faster.

3. Add Expires headers
           Web pages are becoming increasingly complex with more scripts, style sheets, images, and Flash on them. A first-time visit to a page may require several HTTP requests to load all the components. By using Expires headers these components become cacheable, which avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often associated with images, but they can and should be used on all page components including scripts, style sheets, and Flash.

4. Compress components with gzip
            Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.

5. Grade A on Put CSS at top
            Moving style sheets to the document HEAD element helps pages appear to load quicker since this allows pages to render progressively.

6. Put JavaScript at bottom
            JavaScript scripts block parallel downloads; that is, when a script is downloading, the browser will not start any other downloads. To help the page load faster, move scripts to the bottom of the page if they are deferrable.

7. Avoid CSS expressions
            CSS expressions (supported in IE beginning with Version 5) are a powerful, and dangerous, way to dynamically set CSS properties. These expressions are evaluated frequently: when the page is rendered and resized, when the page is scrolled, and even when the user moves the mouse over the page. These frequent evaluations degrade the user experience.

8. Make JavaScript and CSS external
            Using external JavaScript and CSS files generally produces faster pages because the files are cached by the browser. JavaScript and CSS that are inline in HTML documents get downloaded each time the HTML document is requested. This reduces the number of HTTP requests but increases the HTML document size. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the HTML document size is reduced without increasing the number of HTTP requests.

9. Reduce DNS lookups
            The Domain Name System (DNS) maps host-names to IP addresses, just like phone-books map people's names to their phone numbers. When you type URL www.yahoo.com into the browser, the browser contacts a DNS resolver that returns the server's IP address. DNS has a cost; typically it takes 20 to 120 milliseconds for it to look up the IP address for a host-name. The browser cannot download anything from the host until the look-up completes.

10. Minify JavaScript and CSS
            Minification removes unnecessary characters from a file to reduce its size, thereby improving load times. When a file is minified, comments and unneeded white space characters (space, newline, and tab) are removed. This improves response time since the size of the download files is reduced.

11. Avoid URL redirects
            URL redirects are made using HTTP status codes 301 and 302. They tell the browser to go to another location. Inserting a redirect between the user and the final HTML document delays everything on the page since nothing on the page can be rendered and no components can be downloaded until the HTML document arrives.

12.Remove duplicate JavaScript and CSS
            Duplicate JavaScript and CSS files hurt performance by creating unnecessary HTTP requests (IE only) and wasted JavaScript execution (IE and Firefox). In IE, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page. In both IE and Firefox, duplicate JavaScript scripts cause wasted time evaluating the same scripts more than once. This redundant script execution happens regardless of whether the script is cacheable.

13. Configure entity tags (ETags)
            Entity tags (ETags) are a mechanism web servers and the browser use to determine whether a component in the browser's cache matches one on the origin server. Since ETags are typically constructed using attributes that make them unique to a specific server hosting a site, the tags will not match when a browser gets the original component from one server and later tries to validate that component on a different server.

14. Make AJAX cacheable
            One of AJAX's benefits is it provides instantaneous feedback to the user because it requests information asynchronously from the backend web server. However, using AJAX does not guarantee the user will not wait for the asynchronous JavaScript and XML responses to return. Optimizing AJAX responses is important to improve performance, and making the responses cacheable is the best way to optimize them.

15. GET for AJAX requests
            When using the XMLHttpRequest object, the browser implements POST in two steps: (1) send the headers, and (2) send the data. It is better to use GET instead of POST since GET sends the headers and the data together (unless there are many cookies). IE's maximum URL length is 2 KB, so if you are sending more than this amount of data you may not be able to use GET.

16. Reduce the number of DOM elements
            A complex page means more bytes to download, and it also means slower DOM access in JavaScript. Reduce the number of DOM elements on the page to improve performance.

17. Avoid HTTP 404 (Not Found) error
            Making an HTTP request and receiving a 404 (Not Found) error is expensive and degrades the user experience. Some sites have helpful 404 messages (for example, "Did you mean ...?"), which may assist the user, but server resources are still wasted.

18. Reduce cookie size
            HTTP cookies are used for authentication, personalization, and other purposes. Cookie information is exchanged in the HTTP headers between web servers and the browser, so keeping the cookie size small minimizes the impact on response time.

19. Use cookie-free domains
            When the browser requests a static image and sends cookies with the request, the server ignores the cookies. These cookies are unnecessary network traffic. To workaround this problem, make sure that static components are requested with cookie-free requests by creating a subdomain and hosting them there.
20. Avoid AlphaImageLoader filter
            The IE-proprietary AlphaImageLoader filter attempts to fix a problem with semi-transparent true color PNG files in IE versions less than Version 7. However, this filter blocks rendering and freezes the browser while the image is being downloaded. Additionally, it increases memory consumption. The problem is further multiplied because it is applied per element, not per image.

21. Do not scale images in HTML
            Web page designers sometimes set image dimensions by using the width and height attributes of the HTML image element. Avoid doing this since it can result in images being larger than needed. For example, if your page requires image myimg.jpg which has dimensions 240x720 but displays it with dimensions 120x360 using the width and height attributes, then the browser will download an image that is larger than necessary.

22. Make favicon small and cacheable
            A favicon is an icon associated with a web page; this icon resides in the favicon.ico file in the server's root. Since the browser requests this file, it needs to be present; if it is missing, the browser returns a 404 error (see "Avoid HTTP 404 (Not Found) error" above). Since favicon.ico resides in the server's root, each time the browser requests this file, the cookies for the server's root are sent. Making the favicon small and reducing the cookie size for the server's root cookies improves performance for retrieving the favicon. Making favicon.ico cacheable avoids frequent requests for it.

Variables and Parameters in C#

A variable represents a storage location that has a modifiable value. A variable can be a local variable, parameter, field or array element.The stack and the heap are the places where variables and constants reside. Each has very different lifetime semantics. The stack is a block of memory for storing local variables and parameters. The stack automatically grows and shrinks as a function is entered and exited.

static int Factorial (int x)
{
if (x == 0) return 1;
return x * Factorial (x-1);
}

This method is recursive, meaning that it calls itself. Each time the method is entered, a new int is allocated on the stack, and each time the method exits, the int is deallocated.

The heap is a block of memory in which objects reside. Whenever a new object is created, it is allocated on the heap, and a reference to that object is returned. During a program's execution, the heap starts filling up as new objects are created. The runtime has a garbage collector that periodically deallocates objects from the heap, so your computer does not run out of memory. An object is eligible for deallocation as soon as nothing references it. In the following code, the StringBuilder object is created on the heap, while the sb reference is created on the stack:

static void Test()
{
StringBuilder sb = new StringBuilder();
Console.WriteLine (sb.Length);
}

After the Test method finishes, sb pops off the stack, and the StringBuilder object is no longer referenced, so it becomes eligible for garbage collection.Value type instances live wherever the variable was declared. If the instance was declared as a field within an object, or as an array element, that instance lives on the heap. You can't explicitly delete objects in C#, as you can in C++. An unreferenced object is eventually collected by the garbage collector.The heap is also used to store static fields and constants. Unlike objects allocated on the heap (which can get garbage collected), these will live until the application domain is torn down.

How to definite Assignment ?
C# enforces a definite assignment policy. In practice, this means that outside of an unsafe context, it's impossible to access uninitialized memory. Definite assignment has three implications:
  • Local variables must be assigned a value before they can be read.
  • Function arguments must be supplied when a method is called.
  • All other variables (such as fields and array elements) are automatically initialized by the runtime.
For example, the following code results in a compile-time error:

static void Main()
{
int x;
Console.WriteLine (x); // compile-time error
}

Fields and array elements are automatically initialized with the default values for their type. The following code outputs 0 because array elements are implicitly assigned to their default values:

static void Main()
{
int[] ints = new int[2];
Console.WriteLine (ints[0]); // 0
}

The following code outputs 0 because fields are implicitly assigned to a default value:

class Test
{
static int x;
static void Main() { Console.WriteLine (x); } // 0
}

How to set Parameters ?
A method has a sequence of parameters. Parameters define the set of arguments that must be provided for that method. In this example, the method Foo has a single parameter named p, of type int:

static void Foo (int p)
{
p = p + 1; // increment p by 1
Console.WriteLine(p); // write p to screen
}
static void Main() { Foo(8); }

You can control how parameters are passed with the ref and out modifiers.
How to pass arguments by value ?
By default, arguments in C# are passed by value, which is by far the most common case. This means a copy of the value is created when passed to the
method:

class Test
{
static void Foo (int p)
{
p = p + 1; // Increment p by 1
Console.WriteLine (p); // Write p to screen
}

static void Main( )
{
int x = 8;
Foo (x); // Make a copy of x
Console.WriteLine (x); // x will still be 8
}
}

Assigning p a new value does not change the contents of x because p and x reside in different memory locations.Passing a reference type object by value copies the reference, but not the object. In the following example, Foo sees the same StringBuilder object that Main instantiated, but has an independent reference to it. In other words, sb and fooSB are separate variables that reference the same StringBuilder object:

class Test
{
static void Foo (StringBuilder fooSB)
{
fooSB.Append ("test");
fooSB = null;
}

static void Main( )
{
StringBuilder sb = new StringBuilder( );
Foo (sb);
Console.WriteLine (sb.ToString( )); // test
}
}

Because fooSB is a copy of a reference, setting it to null doesn't make sb null. (If, however, fooSB was declared and called with the ref modifier, sb would become null.)

Note:
  1. You can't explicitly delete objects in C#, as you can in C++. An unreferenced object is eventually collected by the garbage collector.

  2. A parameter can be passed by reference or by value, regardless of whether the parameter type is a reference type or a value type.

Write a program in C-Sharp to demostrate Arrays.

An array represents a fixed number of elements of a particular type. The elements in an array are always stored in a contiguous block of memory, providing highly efficient access.An array is denoted with square brackets after the element type. Like,

char[] vowels = new char[5]; // It declare an array of 5

Square brackets also index the array, accessing a particular element by position:

vowels [0] = 'a';
vowels [1] = 'e';
vowels [2] = 'i';
vowels [3] = 'o';
vowels [4] = 'u';
Console.WriteLine (vowels [1]); //To print e.

This prints "e" because array indexes start at zero. We can use a for loop statement to iterate through each element in the array.The Length property of an array returns the number of elements in the array. Once an array has been created, its length cannot be changed. The System.Collection namespace and subnamespaces provide higher-level data structures, such as dynamically sized arrays and dictionaries. All arrays inherit from the System.Array class, which defines common methods and properties for all arrays. This includes instance properties such as Length and Rank, and static methods to:
  • Dynamically create an array (CreateInstance)
  • Get and set elements regardless of the array type (GetValue/SetValue)
Creating an array always preinitializes the elements with default values. The default value for a type is the result of a bitwise-zeroing of memory.

int[] a = new int[1000];
Console.Write (a[123]); // It will print 0(zero).

Multidimensional arrays come in two varieties: rectangular and jagged. Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are arrays of arrays.Rectangular arrays are declared using commas to separate each dimension,

int[,] matrix = new int [3, 3];

A rectangular array can be initialized as follows,

int[,] matrix = new int[,]
{
{0,1,2},
{3,4,5},
{6,7,8}
};

Jagged arrays are declared using successive square brackets to represent each dimension,

int [][] matrix = new int [3][];

A jagged array can be initialized as,

int[][] matrix = new int[][]
{
new int[] {0,1,2},
new int[] {3,4,5},
new int[] {6,7,8}
};

Example: Write a program in C-Sharp to store Student Name, Roll No and Marks of three subjects in an Array. Find the Student record with highest total Marks. Download Code

using System;
using System.Collections.Generic;
using System.Text;

namespace Assignment_3
{
struct StudentInfo
{
public string stdName ;
public long stdRollNo ;
public int stdMarks1 ;
public int stdMarks2 ;
public int stdMarks3 ;
public int total;

}

class Program
{
static void Main(string[] args)
{
StudentInfo[] std = new StudentInfo[2];
int[] total =new int[2];
for (int i = 0; i < std.Length; i++)
{
Console.Write("\nEnter Student Name: ");
std[i].stdName = Console.ReadLine();
Console.Write("Enter Student RollNo: ");
std[i].stdRollNo = long.Parse(Console.ReadLine());
Console.Write("Enter Student Marks1: ");
std[i].stdMarks1 = int.Parse(Console.ReadLine());
Console.Write("Enter Student Marks2: ");
std[i].stdMarks2 = int.Parse(Console.ReadLine());
Console.Write("Enter Student Marks3: ");
std[i].stdMarks3= int.Parse(Console.ReadLine());
std[i].total = std[i].stdMarks1 + std[i].stdMarks2 + std[i].stdMarks3;
Console.WriteLine("The Student Totoal Marks is {0}",std[i].total);
}

double max = std[0].total;
int maxstd = 0;
for (int j = 0; j < std.Length; j++)
{
if (max < std[j].total)
{
max = std[j].total;
maxstd = j;
}

}
Console.WriteLine("\n\nThe Student with Heightest total is : \n\nName: {0}\nRoll No: {1}\nTotal Marks: {2}",std[maxstd].stdName,std[maxstd].stdRollNo,std[maxstd].total);
Console.ReadLine();
}


}
}

What's New in C# 3.0

C# 3.0 features are centered on Language Integrated Query capabilities, or LINQ for short. LINQ enables SQL-like queries to be written directly within a C# program, and checked statically for correctness. Queries can execute either locally or remotely; the .NET Framework provides LINQ-enabled APIs across local collections, remote databases, and XML.

C# 3.0 features include:
  • Lambda expressions
  • Extension methods
  • Implicitly typed local variables
  • Query comprehensions
  • Anonymous types
  • Implicitly typed arrays
  • Object initializers
  • Automatic properties
  • Partial methods
  • Expression trees

Lambda expressions are like miniature functions created on the fly. They are a natural evolution of anonymous methods introduced in C# 2.0, and in fact, completely subsume the functionality of anonymous methods. For example:

Func<int,int> sqr = x => x * x;
Console.WriteLine (sqr(3));



The primary use case in C# is with LINQ queries, such as the following:

string[] names = { "Tom", "Dick", "Harry" };

// Include only names of >= 4 characters:

IEnumerable<string> filteredNames =
Enumerable.Where (names, n => n.Length >= 4);



Extension methods extend an existing type with new methods, without altering the type's definition. They act as syntactic sugar, making static methods feel like instance methods. Because LINQ's query operators are implemented as extension methods, we can simplify our preceding query as follows:

IEnumerable<string> filteredNames =
names.Where (n => n.Length >= 4);



Implicitly typed local variables let you omit the variable type in a declaration statement, allowing the compiler to infer it. Because the compiler can determine the type of filteredNames, we can further simplify our query:

var filteredNames = names.Where (n => n.Length == 4);



Query comprehension syntax provides SQL-style syntax for writing queries. Comprehension syntax can simplify certain kinds of queries substantially, as well as serving as syntactic sugar for lambda-style queries. Here's the previous example in comprehension syntax:

var filteredNames = from n in names
where n.Length >= 4
select n;



Anonymous types are simple classes created on the fly, and are commonly used in the final output of queries:

var query = from n in names where n.Length >= 4
select new {
Name = n,
Length = n.Length
};



Here's a simpler example:

var dude = new { Name = "Bob", Age = 20 };



Implicitly typed arrays eliminate the need to state the array type, when constructing and initializing an array in one step:

var dudes = new[]
{
new { Name = "Bob", Age = 20 },
new { Name = "Rob", Age = 30 }
};



Object initializers simplify object construction by allowing properties to be set inline after the constructor call. Object initializers work with both anonymous and named types. For example:

Bunny b1 = new Bunny {
Name = "Bo",
LikesCarrots = true,
};



The equivalent in C# 2.0 is:

Bunny b2 = new Bunny( );
b2.Name = "Bo";
b2.LikesCarrots = false;


Automatic properties cut the work in writing properties that simply get/set a private backing field. In the following example, the compiler automatically generates a private backing field for X:

public class Stock
{
public decimal X { get; set; }
}


Partial methods let an auto-generated partial class provide customizable hooks for manual authoring. LINQ to SQL makes use of partial methods for generated classes that map SQL tables.

Expression trees are miniature code DOMs that describe lambda expressions. The C# 3.0 compiler generates expression trees when a lambda expression is assigned to the special type Expression<TDelegate>:

Expression<Func<string,bool>> predicate =
s => s.Length > 10;



Expression trees make it possible for LINQ queries to execute remotely (e.g., on a database server) because they can be introspected and translated at runtime (e.g., into an SQL statement).

Write a program in C-Sharp to find the sum of all the digits of a given number.

The problem here is to sum the digits of a give number for example,
if the number x is input as 123 the result should be calculated as 1 + 2 + 3 = 6. To Implement this logic in C, C++, C-Sharp we should use the Modulo operator. For example..,
using System;
using System.Collections.Generic;
using System.Text;

namespace SumOfDig
{
class Program
{
static void Main(string[] args)
{
long modulo,sum=0;
Console.Write("Enter the Number:");
long number = long.Parse(Console.ReadLine());
while (number > 0)
{
modulo = (number % 10);
sum = sum + modulo;
number = number / 10;
}
Console.WriteLine("The Sum of Digits of number is {0}",sum);
Console.ReadLine();
}
}
}

Write a program in C-Sharp to generate E-Bill using Switch Case.

The switch statement is a control statement that handles multiple selections and enumerations by passing control to one of the case statements within its body as the following example:

int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}

Control is transferred to the case statement which matches the value of the switch. The switch statement can include any number of case instances, but no two case statements can have the same value. Execution of the statement body begins at the selected statement and proceeds until the break statement transfers control out of the case body. A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code.

If no case expression matches the switch value, then control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch. Here come's the E-Billing code in C-Sharp,

using System;
using System.Collections.Generic;
using System.Text;

namespace Assignment1
{
class Program
{
static void Main(string[] args)
{
double total_amount;
l: Console.WriteLine("Enter from following choices.\n\n1.Press One For Demostic\n2.Press Two For Commercial\n3.Press Three For Industrial");
Console.Write("\n\nYou hava entered the choice: ");
int choice = int.Parse(Console.ReadLine());
if (choice == 1 || choice == 2 || choice == 3)
{
r: Console.Write("\nEnter Previous Reading: ");
long previous_reading = long.Parse(Console.ReadLine());
Console.Write("Enter Present Reading: ");
long present_reading = long.Parse(Console.ReadLine());
if (present_reading > previous_reading)
{
long total_reading = (present_reading - previous_reading);
switch (choice)
{
case 1:
if (total_reading >= 0 && total_reading <= 50) { total_amount = total_reading * 1.50; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading >= 51 && total_reading <= 100) { total_amount = total_reading * 2.0; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading > 100)
{
total_amount = total_reading * 2.50;
Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount);
}
break;
case 2:
if (total_reading >= 0 && total_reading <= 50) { total_amount = total_reading * 2.50; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading >= 51 && total_reading <= 100) { total_amount = total_reading * 3.0; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading > 100)
{
total_amount = total_reading * 3.50;
Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount);
}
break;
default:
if (total_reading >= 0 && total_reading <= 50) { total_amount = total_reading * 3.50; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading >= 51 && total_reading <= 100) { total_amount = total_reading * 4.0; Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount); } else if (total_reading > 100)
{
total_amount = total_reading * 4.50;
Console.WriteLine("\nThe Amount For Total Reading {0} units Is Rs.{1}/-", total_reading, total_amount);
}
break;

}
}
else
{
Console.WriteLine("\nInvalid Input Reading....");
Console.Write("\nWould You Like To Continue Y or N: ");
string d = Console.ReadLine();
if (d == "y" || d == "Y")
{
goto r;
}
else
{
Console.WriteLine("Your Good For Nothing.....");
}
}
}
else
{
Console.WriteLine("\nInvalid Input");
Console.Write("\nWould You Like To Continue Y or N: ");
string d = Console.ReadLine();
if(d == "y" || d == "Y")
{
goto l;
}
else
{
Console.WriteLine("Your Good For Nothing.....");
}
}
Console.ReadLine();
}
}
}



Output:
Enter from following choices.

1.Press One For Demostic
2.Press Two For Commercial
3.Press Three For Industrial


You hava entered the choice: 1

Enter Previous Reading: 23598
Enter Present Reading: 23958

The Amount For Total Reading 360 units Is Rs.900/-

Write a program in C-Sharp to demostrate 'TYPECASTING'.

'Typecasting' is one of the methods used in programming. The name given to transforming one type into another. There are two types of casting that can be performed on data types, implicit and explicit

Implicit Typecas:

Implicit casting is performed by the compiler when there is no possible loss of data. This is when a smaller data type is copied into a larger data type - e.g., converting a 16-bit short to a 32-bit integer value.

We could also say, implicit casting is used when casting from a basic type to a more general one. Therefore you use implicit typecasts when transforming a square into a rectangle or when transforming a circle into an ellipse. Because the later is the more general, the typecast can be done implicitly.

Here is a simple example to how implicit typecasting is done:

Int32 iNumber = 185;
Double dNumber = 36.485d;

dNumber = iNumber;
// implicit typecast; dNumber is now 185.0d

In this example the typecast can be done implicitly. You can implement an implicit typecast in your classes using the implicit keyword. In our example we want to transform a square into a rectangle.

using System;
using System.Drawing;

public class MySquare
{
// Remember: please do not make private variables public.
// Use accessors instead.
private Point pos;
private Int32 width;

#region Constructors, Methods etc.
// ...
#endregion

#region Methods
public Point Position
{
get { return this.pos; }
set { this.pos= value; }
}

public Int32 Width
{
get { return this.width; }
set { this.width = value; }
}
#endregion
}

public class MyRectangle
{
private Point pos;
private Int32 width, height;

#region Constructors, Methods etc.
// ...
#endregion

#region Implicit Type Conversion
public static implicit operator MyRectangle(MySquare Square)
{
this.pos = Square.Position;
this.width = Square.Width;

// Because MySquare has no heigth property we set a
// default value
this.height = Square.Height;
}
#endregion
}

Now we can do type conversion with ease:

MySquare square = new MySquare(...);
MyRectangle rectangle = square;


Explicit Typecast:

Explicit casting requires the use of the cast operator (parentheses) when there is a possible loss of data - e.g., converting a 32-bit integer into an 8-bit byte as in the code below.


int fourBytes = 0x000000FE;
byte lowestByte = (byte)fourBytes;

Using the implicit example, we want to look at the case if there is a data loss on typecasting:

MyRectangle rectangle = new MyRectangle(...);
MySquare square = rectangle; // Error

Because a rectangle may have different width and height, it's not possible to convert the rectangle into a square. We can solve this issue by defining how to handle this case.

A possibility to do so is checking if the width and height is equal. If so, the rectangle represents a square and we can convert gracefully. Otherwise, either a type cast exception has to get thrown.

public class MySquare
{
// ...

public explicit operator MySquare(MyRectangle Rectangle)
{
if(Rectangle.Width == Rectangle.Height)
{
this.Width = Rectangle.Width;
// no information lost
this.pos = Rectangle.Position;
}
else
{
throw new TypeCastException("Rectangle is not square.");
}
}
}

Alternatively we define how the information is transformed, which does not require any exceptions to be thrown.

public class MySquare
{
// ...

public explicit operator MySquare(MyRectangle Rectangle)
{
this.width = Rectangle.Width;
this.pos = Rectangle.Position;
// ignore the height of the rectangle
}
}

Write a program in C-Sharp to evaluate an equation.

In C#, Console.WrilLine(""); is like printf() function in C. There are three syntax method a programmer can choose to display his result and they are,

Console.WriteLine("Hello, World"); //Normal Method.
//Below is the Concatenation Method.
Console.WriteLine(" The Sum Of "+a+" + "+b+" = "+c);
//Last Method.
Console.WriteLine("Sum Of {0} + {1} = {2}");

Let us now see, How to evaluate an expression like this,

( a + b ) * c
----------------
4 * d
using System;
using System.Collections.Generic;
using System.Text;

namespace prog1
{
class Program
{
static void Main(string[] args)
{
double a, b, c, d;
Console.Write("Enter the values for a: ");
a = double.Parse(Console.ReadLine());
Console.Write("Enter the values for b: ");
b = double.Parse(Console.ReadLine());
Console.Write("Enter the values for c: ");
c = double.Parse(Console.ReadLine());
Console.Write("Enter the values for d: ");
d = double.Parse(Console.ReadLine());
Console.WriteLine("The value of the expression is "+(((a+b)*c)/(4*d)));
Console.ReadLine();
}
}
}

Output:
Enter the values for a: 4
Enter the values for b: 5
Enter the values for c: 2
Enter the values for d: 4
The value of the expression is 1.125

Write a program in C-Sharp to display "Hello World" message.

The .NET Framework supports multiple languages such as Visual Basic, C#, J#, and so on.C# has emerged as one of the most powerful object-oriented programming language. It implements all the object-oriented concepts , such as encapsulation, inheritance, polymorphism, and bstraction. However, there are certain things that differentiate it form C++. For instance, C# does not support multiple inheritance in classes, whereas C++ does.Being a .NET language, C# has access to the classes defined in the .NET Framework and to the unique features of the Common Language Runtime (CLR) such as, garbage collection, just-in-time compilation etc.., All the programs a compiled and tested in Visual Studio 2005. To Download free Trail of Visual Studio 2008 click here


using System;
using System.Collections.Generic;
using System.Text;

namespace prog1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Hello, World.......!");
Console.ReadLine();
}
}
}

Output:
Hello, World.......!


 

About Me

It's Me!Hi, I'm Moinuddin. I'm a Software Engineer at WIPRO working on Microsoft .NET Technology. I'm interested in a wide range of technology topics, mainly Microsoft including Windows Azure, WCF, WPF, Silverlight and any other cool technology that catches the eye.

Site Info

ProjectCSharp.com is mainly about demonstrating real time examples in different technologies like ASP.NET, WCF, WPF, Silverlight, Azure etc..,

Followers

Help Links

Project CSharp (C#) Copyright © 2011. All Rights Reserved.