Asp.Net

Resize image while uploading image

Namespace required:
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
— .cs page coding on Save button—————–
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);

// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

// Save the new graphic file to the server
newBMP.Save(Server.MapPath(“~/StaffImages/” + StaffId + Path.GetExtension(fupImage.FileName)));

// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();

Build an EntityConnection Connection String (edmx) model connectionstring

Change edmx model connectionstring dynamically in class library (Data Access Layer)

// Specify the provider name, server and database.
string providerName = “System.Data.SqlClient”;
string serverName = “.”;
string databaseName = “AdventureWorks”;

// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();

// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;

// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();

// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();

//Set the provider name.
entityBuilder.Provider = providerName;

// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;

// Set the Metadata location.
entityBuilder.Metadata = @”res://*/AdventureWorksModel.csdl|
res://*/AdventureWorksModel.ssdl|
res://*/AdventureWorksModel.msl”;
Console.WriteLine(entityBuilder.ToString());

using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Console.WriteLine(“Just testing the connection.”);
conn.Close();
}

Detect request come from mobile, tablet or desktop

IPhone application are growing in the market. In this example, I will give you a simple tips that how to detect request is coming from iPhone in ASP.NET application. When ASP.NET page is requested at runtime, the information in the request header to determine what type of browser has made the request by the user agent. In this example, you will see that if the request will come from iPhone then we can do what we have required for our application and if request will not from iPhone then we don’t need to do anything.

Here’s an example

protected bool isAgent()
{
if (HttpContext.Current.Request.UserAgent.ToLower().Contains(“iphone”))
return true;
return false;
}

protected void Page_Load(object sender, EventArgs e)
{
if (isAgent())
{
Response.Write(“iPhone Detected”);// what ever you do
}
}

clear previous history in every textbox

Its a problem recently I am facing in my recent project.

So my client told me you should clear previous history in every textbox. So I just write a textbox properties in Page_Prerender event in my page(codebehind).
protected void Page_PreRender(Object sender, EventArgs e)
{
txtPassword.Attributes.Add(“autocomplete”, “off”)
txtConfirmPassword.Attributes.Add(“autocomplete”, “off”);
}

It will solve your problem.

Service Unavailable

IIS 6.0 supports both the 32-bit mode and the 64-bit mode. However IIS 6.0 does not support running both modes at the same time on a 64-bit version of Windows. ASP.NET 1.1 runs only in 32-bit mode. ASP.NET 2.0 runs in 32-bit mode or in 64-bit mode. Therefore, if you want to run ASP.NET 1.1 and ASP.NET 2.0 at the same time, you must run IIS in 32-bit mode.
ASP.NET 1.1, 32-bit version

// To run the 32-bit version of ASP.NET 1.1, follow these steps:

1. Click Start, click Run, type cmd, and then click OK.
2. Type the following command to enable the 32-bit mode:
cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1
3. Type the following command to install the version of ASP.NET 1.1 and to install the script maps at the IIS root and under:
%SYSTEMROOT%\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe -i
4. Make sure that the status of ASP.NET version 1.1.4322 is set to Allowed in the Web service extension list in Internet Information Services Manager.

ASP.NET 2.0, 32-bit version

// To run the 32-bit version of ASP.NET 2.0, follow these steps:

1. Click Start, click Run, type cmd, and then click OK.
2. Type the following command to enable the 32-bit mode:
cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1
3. Type the following command to install the version of ASP.NET 2.0 (32-bit) and to install the script maps at the IIS root and under:
%SYSTEMROOT%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i
4. Make sure that the status of ASP.NET version 2.0.50727 (32-bit) is set to Allowed in the Web service extension list in Internet Information Services Manager.

ASP.NET 2.0, 64-bit version

// To run the 64-bit version of ASP.NET 2.0, follow these steps:

1. Click Start, click Run, type cmd, and then click OK.
2. Type the following command to disable the 32-bit mode:
cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 0
3. Type the following command to install the version of ASP.NET 2.0 and to install the script maps at the IIS root and under:
%SYSTEMROOT%\Microsoft.NET\Framework64\v2.0.50727\aspnet_regiis.exe -i
4. Make sure that the status of ASP.NET version 2.0.50727 is set to Allowed in the Web service extension list in Internet Information Services Manager.

Ref : http://support.microsoft.com/kb/894435

JSON ASP.NET Web Services with jQuery

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.Script.Services;

using System.Collections.Generic;

using System.Linq;

public class Employee

{

public string firstname;

public string lastname;

public int age;

}

///

/// Summary description for Employeeservice

///

[WebService(Namespace = “http://tempuri.org/”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]

public class Employeeservice : WebService

{

List Employees = new List{

new Employee{firstname=”Aamir”,lastname=”Hasan”,age=20},
new Employee{firstname=”awais”,lastname=”Hasan”,age=50},
new Employee{firstname=”Bill”,lastname=”Hasan”,age=70},
new Employee{firstname=”sobia”,lastname=”khan”,age=80},

};

[WebMethod]

public List GetAllEmployees()

{

return Employees;

}

[WebMethod]

public List GetEmployeesByDoors(int doors)

{

var query = from c in Employees

where c.Doors == doors

select c;

return query.ToList();

}

}

All that’s needed now is some Javascript for the getEmployees() method that has been assigned to the onclick event of the html button. This will go into the section of the page:

$(function() {

$(‘#Button1’).click(getEmployees);

});

function getEmployees() {

$.ajax({

type: “POST”,

url: “Employeeservice.asmx/GetAllEmployees”,

data: “{}”,

contentType: “application/json; charset=utf-8”,

dataType: “json”,

success: function(response) {

var Employees = (typeof response.d) == ‘string’ ? eval(‘(‘ + response.d + ‘)’) : response.d;

$(‘#output’).empty();

for (var i = 0; i < Employees.length; i++) {

$('#output').append('

‘ + Employees[i].lastname + ‘ ‘ +

Employees[i].firstname + ‘
Age: ‘ +

Employees[i].age + ‘
Doors: ‘ +

‘);

}

},

failure: function(msg) {

$(‘#output’).text(msg);

}

});

}

JSON ASP.NET Web Services with JavaScript

——————————————WebForm1.aspx——————————————

// This function calls the Web service method

// passing simple type parameters and the

// callback function

function CallWebMethod() {
// debugger;
var User_Name = document.getElementById(”).value;

checkDuplicateUserName.WebService1.CheckDuplicate(User_Name, OnSucceeded, OnError);

}

// This is the callback function invoked if the Web service

// succeeded

function OnSucceeded(result) {

var rsltElement = document.getElementById(“lblDuplicate”);
rsltElement.innerHTML = “”;
if (result.length>0)

for (var i = 0; i < result.length; i++)
{
rsltElement.innerHTML += result[i] + ‘
‘;
}
//rsltElement.innerHTML = “This User Name is exist”;

else

rsltElement.innerHTML = “”;
}

function OnError(error) {

// Display the error.

alert(“Service Error: ” + error.get_message());
}

——————————————WebService—————————————–

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Collections;

namespace checkDuplicateUserName
{
///
/// Summary description for WebService1
///
[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]

public class WebService1 : System.Web.Services.WebService
{

[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public List CheckDuplicate(string username)
{
List userdetail = new List();
PL.UserProperties objuser = DAL.clUsers.LoadByUserName(username);
if (objuser != null)
{
userdetail.Add(objuser.Id.ToString());
userdetail.Add(objuser.FullName.ToString());
userdetail.Add(objuser.Email.ToString());
}
return userdetail;
}
}
}

Preventing duplicate User Names with ASP.NET and jQuery

It’s a common problem: you have a registration form, but you want to prevent user names or other values from being used more than once. You need a user-friendly way to prevent duplicate values being submitted. This is where the simplicity of jQuery excels.

User names and passwords are normally stored within a database. Commonly, developers wait until the form has been submitted before they perform any duplicate checking. This means that the user has to wait for a postback to complete before being informed that the user name they chose is already in use, and that they need to choose another one. Ajax tidies this up by allowing asynchronous querying of databases, so that the checking can be done behind the scenes while the user is still completing the registration form. I choose jQuery for my AJAX instead of ASP.NET AJAX because it is so much simpler to use in my opinion.

This example shows a very simple registration form:

Register

User Name:

Password:

 

A web service will be used to house the method that checks the database for possible duplicates:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Script.Services;

using System.Data.SqlClient;

///

/// Summary description for UserService

///

[WebService(Namespace = “http://tempuri.org/”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[ScriptService]

public class UserService : WebService {

public UserService () {

}

[WebMethod]

public int CheckUser(string username)

{

string connect = @”Server=SERVER;Database=Database;Trusted_Connection=True;”;

string query = “SELECT COUNT(*) FROM Users WHERE UserName = @UserName”;

using(SqlConnection conn = new SqlConnection(connect))

{

using(SqlCommand cmd = new SqlCommand(query, conn))

{

cmd.Parameters.AddWithValue(“UserName”, username);

conn.Open();

return (int)cmd.ExecuteScalar();

}

}

}

}

There’s nothing clever about this code. It is trimmed down to just show the working parts, and ignores error checking, for example – although it makes use of parameters to prevent SQL Injection. IF you are wondering why I don’t close the connection after I’m done, that’s what the using statement does for me behind the scenes. Any disposable object (one that implements IDisposable) can be instantiated within a using block which then takes care of Close() and Dispose() at the end of the block. One (Web) method – CheckUser() – accepts a string as an argument and then returns the number of rows in the database where that name is found. The [ScriptService] attribute is uncommented, so that the service is available to AJAX calls (not just ASP.NET AJAX, incidentally).

Now we’ll look at the Javascript that uses jQuery to effect the call:

$(function() {

$(“#UserName”).change(checkUser);

});

function checkUser() {

$.ajax({

type: “POST”,

url: “UserService.asmx/CheckUser”,

data: “{username: ‘” + $(‘#UserName’).val() + “‘}”,

contentType: “application/json; charset=utf-8”,

dataType: “json”,

success: function(response) {

$(“#duplicate”).empty();

if (response.d != “0”) {

$(“#duplicate”).html(‘ That user name has already been taken’);

}

}

});

}

The first tag brings in the jQuery library from Google’s public code repository. Then an event handler is added to the element with the ID of UserName, which is the TextBox waiting for the user to put their chosen User Name in. The handler is wired up to the TextBox’s onchange event, and calls the checkUser() function. Then the checkUser() function is defined in code.

When the user has added some text to the TextBox and then moves their cursor away, the “change” event is fired, and an AJAX call is made to the web service. If the response is not 0, then the web method has found at least one row that matches the user name that the user is attempting to submit. The with the ID of “duplicate” is emptied of any messages resulting from previous attempts, and the message displayed to the user.

I’ve used ASP.NET controls for the inputs in the registration form, but jQuery is not an ASP.NET component (although it has been embraced by the ASP.NET team). So this approach will work with any server-side technology. One thing to note, though – if you place the registration form within a container, such as a ContentPlaceHolder in a Master Page, you will need to change the jQuery code that references its controls to counter the effects of INamingContainer (which is the bit that adds stuff to the ID of the control, such as ctl00_ContentPlaceHolder1_ControlID). The change needed is to use the control’s ClientID property, so the first 3 lines of jQuery code will look like this:

$(function() {

$(“#”).change(checkUser);

});

And of course, the ClientID will need to be used where controls are referenced in the the checkUser() function too.

—————————————————————————————————————-

— Second Method —

1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.

2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008:

SqlServerDataBase

Then I’ve created tblUsers:

definition

This table and this structure just for our example, you can use your own table to implement this approach.

3-Add new Item to your project or website, Choose Web Service file, lets say WebService.cs .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data.SqlClient;

[WebService(Namespace = “http://tempuri.org/”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

public class WebService : System.Web.Services.WebService {

[WebMethod]

public int CheckDuplicate(string User_Name)

{

string strConn = @”Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True”;

string strQuery = “SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name”;

SqlConnection con = new SqlConnection(strConn);

SqlCommand cmd = new SqlCommand(strQuery, con);

cmd.Parameters.Add(“User_Name”, User_Name);

con.Open();

int RetVal= (int)cmd.ExecuteScalar();

con.Close();

return RetVal;

}

}

Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.

4-Add this simple Registration form :

User Name

onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.

5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.

6-Define the JavaScript code to call the Web Service :

// This function calls the Web service method

// passing simple type parameters and the

// callback function

function CallWebMethod() {

var User_Name = document.getElementById(”).value;

WebService.CheckDuplicate(User_Name, OnSucceeded, OnError);

}

// This is the callback function invoked if the Web service

// succeeded

function OnSucceeded(result) {

var rsltElement = document.getElementById(“lblDuplicate”);

if (result == 1)

rsltElement.innerHTML = “This User Name is exist”;

else

rsltElement.innerHTML = “”;

}

function OnError(error) {

// Display the error.

alert(“Service Error: ” + error.get_message());

}

This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns.

If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :

NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function);

Parameters: you can pass one or many parameters.

Success callback function :handles returned data from the service .

Recursive in C#

public partial class _Default : System.Web.UI.Page
{
List lst = new List();
int mainnode = 0;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
RadTreeView1.Nodes.Insert(0, new RadTreeNode(“Table of Content”));
}

protected void Button1_Click(object sender, EventArgs e)
{
updatemainnode();
lst.Add(“end”);

gv1.DataSource = lst;
gv1.DataBind();
}

public void updatemainnode()
{
for (int i = 0; i 0)
{
mainnode = i;
string str = i.ToString();
lst.Add(str);
updatesubnode(RadTreeView1.Nodes[i]);
ViewState[“BookIndex”] = null;
}
}
}

public void updatesubnode(RadTreeNode treenode)
{
if (ViewState[“BookIndex”] == null)
{
ViewState[“BookIndex”] = mainnode;
}

for (int i = 0; i 0)
{
ViewState[“BookIndex”] = strBookindex;
updatesubnode(treenode.Nodes[i]);
}
}
string strnew = ViewState[“BookIndex”].ToString();
if (strnew.Contains(“.”))
{
strnew = strnew.Remove(strnew.LastIndexOf(“.”));
ViewState[“BookIndex”] = strnew;
}
}
}

Implement Logger in asp.net

First of create LoggingConstant.cs File in that Declare all Pages name as variable without extension.
For ex.
public enum ModuleToLog
{
default,
login
}
public enum LogType
{
DEBUG,
EXCEPTION,
INFO
}

After that create Logger.cs File..

public class Logger
{
public static void Write(LogType eLogType, ModuleToLog eModule, string strMethodName, string LogMessage, string strUserId)
{

string LogFilePath = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath + “/Logs”);

//Create directory for Year/Month/
LogFilePath = string.Format(“{0}/{1}/{2}”, LogFilePath, DateTime.Now.Year.ToString(), DateTime.Now.ToString(“MMM”));
DirectoryInfo ObjDirectoryInfo = new DirectoryInfo(LogFilePath);
//string strLogFile = string.Format(“{0}/{1}.log”, LogFilePath, DateTime.Now.ToString(“dd-MMM-yyyy”));

string strLogFile = string.Format(“{0}/{1}.log”, LogFilePath, strUserId + “_” + DateTime.Now.ToString(“ddMMMyyyy”));
try
{
if (ObjDirectoryInfo.Exists == false)
{
ObjDirectoryInfo.Create();
}

StreamWriter sw = new StreamWriter(strLogFile, true);

sw.WriteLine(string.Format(“[{0}][{1}][{2}][{3}][{4}] {5}”, DateTime.Now.ToString(), eLogType.ToString(), eModule.ToString(), strMethodName, strUserId, LogMessage));
sw.Close();
sw.Dispose();
}
catch (Exception ex)
{

}
}
}

——–call this function —
try
{
Logger.Write(LogType.INFO, ModuleToLog.Default, “btnSave_Click”, “Write Comments”, loggedinUserName);

}
catch (Exception ex)
{
Logger.Write(LogType.EXCEPTION, ModuleToLog.WriteBoardBookComments, “btnSave_Click”, ex.StackTrace.ToString() , userdetail.Name);
}