We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Tuesday, March 24, 2015

Interview Questions and Answers of ASP .NET



1. How To Dynamically Change Page Title?

To change page title with server-side ASP.NET code we can use Title property of Page object. Your code could look like this:
Page.Title = "This first Example";

Note that Title property doesn't exist in ASP.NET 1.1. If we work in ASP.NET 1.1 environment we can change page title if we add runat="server" attribute to tag. Use code like this:<br /> [ HTML ]<br /> <title id="PageTitle" runat="server">WebForm1
// We need this namespace to use HtmlGenericControl
using System.Web.UI.HtmlControls;

namespace FirstExam
{
public class WebForm1 : System.Web.UI.Page
{
// Variable declaration and instantiation
protected HtmlGenericControl PageTitle = new HtmlGenericControl();

private void Page_Load(object sender, System.EventArgs e)
{
// Set new page title
PageTitle.InnerText = "This first Example";
}

}
}

2. How To Check Is JavaScript Enabled

To find out is JavaScript enabled in the client's web browser, We must try to execute some JavaScript code. Simply, if the client-side JavaScript code is executed, then JavaScript is enabled :). After that, we can send that information back to the server and deal with it. One of the possible solutions is like this:
protected void Page_Load(object sender, EventArgs e)
{
bool JavaScriptEnabled;

if (Session["JavaScriptChecked"] == null)
{
Session["JavaScriptChecked"] = true;
// call page again, but with CheckJavaScript=1 in query string
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect",
"window.location.href='" + Request.Url + "?CheckJavaScript=1" +
"';", true);
}
if (Request.QueryString["CheckJavaScript"] == null)
JavaScriptEnabled = false;
else
JavaScriptEnabled = true;
}

3.How To Find Out If Browser Supports JavaScript?

To find out if visitor's web browser supports JavaScript, use this code:
if(Request.Browser.JavaScript)
{
// Browser is supported
}
else
{
// JavaScript is not supported
}

4. How To Create ASP.NET Website for Mobile Devices?

ASP.NET render different markup for every detected browser. If we access our pages with a mobile device, ASP.NET will return the appropriate HTML code. Because of that, we don't need to make another page for displaying on devices.
However, be careful with the client's screen size, since website visitors usually don't like to use the horizontal scroll. Try to correct design problems with CSS styles to be sure that our pages look nice on every screen resolution.
Take care of web browser capabilities. Some web browsers used on mobile devices don't support javascript, some don't support images or cookies.
If some of these features are important for your web application, you need to check it when page loads and take appropriate action (e.g. inform the visitor about web application's requirements or provide using without a cookie or javascript support, etc.)

5.How To Read Connection String From Web.Config File?

Let say we have connection string stored on the web.config file, like this:




To read connection string from web.config with ASP.NET server-side code, we can use simple code line like this:
string myConStr =ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

6. How To Find Which Version of .NET Framework Is Used?

To find out which version our web application currently uses, we can use code like this:
string NetVersion = System.Environment.Version.ToString()

7. Can I Pass QueryString Variable From Classic ASP To ASP.NET?

We can pass QueryString variables from classic ASP to ASP.NET pages. To send variable with name = ID and value = 22, we can use this ASP code:

Then, in Default.aspx, we can use this ASP.NET server side code to read data:
protected void Page_Load(object sender, EventArgs e)
{
int myID;
if (Request.QueryString["ID"] != null)
{
// Read value from query string
myID = Convert.ToInt32(Request.QueryString["ID"]);
}
else
{
// If there is nothing in query string, use default value
myID = 1;
}
Response.Write(myID.ToString());
}

8.How To Provide User Friendly 404 Pages?

Instead of showing ugly "File Not Found" error message we can handle this error with code in global.asax file. You need to write code in Application_Error event:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception myEx = Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(System.IO.FileNotFoundException))
{
// File is not found, so redirect visitor to user friendly 404 page
Response.Redirect("Default404.aspx");
}
}

9. How To Read Key/Value Pairs From AppSettings?

Application parameters in web.config file can be very useful. This is an example of the appSettings section in web.config that contains two parameters:
[ XML ]





To read application parameters from the appSettings section on web.config file, we can use this code:
C#
string FirstParameter = System.Configuration.ConfigurationManager.AppSettings["FirstParameter"];

10. How To Read And Write A Cookie In ASP.NET

We can use cookies to store data about our site visitors. Because cookies are just plain text files, they are usually not used to store sensitive data, especially without some kind of encryption.
To create new cookie or save existing cookie, use this code:
Response.Cookies["CookieName"].Value = "CookieValue";
// Cookies are temporally files, so we need to set how long cookie will be present on client hard disk before it is deleted
Response.Cookies["CookieName"].Expires = DateTime.Now.AddDays(100);
Default.aspx.cs
// check if cookie exists
if(Request.Cookies["CookieName"] != null)
CookieValue = Request.Cookies["CookieName"].Value;

11.How To Find Referrer URL in ASP.NET?

Our web site visitors could come from different sources, like search engines, blogs, banner ads, affiliates, web directories, etc.
To find out which page has generated a request to our page, use this code:
string MyReferrer = Request.UrlReferrer.ToString();

12. How Much Is DataReader Faster Than DataSet?

DataReader and DataSet connect to the database in different ways when reading data. It takes more time to create and populate DataSet than to create DataReader. DataReader is usually a better solution when we need to show data. Real results depend on the size of our database, our web server hardware, how well is our SQL query or stored procedure is written, etc.
Some practical tests showed that DataReader is two times or faster than DataSet when reading different queries on a table with about 100 000 rows.

13. How To Convert Text Box Value To Integer?

We can easily convert string value from TextBox Control with this line of code:
int MyInteger = Convert.ToInt32(TextBox1.Text);

14. How To Allow Only Numbers In TextBox Control?

Very often developers need to allow only numbers in TextBox control. It can be very easily archived with markup code bellow:

Important:
We still need to check user input on the server side, because a malicious user can make POST request without using our web form. We can perform this check by using the Regex class. For this case, code would be:
if (!Regex.IsMatch(txtNumbersOnly.Text,
@"(^([0-9]*|\d*\d{1}?\d*)$)"))
{
// It is not a number, do something!
}

15. How To Close Browser Window With Button Click?

To close a web browser we need to use client side JavaScript code. We can add it to OnClick attribute of Button control, like this:
btnClose.Attributes.Add("OnClick", "window.close();");

16. Should I Use RadioButtonList Or CheckBoxList Control?

Use RadioButtonList when the user needs to select only one option from the list.
Use CheckBoxList control when the user is allowed to select zero, one or more options on the list.
Instead of RadioButtonList and CheckBoxList controls, we can use a few RadioButton or CheckBox controls. If we use a series of RadioButton controls, we need to set the same GroupName property for all RadioButton controls

17. How To Send Email With ASP.NET?

To send a simple e-mail, we can use this code:
using System.Web.Mail;
...
MailMessage SimpleEmail = new MailMessage();
SimpleEmail.To = "mk@gmail.com";
SimpleEmail.From = "mithileshdotnet@.gmail.com";
SimpleEmail.Subject = "Hello World mail";
SimpleEmail.BodyFormat = MailFormat.Text;
SimpleEmail.Body = "E-mail is working!";
SmtpMail.SmtpServer = "ourMailServer";
SmtpMail.Send(SimpleEmail);

18. How To Make Directory In ASP.NET?

To create directory on web server with ASP.NET server side code, we can use this code:
using System;
using System.Data;
using System.Configuration;
// We need this namespace to create directory
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string NewDir = Server.MapPath("FIleFolder");
// Call function for creating a directory
MakeDirectoryIfExists(NewDir);
}

private void MakeDirectoryIfExists(string NewDirectory)
{
try
{
// Check if directory exists
if (!Directory.Exists(NewDirectory))
{
// Create the directory.
Directory.CreateDirectory(NewDirectory);
}
}
catch (IOException _ex)
{
Response.Write(_ex.Message);
}
}
}

19. How To Get URL To Root Of Web Application?

Character ~ (tilde) represents the root of the web application folder. We can use this HTML code to make a link to home page:
Home Page
Note that we must have runat="server" to make this works.
This facility is very useful when we develop a web application on localhost because we can avoid ugly URL like href="/YourWebApplicationName/".
Instead of tilde (~) character, we can use it encoded as %7e, so the code will be:
Home Page

20. How To Create Image Column In GridView?

There are two possible scenarios:
1. The database contains only image file names as strings, and images are stored in the file system.
2. The database contains file names and also images stored in a binary column in the database.
If images are stored in the file system and the database contains only file names, we can use these two common solutions:


<%-- 1. Fast and easy way with ImageField Column --%>

<%-- 2. Or, we can do it on the old way with the template column. Although more complicated, this method provides more flexibility in some scenarios --%>






21. How To Get List Of Folders?

To get a list of all subdirectories from one location, we can use the GetDirectories method, with code like this:
string[] SiteDirectories =
System.IO.Directory.GetDirectories(Server.MapPath("~/"));
Server.MapPath("~/") will simply return the root folder of the web application. To build a more stable application it is recommended to use try-catch block or to check before if directory exists in your specific case.

22. How To Change Page Background Color With ASP.NET Server-Side

To change the background color of ASP.NET page we need to add bgcolor parameter to tag. By default, body tag is not visible to server side code. First, we need to add runat="server" attribute and some ID to body tag, like this:

After that, in code behind to change background color to some other (e.g. yellow), use this code:
PageBody.Attributes.Add("bgcolor", "yellow");
Note that, if we use ASP.NET 1.1 we need to declare protected variable in page class, like this:
public class WebForm1 : System.Web.UI.Page
{
protected HtmlGenericControl PageBody;
...
}

23. How To Write XML File From DataSet or DataTable?

It is very easy to create an XML file filled with data from DataSet or DataTable object. Let say that we already filled DataSet object, named MyDataSet, with some data from the database. Code to write XML file would be:
dataset.WriteXml(Server.MapPath("XMLFiles/MyXMLFile.xml"));
In the same way, by using WriteXML property you can create an XML file from data table object.

24. How To Read Data From XML To DataSet And Show In GridView?

Let say we have an XML file and we need to show its content on web form inside GridView control. You can do it with code like this:
DataSet dsContacts = new DataSet();
dsContacts.ReadXml(Server.MapPath("Contact.xml"));
GridView1.DataSource = dsContacts;
GridView1.DataBind();

25. How To Delete A File In ASP.NET?

To delete a file on server we can use code like this:
// We need this namespace
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string FileToDelete;
// Set full path to file
FileToDelete = Server.MapPath("~/Files/SomeFile.txt");
// Delete a file
File.Delete(FileToDelete);
}
}

26.How To Fill DropDownList Control With ArrayList?

We can fill DropDownList control with items of ArrayList control by using its DataSource property. One of solutions is code like this:
// Create ArrayList alColors and populate it
// with some items
ArrayList alColors = new ArrayList();
alColors.Add("Red");
alColors.Add("Green");
alColors.Add("Yellow");
alColors.Add("Blue");
// Show ArrayList items in DropDownList named ddlColors
ddlColors.DataSource = alColors;
ddlColors.DataBind();

27. How To Post Back To Other Page With Button Control Click?

If we click to button control on-page, the form will submit and the same page will be loaded again. That is the default behavior, but it is possible to post back to another page by using button control PostBackUrl property, with code like this:

Or, we can set it at run time, with server-side code, like this:
btnGO.PostBackUrl = "~/SecondPage.aspx";

28. Can I Create First Letter As Drop Case By Using CSS Styles?

To create a large first letter of paragraph (drop case), you need to use CSS class like this:
[ CSS ]
.TextWithDropCap:First-Letter

{

color: Maroon;

font-size: 500%;

float:left;

}
Now you can set the class parameter of some tag (e.g. paragraph) to this CSS class, like this:
This is some text......
Then, at run time you will get an output similar to this:
Drop case of the first letter with CSS and ASP.NET

29. How To Link CSS file to ASP.NET page?

I don't know how you deal with this problem, but I always forget this simple line and then looking for some older project to see the syntax :o). Maybe it is a good idea to write it as a quick reference. So, in section of your .aspx file insert line like this:

...

This line will link css file named StyleSheet.css which is located in the same directory like .aspx page.

30. How To Get All Session Variables And Values?

Session variables are very useful, but we must use them carefully because they could spend too much of our memory resources. It could be useful to find out are current session variables and their values in some scenarios. We can do it with code like this:
[ C# ]
string SessionVariableName;
string SessionVariableValue;

foreach (string SessionVariable in Session.Keys)
{
// Find Session variable name
SessionVariableName = SessionVariable;
// Find Session variable value
SessionVariableValue = Session[SessionVariableName].ToString();

// Do something with this data
...

}

31. How To Allow Only One Button Click In Long Time Operations?

If we need to execute long time operation, there is a possibility that visitor could think that something is wrong with your web application and will try to click the button again and start operation again. In that case, you need to allow only one click to button and disable other clicks until the long operation is completed. There are a few different ways to achieve this, I use this one:

public partial class _Default: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Client-side code will change the button text to
// Please wait... and disable future clicks
btnOnlyOnce.OnClientClick = @"if(this.value == 'Please wait...')
return false;
this.value = 'Please wait...';";
}

protected void btnOnlyOnce_Click(object sender, EventArgs e)
{
// Code execution will wait for a 5 seconds
// so you can try to click a button more than once
System.Threading.Thread.Sleep(5000);
btnOnlyOnce.Text = "Long operation is finished";
}
}

32. How To Get Two Button's Click Execute The Same Function?

Sometimes we need to execute the same code for two or more button controls. That could be for example if we have long data form and we want to enable Update and Cancel buttons on top and on the bottom of the web form. We can solve this problem if you call the same function on buttons' events handlers, but it is more professional to use the same event handler for both button controls. You can do it with code like this:
[ C# ]
Hmm, there is no C# code for this. It looks like C# only places this information in markup code. For example, if you want the same function btnFirst_Click to be executed for two buttons, btnFirst and btnSecond, .aspx code will be:


33. Can I Get Conditional RequiredFieldValidator On Client Side?

Let say we have one text box that requires validation only if some condition on the client-side is true. A good example could be a form for feedback that contains one CheckBox "Please Answer Me". If a visitor wants to receive an answer from the site admin, she must give an e-mail address in the next TextBox control. In another case, if CheckBox control is not checked, she can send a feedback comment without giving an e-mail address.
It is pretty easy to implement required field validation for static cases. Just use theRequiredFieldValidator and set its ControlToValidate property to the ID of a TextBox control. But, if validation depends on any client-side condition, we need to use a custom validator. We can do it with code like this:


Your Comment:

E-mail:


You can test this code if you click "Send Comment" button while chkPleaseAnswerMe CheckBox control is not checked the form will submit, but if the check box is checked and txtEmail is empty, TextBox txtEmail will not pass client-side validation and you'll get a message that e-mail is in this case required.

35. FileUpload Control Validation

With FileUpload control, we can receive files from our web application users. Often, we don't want to receive all file types, but only specific extensions (e.g. images only) depending on our application requirements. Unfortunately, FileUpload control still has not some Filter property like Open and Save File dialogs in .NET Windows Forms to limit file types. Because of that, we need to write some additional code to be sure that the user will upload a regular file type.
Let say we have two web controls on a web form, on FileUpload Control to select a file and one-button control, like in the image below:
FileUpload Control on the webform

Image 1: FileUpload and Button on the webform
Because in ASP.NET we have client and server-side, validation could be done on the client and on the server. You need to have server-side validation because of security reasons, but we also need client-side validation because it is faster and more user-friendly. Let see how to implement both types, for example, our web application will allow the only upload of .xls or .xml files.

FileUpload Control client-side validation
We can use CustomValidator to implement FileUpload validation on the client side. A possible implementation could be with code like this:

 



If a visitor tries to upload wrong file type or FileUpload have an empty value, CustomValidator will return an error message, like in the image below:

The error message is shown if FileUpload control has an incorrect value
Image 2: an Error message is shown

FileUpload Control server side validation
Because of security reasons, we need to validate FileUpload control on the server side too. We can use the same idea as for client-side validation. In this case, just use OnServerValidate event, like in code bellow:
[ C# ]
protected void CustomValidator1_ServerValidate(object source,ServerValidateEventArgs args)
{
// Get file name
string UploadFileName = fuData.PostedFile.FileName;

if(UploadFileName == "")
{
// There is no file selected
args.IsValid = false;
}
else
{
string Extension = UploadFileName.Substring(UploadFileName.LastIndexOf('.') + 1).toLower();

if (Extension == "xls" || Extension == "xml")
{
args.IsValid = true; // Valid file type
}
else
{
args.IsValid = false; // Not valid file type
}
}
}

37.How To Register Controls In Web.Config?

To register custom web controls or user controls developers often use Register directives on top of the page, like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"Inherits="_Default" %>

<%@ Register TagName="poll" TagPrefix="uc" Src="~/UserControls/Poll.ascx" %>

<%@ Register TagPrefix="cc1" Namespace="mithileshdotnet.NET2"Assembly="WebSearchControl_v3_NET2-0" %>
After that, later in page, we can access to these controls by using its tag prefix and tag or class name in markup code, like this:

This is a correct procedure, but if we need to insert the same user controls or web custom controls in many pages, we can consider using of Controls section in web.config. To register controls in web.config, use code like this:

Now we can use these controls on every page without registrations! If we need to use the same user or custom controls on many pages, registering in every page looks a little bit hardcoded and harder to maintain. By using web.config we have information in one place, which is easier to manipulate and change if needed.

Web.config registration remarks

Note that our web application will restart every time we register new control because we changed web.config file and even every time we update any registered control. Also, we can't place user controls and pages in the same folder, we need separate folder for user controls. If some user control uses other user control then it needs a separate folder too. If user control is in the same folder as page, we will receive an error. Also, we can't register controls in web.config if we use ASP.NET 1.1 since the Controls section is introduced in ASP.NET 2.0.

38. How To Read Web Page HTML Code With ASP.NET?

If data are not available in some kind of XML format (like RSS or web services), sometimes we need to deal with the HTML output of the web page. HTML is usually much harder to analyze than XML because you need to write our own parser which is different for every web site. But, the first step, reading of HTML output of the web page is pretty simple. To get HTML of the web page we need only a few lines of code.

To start, place two TextBox controls named txtURL and txtPageHTML, and one-button control on a web form, like in image below:

Webform for getting page HTML at design time

// We have to add namespaces
using System;
using System.Text;
using System.Net;

public partial class DefaultCS : System.Web.UI.Page
{

protected void btnGetHTML_Click(object sender, EventArgs e)
{
// We will use WebClient class for reading HTML of web page
WebClient MyWebClient = new WebClient();

// Read web page HTML to byte array
Byte[] PageHTMLBytes;
if (txtURL.Text != "")
{
PageHTMLBytes = MyWebClient.DownloadData(txtURL.Text);

// Convert this result from byte array to string
// and display it in TextBox txtPageHTML
UTF8Encoding oUTF8 = new UTF8Encoding();
txtPageHTML.Text = oUTF8.GetString(PageHTMLBytes);
}
}
}

Now we can have to start sample project, type some valid URL in first TextBox control and click to "btnGetHTML" button. Code listed above will return HTML code of requested URL and display it in the second text box, like in the image below:

HTML code is read and shown in the text box

As we see, the loading of the HTML code of the web page is relatively easy. Analyzing this data is much harder and depends on page structure.

39. How To Read File Information With ASP.NET?

If we try to create a file manager in ASP.NET or simply we want to know some specific attribute of some file, we can use FileInfo class to get all needed file information. Bellow is a simple code example about how to use FileInfo class. We can copy/paste this code to see how it works. Just replace "products.xml" with the needed file.
[ C# ]
// To read file information, we need System.IO namespace

using System.IO;

public partial class DefaultCS : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
string FilePath = Server.MapPath("products.xml");
FileInfo MyFileInfo = new FileInfo(FilePath);
string FileInformation = "File information:
";
// Check if file exists
if(MyFileInfo.Exists)
{
// File exists, take data about it
FileInformation = "File Name: " + MyFileInfo.Name + "
";
FileInformation += "Directory: " + MyFileInfo.DirectoryName + "
";
FileInformation += "Full path: " + MyFileInfo.FullName + "
";
FileInformation += "Time Created: " + MyFileInfo.CreationTime + "
";
FileInformation += "Time Modified: " + MyFileInfo.LastWriteTime + "
";
FileInformation += "Last Access Time: " + MyFileInfo.LastAccessTime + "
";
// Gets file size in bytes
FileInformation += "File Size: " + MyFileInfo.Length + "
";
// Gets extension part of file name
FileInformation += "File Extension: " + MyFileInfo.Extension;
}
else
{
// File not exists, inform a user about it
FileInformation = "There is no file on " + FilePath + ".";
}
Response.Write(FileInformation);
}
}

40. How To Change Status Bar Text With ASP.NET?

Changing of web browser's status bar text can be useful in some scenarios. We can do this with JavaScript, but we can manipulate JavaScript with server-side ASP.NET code. One of the possible implementations could be code like this:
[ C# ]

public partial class DefaultCS : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
// Create a message string
string strMessage = "This is a message in status bar";
// Register startup script to show a message in status bar
this.RegisterStartupScript("SetStatusText", "");
}
}

41. How To Get Current URL?

Sometimes we need to find the current URL by using ASP.NET server-side code. That could be, for example, if we want to switch users from HTTP to HTTPS protocol we need to find current URL first and then redirect to URL with prefix https://.

To get the URL of the current page in ASP.NET you can use Request.Url.AbsoluteUri property, like in example code line below:

[ C# ]
string CurrentURL = Request.Url.AbsoluteUri;

42. Why DataList Control Is Not Visible On Page?

When we drag DataList control from the toolbox to web form, the gray rectangle is displayed, like in the image below:
DataList control on the webform

If we try to run the page, nothing will be displayed. This happens because DataList control requires a tag.

ItemTemplate defines how DataList control will look at run time. We can mix HTML and ASP.NET markup do design an appropriate look. This simple example shows customers names listed in DataList control:


Customer name: <%#DataBinder.Eval(Container.DataItem, "FirstName")%>
<%#DataBinder.Eval(Container.DataItem, "LastName")%>

43. How To Read And Write Connection String In Web.Config?

Web.config file is recommended the place for storing connection strings in ASP.NET web application.

To add the connection string to web.config, you need to add a new item in the ConnectionStrings section. You can use XML code like this:



When we have one or more connection strings in our web.config file, we can read them when needed with ASP.NET server-side code.

[ C# ]

using System;

using System.Data.SqlClient;

// We need this namespace to access web.config file

using System.Configuration;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

// Receive connection string from web.config

string myConnStr = ConfigurationManager.ConnectionStrings

["YourConnectionStringName"].ConnectionString;

// Create a new connection to the database and open database

SqlConnection myConn = new SqlConnection();

myConn.ConnectionString = myConnStr; // Set connection string

myConn.Open();

}

}

44.Difference Between Image Class And Bitmap Class?

Bitmap Class is inherited from Image class. Image class is an abstract class. Bitmap class has 12 constructors and represents an image composed of pixels.

With Image class, we can load an image from a file, get image information, execute simple operations like flip or rotate, draw on image with Graphics object and finally save the image

Bitmap class has additional features like creating a new image in memory, methods to work with single pixels, etc.

Other inherited class from Image is Metafile class. Metafile class describes an image as a set of recorded operations that can be executed in sequence when the image is displayed.

There is also web control, named Image in System.Web.UI.WebControls namespace. Although both classes name is Image they have a different use. Image web control is used to show an image on the ASP.NET webform.

46. How To Create Thumbnail From Larger Image?

If we are creating an image gallery application, we need to show smaller images (thumbnails) so visitors could browse the gallery easily. Also, if users of our web application have an option to upload images, we probably need to check image size and shrink it if the image is too large and can't fit in page design.

This function will create a thumbnail on disk from an existing larger image:

using System;

// Include these namespaces

using System.Drawing;

using System.Drawing.Drawing2D;


...


void CreateThumbnail(int ThumbnailMax, string OriginalImagePath, stringThumbnailImagePath)

{

// Loads original image from file

Image imgOriginal = Image.FromFile(OriginalImagePath);

// Finds the height and width of the original image

float OriginalHeight = imgOriginal.Height;

float OriginalWidth = imgOriginal.Width;

// Finds the height and width of the resized image

int ThumbnailWidth;

int ThumbnailHeight;

if (OriginalHeight > OriginalWidth)

{

ThumbnailHeight = ThumbnailMax;

ThumbnailWidth = (int)((OriginalWidth / OriginalHeight) * (float)ThumbnailMax);

}

else

{

ThumbnailWidth = ThumbnailMax;

ThumbnailHeight = (int)((OriginalHeight / OriginalWidth) * (float)ThumbnailMax);

}

// Create new bitmap that will be used for the thumbnail

Bitmap ThumbnailBitmap = new Bitmap(ThumbnailWidth, ThumbnailHeight);

Graphics ResizedImage = Graphics.FromImage(ThumbnailBitmap);

// Resized image will have the best possible quality

ResizedImage.InterpolationMode = InterpolationMode.HighQualityBicubic;

ResizedImage.CompositingQuality = CompositingQuality.HighQuality;

ResizedImage.SmoothingMode = SmoothingMode.HighQuality;

// Draw resized an image

ResizedImage.DrawImage(imgOriginal, 0, 0, ThumbnailWidth, ThumbnailHeight);

// Save thumbnail to file

ThumbnailBitmap.Save(ThumbnailImagePath);

}

47. How to Find If User Is Logged In?

If our web application uses the membership, then we need to know if the web request is authenticated or not. To find is user currently logged in using this code:
[ C# ]

// To check if a user is logged in use

// IsAuthenticated property

if (Context.User.Identity.IsAuthenticated)

{

// User is logged in

}

else

{

// Anonymous request
}

47. How to Logout User in ASP.NET Membership?

If we use ASP.NET membership, then we need an option to logout the user on click to Logout button. To avoid repetitive code we can place this in the master page. Here is an example:
[ C# ]
using System;

// We need this namespace to use FormsAuthentication class
using System.Web.Security;

public partial class MasterPages_DeafultMasterPage : System.Web.UI.MasterPage
{

protected void btnLogout_Click(object sender, EventArgs e)
{
// Sign out
FormsAuthentication.SignOut();
// Now need to redirect user to login page
// or to the same URL
Response.Redirect(Request.Url.AbsoluteUri);
}
}

49. How To Change User's Email In ASP.NET Membership?

It is very simple to change email or password of the user if you use ASP.NET Membership provider. You can use code like this:
[ C# ]
using System;

// You have to include System.Web.Security namespace to use Membership class

using System.Web.Security;

public partial class ChangeEmailPage : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

// First, get an instance of certain user

MembershipUser mu = Membership.GetUser("YourUserName");

// Change password. You can change password only if enablePasswordRetrieval="true" in web.config

mu.ChangePassword("oldPassword", "newPassword");

// Change email address

mu.Email = "new@email.com";

// Save changes

Membership.UpdateUser(mu);

}

}

49. How to Load Text File To String?

Loading text file to string is a very common task. Here is the code that read a text file from the disc and stores its content to string variable:
[ C# ]

using System;

// We need System.IO namespace to read and write to disc

using System.IO;
public partial class _Default : System.Web.UI.Page

{
protected void Page_Load(object sender, EventArgs e)

{

// Gets full path to a text file, in this example page will read itself

string FilePath = Server.MapPath("Default.aspx");

// Creates an instance of StreamReader class

StreamReader sr = new StreamReader(FilePath);

// Finally, loads file to string

string FileContent = sr.ReadToEnd();

}

}

No comments: