European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Hosting - Germany :: The Difference Between DataSet, DataReader, DataAdapter and DataView in .net

clock March 24, 2015 11:38 by author Scott

Here is short tutorial only about the difference DataSet, DataReader, DataAdapter and DataView in .net.

1. DataSet

Dataset is connection-less oriented, that means whenever we bind data from database it connects indirectly to the database and then disconnected. It has read/write access on data tables. It supports both forward and backward scanning of data.

DataSet is a container of one or more DataTable. More often than not, it will just contain one table, but if you do a query with multiple SELECT statements, the DataSet will contain a table for each.

You have to be careful about how much data you pull into a DataSet, because this is an in-memory representation. You can Fill a DataSet using the Fill() method of a DataAdapter.

You can download example code at the end of this tutorial!

2. DataReader

DataReader is connection-oriented, that means whenever we bind data from database it must require a connection and after that disconnected from the connection. It has read-only access, we can’t do any transaction on them. It supports forward-only scanning of data, in other words you can’t go backward.

DataReader fetches one row at a time so very less network cost as compare to DataSet(that fethces all the rows at a time). It is scalable to any number of records, at least in terms of memory pressure, since it only loads one record at a time. One typical way to get a DataReader is by using theExecuteReader() method of a DbCommand.

You can download example code at the end of this tutorial!

3. DataAdapter

DataAdapter is an ADO.NET Data Provider. DataAdapter can perform any SQL operations like Insert, Update, Delete, Select in the Data Source by using SqlCommand to transmit changes back to the database.

DataAdapter provides the communication between the Dataset/DataTable and the Datasource. We can use the DataAdapter in combination with the DataSet/DataTable objects. These two objects combine to enable both data access and data manipulation capabilities.

You can download example code at the end of this tutorial!

4. DataView

Generally, we use DataView to filter and sort DataTable rows. So we can say that DataView is like a virtual subset of a DataTable. This capability allows you to have two controls bound to the same DataTable, but showing different versions of the data.

For example, one control may be bound to a DataView showing all of the rows in the table, while a second may be configured to display only the rows that have been deleted from the DataTable. The DataTable also has a DefaultView property which returns the default DataView for the table.



ASP.Net 4.5.1 Hosting UK :: Concurrent Queue in Thread Safe collections

clock August 18, 2014 07:42 by author Onit

What is Thread Safe Collection?

People use to said that writing a collection which is mutable, thread safe and usable is an extremely difficult process. Since the .NET 4 introduce the system.collection.concurrent namespace, multiple threads can safely and efficiently add or remove items from these collection without requiring additional synchronization in user code. When you write new code, use the concurrent collection classes whenever the collection will be writing to multiple threads concurrently and in this article I’ll going to show you about thread safe collection in Concurent Queue.

Concurent in .Net

Concurrent collections in .NET work very much like their single-thread counterparts with the difference that they are thread safe. These collections can be used in scenarios where you need to share a collection between Tasks. They are typed and use a lightweight synchronisation mechanism to ensure that they are safe and fast to use in parallel programming.

Concurrent queues

The Queue of T generic collection has a thread-safe counterpart called ConcurrentQueue. Important methods:

  1. Enqueue(T element): adds an item of type T to the collection
  2. TryPeek(out T): tries to retrieve the next element from the collection without removing it. The value is set to the out parameter if the method succeeds. Otherwise it returns false.
  3. TryDequeue(out T): tries to get the first element. It removes the item from the collection and sets the out parameter to the retrieved element. Otherwise the method returns false

The ‘try’ bit in the method names implies that your code needs to prepare for the event where the element could not be retrieved. If multiple threads retrieve elements from the same queue you cannot be sure what’s in there when a specific thread tries to read from it.

Example

Declare and fill a concurrent queue:

ConcurrentQueue<int> concurrentQueue = new ConcurrentQueue<int>(); 
for (int i = 0; i < 5000; i++)
{
    concurrentQueue.Enqueue(i);
}

We’ll want to get the items from this collection and check if all of them have been retrieved using a counter. The counter will also be shared among the threads using the ‘lock’ technique we saw in this post – or actually something that is similar to the ‘lock’ keyword: the Interlocked class. Interlocked has an Increment method which accepts a ref int parameter. It will increment the incoming integer in an atomic operation.

int itemCount = 0;
Task[] queueTasks = new Task[20];

for (int i = 0; i < queueTasks.Length; i++)
{
    queueTasks[i] = Task.Factory.StartNew(() =>
    {
        while (concurrentQueue.Count > 0)
        {
            int currentElement;
            bool success = concurrentQueue.TryDequeue(out currentElement);
            if (success)
            {
                Interlocked.Increment(ref itemCount);
           }
        }
    });
}

The while loop will ensure that we’ll try to de-queue the items as long as there’s something left in the collection.
Wait for the tasks and print the number of items processed – the counter should have the same value as the number of items in the queue:


Task.WaitAll(queueTasks);
Console.WriteLine("Counter: {0}", itemCount);



European ASP.NET 4.5 Hosting - Amsterdam :: Change Session Timeout in ASP.NET

clock July 1, 2013 11:53 by author Scott

You’re trying to increase session timeout on your ASP.NET site? In this tutorial, I will gonna talk about this issue. But, if you use shared hosting, you cant use session as it will impact to other clients site.

ASP.NET

Usually, the first and easiest thing to do is just change the configuration/system.web/[email protected] value to something like “90″.  This should mean that you’d like your users’ sessions to be persisted until a 90 minute window of idle time has elapsed.

<configuration>
  <system.web>
  ...
   <sessionState timeout="90" />
  ...
 </system.web>
</configuration>

Hmm… Not only about change on your code, but please check this application pool timeout on your IIS setting.

Ensure this value is set to the timeout of your session, at a minimum, to ensure that all sessions persist for the entire session timeout period.

The reason that these two values are dependent on one another is because the session information is actually stored within the worker process of the application pool. That is to say, if the worker process is shutdown or killed for any reason, the session information will be lost.

Session Storage Mode

There are the modes of storing the session information:

  • InProc (or In Process) – Default – Stores session information within the IIS worker process
  • StateServer – Stores session information in a separate process (the ASP.NET state service)
  • SQLServer – Stores session information in a SQL database

The only mode that is vulnerable to losing session information on a worker process is when the state is stored in the worker process. Both StateServer and SQLServer modes are not affected by worker process resets. Likewise, StateServer and SQLServer modes are the only options when it is necessary to share session state across more than a single IIS server.

For more information about these modes, check out MSDN.

ASP

There’s two ways to change the session timeout when you’re dealing with classic ASP.

You can set it at the application level, or programmatically, which means that the value can be different within the application.

Since it doesn’t specifically state that the setting is for classic ASP, it may be confusing to know that the value is in: Application Properties -> Configuration… -> Options -> Enable session state.

It’s as simple as updating this value, and the session timeout for your entire classic ASP application is changed!

Programmatically

You can also use modify the Session.Timeout property at runtime to affect the timeout period of the session. One popular location to put this piece of code is in the global.asa file.

<script language="VBScript" runat="Server">
Sub Session_OnStart
 Session.Timeout = 90
End Sub
</SCRIPT>

Hope this tutorial helpful. 



European ASP.NET Hosting - Amsterdam :: The Parallel.Invoke() Method C# / .NET

clock February 4, 2013 10:17 by author Scott

Many times in software development, we want to invoke several processes at one time and continue when we get all the results back.  Obviously, if we were needing to process a sequence of items in a similar matter, we could use PLINQ.  Unfortunately, when the things we want to invoke asynchronously are heterogeneous tasks, PLINQ doesn’t really fit the bill.  Today we will look at a handy method in the Parallel class that can help us accomplish this.

Invoking processes asynchronously

Let’s say we have three completely separate methods and we want to invoke all three of them and the continue when they have returned.  These methods may be from separate classes and have completely different parameters and/or return types.  Thus, it may not be possible to use facilities likeParallel.ForEach() or PLINQ.

So how would we do this?  Well, we could obviously create three threads, start them, and join on them to come back:

   1: var threads = new List<Thread>
   2:                   {
   3:                       new Thread(SomeMethod),
   4:                       new Thread(() => SomeOtherMethod(x, y)),
   5:                       new Thread(() => { result = YetAnotherMethod(x, y, z); })
   6:                   };
   7: threads.ForEach(t => t.Start());
   8: threads.ForEach(t => t.Join());

Which, as you can see, can be used to call any method that fits Thread’s constructor (or can be adapted to it using a lambda, etc.). 

But that’s a bit heavy.  In addition, if an unhandled exception is thrown in one of those methods it will kill the thread, but we don’t have a very clean way of catching it here at the point of invocation.

Of course, we also have the Task class from the TPL which can help simplify threads:

   1: var tasks = new []
   2:
                 {
   3:                     Task.Factory.StartNew(SomeMethod),
   4:                     Task.Factory.StartNew(() => SomeOtherMethod(x, y)),
   5:                     Task.Factory.StartNew(() => { result = YetAnotherMethod(x, y, z); })
   6:                 };
   7: Task.WaitAll(tasks);

This simplifies things on the surface, and better yet simplifies things a lot more with exception handling as well (TPL task exceptions get wrapped into a AggregateException and can be caught at the WaitAll() – and other possible places).

But there’s an even easier way…

Parallel.Invoke() – Easily invoke asynchronously

Just as the TPL gave us Parallel.For() and Parallel.ForEach() to make processing loops asynchronously a breeze, it also gave us Parallel.Invoke(), which takes any number of Action delegates and invokes them asynchronously and waits for them to rejoin.  If your methods have return values you want to store or need parameters, you can easily use lambda expressions as well:

   1: Parallel.Invoke(
   2:
     SomeMethod,
   3:     () => SomeOtherMethod(x, y)),
   4:     () => { result = YetAnotherMethod(x, y, z); })

As long as the method can convert to an Action or you can form a lambda that will allow it to do so, you can use the Parallel.Invoke() to easily call them all in parallel without having to worry about starting or joining the threads or tasks.  And, because this is part of the TPL, you get the nice AggregateException handling as well that lets you easily catch tasks thrown from the underlying tasks.

Summary

When you just need to fire off several methods in parallel, consider the Parallel.Invoke().  It is a very handy way to invoke several different methods easily without having to worry about all the details of creating tasks or threads.

 



European ASP.NET Hosting - Amsterdam :: jQuery and Clicking an ASP.NET Linkbutton

clock October 11, 2012 08:15 by author Scott

As a web developer one common request is to make sure that the interfaces we build out for users look the best that they can and also provide users with the best experience both via the keyboard and mouse. As part of this we will often have areas of conflict. This post is going to cover one common scenario that will impact users that might be using DotNetNuke common styles or working to create their own custom button styles. With ASP.NET it is common for people to use "LinkButton" controls to trigger actions rather than your standard "Button" controls as they are easier to style.

There is nothing wrong with this until you try to perform actions against the 'LinkButton' and it doesn't function as you would expect. For this purposes of this post lets say we are building a custom login form that has two textboxes; txtUsername and txtPassword and a single LinkButton btnLogin. We want to ensure that if the user presses enter on either of the textboxes that they are logged in.


Using standard jQuery we would try something like this:


   1:  $("#<%=txtPassword.ClientID %>").keydown(function(event) {
   2:      if (event.keyCode == 13) {
   3:          $("#<%=btnLogin.ClientID %>").click();
   4:      }
   5:  });


This is a pretty standard jQuery method to listen for the enter key and simply "click" the button. However, if you are using a LinkButton this code will not work. The reason for this is that a LinkButton is rendered to the browser as an Anchor tag with a href property that contains a javascript action to trigger the postback. Click does nothing on the button as there is nothing for it to complete.


To get around this you need to actually look into the generated anchor tag, grab the href value and evaluate it. Similar to the following:


   1:  $("#<%=txtPassword.ClientID %>").keydown(function(event) {
   2:      if (event.keyCode == 13) {
   3:          eval($("#<%=btnLogin.ClientID %>").attr('href'));
   4:      }
   5:  });


Using this structure the postback will be triggered and the user will be logged in as you expect them. This works great for any linkbutton, including those styled with the default DotNetNuke 6.x form pattern styles.

 



European ASP.NET Hosting - Amsterdam :: HTML5 for the ASP.NET Developer

clock August 28, 2012 06:39 by author Scott

New Features in HTML5

HTML5 is an umbrella term for the new HTML, JavaScript, and Cascading Style Sheets (CSS) features that are being standardized. New HTML tags include the <nav> tag, which is used for general website navigation; the <video> tag, which is used for displaying video content; and the <audio> tag, which is used for playing audio content. In general, these tags replace the <object> tag that websites used previously. HTML5 also includes new input controls that are designed to handle some of the more common input scenarios, such as issues with dates and times. Finally, numerous attributes have been added to existing controls. Many of the existing input controls have new and enhanced attributes that allow browsers to expose users to new functionality.

Along with the new markup specifications, new JavaScript classes let programmers capitalize on the latest features that developers have been asking for. The following paragraphs discuss some of these features.

JavaScript selectors
. There are new JavaScript selectors for getElementById and getElementByTagName. There are also selectors, such as getElementByClassName and querySelector.

LocalStorage
. Developers have long been using cookies for local storage. However, cookies are sent across the wire and back to the server, a transfer that increases sent data volumes. HTML5 introduces support for a storage feature named LocalStorage. With this feature, data is no longer sent across the wire with each server request. Also, more data can be stored with LocalStorage than with cookies.

WebSQL
. Although WebSQL is no longer a part of the HTML5 standard, this feature has been implemented in several browsers, such as iPhone's Safari and the Android browser. This feature can be tested for and used.

Threads
. On a desktop application, a long-running operation can be spun off into another thread, allowing the user to continue working without blocking the application's UI. HTML5 introduces this concept of threads in the browser environment, a feature known as Web Workers.

Application caching
. What happens when an application cannot connect to its web server? There may be a variety of reasons, but the user only knows that the application is offline. HTML5 provides an offline application-caching API that allows an application to degrade more gracefully when it cannot connect to its web server.

Web sockets
. When there is a long-running event on the server, the browser can be set to poll for a completion. What happens when 100,000 users continually nag the server with the online equivalent of "Are we there yet?" To address this issue, the HTML5 standard has web sockets. However, there are some security issues in the underlying communications protocol that must be addressed.

Drawing. It's possible to draw in the browser by using the Canvas tag and its associated JavaScript commands.

Geolocation
. Geolocation is not a part of, but is associated with, the HTML5 specifications. Because it is often discussed as a part of HTML5, we'll consider it that way for this article. Geolocation allows a browser to determine its current location so that the user can be presented with local information. Geolocation allows for more accurate location information than is typically possible through IP address lookup services.

Other features allow for drag-and-drop support, audio and video tag manipulation, server-sent events, and other features. Some of these features will also require server support for optimal performance.


A Peek at HTML5


Let's take a peek at a simple HTML5 web page and make some key observations about the code. Figure 1 shows some sample source code.


Figure 1: Sample HTML5 source code


<!DOCTYPE html>
 <html lang="en">
     <head>
         <meta charset="utf-8" />
         <meta http-equiv="X-UA-compatible" content="IE=edge,chrome=1" />
         <title>About My HTML5 Site</title>

    </head>
     <body>
     <div id="container">
             <header  >               

                <h1>About My HTML5 Site</h1>
             </header>
                 <p>
     This web page was built using ASP.NET. For more information, visit the
     <a href="http://www.asp.net">ASP.NET homepage</a>.
 </p>
             <footer>               

                <span style="margin-left:auto;margin-right:auto;"><a href="http://www.scalabledevelopment.com">SDI</a></span>
             </footer>
         </div>
     </body>
 </html>

Notice that the doctype tag, which tells a browser which version of HTML to use, is now much simpler. In HTML5, there is only one doctype tag. The X-UA-Compatible meta tag tells the browser to use the most recent engine available. My system has the Google Chrome frame plug-in installed, so this information is included, as well as the instruction to use the most recent version of the Internet Explorer (IE) engine. Finally, the page is logically divided by header, content, and footer tags. These tags instruct a browser to separate the content visually. This instruction is particularly important for a mobile web browser.


Browsers Galore

Currently, there is no single dominant browser. We've got IE, Firefox, Chrome, Safari, and Opera for the desktop. Add to those the many mobile device browsers such as Safari, the Android browser, and the mobile IE for Windows Phone 7, along with the various versions of each browser. Developers are presented with a vast and complex array of scenarios to code for. In this vein, you may be familiar with the following JavaScript code:

If ( navigator.useragent.indexOf(…….) > -1)
{
// do something...

This code determines whether the browser is of a specific type. It then responds accordingly—for example, by redirecting the browser to a page optimized for that browser.

Similar functionality exists on the server. The ASP.NET developer can use the Request.Browser server-side object. Some of the properties of this object that you may find useful include the following:

• Request.Browser.IsMobileDevice
• Request.Browser.MobileDeviceManufacturer
• Request.Browser.MobileDeviceModel
• Request.Browser.ScreenPixels

Along with the Request.Browser server-side object, ASP.NET controls contain support for various browsers, based on the user-agent header value. You can also use the Wireless Universal Resource File (WURFL) project. The WURFL project contains a more current set of browser definitions that allow a user to determine device features on the server, such as device input method, audio format support, and other features that are not part of the built-in ASP.NET capabilities. This general technique is referred to as browser detection. While conceptually simple, browser detection tends to be problematic. Browser detection typically results in a large number of if/else statements. This can be confusing and difficult to change.

Feature detection is another useful HTML5 option. A browser is tested for its support of various features. If it supports a particular feature, the browser uses it; if support for the feature is not available in the browser, the feature is not used. Although slightly different from browser detection, feature detection results in simpler code that is ultimately easier to maintain. Although browser detection was fairly common for years, feature detection is better for creating maintainable code.

Along with feature detection, a JavaScript library named Modernizr helps developers implement reliable feature detection. The following code sample uses the Modernizr library to test for geolocation support and then apply geolocation.

       if (Modernizr.geolocation) {
             var navgeo = navigator.geolocation;
             navgeo.getCurrentPosition(WhereIsUser, WhereIsUserError, PosOptions);
         }

Native IE9

At the MIX11 conference, Microsoft made a lot of predictable noise in support of IE because of its "native" status. Terms like native HTML were bandied about. Add to that an early June 2011 demo of Windows 8 with HTML and JavaScript, and there has been some understandable confusion in the marketplace. With all these terms and ideas being tossed around, what's a developer to do? Microsoft will have its BUILD conference in September, so hopefully we'll know more then. In the mean time, there are a few things that we do know about IE9 regarding its optimizations and hardware acceleration.

First, we know that the JavaScript engine has been rewritten to support multiple processor cores. Specifically, a background compilation takes JavaScript and converts it into machine code that runs faster on a given system. Secondly, the machine code that the JavaScript engine produces takes advantage of the most recent and optimized machine commands. Finally, we know that the HTML, Scalable Vector Graphics (SVG), CSS, audio, and video support have been reconfigured for hardware acceleration. Microsoft may have added these features to support modern hardware capabilities such as graphics processing units (GPUs), multiple cores, and other new developments. For example, the <canvas> tag will attain a big boost in performance when it is used in IE9. Overall, it appears that the folks at Microsoft are promoting their browser as the best platform because there are fewer operating system layers to go through when you use IE in a Windows environment.

How ASP.NET Developers Can Be Involved

If you're an ASP.NET developer, you're faced with a couple of questions when designing an ASP.NET application to support HTML5. The first question concerns how to present an application to the user. Currently, HTML5 browsers are more frequently found in mobile devices than in desktop browsers. Since there is a profound difference between a four-inch mobile device and a 25-inch desktop browser, you must understand the differences between the two. A web application designed for a desktop browser (as shown in Figure 2) will most likely present a horrible experience to a user who connects to the application over a mobile device (as shown in Figure 3).





Given the significant differences in device dimensions, successful sites, such as ESPN and Ruby Tuesday design their applications for a general display size. If a user comes to a site through a desktop browser, the user goes right on into the site. If a user comes to a site through a mobile browser, the user is redirected to a mobile version of the application. The code to detect the type of browser and perform the redirection can be placed within the session's Start event.


The second question concerns which ASP.NET display technology to use. Thankfully, it doesn't matter if an application uses ASP.NET Web Forms, ASP.NET MVC, or ASP.NET Web Pages (aka Razor). All these technologies can be used to build an HTML5 ASP.NET application. ASP.NET, MVC, and Web Pages let you directly interact with the HTML output, so you don't need to do anything special when using these types of projects. You only need to write valid HTML5 code for the devices you're planning to support. With a few changes of the standard features in ASP.NET Web Forms, you can use HTML5 features quickly and easily.

Web Forms


ASP.NET Web Forms is a very popular development framework. The problem with Web Forms is that some of its standard features create confusion. The most problematic features in HTML5 and mobile spaces are ViewState, ClientIDs, and MasterPages. We'll walk through ways to provide users with a more optimal solution to the problems encountered when using these features.

ViewState. ASP.NET developers are used to working with ViewState, the feature that makes Web Forms work. However, ViewState increases the size of the web page. For example, if you bind a set of objects to a grid, the size of the page increases dramatically. While the size of the page is not necessarily a big deal for applications that are running over a fairly reliable network, increased page size greatly increases the risk of an error when the page is transmitted over wireless 3G and 4G networks. To work around this issue, you have two options.

First, you can turn off ViewState unless it's needed by a specific control on a page. When you turn off ViewState, it is minimized unless it's absolutely needed, as determined by a developer. However, a page may still be too large because ViewState is stored on the client web page. In this scenario, ViewState can be turned off at the container, page, application, or server level. Turning it off at these levels eliminates the ViewState payload unless it's absolutely necessary for a control.

ASP.NET 4 introduces a feature that lets you turn off ViewState at a higher level in the hierarchy, then turn it on as necessary. Specifically, ViewState can be modified by the ViewStateMode attribute in an ASP.NET control. In the examples in Figure 4 and Figure 5, a grid of data is displayed to the user. The GridView doesn't require many of the more complicated features typically associated with HTML5, so turning off ViewState has no effect on the application or the user. Note that the ViewState mode is turned off within the Content2 container. Figure 4 shows the code for the content view. Figure 5 shows the output of the code in Figure 4.


Figure 4: Code for the content view


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server" ViewStateMode="Disabled">

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
 View State Size: <span id="ViewStateSize"></span>
 <script language="javascript" type="text/javascript">
     $(document).ready(function () {
         // put all your jQuery goodness in here.
         var vs = document.getElementById("__VIEWSTATE");
         var outPut = document.getElementById("ViewStateSize");
         outPut.innerHTML = vs.value.length;
     });
 </script>
 <asp:GridView ID="gvCustomer" runat="server">
 <Columns>
 <asp:TemplateField AccessibleHeaderText="Get Info" HeaderText="Get Info">
 <ItemTemplate>
     <asp:HyperLink ID="hl" runat="server" Text="Get Info"
         NavigateUrl='<%# String.Format("CustomerInformation.aspx?CustomerID={0}", Container.DataItem) %>' />
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 </asp:GridView>
 </asp:Content>



The second option is to store ViewState on the server. When you use this option, the data is never transferred across the wireless connection. This requires some setup on the pages, but once configured, this option is relatively painless. There are a number of articles about this topic on the web, so there's not much reason to go over the details here.


ClientIDs
. Automatically generated ClientIDs represent the next issue that ASP.NET developers must negotiate. By default, the client IDs that are generated comprise a munged version of the server-side parent containers and control IDs. For example, the grid shown in the ViewState example has the ID MainContent_gvCustomer. You can use the following JavaScript command to get a client-side reference to a server-side object:

var serverObject = document.getElementById('<%: gvCustomer.ClientID%>');

Unfortunately, developers are not the only folks who work on a project. Designers are also involved, and they may not be familiar with the functionality behind control IDs. Therefore, a new feature was introduced in ASP.NET 4 to grant programmers complete control over the client IDs that are generated. This feature is controlled by the ClientIDMode attribute. The values of particular interest for this attribute are Static and Predictable. The Static attribute makes sure that the client ID that is generated remains the same as the server ID. The Predictable attribute is used in conjunction with the data-bound controls and the Static value to generate repeatable client IDs in a grid.


MasterPages. Although not necessarily a requirement for Web Forms developers, MasterPages is a great tool for sharing display layout among pages. I don't recommend that you try to use the same general layout for both a desktop web application and a mobile web application. Instead, it makes sense to create a master page optimized for mobile devices and to continue using this design and layout technique, although MasterPages will certainly be different because of the difference in the layout capabilities of a mobile device and a desktop web browser.

HTML5 Validation

In the Visual Studio 2010 SP1 release, the April 2011 ASP.NET MVC 3 Tools update, and the June 2011 release of the Visual Studio Web Standards update, Microsoft not only updated its MVC tools, but it also added support for HTML5, as illustrated in Figures 6A and 6B. Developers now get support for HTML5, CSS3, and the JavaScript objects that support the new features. With CSS3 support, even the IE, Mozilla, and Safari extensions are supported.





Saving Bandwidth with CDNs


Most developers are accustomed to copying files locally to a solution, then running the application as a self-contained unit. There are a number of files that applications share, not only across a single company but also across many applications. These are libraries such as jQuery and many of the JavaScript libraries that are a part of the ASP.NET 4 framework. Many companies and organizations share these libraries. Instead of using this bandwidth on your servers and routinely downloading these files, based on caching settings, it makes sense to use the same copies that others may have already downloaded to their systems. This means that instead of loading JavaScript files, CSS files, and others from your web server, the user's browser downloads the files from various content delivery networks (CDNs). Although this approach may not sound like a significant improvement, your users will typically obtain a better response time for various libraries from these CDNs. Along with shipment of ASP.NET 4, Microsoft has provided support for its CDN within the ASP.NET ScriptManager by setting the EnableCdn attribute to true.


To illustrate the difference between using a CDN and using content from your own local web server, let's look at the results from a simple ASP.NET Web Form by using the Firebug and YSlow tools. Let's look at a simple page with only the master page and the script manager installed, as shown in Figure 7.




Once the four standard ASP.NET JavaScript files are cached locally, 56.6KB of data is being pulled from the local cache. This may not sound like a lot of data, but in an HTML5 mobile world, this amount can be significant.


Now, what would have happened if we had not used the CDN? As you can see from Figure 8, YSlow reports that the files are cached coming from our own web server.




However, it is highly unlikely that other applications are pulling this content from our servers; at least we hope that they aren't. By using the files from our local server, users are paying the "bandwidth tax" instead of using the files that may already be cached locally from another application. Every little bit of bandwidth savings helps, especially in the mobile space. A second advantage is that on public-facing websites where bandwidth may cost money, the bandwidth cost for your website will most likely go down by using a CDN. For more information about why to cache files through CDNs, check out Dave Ward's excellent set of articles in the Links of Interest sidebar at the end of this article


ASP.NET MVC


In pages and applications based on the MVC design pattern, the presentation logic is decoupled from the underlying application logic. If an application needs to present different views of the same data to a desktop and a mobile client web client, it is possible to reuse the underlying models and controllers and merely swap the views as necessary. I think this is a huge win for web developers who are using the ASP.NET MVC framework.


With the recent MVC3 Tools update, the ASP.NET team has added the ability to use HTML5 by default. You can do so by selecting the Use HTML5 semantic markup check box, as shown in Figure 9.


 



European ASP.NET Hosting - Amsterdam :: Steps for Session InProc Mode to Session StateServer

clock August 14, 2012 08:17 by author Scott

Main Advantage of Session StateServer (Best to choose while hosting on third party server)

1. Session is persistent and reliable.

2. Avoid Session Timeout due to Memory shortage on server (IIS Setting).

Main Disadvantage


1. Poor Performance compare to Session="InProc"

2. Session_End Event would not fire.

Steps for changing Session InProc Mode to Session StateServer Mode.


Step 1: Start Asp.net State Servcie


1. Go to Control Panel > Administrative Tools > Services


2. Select Asp.Net State Service.


3. Right Click on Asp.net State Service and choose start from popup menu.






If you forget to Start Service you will receive following error.

Server Error in '/' Application.


Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection. If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.

Step 2: Change Session Mode in Web.Config File

<sessionState mode="StateServer"
               
stateConnectionString="tcpip=127.0.0.1:42424"
               
cookieless="false"
               
timeout="120"/>


Note: You can adjust timeout minutes based on your requirement. Let the tcpip server to be localhost i.e. 127.0.0.1. Most webhosting company uses these settings unless you have different IP for StateServer and You are not required to change Port Number.

Step 3: Make All Object Serializable

You should make all object in your website to serializable.

Note: To take advantage of Session StateServer or SQLServer or Custom Mode, object needs to be serialized.

Example: If your project contains class files for creating DAL (Data Access Layer), you should append Serializable to every class definition in order to make class Serializable.

[Serializable]

Class Department
{
          long _deptId;
          string _deptName;

          public long DeptId
          {
                    get { return _deptId; }
                    set { _deptId = value; }
          }

          public string DeptName
          {
                   get { return _deptName; }
                   set { _deptName = value; }
          }
}

IMPORTANT While doing Serialization

Remember SQLConnection cannot be serialized.

You might receive following error if you don't handle this situation.

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

So to handle this situation you need to do following thing.

1. Mark SQLConnection Object as NonSerialized [NonSerialized] protected SqlConnection _mainConnection;

2. Mark your Class as Serializable and derive from IDeserializationCallback
Example:

[Serializable]

Class Department: IDeserializationCallback
{
   
long _deptId;
   
string _deptName;

   
public long DeptId
   
{
       
get { return _deptId; }
       
set { _deptId = value; }
   
}

   
public string DeptName
   
{
       
get { return _deptName; }
       
set { _deptName = value; }
   
}

   
//Create this Method Inside your Class
   
void IDeserializationCallback.OnDeserialization(object sender)
   
{
       //Recreate your connection here
      
_mainConnection = new SqlConnection();
      
_mainConnection.ConnectionString =
           
ConfigurationSettings.AppSettings["connStr"].ToString();
   
}
}



European ASP.NET Hosting - Amsterdam :: Commenting Server Controls in ASP.NET

clock July 10, 2012 07:39 by author Scott

How often do you just use an HTML comment to remove old code, or new functionality that isn’t ready yet? Are HTML comments effective for ASP.Net server controls? From a pure development context, they probably are. When we factor in security, they no longer provide the functionality that was intended. This post will explain an issue with how ASP.Net handles this situation and why it is not sufficient from a security perspective.

I am going to use a very simplistic example to make it easier to understand and to save space. Please do not let this simple example downplay the significance of this issue. In this example, I have added two label controls and a button control. I will walk through a few different scenarios to explain what is happening. Here is what the relevant part of the html page looks like:


  1: <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
  2:     <h2>
  3:         HTML Comment Test Page
  4:     </h2>
  5:     <p>
  6:         <asp:Label ID="lblUserName" runat="server" />
  7:         <asp:Label ID="lblAcctNum" runat="server" />
  8:         <asp:Button ID="cmdSubmit" runat="server" Text="Submit"
  9:             onclick="cmdSubmit_Click" />
 10:     </p>
 11: </asp:Content>

Below is the relevant code from the default.aspx.cs code behind file.  This is the code that contains the button click event that will be important throughout this post.

  1: protected void Page_Load(object sender, EventArgs e)
  2: {
  3:     lblUserName.Text = "joeUser";
  4:     lblAcctNum.Text = "933-3222222-939239";
  5: }
  6: protected void cmdSubmit_Click(object sender, EventArgs e)
  7: {
  8:     lblUserName.Text = "This shouldn't have happened.";
  9: }

When we run the page, the following output is exactly what we expect.  The labels are populated with their respected values and the button is there. 

  1: <h2>
  2:     HTML Comment Test Page
  3: </h2>
  4: <p>
  5:     <span id="MainContent_lblUserName">joeUser</span>
  6:     <span id="MainContent_lblAcctNum">933-3222222-939239</span>
  7:     <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="MainContent_cmdSubmit" />
  8: </p>

I would like to call out separately the EventValidation value.  It is beyond the scope of this post to fully explain EventValidation within .Net, but the short explanation is that it is used to only allow expected events to be triggered on the server.  The value is a hash of the allowed values and events.  Here is the value for this page:

  1: /wEWAgLFs4viAgKP5u6DCOTYhw/mo3AHFQHnB8XMEMHlrATJQZUNTjLevOMdQoay

Now lets comment out the button control and a label control and see what happens.  I will comment out the account number because I realized there are some problems with it.  It is displaying sensitive information and it is vulnerable to cross-site scripting.  I want to remove the button, because it is old functionality and I don’t want anyone to be able to perform that action going forward.  Here is what the new HTML data looks like:

  1: <h2>
  2:     HTML Comment Test Page
  3: </h2>
  4: <p>
  5:     <asp:Label ID="lblUserName" runat="server" />
  6:
  7:     <!--<asp:Label ID="lblAcctNum" runat="server" />-->
  8:     <!--<asp:Button ID="cmdSubmit" runat="server" Text="Submit"
  9:         onclick="cmdSubmit_Click" />-->
 10: </p>

It is important to note that I did not make any changes to the code behind file, because it was a) easier to update the html document and b) it doesn’t require me to change compiled code.  Although neither of these are good reasons, they are just used for the example.

Here is what the new HTML output looks like:


  1: <h2>
  2:      HTML Comment Test Page
  3: </h2>
  4: <p>
  5:      <span id="MainContent_lblUserName">joeUser</span>
  6:
  7:      <!--<span id="MainContent_lblAcctNum">933-3222222-939239</span>-->
  8:      <!--<input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="MainContent_cmdSubmit" />-->
  9: </p>

The good news is that the elements are commented out, as we expected, but do you see a problem?  On line 7, the account number is still being populated and on line 8 the button was processed as well to a proper HTML button, rather than the asp:control that we commented out.  I would have expected that the controls would not have been processed because they were commented out. 

The .Net framework does not detect that the ASP.Net server controls are within HTML comments and still processes them as if they were not commented out.  Now, that sensitive data I was trying to remove, is just not displayed on the page, but still available in the source of the page.  All a user would have to do is View Source to see it. 

Remember I also mentioned I wanted to remove this label because it was vulnerable to cross-site scripting.  Well, unfortunately, it still is.  Just because it lives inside of HTML comments doesn’t mean if the proper values are sent down it is still protected.  It is possible for an attacker to submit data that will break out of the comment and then add their own execution steps.

Also, notice that the button looks valid.  What would happen if the end user decided to remove the comments around the button?  In this case, the button would still fire as it did in the first example.  There are other ways to trigger this button, but re-enabling it with a proxy or browser add-in is the easiest.  Lets take another look at our EventValidation value:

  1: /wEWAgLFs4viAgKP5u6DCOTYhw/mo3AHFQHnB8XMEMHlrATJQZUNTjLevOMdQoay

This value is the same as the last time we checked it before commenting out the button control.
  Since it is the same, we know that the same events are available to us and the button will be accepted.  This could cause a problem if the code is not ready for prime time, or has been removed due to issues of some sort.

A better way to resolve this issue is to set the Visible property for each of the server controls you no longer want to exist on the page, or just remove them if you are using source control.
  By setting the visible property to “False”, the .Net framework will not process that control and send it to the browser.  This also effects the EventValidation.  Lets look and see what happens when we set the Visible property in the HTML.

  1: <h2>
  2:     HTML Comment Test Page
  3: </h2>
  4: <p>
  5:     <asp:Label ID="lblUserName" runat="server" />
  6:
  7:     <asp:Label ID="lblAcctNum" Visible="false" runat="server" />
  8:     <asp:Button ID="cmdSubmit" runat="server" Visible="false" Text="Submit"
  9:         onclick="cmdSubmit_Click" />
 10: </p>

Here is the output:


  1: <p>
  2:     <span id="MainContent_lblUserName">joeUser</span>
  3:
  4:    
  5:    
  6: </p>

Notice how the button and label are no longer being output to the browser at all.
  This is much better and more secure.  Lets check the EventValidation value just to make sure it has changed. Oh, wait, because there are no other events on this page, EventValidation not longer exists.  That means that no events would be accepted by our page.  If other events existed, or if a listbox existed, then our value would have been different.  If we tried to then submit the button click event, an ASP.Net error would have been raised. 

As you can see, there are some issues when just using HTML comments for your server controls.
  ASP.Net has an issue, maybe a bug, that doesn’t detect this behavior and processes the controls as if they were allowed.  Remember, it is easy to re-enable a commented out control, so make sure you avoid that situation.  Just because a controls is commented, doesn’t mean it will represent a security risk, but any instance of this should be examined for potential security problems.




 



European ASP.NET Hosting - Amsterdam :: Improving the C# Debugging Experience - DebuggerDisplay

clock May 28, 2012 09:25 by author Scott

In an effort to start blogging more about the "helpful" items that I have encountered over the years this is one of my first "Quick Tips" related to improving the life of the developer. We all have had those times where we are tracking down a complex problem within an application and all along the way we have to spend endless time mousing over individual classes to find out what their values are when most commonly we just want to know about one or two key values. Well in this post, I'll show you a neat trick using the "DebuggerDisplay" attribute to help make this process easier.

The Code


To get us started I'm going to just dive into the code, consider the following super condensed code sample.


   1:  static void Main(string[] args)
   2:  {
   3:      var badSampleInstance = new BadSample()
   4:                              { Name = "John Smith",
   5:                                  Address = "123 Main Street",
   6:                                  Phone = "515-555-1212" };
   7:      var goodSampleInstance = new GoodSample()
   8:                              { Name = "John Smith",
   9:                                  Address = "123 Main Street",
  10:                                  Phone = "515-555-1212" };
  11:      Console.ReadLine();
  12:  }
  13:   
  14:  public class BadSample
  15:  {
  16:      public string Name { get; set; }
  17:      public string Address { get; set; }
  18:      public string Phone { get; set; }
  19:  }
  20:   
  21:  [DebuggerDisplay("{Name} ({Phone})")]
  22:  public class GoodSample
  23:  {
  24:      public string Name { get; set; }
  25:      public string Address { get; set; }
  26:      public string Phone { get; set; }
  27:  }

From here we can see a very simple set of code with two classes. If you notice I have added an attribute "DebuggerDisplay" to the top of the GoodSample class. The value used for the display contains a few substitutions "{Name}" and "{Phone}". What this does is update all of the display areas in the debugger, that would typically show the type name for the value which isn't helpful to show the formatted value we supplied. An example of this can be seen here.




So as you can see this can help to get a good glance into your custom objects, and reduce a lot of the "mouseover" action that is common while debugging.


I hope that this content was helpful.



European ASP.NET Hosting - Amsterdam :: Read or Write connection strings in web.config file using asp.net

clock May 4, 2012 08:40 by author Scott

In this article I will explain how to read or write connection strings in web.config file using asp.net.

I have one web application that contains many pages and each page contains relationship with database connection to get data from database and display it on page because of that I need to write database connections for each page to interact with database. Now the server name or credentials of database server has changed in that situation it will create problem because we need to modify the database connections of each page using asp.net.


To avoid this situation it would be better if we place connection string in one place and reuse it in every page wherever we need to connect to SQL Server. Web.config is the best place to store the connection strings in asp.net and it would be safer place to store the connection strings instead of writing connection strings in every web page.


Now we want to add connection string in web.config file for that first create new website using visual studio after that create new website open web.config file and search for “connectionStrings” and add new item in connectionStrings section


After open
web.config file in application and add sample db connection in connectionStrings section like this

<
connectionStrings>
<
add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; "
providerName="System.Data.SqlClient"/>

</
connectionStrings >

Example of declaring connectionStrings in web.config file like this


<
connectionStrings>
<
add name="dbconnection" connectionString="Data Source=Scott;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</
connectionStrings >

Here to access my database server there is no need of username and password for that reason I didn’t enter username and password in connection string.


After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code


using
System.Configuration;

This namespace is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

C# code

using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}

VB.NET

Imports
System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String =
ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class

OK, finish.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, ASP.NET MVC 5 Hosting and SQL 2014 Hosting.


Tag cloud

Sign in