Thursday, August 4, 2011

Creating a SOLID Visual Studio Solution - Steven Smith

I found this article really a very important for developer. So I would like to share this with you. Hope that it may help you for better development.

The SOLID acronym describes five object-oriented design principles that, when followed, produce code that is cleaner and more maintainable. The last principle, the Dependency Inversion Principle, suggests that details depend upon abstractions. Unfortunately, typical project relationships in .NET applications can make this principle difficult to follow.


In this article, describe how one can structure a set of projects in a Visual Studio solution such that DIP can be followed, allowing for the creation of a SOLID solution......

For more details please visits: Creating a SOLID Visual Studio Solution

Thursday, July 7, 2011

"System.Security.SecurityException: Security error" error message when the virtual directory points to a remote share in ASP.NET

Very recently I have faced a problem when hosting a web application in hosting server. This application is running perfectly on local PC but security exceptions occurs when hosting to a server.

Problem
I have got the following error message:

Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Security error.

After consult with senior guys they refer the solution which is sharing with you.

Main Cause

The System.Web namespace does not have the AllowPartiallyTrustedCallersAttribute applied to it.

Any code that is not in the My_Computer_Zone code group that does not have this attribute requires the FullTrust user right. Therefore, the remote share that holds the Web applications content requires FullTrust.

Solution

To resolve this behavior, grant the FullTrust right to the remote share:

1.On the Web server, open Administrative Tools, and then double-click Microsoft .NET Framework Configuration.
2.Expand Runtime Security Policy, expand Machine, and then expand Code Groups.
3.Right-click All_Code, and then click New.
4.Select Create a new code group. Give your code group a relevant name, such as the name of the applications share. Click Next.
5.In the Choose the condition type for this code group list, select URL.
6.In the URL box, type the path of the share in the following format:
file:////\\computername\sharename\*
7.Note Replace computername with the name of the computer that is hosting the remote share. Replace sharename with the name of the share.
8.Click Next. On the next page, select Use an existing permission set, and then select FullTrust.
9.Click Next, and then click Finish.

Restart Microsoft Internet Information Services (IIS) to restart the ASP.NET worker process.

If Microsoft .NET Framework Configuration is not displayed under Administrative Tools, you can install the .NET Framework SDK to add Microsoft .NET Framework Configuration.

Alternatively, you can run the following command to make the change:

Drive:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url "file:////\\computername\sharename\*" FullTrust -exclusive on

Monday, April 18, 2011

Web Security Tip: How to prevent Denial of Service (DoS) attack?

What is a denial-of-service (DoS) attack?
In a denial-of-service (DoS) attack, an attacker attempts to prevent legitimate users from accessing information or services. By targeting your computer and its network connection, or the computers and network of the sites you are trying to use, an attacker may be able to prevent you from accessing email, websites, online accounts (banking, etc.), or other services that rely on the affected computer.

How it works?

Let's see how it make the problem,"n" is a typical connection, the user sends a message asking the server to authenticate it. The server returns the authentication approval to the user. The user acknowledges this approval and then is allowed onto the server.

In a denial of service attack, the user sends several authentication requests to the server, filling it up. All requests have false return addresses, so the server can,t find the user when it tries to send the authentication approval. The server waits, sometimes more than a minute, before closing the connection. When it does close the connection, the attacker sends a new batch of forged requests, and the process begins again--tying up the service indefinitely.

How to Prevent?
Unfortunately, there are no effective ways to prevent being the victim of a DoS or DDoS attack, but there are steps you can take to reduce the likelihood that an attacker will use your computer to attack other computers:

1.Install a firewall, and configure it to restrict traffic coming into and leaving your computer.

2.One of the more common methods of blocking a "denial of service" attack is to set up a filter, or "sniffer," on a network before a stream of information reaches a site,s Web servers. This filter can set in firewall or pro grammatically.

The filter can look for attacks by noticing patterns or identifiers contained in the information. If a pattern comes in frequently, the filter can be instructed to block messages containing that pattern, protecting the Web servers from having their lines tied up.

3.Follow good security practices for distributing your email address.

Sunday, April 17, 2011

How to save image from direct local URL to File

In my recent project its an requirement to save images from URL to hard disk or any media. After binged I have got several solutions. Now sharing you the right solution which is work for me.

Code(C#):

protected void Page_Load(object sender, EventArgs e)
{
string url = "http://img510.imageshack.us/img510/5523/aspnet4jh.jpg";
string DestinationPath ="C:/temp";
string filename = url.Substring(url.LastIndexOf('/')+1);
byte[] bytes=GetBytesFromUrl(url);
WriteBytesToFile(DestinationPath +"/"+filename, bytes);
}

static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

Stream stream = myResp.GetResponseStream();
//int i;
using (BinaryReader br = new BinaryReader(stream))
{
//i = (int)(stream.Length);
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}

static public void WriteBytesToFile(string fileName, byte[] content)
{
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);
try
{
w.Write(content);
}
finally
{
fs.Close();
w.Close();
}
}

Hope that it may help other guys. Thanks.

Saturday, April 2, 2011

Achieve MVP award from Microsoft

Yesterday I got an email from Microsoft Community ..

"
Dear Ahsan

Congratulations on getting awarded as an MVP for contributing to the technical communities!

I am Abhishek Kant, your MVP Lead and would facilitate your interaction with Microsoft including administration of award benefits and providing latest information.............

"

Thanks to Microsoft Community to give this reward to the community contributor. It is really inspired the community member to keep up their activities.

I feel lucky to join in MVP community for the first time, hope that this is a great opportunity for me to rich my experience by sharing knowledge with other MVP.

Thanks to all for their co operation.

Tuesday, March 29, 2011

How to run 32-bit ASP.NET Applications on 64-bit Windows server

In my workstation I have used 32bit PC. There is no problem every this is working nice. But an unexpected situation arise recently when I try to deploy my application in to a 64 bit windows server. I never face this problem before.

Don't worry Technet library(Microsoft) is there. Just one line need to execute to solve my problem.

Actually I need to configure IIS to run 32-bit ASP.NET Applications on 64-bit Windows server.For this, we must configure IIS to create 32-bit worker processes. For more information about running 32-bit applications on 64-bit Windows.

IIS cannot run 32-bit and 64-bit applications concurrently on the same server.To enable IIS 6.0 to run 32-bit ASP.NET applications on 64-bit Windows.

Follow this steps:


1.Open a command prompt and navigate to the %systemdrive%\Inetpub\AdminScripts directory.

2.Type the following command:
cscript.exe adsutil.vbs set W3SVC/AppPools/Enable32BitAppOnWin64 true

3.Press ENTER.

Now your 64 bit server is ready for run 32 bit application.

Some Important information

Before you configure IIS to run 32-bit applications on 64-bit Windows, note the following:

1.IIS only supports 32-bit worker processes in Worker Process Isolation mode on 64-bit Windows.

2.On 64-bit Windows, the World Wide Web Publishing service can run 32-bit and 64-bit worker processes. Other IIS services like the IIS Admin service, the SMTP service, the NNTP service, and the FTP service run 64-bit processes only.

3.On 64-bit Windows, the World Wide Web Publishing service does not support running 32-bit and 64-bit worker processes concurrently on the same server.

After configure problem may occurs

After you configure IIS 6.0 to run 32-bit Web applications, IIS stores 32-bit DLLs and ISAPIs in the %windir%\syswow64\inetsrv directory. All other IIS files, including the MetaBase.xml file, are stored in the %windir%\system32\inetsrv directory.

File access to the System32 and sub directories are transparently redirected based on the bitness of the process making that file access (64-bit processes have full access, while 32-bit processes have access to System32 redirected to Syswow64).

If your legacy applications have specific 32-bit file access needs and you notice application failures, see if the application needs to reference the new %windir%\syswow64\inetsrv to resolve the problem.

For more information visits here.

What is HTTP Handler and HTTP Module in asp.net? Co-Relation and Differences

I have little bit confusion about HTTP Handler and HTTP Module. Then I move to community and get a huge response. After studying for a while now I get a clear idea. Now sharing with you hope that it will also help other guys.


What is HTTP handler?


An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.(msdn)

HTTP handlers process the request and are generally responsible for initiating necessary business logic tied to the request. Custom handlers must implement the System.Web.IHttpHandler interface. Additionally, a handler factory can be created which will analyze a request to determine what HTTP handler is appropriate. Custom handler factories implement the System.Web.IHttpHandlerFactory interface.

ASP.net execution process(Image source:MSDN)

What is HTTP Module?

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.(msdn)

HTTP modules are executed before and after the handler and provide a method for interacting with the request.
Custom modules must implement the System.Web.IHttpModule interface. Modules are typically synchronized with events of the System.Web.IHttpModule class (implemented within the Global.asax.cs or .vb file).

The following consists of a list of events that should be considered when implementing your module:

1.BeginRequest
2.AuthenticateRequest
3.AuthorizeRequest
4.ResolveRequestCache
5.AcquireRequestState
6.PreRequestHandlerExecute
7.PostRequestHandlerExecute
8.ReleaseRequestState
9.UpdateRequestCache
10.EndRequest
11.PreSendRequestHeaders
12.PreSendRequestContent
13.Error

Co-Relation
The co-relation between HTTP handler and HTTP module is both are an integral part of the ASP.NET application.
Every request flows through a number of HTTP modules, which cover various areas of the application (i.e. authentication and session information). After passing through each module, the request is assigned to a single HTTP handler, which determines how the system will respond to the request. Upon completion of the request handler, the response flows back through the HTTP modules to the user.


Differences


HTTP Module
1.It represents more something like an modulare peace of code that's similar to another Global.asax.
2.It represent code that is in play for all page requests.
3.These are objects which also participate the pipeline.

HTTP Handler
1.Its a handler for one request.
2.It is more like a single page.
3.These are the end point objects in ASP.NET pipeline.
4.These are essentially processes the request and produces the response

Tuesday, March 22, 2011

Javascript library for Dom inspector

Very recently, I have need to develop an application using JavaScript by which when any user click on an image of this site it will send image URL to a specific location. There is another business behind it.

After binged I get nice script which is solved my problem.

Now share this with you , hope that it will help other developers.

http://userscripts.org/scripts/review/3006

JavaScript Numeric Format - Decimal Precision

Today's discussion about JavaScript number format based on decimal precision. Round a number to a certain number of places you can use JavaScript built-in methods toFixed and toPrecision. This two methods toFixed and toPrecision are part of the Number object. Any browser that supports ECMAScript version 3 should support toFixed and toPrecision.

How to use?
Its very simple and easy to use. Let's see some example which is help us to understand better.

Example : toFixed()

Use toFixed to set precision after the decimal point. It doesn't matter how large the number is before the decimal point. For normal decimal formatting, this is your best option.

// Example: toFixed(2) when the number has no decimal places
// It will add trailing zeros
var num = 10;
var result = num.toFixed(2); // result will equal 10.00

// Example: toFixed(3) when the number has decimal places
// It will round to the thousandths place
num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

Example: toPrecision ()
Use toPrecision when you're setting the overall precision. Here, it matters how large the number is before and after the decimal point. This is more useful for mathematical purposes than for formatting.

// Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
// It will round to the tenths place
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

// Example: toPrecision(4) when the number has 8 digits (4 before, 4 after)
// It will round to the ones place
num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

// Example: toPrecision(2) when the number has 5 digits (3 before, 2 after)
// It will round to the tens place expressed as an exponential
num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2

Floating-point errors

toFixed and toPrecision are subject to floating-point errors.

Here is a test where the starting number is 162.295. The following should show the JavaScript results:

162.30 // toFixed(2)
162.30 // toPrecision(5) 162.29 // toFixed(2)
162.29 // toPrecision(5)

Do they show up correctly as 162.30 in your browser? Most JavaScript implementations will display it as 162.29

Here is basically what happens when rounding 162.295 to two decimal places

num = 162.295
num *= 100 // 16229.499999999998
num = Math.round(num) // 16229
num /= 100 // 162.29

As you can tell, it's in the second step that the number changes from its actual value.

Monday, March 7, 2011

Android-based applications using C# : MonoDroid

MonoDroid is a development stack for using C# and core .NET APIs to develop Android-based applications.



MonoDroid will be a commercial product licensed in a similar fashion
to our Mono for iPhone product MonoTouch.

To quickly get started read the installation guide and our Tutorials. If you have questions, you can contact us or discuss directly with the MonoDroid community on the mailing list, or in our IRC Chat.

You should familiarize yourself with the API, the API Design, MonoDroid's architecture, the list of class libraries that are part of MonoDroid, MonoDroid's Limitations.

Download MonoDroid from here
http://mono-android.net/

For sample you can visit
http://www.c-sharpcorner.com/UploadFile/mahesh/5795/

Monday, February 28, 2011

Thin Vs. Thick Clients

Basically, a thin client is a web based application and most of the processing is done on the server side.

A thick client is installed into the client side. It is still connected to the server, but most of the processing is done on client side. With thick client, there won't be much processing via the network. In a way, it will be a much faster option if your network is slow or congested.


The codes are different for thick and thin clients. I think if you code in components, you can reuse the code about 60% - 80% of the time depending on the requirements.

More specific..

Thin Client: Is a Web Application, and runs on Internet Explorer. You access the application using http://hostname:portNumber/iSupport=20 Here you have a webserver and database in the background. It can be 2-tier or N-tier.

List of protocols used with thin clients

* Appliance Link Protocol
* Citrix ICA
* Remote Desktop Protocol
* Secure Shell or SSH, an encrypted replacement for telnet.
* Virtual Network Computing
* X11, central to Unix windowing
* XML, HTML, or JSON over HTTP (Ajax)
* DisplayLink over USB
* NFS

Thick Client: Is the Application which runs on Windows. It's like any other Windows based program/software. It can be accessed on the same system on which you have it installed.

Advantages of thick clients

1. Fewer server requirements. A thick client server does not require as high a level of performance as a thin client server (since the thick clients themselves do much of the application processing). This results in drastically cheaper servers.
2.Offline working. Thick clients have advantages in that a constant connection to the central server is often not required.
3.Better multimedia performance. Thick clients have advantages in multimedia-rich applications that would be bandwidth intensive if fully served. For example, thick clients are well suited for video gaming.
4.More flexibility. On some operating systems software products are designed for personal computers that have their own local resources. Running this software in a thin client environment can be difficult.
5.Using existing infrastructure. As many people now have very fast local PCs, they already have the infrastructure to run thick clients at no extra cost.
6.Higher server capacity. The more work that is carried out by the client, the less the server needs to do, increasing the number of users each server can support.

String Format for Double [C#]

This information help me a lot to solve my currency related calculation... so share with you. Hope that it may also helpful for other guys...

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString() and float.ToString().

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.
[C#]

// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.
[C#]

// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"

Digits before decimal point


If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.
[C#]

// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.
[C#]

String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"

Zero

Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).

Following code shows how can be formatted a zero (of double type).
[C#]

String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.
[C#]

String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator „;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.
[C#]

String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.
[C#]

String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"

You will get more help from here

Saturday, February 12, 2011

Handling JSON Arrays returned from ASP.NET Web Services with jQuery

The Web Service methods that I will use revolve around cars. Having set up a web site in Visual Studio 2008, I have added a new item of type "Web Service" to the project, calling it EmpInfoService.asmx. The code-behind - EmpInfoService.cs - is automatically generated within the App_Code folder. The full code for that class file is as follows:

Code: asmx

public class Employee
{
public string FullName;
public string Designation;
public string PhoneNo;
}


/// <summary>
/// Summary description for Emp info
/// </summary>


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]


[ScriptService]
public class EmpInfoService : WebService
{
List Employees = new List{
new Employee{FullName="Shakil",Designation="Manager",PhoneNo=5555454},
new Employee{FullName="Ahsan",Designation="Director",PhoneNo=4545454},
new Employee{FullName="Murhsed",Designation="Director",PhoneNo=5454545},
new Employee{FullName="Khurshid",Designation="Officer",PhoneNo=4545545},
new Employee{FullName="Abdul",Designation="Sr.Executive",PhoneNo=45454545},
new Employee{FullName="Yususf",Designation="Sr.Officer",PhoneNo=4545454545},
new Employee{FullName="Farid",Designation="Executive",PhoneNo=45454545},
new Employee{FullName="Munir",Designation="Executive",PhoneNo=454545454},
new Employee{FullName="Foyez",Designation="Executive",PhoneNo=45454545454}
};



[WebMethod]
public List GetAllEmployees()
{
return Employees;
}

[WebMethod]
public List GetEmployeesByName(string name)
{
var query = from c in Employees
where c.FullName == name
select c;
return query.ToList();
}
}


Code: ASPX

The mark-up in the aspx page that will call the Web Service is extremely simple:

<form id="form1" runat="server">
<input type="button" id="btnEmpId" value="Get Employe List" />
<div id="output"></div>
</form>



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 <head> section of the page:

First, jQuery is referenced via the src attribute of the first <script> tag. Then a click event is registered with the button which will invoke the getEmployees() function. After that is the getEmployees() function that is fired when the button is clicked.



Jquery:(Without parameter)

<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(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 = response.d;
$('#output').empty();
$.each(Employees, function(index, Employee) {
$('#output').append('<p><strong>' + Employee.FullName + ' <br />' +
Employee.Designation + '</strong><br /> Designation: ' +
Employee.PhoneNo + '<br />Phone: ' +'</p>');
});
},

failure: function(msg) {
$('#output').text(msg);
}
});
}
</script>


It makes use of the $.ajax(options) function within jQuery, and accepts an object with a number of optional properties.
type specifies the HTTP method, which in this case is POST.
url specifies the URL of the Web Service, together with the web method that is being called. This is followed by the parameters, which are applied to the data property.

In this case, no parameters are being passed, as we are calling the method that retrieves the entire collection of Employee.
The contentType and dataType MUST be specified.
Following this are two further functions: success defines what should be done if the call is successful, and failure handles exceptions that are returned.

In this case, the success callback is passed the resulting HTTP response. In response an object with a property - d - is returned, which contains an array of objects. Each object has a __type property which tells you that it is a Employee object, followed by the other properties of our Web Service Employee object.

The div with the id of output is emptied, in case there was clutter there from a previous ajax call. The jQuery each() function is used to iterate over the collection of objects. Each Employee object is accessed in turn, and its properties are written to a paragraph, which is then appended to the content of div output.

Now, share with you how to send parameter using jquery,
Here we want to filter employee info with employee name from DropDownList

<asp:DropDownList ID="ddlEmpName" runat="server">
<asp:ListItem>Shakil</asp:ListItem>
<asp:ListItem>Ahsan</asp:ListItem>
<asp:ListItem>Murshed</asp:ListItem>
<asp:ListItem>Farid</asp:ListItem>
</asp:DropDownList>

Jquery(with parameter see the bold):

<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(function() {
$('#Button1').click(getEmployees);
});


function getEmployees() {
$.ajax({
type: "POST",
url: "EmployeeService.asmx/GetEmployeesByName",
data: "{name: " + $('#<%= ddlEmpName.ClientID %>').val() + " }",

contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var Employees = response.d;
$('#output').empty();
$.each(Employees, function(index, Employee) {
$('#output').append('<p><strong>' + Employee.FullName + ' <br />' +
Employee.Designation + '</strong><br /> Designation: ' +
Employee.PhoneNo + '<br />Phone: ' +'</p>');
});
},

failure: function(msg) {
$('#output').text(msg);
}
});
}
</script>

The url option now points to the appropriate method, and a parameter is passed into the data option, which uses jQuery syntax to reference the selected value from the DropDownList. I have used inline ASP.NET tags in this case to dynamically render the ID of the DropDownList using the ClientID property, so that there will be no issues in referencing the DropDownList if this code was transferred to a User Control or another control that implements INamingContainer.

All credits goes to Mr.Mikesdotnetting because I solved my problem from this superb article.

Friday, February 11, 2011

JScript Editor Extensions for the Visual Studio 2010 JScript editor

This really a nice extensions which is make life easy for developer specially for JavaScript development.

Bundles the following extensions for the Visual Studio 2010 JScript editor:

Brace Matching

Adds support for automatically highlighting the matching opening or closing brace to the one currently at the cursor. Supports matching parenthesis: (), square brackets: [], and curly braces: {}. Braces in strings, comments and regular expression literals are ignored.



Outlining / Cold-folding

Adds support for automatically creating outlining regions for JScript blocks. Blocks are detected via opening and closing curly braces. Braces in strings, comments and regular expression literals are ignored.

Current Word Highlighting

Adds support for highlighting all instances of the word currently at the cursor.
IntelliSense Doc-Comments Support

Adds support for the element in JScript IntelliSense doc-comments to allow display of new lines in IntelliSense tooltips, e.g.

function hello(name) {
/// A great function
/// Some info on a new line
///

/// The name to say hello to return "hello " + name;
}

Updated vsdoc files for jQuery with tags are available for jQuery 1.4.3, 1.4.4 and 1.5

Source Code

The source code for these extensions is available on the ASP.NET CodePlex site in the folder: $/VisualStudioWebTooling/JScriptExtensions

For more information:
http://visualstudiogallery.msdn.microsoft.com/872d27ee-38c7-4a97-98dc-0d8a431cc2ed/

Thursday, February 10, 2011

Check/Uncheck all items in a CheckBoxList using Javascript

In my previous article show how to check/uncheck all items in a CheckBoxList using ASP.NET. Today we do the same using javascript.

Note: If you use the master page in your application remember that you need to use 'Control.ClientID'. Because When the page is rendered in the browser, the content and master pages get merged into a single page. This means that the IDs for the controls get renamed. ASP.NET renames the IDs to prevent naming conflicts. Now to handle the renamed controls, ASP.NET provides the ‘Control.ClientID’ and ‘Control.UniqueID’ to get the renamed ID’s.


Use the following code at the Page load event to add items to the CheckBoxList programmatically:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
cblTest.Items.Add(new ListItem("Dhaka", "Dhaka"));
cblTest.Items.Add(new ListItem("Chittagong", "Chittagong"));
cblTest.Items.Add(new ListItem("Shylet", "Shylet"));
cblTest.Items.Add(new ListItem("Rajshahi", "Rajshahi"));
}
}

The prototype of our javascript function will be the following :
function CheckBoxListSelect(<pass the control>, <state i.e true or false>)
{
// Our code will come here
}

Now drag and drop two asp:button which are named as "CheckedAll" and "UnCheckedAll" respectively.

In this event, we will call the javascript function and pass the respective checkboxlist controls and the state which will describe ‘true’ for CheckedAll button or ‘false’ for UnCheckedAll button.

Check All:
For Check all write the following code in the onClientClick event of "CheckedAll" button
<asp:Button ID="btnCheckAll" runat="server" Text="CheckedAll" OnClientClick="javascript: CheckBoxListSelect ('<%= cblTest.ClientID %>',true)"


Uncheck All:
For UnCheck all write the following code in the Click Event of "UnCheckedAll" button
<asp:Button ID="btnUnCheckAll" Text="UnCheckedAll" runat="server" OnClientClick="javascript: CheckBoxListSelect ('<%= cblTest.ClientID %>',false)"


JavaScript function:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = state;
}

return false;
}
</script>
// ASP.NET Controls are placed here
</asp:Content>


In this javascript function, we accept two parameters, the checkboxlist control and the state (i.e true or false) of each checkbox, that we would like it to be.Since asp.net renders each checkbox as an input tag, what we are really doing over here is first getting the checkboxlist control using document.getElementById(cbControl) and then counting the number of <input> tags inside that control. Once we get the count, we use a loop to set the state of each control.

Monday, February 7, 2011

Check/Uncheck all items in a CheckBoxList using ASP.NET

The CheckBoxList control in ASP.NET 2.0 is one of the useful control for asp.net developer. But it is not so easy(also not complicated :))to handling like checkbox. This control provides a group of checkboxes that can be dynamically generated by binding it to a data source.

You can handling its operation programmatically using both asp.net or JavaScript. Today I discuss how to checked and unchecked items in CheckBoxList using ASP.net/C#.

First you can bind data to CheckBoxList control using a smart tag appears which allows you to specify a datasource or add items manually to the CheckBoxList.Click on the ‘Edit Items’ to open the ListItem Collection Editor and add items.

Bind data into this control from data source like this:


// Assuming that GetCityList() returns a list of CityID and CityName items in a sqldatareader

SqlDataReader dr = GetCityList ();
cblTest.DataSource = dr;
cblTest.DataValueField = "CityID ";
cblTest.DataTextField = "CityName ";
cblTest.DataBind();


Or, use the following code at the Page load event to add items to the CheckBoxList programmatically:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
cblTest.Items.Add(new ListItem("Dhaka", "Dhaka"));
cblTest.Items.Add(new ListItem("Chittagong", "Chittagong"));
cblTest.Items.Add(new ListItem("Shylet", "Shylet"));
cblTest.Items.Add(new ListItem("Rajshahi", "Rajshahi"));
}
}

Now drag and drop two asp:button which are named as "CheckedAll" and "UnCheckedAll" respectively.

Check All:
For Check all write the following code in the Click Event of "CheckedAll" button

protected void CheckedAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in cblTest.Items)
{
li.Selected = true;
}
}


Uncheck All:
For UnCheck all write the following code in the Click Event of "UnCheckedAll" button

protected void UnCheckedAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in cblTest.Items)
{
li.Selected = false;
}
}

"System.Security.SecurityException: Security error" error message when the virtual directory points to a remote share in ASP.NET

Very recently, We have faced a problem to deploy application. The problem is raised when virtual directory points to a remote PC. The scenario is describe below..
PC1-- Web server(where IIS and .net framework is installed)
PC2-- Remote pc where precompile application directory located.

When deploy application virtual directory is created in PC1 but precompile application folder is points to remote PC2. After configure everything it shows me exception about security permission. After searching I added <trust level="Full"/ > in web.config file. Unfortunately, it shows me the same error

Parser Error Description:
An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

After search in various site I found the solution in msdn.

Why this problem occur?

The System.Web namespace does not have the AllowPartiallyTrusted CallersAttribute applied to it.
http://msdn2.microsoft.com/en-us/library/ms994923.aspx

Any code that is not in the My_Computer_Zone code group that does not have this attribute requires the FullTrust user right. Therefore, the remote share that holds the Web applications content requires FullTrust.

Solution 1:Using Administrative Tools

To resolve this behavior, grant the FullTrust right to the remote share:

1. On the Web server, open Administrative Tools, and then double-click Microsoft .NET Framework Configuration.
2. Expand Runtime Security Policy, expand Machine, and then expand Code Groups.
3. Right-click All_Code, and then click New.
4. Select Create a new code group. Give your code group a relevant name, such as the name of the applications share. Click Next.
5. In the Choose the condition type for this code group list, select URL.
6. In the URL box, type the path of the share in the following format:
file:////\\computername\sharename\*
Note:Replace computername with the name of the computer that is hosting the remote share. Replace sharename with the name of the share.
7. Click Next. On the next page, select Use an existing permission set, and then select FullTrust.
8. Click Next, and then click Finish.
9. Restart Microsoft Internet Information Services (IIS) to restart the ASP.NET worker process.

If Microsoft .NET Framework Configuration is not displayed under Administrative Tools, you can install the .NET Framework SDK to add Microsoft .NET Framework Configuration.

Solution 2:Using Command line
Alternatively, you can run the following command to make the change:

Drive:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url "file:////\\computername\sharename\*" FullTrust -exclusive on

Note For more information about what these arguments do, run the following command:
caspol.exe -?

Additional Information:

In this configuration, the account under which the ASP.NET worker process runs must have sufficient rights to the remote share. You can set the account under which the worker process runs by using the Processmodel tag in the Machine.config file.
Back to the top
Steps to reproduce the behavior

1. Create a new virtual directory that points to a remote share.
2. Create an application for the virtual directory. Make sure that the user who connects to the share has read access to the remote content.
3. In the Processmodel tag of the Machine.config file, change the user to a domain user who has list, read, and execute permissions on the remote share.
4. Create an inline .aspx file, and then put the file in the remote share.
5. Make a request for the page.

For more information:
Please visits
http://support.microsoft.com/kb/317012
http://support.microsoft.com/kb/306590

Thursday, January 13, 2011

Dynamically Add/Remove rows in HTML table using JavaScript

This is very often for web developer when we need to use dynamically generate HTML table using JavaScript. I have found frequent request in various forum about this issue...so now there is very easy sample for them...



Demo:
Click here

Source code :(Html & JavaScript)

<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {

var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
cell1.appendChild(element1);

var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;

var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
cell3.appendChild(element2);

}

function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;

for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}

}
}catch(e) {
alert(e);
}
}

</SCRIPT>
</HEAD>
<BODY>

<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>

</BODY>
</HTML>

You can get more help from here.

Get URL Parameters (QueryStrings) using Javascript

Today I have got a request from a newbie .."How to get value from Querystring using Javascript in asp.net?" So I want to share with you ....

Unfortunately there is no method in JavaScript for parsing the querystring to get the value. So we try with regular expression to solve this problem..

JavaScript method for get URL parameter(QueryStrings)

function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
The following javascript code snippet facilitates Javascript's built in regular expressions to retrieve value of the key. Optionally, you can specify a default value to return when key does not exist.

Example:
The getQuerystring function is simple to use. Let's say you have the following URL:

http://www.dotentboss.com?author=ahsan

and you want to get the "author" querystring's value:

var author_value = getQuerystring('author');

Wednesday, January 12, 2011

How to generate ASCII Table

Very recently I get some request about ASCII code generate.
So that I share with this code...

using System;
using System.Web.UI;

public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<table><tbody<tr>
<td>Decimal</td><td>ASCII character
</td><td>Hexadecimal</td></tr>\n");
int min = 0;
int max = 128;
for (int i = min; i <>// Get ascii character.
char c = (char)i;

// Get display string
string display = string.Empty;
if (char.IsWhiteSpace(c))
{
display = c.ToString();
switch (c)
{
case '\t':
display = "\\t";
break;
case ' ':
display = "space";
break;
case '\n':
display = "\\n";
break;
case '\r':
display = "\\r";
break;
case '\v':
display = "\\v";
break;
case '\f':
display = "\\f";
break;
}
}
else if (char.IsControl(c))
{
display = "control";
}
else
{
display = c.ToString();
}
// Write table row
Response.Write(string.Format("<tr><td>{0}</td>
<td>{1}</td><td>{0:X2}</td>
</tr>\n", i, display));
}
Response.Write("</tbody></table>");
}
}

Tuesday, January 11, 2011

Open new window with Response.Redirect() in Asp.net- 3rd part

In 2nd part of the following post I show you how to open a new window in asp.net using "ResponseHelper "class. Now today I want to share another approach with "Extension method".

Third approach(Extension method)
public static class ResponseHelper {
    public static void Redirect(this HttpResponse response,
        string url,
        string target,
        string windowFeatures) {
 
        if ((String.IsNullOrEmpty(target) ||
            target.Equals("_self", 
StringComparison
.OrdinalIgnoreCase)) &&
                         String.IsNullOrEmpty(windowFeatures)) {
 
            response.Redirect(url);
        }
        else {
            Page page = (Page)HttpContext.Current.Handler;
            if (page == null) {
                throw new InvalidOperationException(
                    "Cannot redirect to new window outside
Page context."
);
            }
            url = page.ResolveClientUrl(url);
 
            string script;
            if (!String.IsNullOrEmpty(windowFeatures)) {
                script = @"window.open(""{0}"", ""{1}"",
""{2}"");"
;
            }
            else {
                script = @"window.open(""{0}"", ""{1}"");";
            }
 
            script = String.Format(script, url, target,
windowFeatures);
            ScriptManager.RegisterStartupScript(page,
                typeof(Page),
                "Redirect",
                script,
                true);
        }
    }
}

Note the 'this' keyword in the first parameter.
Now whenever we include the namespace this class
is defined within, we get a nice override on the
actual Response object.

Ex:
Response.Redirect("popup.aspx", "_blank", "menubar=0,width=100,height=100");

Thursday, January 6, 2011

Open new window with Response.Redirect() in Asp.net- 2nd part

In my previous post I show you how to open a new window in asp.net using "aspnetForm.target".

Second approach(Using ResponseHelper class)

public static class ResponseHelper {
    public static void Redirect(string url, string target,
string windowFeatures) {
        HttpContext context = HttpContext.Current;
 
        if ((String.IsNullOrEmpty(target) ||
            target.Equals("_self", 
StringComparison
.OrdinalIgnoreCase))
&&
String.IsNullOrEmpty(windowFeatures))
{
             context.Response.Redirect(url);
        }
        else {
            Page page = (Page)context.Handler;
            if (page == null) {
                throw new InvalidOperationException(
                    "Cannot redirect to new window outside
Page context."
);
            }
            url = page.ResolveClientUrl(url);
 
            string script;
            if (!String.IsNullOrEmpty(windowFeatures)) {
                script = @"window.open(""{0}"", ""{1}"",
""{2}"");"
;
            }
            else {
                script = @"window.open(""{0}"", ""{1}"");";
            }
 
            script = String.Format(script, url, target,
windowFeatures);
            ScriptManager.RegisterStartupScript(page,
                typeof(Page),
                "Redirect",
                script,
                true);
        }
    }
}


Now you can just call ResponseHelper.Redirect, first parameter is desired "url", second parameter is for specify a target to be "_self" or "_blank" and third parameter is "windowFeatures" by which you can specify whether the new window should have a menu bar, and what its width and height are.

Disclaimers:

Note: If you use it outside the context of a Page request, you can't redirect to a new window. The reason is the need to call the ResolveClientUrl method on Page, which I can't do if there is no Page. I could have just built my own version of that method, but it's more involved than you might think to do it right. So if you need to use this from an HttpHandler other than a Page, you are on your own.

Note: Beware of popup blockers.

Note: Obviously when you are redirecting to a new window, the current window will still be hanging around. Normally redirects abort the current request -- no further processing occurs. But for these redirects, processing continues, since we still have to serve the response for the current window (which also happens to contain the script to open the new window, so it is important that it completes).

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...