Tag Archives: ASP.NET

Useful Features of ASP.NET


In this post, lets discuss about some of the useful features of ASP.NET

1. Faster compilation.

This configuration setting was introduced post .NET 3.5 SP1. Add it to web.config file.

<compilation optimizeCompilations="true">

Refer MSDN for details.

2. Retail mode at the machine.config

<configuration>
  <system.web>
    <deployment retail="true"/>
  </system.web>
</configuration>

It overrides the web.config settings to enforce debug to false, turns custom errors on and disables tracing. No more forgetting to change attributes before publishing – just leave them all configured for development or test environments and update the production retail setting.

3. Intellisense for MasterPages in the content pages

Most of the time you have to use the “findcontrol” method and cast the controls in master page from the content pages when you want to use them, the MasterType directive will enable intellisense in Visual Studio once you do this

Just add one more directive to the page

<%@ MasterType VirtualPath="~/Masters/MainMasterPage.master" %>

If you don’t want to use the Virtual Path and use the class name instead

<%@ MasterType TypeName="MainMasterPage" %>

4. Is Client Connected?

Check to see if the client is still connected, before starting a long-running task

if (this.Response.IsClientConnected)
{
   // long-running task
}

5. Server control properties based on target browser

<asp:Label runat="server" ID="labelText" ie:Text="This is IE text" mozilla:Text="This is Firefox text" Text="This is general text" />

6. Page.ViewStateUserKey to Counter One-Click Attacks

Consider using Page.ViewStateUserKey to counter one-click attacks. If you authenticate your callers and use ViewState, set the Page.ViewStateUserKey property in the Page_Init event handler to prevent one-click attacks.

void Page_Init (object sender, EventArgs e) {
ViewStateUserKey = Session.SessionID;
}

Set the property to a value you know is unique to each user, such as a session ID, user name, or user identifier.

A one-click attack occurs when an attacker creates a Web page (.htm or .aspx) that contains a hidden form field named __VIEWSTATE that is already filled with ViewState data. The ViewState can be generated from a page that the attacker had previously created, such as a shopping cart page with 100 items. The attacker lures an unsuspecting user into browsing to the page, and then the attacker causes the page to be sent to the server where the ViewState is valid. The server has no way of knowing that the ViewState originated from the attacker. ViewState validation and HMACs do not counter this attack because the ViewState is valid and the page is executed under the security context of the user.

By setting the ViewStateUserKey property, when the attacker browses to a page to create the ViewState, the property is initialized to his or her name. When the legitimate user submits the page to the server, it is initialized with the attacker’s name. As a result, the ViewState HMAC check fails and an exception is generated.

Check out this link for details.

7. Emails to local folder

While testing, you can have emails sent to a local folder on your computer instead of an SMTP server

 <system.net>
    <mailSettings>
        <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="c:\EmailFolder\" />
        </smtp>
    </mailSettings>
</system.net>

This is not a complete list, but will keep adding and updating this.

Realtime Currency Converter in C# ASP.NET using Yahoo API


In this article, Let’s see how to convert worldwide currencies in realtime using Yahoo API.

Steps:

1. Create a ASP.NET empty project, call it as “RealtimeCurrencyConverterUsingYahooAPI”.

2. Add a webpage called “Default.aspx” to the project.

3. Since we are using jQuery, include the jQuery latest library in the project. Add a reference to it on “Default.aspx” page.


<script src="jquery-1.10.2.js"></script>

4. Add the following webmethod in code behind.


using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Services;

[WebMethod]
public static Decimal ConvertCurrency(decimal amount, string fromCurrency, string toCurrency)
{
WebClient client = new WebClient();
Stream response = client.OpenRead(string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", fromCurrency.ToUpper(), toCurrency.ToUpper()));
StreamReader reader = new StreamReader(response);
string yahooResponse = reader.ReadLine();
response.Close();
if (!string.IsNullOrWhiteSpace(yahooResponse))
{
string[] values = Regex.Split(yahooResponse, ",");
if (values.Length > 0)
{
decimal rate = System.Convert.ToDecimal(values[1]);
return rate * amount;
}
}
return 0;
}

The webmethod simple get response from yahoo URL. Parses it and returns the calculated result back on the screen.

5. To call this webmethod from “Default.aspx”, just add the following jQuery Code.


<script type="text/javascript">

$(document).ready(function () {
$('#submit').click(function () {
var errormsg = "";
var amount = $('#txtAmount').val();
var fromCurrency = $('#drpFromCurrency').val();
var toCurrency = $('#drpToCurrency').val();
$.ajax({
type: "POST",
url: "Default.aspx/ConvertCurrency",
data: "{amount:" + amount + ",fromCurrency:'" + fromCurrency + "',toCurrency:'" + toCurrency + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#results').html(amount + ' ' + fromCurrency + ' equals ' + data.d.toFixed(2) + ' ' + toCurrency);
},
error: function (jqXHR, exception) {
$('#results').html(jqXHR.responseText);
}
});
});
});

</script>

If you don’t know how to call a webmethod in jQuery, Please refer this.

6. To style the table, I have just added a stylesheet and referred it in the “Default.aspx” page. You can generate such styles very easily from here.

7. Now run the project and you will find the output like e.g

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

LINQ to Twitter Library using ASP.NET


In the last article, we have discussed, how to create and setup a twitter application. In this post, let’s discuss about how to use LINQ to twitter library using C# ASP.NET.

About LINQ to Twitter:

“LINQ to Twitter is an open source 3rd party LINQ Provider for the Twitter micro-blogging service. It uses standard LINQ syntax for queries and includes method calls for changes via the Twitter API.”

Let’s discuss an example which uses LINQ to Twitter library.

1. Create a new ASP.NET empty web application. We call it as “LinqtoTwitterExample”.

2. Download LINQ to Twitter library from here. Since we are using .NET framework 4.5, add a reference to “LinqToTwitter.dll” file from net45 folder.

3. Add the 5 keys in the web.config file namely “TwitterConsumerKey”, “TwitterConsumerSecret”, “TwitterAccessToken”, “TwitterAccessTokenSecret” and “TwitterScreenName” (it will hold your twitter screen name).


<appSettings>
 <add key="TwitterConsumerKey" value=""/>
 <add key="TwitterConsumerSecret" value=""/>
 <add key="TwitterAccessToken" value=""/>
 <add key="TwitterAccessTokenSecret" value=""/>
 <add key="TwitterScreenName" value="deshpandesuraj"/>
 </appSettings>

You can get the settings from the Twitter App.

4. Add a new aspx page call it as “Default.aspx”.

5. Add a button and a textbox on “Default.aspx” page. Set the max length of textbox to 140 since twitter uses only 140 characters.

In the code behind add reference to namespace: using LinqToTwitter;


var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);
 if (twitterCtx != null)
 {
 twitterCtx.UpdateStatus(textbox1.Text.Trim());
 }

6. Add another button and a listbox on “Default.aspx” page to hold the list of tweets.


var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

var tweets = from t in twitterCtx.Status
 where t.Type == StatusType.User
 select t;

if (tweets != null)
 {
 foreach (var tweetStatus in tweets)
 {
 if (tweetStatus != null)
 {
 listbox1.Items.Add(new ListItem(tweetStatus.Text, tweetStatus.ID));
 }
 }
 }

Please Note: Your twitter application name will appear over tweet you sent.

Following are the commonly required twitter functions.

Get list of Followings:


List<string> followingsCollection = new List<string>();
 var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

//cursor is used because twitter returns list partially
 string nextCursor = "-1";

while (!string.IsNullOrEmpty(nextCursor) && nextCursor != "0")
 {
 var followings =
 (from frndship in twitterCtx.Friendship
 where frndship.Type == FriendshipType.FriendsList &&
 frndship.ScreenName == ConfigurationManager.AppSettings["TwitterScreenName"] && frndship.Cursor == nextCursor
 select frndship)
 .SingleOrDefault();

if (followings != null)
 {
 foreach (var follower in followings.Users)
 {
 if (follower != null)
 {
 followingsCollection.Add(follower.Name);
 }
 }
 nextCursor = followings.CursorMovement.Next;
 }
 }
 return followingsCollection;

Get list of Followers:


List<string> followersCollection = new List<string>();

var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

//cursor is used because twitter returns list partially
 string nextCursor = "-1";

while (!string.IsNullOrEmpty(nextCursor) && nextCursor != "0")
 {
 var followers =
 (from frndship in twitterCtx.Friendship
 where frndship.Type == FriendshipType.FollowersList &&
 frndship.ScreenName == ConfigurationManager.AppSettings["TwitterScreenName"] && frndship.Cursor == nextCursor
 select frndship)
 .SingleOrDefault();

if (followers != null)
 {
 foreach (var follower in followers.Users)
 {
 if (follower != null)
 {
 followersCollection.Add(follower.Name);
 }
 }
 nextCursor = followers.CursorMovement.Next;
 }
 }
 return followersCollection;

Get list of Favorites:


List<string> favoritesCollection = new List<string>();
 var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

var favorites =
 (from fav in twitterCtx.Favorites
 where fav.Type == FavoritesType.Favorites &&
 fav.IncludeEntities == true
 select fav)
 .ToList();

if (favorites != null)
 {
 foreach (var fav in favorites)
 {
 if (fav != null)
 {
 favoritesCollection.Add(fav.Text);
 }
 }
 }
 return favoritesCollection;

Source Code Download:

Github [Repository Link]

Please note: For security point of view, I have removed twitter config key values from web.config file. If you are using my downloaded example, please add appropriate key values.

If you have any questions or doubts, please comment below.

Simple Browser Based SignalR Chat Application in ASP.NET


In this article, let’s discuss how to build a simple browser-based SignalR chat application.

ASP.NET SignalR is a new library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and side. Servers can now push content to connected cliently instantly as it becomes available. SignalR supports Web Sockets, and falls back to other compatible techniques for older browsers. SignalR includes APIs for connection management (for instance, connect and disconnect events), grouping connections, and authorization.

SignalR simplifies the process of building real-time applications. It includes an ASP.NET server library and a JavaScript client library to make it easier to manage client-server connections and push content updates to clients. You can add the SignalR library to an existing ASP.NET application to gain real-time functionality.

Steps:

1. Create an ASP.NET empty web application project. Call it as “SignalRChat”.

2. Add a new “SignalR Hub Class”, call it as e.g ChatHub.cs

3. Once you added SignalR Hub Class, Script libraries for jQuery and SignalR are automatically added in the project by visual studio. Since it uses old jQuery, you can remove it and add latest jQuery file (1.10 version) which is optional.

4. Add following method in the ChatHub class.


public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}

5. Add a “Gloabal Application Class” file to project.

6. Include following namespaces.


using System.Web.Routing;
using Microsoft.AspNet.SignalR;

7. Add the following line of code in the Application_Start method of the Global class to register the default route for SignalR hubs.


RouteTable.Routes.MapHubs();

8. Add a ASPX page in the project, call it as “Default.aspx”, include following css and code.


<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>

<div>
<div>
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.10.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
</div>

9. Save the project and rebuild the solution. Run the project.

10. First you will be asked to enter your name.

11. Enter your name, click “ok” button to continue. Open another instance of browser, just copy paste the URL from first browser to another. Enter your name on another instance of browser, hit “ok” button.

12. Now enter a message and and click “Send” button. You will see messages you sent will be appeared on all instances of browser.

Hope this help you.

Source Code Download:

Github [Repository Link]

Fill a Dropdownlist using jQuery in ASP.NET


In this article, let’s discuss how to fill a dropdownlist using jQuery in ASP.NET

1. Let’s start by adding a dropdownlist on page.


<asp:DropDownList ID="ddlRecords" runat="server" ClientIDMode="Static"></asp:DropDownList>

Notice that we have set ClientIDMode property to “Static” which means The ClientID value is set to the value of the ID property. So that we can directly refering this control using ID.

2. To fill a dropdownlist, using  jQuery, let’s write a webmethod, which we will call through jQuery Ajax method.


[WebMethod]
 public static string GetResultset()
 {
 DataTable dataTable = new System.Data.DataTable("Employees");
 using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
 {
 try
 {
 SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT EmployeeID, FirstName + ' ' + LastName AS Name FROM Employees", sqlConnection);
 sqlDataAdapter.Fill(dataTable);
 return JsonConvert.SerializeObject(dataTable);
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 }

Notice that we have applied “WebMethod” attribute to this method which is defined in the namespace “using System.Web.Services;”, so we need to include it in the code.


using System.Web.Services;

Set the connection string in the config file.


<connectionStrings>
 <add name="MyConnectionString" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;User ID=sa;Password=123456" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Webmethod Explained:

In the webmethod, we have taken a sql connection and sql adapter to fill a datatable. And the datatable object is serialized using json.net.

3. To call this webmethod, let’s write a jQuery code. Before using jQuery, we need to include the reference to it.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

4. On document.ready, we will call our webmethod to fill dropdownlist.


<script type="text/javascript">
 $(document).ready(function () {

//fill dropdownlist
 $.ajax({
 type: "POST",
 url: "Default.aspx/GetResultset",
 data: "{}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
 $.each(jQuery.parseJSON(data.d), function () {
 $("#ddlRecords").append($("<option></option>").val(this['EmployeeID']).html(this['Name']));
 });
 },
 error: function (msg) {
 //error
 }
 });

});
 </script>

Here data will have number of records, so we have iterated through each record using .each() and appended a record to our dropdownlist. Since we are getting serialized data, we have parsed data using jQuery.parseJSON()

Source Code Download:

Github [Repository Link]

What is the future of ASP.NET and MVC?


There are lots of articles on the internet that will put some thoughts on “What is the future of ASP.NET?”

Some thoughts:

As a developer, do you know Silverlight? Yes/No ?

Few years back, Microsoft marketing team promoted it. They promoted it in such a way that developers thought Silverlight will be the next Adobe Flash. A very popular companies such as Netflix, Renault Megane, NBC etc developed their websites using Silverlight.

But Where is Silverlight today? What is the share of Silverlight today in the market? What is the trend?

Now what about upcoming things like HTML 5TypeScriptMVC etc.. etc..?

Back to the main point, what is the future of ASP.NET and MVC?

It is true that, there is a shift to MVC from ASP.NET web forms. ASP.Net MVC is on the rise and growing more popular everyday. Another reason, ASP.Net MVC is becoming very popular, since it can take advantage of all the fantastic features coming with HTML 5 as well as new client-side libraries with ease . But they are much harder to integrate in ASP.NET webForms than MVC.

As the technologies are advancing, things are getting better and better with every advancements. So it’s the trend which will lead us the way we develop the sites.

So I don’t think that a technology is coming that would replace everything, rather think that new improvements would be made in the existing technology and knowledge of current technology would help you adapt to those new changes.

What do you think the future of ASP.NET and MVC should be? Thumbs up, or thumbs down? Share your thoughts please.

Inline Expressions in ASP.NET


Inline expressions are used to write server side code directly on aspx, ascx, javascript pages or files.

Let’s discuss Inline expressions in ASP.NET

1. <% … %> embedded code blocks

They are supported in ASP.NET Web pages primarily to preserve backward compatibility with older ASP technology. It is NOT recommended to use embedded code blocks for complex programming logic, because when the code is mixed on the page with markup, it can be difficult to debug and maintain. Also the code is executed only during the page’s render phase

Consider following example, it shows an ASP.NET page with an embedded code block that displays the results of a for loop.


<%@ Page Language="C#" %></pre>
<form id="form1">
 <% for(int index=0;index<10;index++){%>
 <% Response.Write(index)%>
 <% }%>
 </form>
<pre>



2. <%= … %> displaying expression

It is an equivalent of the embedded code block. It is the simplest way to display information from an ASP.NET program such as a single string, an int variable, or a constant.

For example, the following sample code displays the current time:


<%@ Page Language="C#" %>

</pre>
<form id="form1">
 <%=DateTime.Now.ToString() %>
 </form>
<pre>



3. <%@ … %> directive expression

It is the syntax that specifies settings that are used by the page and by user control.

The @ Page directive can be used only in .aspx files, and the @ Control directive can be used only in .ascx files.

The ASP.NET page framework supports directives such as @ Page, @ Control, @ Register etc.

4. <%# … %> data-binding expression

It creates binding between a server control property and a datasource when the control’s DataBind method of this server control is called on the page.

e.g


<%@ Page Language="C#" %>
<script type="text/javascript">// <![CDATA[
 Protected string SayHello()
{
 Return "Hello World";
}
// ]]></script>

</pre>
<form id="form1"></form>
<pre>


5. <%$ … %> expression builder

The expression builder is used to set values of control properties based on the informationthat is contained in an application’s configuration or resource files. The following is the basic syntax of the expression builder:

<%$ Expression Prefix: Expression Value %>

The dollar sign ($) indicates to ASP.NET that the following expression is an expression builder. The expression prefix defines the kind of expression, such as AppSettings, ConnectionStrings, or Resources. Additionally, you can create and define your own expression builder. The expression value that follows the colon (:) is what ASP.NET will actually use as the value of a certain property.



 


The expression builder can be used in the ASP.NET Web Form page as:




6. <%– … — %> server-side comments block

It will allow developers to embed code comments in any location of the HTML source except for within <script> code blocks.

The following code example shows how to use the server-side comments block in an ASP.NET page:


<%@ Page Language="C#" %>

</pre>
<form id="form1">
 <%-- This is comment and wont be rendered

 --%>
 </form>
<pre>