All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

ASP.NET Hosting - ASPHostPortal.com :: Key Points of ASP.NET VNext

clock February 12, 2015 05:58 by author Mark

Microsoft openness and open source approach leads to ASP.NET vNext – The next generation of .NET. In this article we will discuss some of key points of vNext.
In vNext we have cloud optimization mode. Traditional scenario, we are having entire .NET Framework and CLR install to design and deploy ASP.NET application.
According to me Microsoft had spilt the framework and CLR in vNext as .NET Core and everything else. In the .NET Core we have cloud optimized runtime core with very minimum foot prints. Everything else can be very easily downloaded using Nuget repository. This is actually made compiler as service (CaaS) scenario.

(kpm restore – To compile and download required libraries from nuget.)
We would be having only minimum footprint and essential libraries to run the ASP.NET application. A minimum footprint delivers faster results. During compile time only essentials components are deployed application wise, each application can have different version of .NET vNext side by side.

(kvm list - to see what versions of the ASP.NET vNext are available.)
Dependency injection is design pattern used to manage orchestration between loosely coupled objects. Build in DI in ASP.NET vNext manages configuring services and libraries. Environment specific service / libraries can configure through DI. This is very useful methodology while working with cross platform development and deployment.
ASP.NET MVC and Web API have been unified into a single programming model. The new framework removes a lot of overlap between the existing MVC and Web API frameworks. It uses a common set of abstractions for routing, action selection, filters and model binding.
The Roslyn provides open-source C# and Visual Basic compilers with rich code analysis APIs. It enables building code analysis tools with the same APIs that are used by Visual Studio. (more details on Roslyn compiler in next article)
The .NET Foundation is an independent organization to foster open development and collaboration around the growing collection of open source technologies for .NET. We can find more details at this link.

Summary

  • Cloud and server-optimization.
  • NuGet everything - even the runtime itself.
  • Side by side - deploy the runtime and framework with your application.
  • ASP.NET MVC and Web API have been unified into a single programming model.
  • Dependency injection out of the box.
  • New flexible and cross-platform runtime.
  • All Open Source via the .NET Foundation and takes contributions.
  • Roslyn compiler.

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET 5 Hosting - ASPHostPortal.com :: Debugging jQuery in ASP.NET

clock February 10, 2015 07:17 by author Mark

When an ASP.NET developer uses jQuery or JavaScript (clientside programming) in his code, the question always arises of how to debug this code. We can debug in code behind with breakpoints. But what for clientside scripting. Some people say use "alert()", but I don't think this is a sufficient way to do it.
So the good news is that we have the "debugger" keyword to debug your line of code.
Use debugger before your code, where you want to start debugging.
See the following code:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-1.7.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $(':radio').click(function () {
                    debugger;
    //Get the value of Radio button
                    var _GetVal = $(this).attr('value');
                });
             });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
           First
            <input type="radio" name="rd1" value="10" />
            <input type="radio" name="rd1" value="11" />
            Second
            <input type="radio" name="rd1" value="12" />
            <input type="radio" name="rd1" value="13" />
        </div>
        </form>
    </body>
    </html>

This is a simple ASP.NET in page code. When the user clicks a radio button, debugging will automatically start, due to the debugger command. In the above program, when the user clicks on the radio button we stored its value in the _Getval variable.

$(document).ready(function () {
                $(':radio').click(function () {
                    debugger;
    //Get the value of Radio button
                    var _GetVal = $(this).attr('value');
                });
             });

You can see that when I declare a _GetVal variable, before I use "debugger" because from here I want to start debugging. See the following images.
Figure 1: When user clicks in the radio

Figure 2: When the user presses F10 (the same way as what we did in code behind using a breakpoint).

In the image above you can see that the _GetVal value is 10 now. So with the use of the debugger you can start your debugging in ASP.NET.
And please remember, when you finish debugging or publish your page, please remove debugger from your code.
If you have any query, Please send your valuable Comments. Happy Programming

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET Hosting - ASPHostPortal :: Step by step instructions to disable Session state on your ASP.NET page

clock February 9, 2015 06:43 by author Dan

Each ASP.NET page has the session state of course, this may diminish the aggregate execution a tad bit. So You can incapacitate the session state from the pages when you don't have to utilize sessions. What's more you can do as such to set the false estimation of the EnableSessionState characteristic in the page mandate of your page like as:

<%@ page EnableSessionState="False" %>

Full deceleration:

<%@ Page Title="Home Page" Language="C#" EnableSessionState="False"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Essentially EnableSessionState can have three qualities: False, ReadOnly and True. Assume on the off chance that you need to peruse the qualities from the session at exactly that point you can set the ReadOnly to the EnableSessionState characteristic.
Also Now on the off chance that you need to handicap Session state on whole site then you can change your site's web.config document by simply including after lines

<configuration>

    <system.web>
        <sessionState mode="Off">
        </sessionState>
        </system.web>
    </configuration>


When you set the handicap session state from the web.config, after that you can utilize the EnableSessionState="True" in any page of your site.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal :: Automatically Clean Up Temporary ASP.NET Files

clock February 6, 2015 06:24 by author Dan

The Problem

One of the test situations I help keep up is subject to dynamic and general changes in .NET applications. The improvement group are always discharging new forms that are marginally distinctive.

You may not be mindful that .NET applications experience an assemblage process when they first start up. I've additionally been told on application pool reuse anyway I haven't affirmed this. Then again, after the application has been evacuated or overhauled, the arrangement interim records remain. On a test situation like my above situation, an aggregate of 50gb of circle space can be effortlessly squandered, doing nothing. So in case you're in a comparable situation, you may need to routinely clean up these records.

I know of four areas where these records can develop:

  • C:\Windows\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files
  • C:\Windows\Microsoft.NET\Framework64\v1.1.4322\Temporary ASP.NET Files
  • C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
  • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files

On the off chance that you application pools run in 64bit mode, you'll discover the "Framework64″ areas more appropriate. In the event that your application pools utilize 32bit mode, you'll have to consider the "Structure" areas.

The following is an illustration of a creation domain utilizing almost 13gb:

Powershell Script to Automatically Delete Temp Files

As framework directors, we have to robotize and script our workload so we can concentrate on the vital stuff! So we formulated a basic execution of Powershell script which deals with this clean up issue in one line:

Get-Childitem "C:\windows\microsoft.net\framework*\v*\temporary Asp.net Files" -Recurse | Remove-Item -Recurse

In case you're perusing this and considering, EWWWW Powershell. Don't deride it until you attempt this single line summon.

I spared the above charge into a record names Cleanupaspnettempfiles.ps1 and spared it to D:\tools\. Name and recovery yours as you see fit.

To relax, you can plan this script with a planned assignment. You can click on these screenshots in the event that you require more detail:

(I picked to run on the first Saturday of the month. Utilize your own inclination.)

(My powershell.exe was at %systemroot%\system32\windowspowershell\v1.0\powershell.exe)

(Note you have to tick the choice box to get to the following screenshot or burden the properties on the recently made undertaking.)

Execution Policy Errors

In case you're being advised to sign your recently made script, you can either do that for high security situations or you can turn off the marking prerequisite. It's extraordinary to have this choice incorporate with the dialect yet in the commonplace environment I've discovered it a trouble.

In a Powershell summon window, sort the accompanying to check your current Executionpolicy:

Get-Executionpolicy

You can transform it to Unrestricted by writing:

Set-Executionpolicy Unrestricted

A Few Notes

An update that records in these areas are typical. Don't go over the top attempting to clean them up.

It ought to be noted that while the records are being used by the web server, you won't have the capacity to erase them – this is fine; the objective is to clean up unused documents.

You ought to additionally be mindful whenever the application wakes up, on application pool begin, the application will re-gather once more. This may prompt a more drawn out than normal starting page load. On the off chance that this is of concern, consider just uprooting records that are more seasoned than 30 days.

Obviously, this script is given as may be. You ought to test it completely in a test situation before utilization underway (however I surely do).

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Describes Caching Methods In ASP.NET

clock February 5, 2015 06:45 by author Mark

Today I will describes caching methods in ASP.NET. It's a good habit to use caching in your application and coding standards too.

Overview

Caching is one of the most interesting concepts and operations in ASP.NET. If you can handle it, you can run any web application by applying the caching concept depending on the requirements.
Currrently a majority of websites/portals (or I can say simply web pages) are dynamic (if I do talk about a dynamic website, then it doesn't mean all the pages of that website is dynamic or will be. The probability of happening this is dependent on the user's perspective and the requirements).
In veru common words I can define dynamic pages as including the following:

  • Pages that directly interact with people
  • Communication (on page)
  • Any media content
  • Any Type of grafic Interaction

So, generally these types of pages or webs are called dynamic. Now let's find why we really need caching.

Why Caching

Caching is for providing solutions or the results to the users depending on their requested request, admin needs to recreate the pages often depending on user requests…STOP!!!

The process

The process is quite bulky and time-consuming. So to overcoming that problem some websites have a page creation engine that automatically creates all the pages in one action and directly saves those pages as a HTML structured page. These HTML pages serve the user depending on their requirements.

Multiple sorts of pages

But, do you still think this will be enough? If your answer is yes, then please think some more!
Actually, the preceding solution will only work if and only if the requested pages are of the same type. Now think, what will happen if the users request a different sort of page?
In that case your web will be stuck again.
So for dealing with that kind of complex but necessary requirements, ASP.NET provides support for caching. Caching is the hero/heroine in this context that will help us to a great extent.

What a Cache does

What a cache does, in the most simple words I can say is:
"A cache simply stores the output generated by a page in the memory and this saved output (cache) will serve us (users) in the future." That's it.

Types

Page Caching

Let's explore the caching of an entire page, first.
To cache an entire page's output we need to specify a directive at the top of our page, this directive is the @ OutputCache.
Let's figure out a simple demo of it.

<%@ OutputCache Duration = 5 VaryByParam = "ID" %> 

Here, in that statement Duration and VarByParam are the two attributes of the OutputCache directive. Now let's explore how they work.

  • Duration Attribute : This attributes represents the time in seconds of how long the output cache should be stored in memory. After the defined duration the content stored in the memory will be cleared automatically.
  • VarByParam Attribute : This is the most important attributes; you can't afford to miss that in the OutputCache directory statement. It generally defines the query string parameters to vary the cache (in memory).

You can also pass multiple parameter names too, but for that you need to separate them using a semicolon (;).
You can also specify it as "*". In this case the cached content is varied for all the parameters passed using the querysrting.
For example:

<%@ OutputCache Duration = 5 VaryByParam = "*"%> 

In case of caching a page, some pages can generate different content for different browsers. In that scenario we need to add an additional attribute to our statement for overcoming the preceding problem.
For example:

<%@ OutputCache Duration = 5 VaryByParam = "ID" VaryByCustom = "Browser" %> 

Or:

<%@ OutputCache Duration = 5 VaryByParam = "*" VaryByCustom = "Browser" %>

Fragment caching

In some scenarios we only need to cache only a segment of a page. For example a contact us page in a main page will be the same for all the users and for that there is no need to cache the entire page.
So for that we prefer to use fragment caching option.
For example:

<%@ OutputCache Duration = 10 VaryByParam = "None" %> 

Or:

<%@ OutputCache Duration = 5 VaryByParam = "None" VaryByCustom = "Browser" %> 

Data Caching

Data caching is slightly different from the 2 other caching types. It's much more interesting to see how data caching actually works.
As we know in C# everything is about classes and objects. So ASP.NET supports data caching by treating them as small sets of objects. We can store objects in memory very easily and use them depending on our functionality and needs, anywhere across the page.
Now you must be thinking where is the class in that entire scenario?
Actually, this feature is implemented using the Cache class and data is treated as its object. Let's see how it works using a demo.

I am inserting a string value in the cache as:

Cache["Website"] = "CSharpCorner"; 

Now, for inserting the cache into the objects, the insert method of the Cache class can be used. This insert method is used as follows:

Cache.Insert("Website", strName, 
new CacheDependency(Sever.MapPath("Website.txt")); 

What we are missing something
We missed the Time for the cache (don't forget to use it), let's provide it:

Cache.Insert("Website", strName, 
new CacheDependency(Sever.MapPath("Website.txt") 
DateTime.Now.Addminutes(5), TimeSpan.Zero); 

Happy coding!

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET Hosting - ASPHostPortal.com :: Sending an email using exchange server from the ASP.NET Application

clock February 2, 2015 07:27 by author Dan

The .NET Framework 1.x had a System.web.mail class to send an email from the ASP.NET system. While this namespace and these classes still exist in the .NET Framework form 2.0 and later, they have been expostulated and supplanted by the new Mail API in the System.net.mail namespace in the Asp.net 2.0 structure. Asp.net 1.x's System.web.mail API was focused around CDO libraries. With the new Apis, Microsoft moved far from CDONTS based wrapper Apis and composed the new API utilizing Com+ segments to enhance the execution.

ASP.NET 2.0 sends an email utilizing Smtpclient class. In the most fundamental arrangement, You need to set the hostname of the hand-off server in the event that you are utilizing trade server or localhost in the event that you are utilizing neighborhood SMTP administration, port (25 as a matter of course), authentican certifications, or pointed out pickup index through the Deliverymethod property.

Here is the template for the System.NET.Mail configuration.

<configuration>
<!– Add the email settings to the element –>
<system.net>
<mailSettings>
<smtp deliveryMethod=”PickupDirectory” from=”fromemailaddress”>
<network
host=”relayServerHost”
port=”portNumber”
userName=”username”
password=”password”
defaultCredentials=”true/false”/>
</smtp>
</mailSettings>
</system.net>
</configuration>

localhost – local web server SMTP administration – If you need to send an email through neighborhood SMTP Service of the web server, basically include emulating lines of code in your web.config to send an email from the ASP.NET Pages.

<system.net>
<mailSettings>
<smtp deliveryMethod=”PickupDirectoryFromIis”>
<network host=”(localhost)” port=”25″ defaultCredentials=”true” />
</smtp>
</mailSettings>
</system.net>

Exchange Server – If you need to send an email from existing trade server email account, you need to setup the transfer administration from your webserver to trade server. Emulating web.config setup permits you utilize hand-off administration for trade server.

How about we say's exchange server name is "exmail.domainname.com", exchange username and secret key is "exchangeuserid" and "exchangepassword", you web.config settings would be

<system.net>
<mailSettings>
<smtp>
<network host=”exmail.domainname.com” port=”25″ userName=”exchangeuserid” password=”exchangepassword” defaultCredentials=”false” />
</smtp>
</mailSettings>
</system.net>

Next step would be to make a class to send a messages utilizing SMTP Service: Note that emulating code utilizes Web.config settings. Remarked out code won't utilize web.config mail settings. In spite of the fact that its preferrable, on the off chance that you don't need email designs in web.config document, utilize the remarked out code to design and send an email from the ASP.NET pages.

using System;using System.Net;using System.Net.Mail;
public class SMTPEmailSender
{
public SMTPEmailSender()
{
//
// TODO: Add constructor logic here
//
}

public static void SendSMTPEmail(string senderMailAddress,
string recipientMailAddress,
string mailSubject,
string mailBody)
{

//Create MailMessage to send an email.
MailMessage message = new MailMessage(senderMailAddress, recipientMailAddress);
message.Subject = mailSubject;
message.Body = mailBody;

//Use SMTPClient to send an email.
//Uses SMTP settings from web.config
SmtpClient client = new SmtpClient();
client.Send(message);

//Uses SMTP Settings from Code
/*
//Sample Code
//SmtpClient smtp = new SmtpClient(“exmail.domainname.com”, portnumber);
//smtp.Credentials = new NetworkCredential(“exchangeuserid”, “exchangepassword”, “DOMAIN”);
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //smtp.Send(message);
*/
}
}

Create a Test Page to send out emails. Here is the source code from the code behind to send an email from the test email page.

public partial class TestEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string fromEmailAddress = “[email protected]“;
string recipientEmailAddress = “[email protected]“;
string mailSubject = “Nik’s Website: Test Email”;
string mailBody = “Test Email.”;
if (recipientEmailAddress != null && recipientEmailAddress.Trim().Length != 0)
{
SMTPEmailManager.SendSMTPEmail(fromEmailAddress, recipientEmailAddress, mailSubject, mailBody);
}
Response.Write(“Test Email Sent Out”);
}
}

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: RowDatabound event tips and tricks in Gridview control

clock January 30, 2015 06:39 by author Dan

In this article, I will depict about few tips and tricks in rowdatabound occasion which is accessible in ASP.NET gridview control and these tips will give the answer for all conceivable necessities when working with rowdatabound occasion in gridview control.

Introduction

Gridview control is most regular control in all asp.net applications to show the information and its capable control and parcel of implicit peculiarities. In this article, i will investigate a few tips and traps in rowdatabound occasion in gridvew control, Actually Rowdatabound occasion will happen when information column is sure to the control in the gridview control.

Discover control in Rowdatabound occasion

Utilizing this occasion we can ready to discover the particular controls, for example, textbox, dropdown, checkbox and get values from control which is utilized inside gridview control.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {   //Get data row view
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Find dropdown control & get values
                DropDownList dpEmpdept = (DropDownList)e.Row.FindControl("DrpDwnEmpDept");
                string value = dpEmpdept.SelectedItem.Value;
                //Find textbox control
                TextBox txtname = (TextBox)e.Row.FindControl("txtName");
                string Name = txtname.Text;
                //Find checkbox and checked/Unchecked based on values
                CheckBox chkb = (CheckBox)e.Row.FindControl("ChckBxActive");
                if (drview[5].ToString() == "True")
                {
                    chkb.Checked = true;
                }
                else
                {
                    chkb.Checked = false;
                }
            }
        }

Format specific row

We can ready to do arranging a particular column in a gridview focused around a few conditions, say for instance if value would be all the more then 100 then show, those columns with foundation as tan, fore shade as dark and striking letters.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblPrice = (Label)e.Row.FindControl("lblPrice");
                if (Convert.ToInt32(lblPrice.Text) > 100)
                {
                    e.Row.ForeColor = System.Drawing.Color.Black;
                    e.Row.Font.Bold = true;
                    e.Row.BackColor = System.Drawing.Color.Brown; 
                }
            }
        }

Gridview row color change

In the event that you need to change the gridview column shade change on mouse over and mouse out then compose the beneath code in rowdatabound occasion.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "self.MouseOverOldColor=this.style.backgroundColor;this.style.backgroundColor='#C0C0C0'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=self.MouseOverOldColor");
            }
        }

Bind dropdown list in footer

At some point we utilize footer column to include/supplement records, so for this situation in the event that you utilize dropdown list as a part of footer line to include new record then we have to load the information in dropdown list when scrape the information with gridview control and see the beneath code in what manner would we be able to load dropdown list in footer column while rowdatabound occasion happens.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList dp = (DropDownList)e.Row.FindControl("DrpDwnAddEmpDept");
                dp.DataSource = GetEmpDept();
                dp.DataTextField = "DepName";
                dp.DataValueField = "DepName";
                dp.DataBind();
            }
        }
        private DataTable GetEmpDept()
        {
            //Get Employee department
            DataTable dt = new DataTable();
            dt.Columns.Add("DepName");
            DataRow rw1 = dt.NewRow();
            rw1[0] = "IT";
            dt.Rows.Add(rw1);
            DataRow rw2 = dt.NewRow();
            rw2[0] = "Finance";
            dt.Rows.Add(rw2);
            DataRow rw3 = dt.NewRow();
            rw3[0] = "Security";
            dt.Rows.Add(rw3);
            return dt;
        }

HyperLink and redirect

By and large we utilize hyperlink to divert other page or open new page to view particular subtle elements focused around a few conditions, beneath case diverting to other page if client is qualified to view.

<asp:GridView ID="GVSample" runat="server" AutoGenerateColumns="false" OnRowDataBound="GVSample_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Userprofile">
                    <ItemTemplate>
                        <asp:HyperLink ID="hyprlnkdetails" runat="server" />
                        <asp:Label ID="lblText" runat="server" Text=""></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HyperLink HLdetails = e.Row.FindControl("hyprlnkdetails") as HyperLink;
                Label lblText       = e.Row.FindControl("lblText") as Label;
                if (drview[5].ToString()=="True")
                {
                    HLdetails.Text          = "Click here to view";
                    HLdetails.NavigateUrl   = String.Format("~/details.aspx?UserID={0}", drview[8].ToString());
                }
                else
                {
                    HLdetails.Visible   = false;
                    lblText.Text        = "View Restricted";
                }
            }
        }

Get DataKeyValues in RowDatabound

For the most part we set the essential key qualities to the datakeyname property in gridview control and underneath code will help to get that date key qualities connected with a line in rowdatabound occasion.

protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                    string userID = GVSample.DataKeys[e.Row.RowIndex].Values[0].ToString();
            }
        }

Above rundown of tips on rowdatabound occasion in gridview control will help you when work with this occasion, a debt of gratitude is in order regarding perusing this article and give your proposals and criticism about this article.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: return View() vs return RedirectToAction() vs return Redirect() vs return RedirectToRoute()

clock January 28, 2015 05:47 by author Ben

There are various approaches for returning/rendering a view in MVC Razor. Numerous developers got confused when to utilize return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute(). In this article, I'd prefer to explain the difference amongst "return View()" and "return RedirectToAction()", "return Redirect()" and "return RedirectToRoute()".


return View()

This tells MVC to create HTML to become displayed for the specified view and sends it to the browser. This acts like as Server.Transfer() in Asp.Net WebForm.


    public ActionResult Index()
    {
    return View();
    }
    
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Server.Transfer() in Asp.Net WebForm
    return View("MyIndex");
    }
    
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
    return View("MyIndex");
    }


What happens if we contact the action strategy directly like return MyIndex(). It is basically a technique call which returns a rendered view which is specified in MyIndex() action method.

public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Server.Transfer() in Asp.Net WebForm
return MyIndex();
}
public ActionResult MyIndex()
{
ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
return View("MyIndex");

}

return RedirectToAction()

This tells MVC to redirect to specified action instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified action. This acts like as Response.Redirect() in Asp.Net WebForm.
Moreover, RedirectToAction construct a redirect url to a specific action/controller in your application and use the route table to generate the correct URL. RedirectToAction cause the browser to receive a 302 redirect within your application and gives you an easier way to work with your route table.


    public ActionResult Index()
    {
    return View();
    }
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Response.Redirect() in Asp.Net WebForm
    return RedirectToAction("MyIndex");
    }
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : Null
    return View("MyIndex");
    }


return Redirect()

This tells MVC to redirect to specified URL instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified URL. This also acts like as Response.Redirect() in Asp.Net WebForm. In this case, you have to specify the full URL to redirect.
Moreover, Redirect also cause the browser to receive a 302 redirect within your application, but you have to construct the URLs yourself.


    public ActionResult Index()
    {
    return View();
    }
    
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Response.Redirect() in Asp.Net WebForm
    return Redirect("Home/MyIndex");
    }
    
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : Null
    return View("MyIndex");
    }


return RedirectToRoute()

This tells MVC to look up the specifies route into the Route table that is is defined in global.asax and then redirect to that controller/action defined in that route. This also make a new request like RedirectToAction().

Defined Route


    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.MapRoute(
    "MyRoute", // Route name
    "Account/", // URL
    new { controller = "Account", action = "Login"} // Parameter defaults
    );
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "MyIndex", id = UrlParameter.Optional } // Parameter defaults
    );
    }


HomeController

public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("MyRoute");
}

AccountController

public ActionResult Login()
{
return View();
}

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers SSRS hosting starts from $5/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable SSRS Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal :: Describe the Lifecycle of an ASP. NET Web API Message

clock January 27, 2015 05:36 by author Mark

In this article we will describe the Lifecycle of an ASP. NET Web API message. We know that the ASP. NET Web API is a framework that helps build the services over the HTTP server. It provides the lightweight services used by multiple clients and devices of the platform to access the data via the API. For transferring the data over the wire , it uses the JavaScript Object Notation (JSON) and Extensible Markup Language (XML)
Now we will define the Lifecycle of an ASP. NET Web API Message from the client to the server and the server to the client. The request is generated by the client using HttpRequest and the return response is generated by HttpResponse.

Diagram of Web API Pipeline

Hosting of web API

We perform two types of hosting on the Web API. They are ASP.NET and Selfhosting, as described in the following:

  • ASP.Net Hosting:  When we perform the ASP.NET hosting then the Lifecycle starts from HttpControllerHeader which is the implementation of IHttpAsyncHandler and the responsibility of it is to send the request to the HttpServer pipeline.
  • Self Hosting:  In self hosting the HttpServer pipeline starts from the HttpSelfHostServer that performs the implementation of HttpServer and the responsibility is that it can be directly listen to the HTTP request.

HTTP Message Handler

After leaving the service host the request travels in the pipeline as a HttpRequestMessage. There is the Handler used in the Lifecycle.

Delegating Handler

This handler is provided to you as a Message of the request before passing onto the rest of the pipeline. The response message can be sent through the delegating handler. And other messages can be monitored and filtered at this point.

Routing Dispatcher

When the request is made using the option Delegation Handler it can be passed to the Routing Dispatcher. The dispatcher checks whether the Route Handler is Null. If the the Route Handler is null then it is passed to the next step in the pipeline.
If it is not null then there are many handlers for routing the message and the desired request is passed to the handler. We select the matching message handler to handle the request.

Controllers

After leaving the service host the request is travels in the pipeline as a HttpRequestMessage. These are the handlers used in the Lifecycle.

Authorization Filter

In the control section the first step is passed to the authorization. If there are Authorization Filters available and the authorization is failed by the request then the request is truncated and sent as a auth failure response.

Model Binding

If the authorization test is successful then it is passed to the model binding section. It is not a single-step process.
If we want to see the model binding process then it looks like the following.

View of Model Binding

In the model binding we can see the three parts of the HTTP request; they are URI, Headers and Entity Body.

 

URI

The URI works as a ModelBinderParameterBinder object that checks that there are custom IModelBinder an IValueProvider.

Formatter Binding

The Entity body of the model binding is managed by the FrmatterParameterBinding. If there is a request that needs to utilize one or two Media Type Formatters then it is piped through the appropriate Media Type Formatter.

HTTP parameter binding

There is a need for the entire request to be piped through the HTTP parameter binding module, if there is a custom HTTP Parameter Binding module.

Action Filter

After completion of the Model Binding the Action Filter is done. It is invoked two times in the pipeline before the OnExecuting event and after the OnExecution event.

Action Invoker

The action invoker invokes the actions of the control. It binds and models the state for invoking the action in HttpActionContext. It can invoke the action and also return the message in the form of a HttpResponseMessage. If there is an Exception at the time of invoking the action then the exception is routed to the Exception Filter that can send the Error Message.

Controller Action

Controller Action executes the Action Method code. And it generates the HttpResponseMessage.

Result Conversion

Now we see the image of the Result Conversion:

  • HttpResponseMessage: The message is directly passed in it and nothing needs conversion.
  • Void: The action method returns the void result in it and there is a need for conversion into a HttpPesponseMessage.

If the Action Method returns any other type then the Content Negotiation and Media Type Formatters are used. The Content Negotiation checks that we can return the requested content using the appropriate Media Type formatter.

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.




ASP.NET Hosting - ASPHostPortal :: How to Disable Cut, Copy and Paste in the Entire ASP.NET Web Form

clock January 22, 2015 06:22 by author Mark

This article shows how to restrict the use of cut, copy and paste by the end user in the whole page.

In the real world, sometimes a developer needs to restrict a basic facility such as cut, copy and paste on an entire web page but not on a specific control. At that time you will need some easy way to stop these kinds of facilities on the page but not create code in every control to disable these facilities.
Suppose you have 20 "TextBox" controls in your page and you want to restrict the cut, copy and paste in all the textboxes, then you do not need to write the disable code in each TextBox. In this scenario, you need to just write the disable code only in the "body" tag.
To explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

Step 2

Add a new web form named "Default.aspx" into it.

Step 3

Add 2 "TextBox" controls to the page named "Default.aspx" .

Step 4

On Cut: By this, you can disable the "Cut " facility in both of the "TextBox" Controls.
Syntax: oncut= “return false”;


On Copy: By this, you can disable the "Copy " facility in both of the "TextBox" controls.
Syntax: oncopy= “return false”;


On Paste: By this, you can disable the "Cut" facility in both of the "TextBox" controls.
Syntax: onpaste= “return false”;

To disable the All (Cut, Copy and Paste) in the entire page:

Conclusion

In this article, I have described how to restrict the user to use the cut, copy and paste facilities in the entire page and I hope it will be beneficial for you.

TOP No#1 Recommended ASP.NET MVC 5 Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



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

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

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

Tag cloud

Sign in