ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 HOSTING - ASPHostPortal.com | How to Create Dynamic GridView Control in C#/ASP.Net

clock November 18, 2014 06:54 by author Dan

Introduction

In webapplications, one the most widely task is showing a table of information to clients. In Asp.net, we make utilization of the Datagrid, Datalist and Repeater controls. Every day, the need of showing the information will be diverse. Now, we will explain to you about "How to Create Dynamic GridView Control in C#/ASP.Net". Please read the steps carefully.

Implementing Dynamic GridView Control

Utilizing the gridview to show the articles will show the article a little in diverse layout when compared with Datalist. Appoint the below figure, Dynamic Gridview.

Constructing Dynamic GridView

Showing the articles in gridview will be different from showing in datalist. For that, i have made two Template classes :

  • DynamicGridViewTextTemplate
  • DynamicGridViewURLTemplate

Dynamicgridviewtexttemplate class is utilized to include a layout column with label while Dynamicgridviewurltemplate class is utilized to include URL of the article.

TemplateClass for GridView

public class DynamicGridViewTextTemplate : ITemplate
{
    string _ColName;
    DataControlRowType _rowType;
    int _Count;
    public DynamicGridViewTextTemplate(string ColName, DataControlRowType RowType)
    {
        _ColName = ColName;
        _rowType = RowType;
    }
    public DynamicGridViewTextTemplate(DataControlRowType RowType, int ArticleCount)
    {
        _rowType = RowType;
        _Count = ArticleCount;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + _ColName + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:              
                 Label lbl = new Label();
                 lbl.DataBinding += new EventHandler(this.lbl_DataBind);
                 container.Controls.Add(lbl);              
                break;
            case DataControlRowType.Footer:
                Literal flc = new Literal();
                flc.Text = "<b>Total No of Articles:" + _Count + "</b>";
                container.Controls.Add(flc);
                break;
            default:
                break;
        }
    }
 
  
    private void lbl_DataBind(Object sender, EventArgs e)
    {
        Label lbl  = (Label)sender;
        GridViewRow row = (GridViewRow)lbl.NamingContainer;
        lbl.Text =DataBinder.Eval(row.DataItem, _ColName).ToString();
    }
 
}
public class DynamicGridViewURLTemplate : ITemplate
{
    string _ColNameText;
    string _ColNameURL;
    DataControlRowType _rowType;
 
    public DynamicGridViewURLTemplate(string ColNameText, string ColNameURL, DataControlRowType RowType)
    {
        _ColNameText = ColNameText;
        _rowType = RowType;
        _ColNameURL = ColNameURL;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + _ColNameURL + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                HyperLink hpl = new HyperLink();
                hpl.Target = "_blank";
                hpl.DataBinding += new EventHandler(this.hpl_DataBind);
                container.Controls.Add(hpl);
                break;
            default:
                break;
        }
    }
 
    private void hpl_DataBind(Object sender, EventArgs e)
    {
        HyperLink hpl = (HyperLink)sender;
        GridViewRow row = (GridViewRow)hpl.NamingContainer;
        hpl.NavigateUrl = DataBinder.Eval(row.DataItem, _ColNameURL).ToString();
        hpl.Text = "<div class=\"Post\"><div class=\"PostTitle\">" + DataBinder.Eval(row.DataItem, _ColNameText).ToString() + "</div></div>";
    }
}

Using the Template Class in GridView

Utilizing dynamic template in gridview is not the same as datalist i.e. we will make the dynamic gridview in column wise with header layout, item template and footer layout from the first column till the last.

Steps:

  1. Create a Gridview Object.
  2. Create an instance of TemplateField object.
  3. Instantiate the Dynamic template class with proper ListItemType and assign it to corresponding template property of TemplateField object and finally add this object to the column collection of GridView. Refer the below code for better understanding.

Templates of GridView

TemplateField tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);
                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count); 

In the event that you analyze the usage of Datalist, in Gridview we won't make dynamic template for the grid within we make it for the grid's column (Templatefield). Appoint the below code (Using Template class) for clear understanding.

Using Template class

for (int i = 0; i < ds.Tables.Count; i++)
        {
            if (ds.Tables[i].Rows.Count > 0)
            {
                GridView gvDynamicArticle = new GridView();
                gvDynamicArticle.Width = Unit.Pixel(700);
                gvDynamicArticle.BorderWidth = Unit.Pixel(0);
                gvDynamicArticle.Caption = "<div id=\"nifty\" class=\"PostCategory\"> + ds.Tables[i].Rows[0]["Category"].ToString() + " Articles</div>";
                gvDynamicArticle.AutoGenerateColumns = false;
                gvDynamicArticle.ShowFooter = true;
                TemplateField tf = null;
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);
                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count);               
              
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Author", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("CreatedBy", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
 
                gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(this.DynamicGrid_RowDataBound);
 
                gvDynamicArticle.DataSource = ds.Tables[i];
                gvDynamicArticle.DataBind();
                phDynamicGridHolder.Controls.Add(gvDynamicArticle);
            }
        }
In the above code (Using Template class), we can unmistakably comprehend that we are making the dynamic template for the gridview's column instead of Datalist where we made the template for the grid itself. To throw more light on this it implies that we are making the first column's header, item and footer and adding it to the gridview's column list through Templatefield article till the last column as I said before.


ASP.NET 4.5 Hosting - Security Improvement in ASP.NEt 4.5

clock March 18, 2013 08:21 by author andy_yo

The .NET 4.5 framework was released a couple of months ago and it included several improvements in the security area. To benefit from these improvements you need to do a few changes to you application's configuration file.
There are some important improvement in ASP.NET 4.5:

  • There are changes to the ASP.NET request validation, it now supports deferred (lazy) validation, as well as giving the option to fetch data unvalidated.
  • The AntiXSS library is included in the framework.
  • There are significant Cryptographic Improvements in ASP.NET 4.5.
  • Windows Identity Foundation is now included in the framework, referred to as WIF 4.5.

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

To take advantage of these new bits you'll have to do a bit of configuration, we'll get into that right away:

Switching to 4.5
While retargeting a couple of MVC applications to the new framework version, I learned that it's not enough to install the 4.5 framework and change the "Target framework" accordingly. You'll find that a comment appears in the web.config file:
<!--
    For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367.       
    The following attributes can be set on the <httpRuntime> tag.      
     <system.Web>
        <httpRuntime targetFramework="4.5" />
     </system.Web>

-->
It's important that you set the targetFramework in your configuration file, else your application will run in "4.0" mode.

Enabling AntiXss
You'd want to set the AntiXss library as the default encoder — that can easily be done in the httpRuntime configuration element:

<httpRuntime targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder,System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

Note that there can be side effects to this, as AntiXSS takes a white list approach to encoding. That means that there may be characters that weren't encoded before, that will be encoded by AntiXSS.

Request validation
Lazy validation was introduced in ASP.NET 4.5, I just did some testing on it and it seems that lazy validation is the enabled regardless of how you set the "requestValidationMode", after you've installed the 4.5 framework. However, if you need access to any request parameters unvalidated, you'll need to set the validation mode to "4.5", as such:
<httpRuntime targetFramework="4.5" requestValidationMode="4.5" />
This will give you access to the unvalidated collections of parameters, e.g.:

Request.Unvalidated.QueryString["lastName"];
This is a much better approach than disabling request validation altogether. But use it with care, as always you should throroughly validate the input.

WIF 4.5
WIF is now part of the framework — that meant some breaking changes. It shouldn't take to much time to upgrade though,  particularly if you're concerned with RP's. There's a great article on MSDN with Guidelines for Migrating an Application Built Using WIF 3.5 to WIF 4.5.
There's two apparent changes I'd like to point out. First, you no longer need to set the "requestValidationMode" to "2.0" to cope with the request validation exceptions on the SignInResponseMessage's posted from an STS. WIF 4.5 plays nicely with the 4.5 request validation. Second, WIF now includes a MachineKeySessionSecurityTokenHandler which encrypts and MAC's WIF cookies based on the machine key. You'll find everything you need to set it up in: WIF and Web Farms.

 

 



ASP.NET Hosting - Resolve Errror "Validation of viewstate MAC failed"

clock March 5, 2013 08:57 by author andy_yo

Usually we won’t got “Validation of viewstate MAC failed” error in our site all the time. Normally the site works fine and doesn't throw any errors if you load the site and use it at a regular pace.  The error only occurs when you load the page, leave it for a while, and then continue working on the page without reloading or refreshing it.  I discovered this error because I opened the site, began using it, left for lunch, came back an hour later, and when I resumed using it and did anything that caused postback, it immediately threw the above error.  Unfortunately in order to re-create the error, I have to wait a while, which is very inconvenient for testing/troubleshooting. After a few hours of reasearch I found the solutions:

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

Error message:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Solution:

Yet another very teasing issue ASP .Net developers face. Solution is pretty much simple.

Add following link in your web.config file.

<pages enableEventValidation="false" viewStateEncryptionMode="Never" />

Above line should be included within section.

OR

if you don't want this solution to implemented on project level then you can add these attribute to the page(Top most line of HTML view) directive of the page which is creating issue.

That means you have to add enableEventValidation="false" viewStateEncryptionMode="Never" in page directive.

 



ASP.NET Hosting - How To Make URL More User Friendly (URL Rewriting)

clock February 27, 2013 05:24 by author andy_yo

Sometimes we need a user friendly URL, but if we use query string variables, our site url will become messy.

Like we may be having

URL A: http://www.asphostportal.com/product.aspx?id=123456

and we want to have a URL for above as

URL B: http://www.asphostportal.com/product_123456.aspx

Obviously from above two the 2nd one is more user friendly and easily readable. Now the question is how to accomplish this task. The solution is very simple. In following I will be explaining the solution in detail

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

The Solution

Though there are more than one ways for this task but I will make use of the method "application_beginrequest" of "Global.asax". This method is called every time some request is made to the website.

Following will be the code to convert URL A into URL B in VB and C# programming language. You can modify this code as per your need.

VB

Public Sub application_beginrequest(ByVal sender As Object, ByVal e As EventArgs)
     Try
        Dim initialurl As String = Request.Url.ToString
        If initialurl.ToLower.IndexOf("product_") >= 0 Then
            Dim mTemp As String = initialurl.Substring(initialurl.LastIndexOf("_") + 1)
            Dim mProductID As Integer = mTemp.Substring(0, mTemp.LastIndexOf(".aspx"))
            Dim mOriginalURL As String = "product.aspx?id=" + mProductID
            Context.RewritePath(mOriginalURL)
        End If
        'Code to Log your Error
     Catch ex As Exception
     End Try
End Sub

CSharp (C#)

public void application_beginrequest(object sender, EventArgs e)
{
    try
    {
        string initialurl = Request.Url.ToString();
        if (initialurl.ToLower().IndexOf("product_") >= 0)
        {
            string mTemp = initialurl.Substring(initialurl.LastIndexOf("_") + 1);
            int mProductID = Convert.ToInt32(mTemp.Substring(0, mTemp.LastIndexOf(".aspx")));
            string mOriginalURL = "product.aspx?id=" + mProductID;
            Context.RewritePath(mOriginalURL);
        }
    }
    catch (Exception ex)
    {
        //Code to Log your Error
    }
}



ASP.NET 4 Hosting - ASPHostPortal :: How to Zip Your Files

clock November 1, 2010 09:58 by author Jervis

Tonight I was using the ICSharpCode zip library to zip files for my Codewise implementation.  Basically, when users nominate to make a Relase visible to Codeshare, I create a manifest file and package it and the Release file into a Codewise package.

I ran the code which comes in the .chm file but, noticed that my .zip files wouldn't show any content when viewing them through the default Windows Zip File viewer.  I little bit of investigation led me to the FAQ site for the library which answered my question.  Basically, you cannot pass a fullpath to the ZipEntry class if you want it to be visible to Windows.  So, you just remove the path portion of the filename:

ZipEntry entry = new ZipEntry(Path.GetFileName(fullPath));

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in