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 Hosting - ASPHostPortal.com :: How to implement Windows authentication and authorization in ASP.NET

clock January 10, 2017 05:21 by author Armend

This step-by-step article describes how to implement Windows authentication and authorization in an ASP.NET application. To use the built in security of Windows and ASP.NET, implement Windows authentication and authorization on groups and users. To use Windows authentication, you must adjust settings in both Microsoft Internet Information Services (IIS) and the ASP.NET application Web.config file.

Requirements

  • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows XP Professional
  • Microsoft .NET Framework
  • Microsoft Internet Information Services (IIS)
  • Microsoft Visual Studio .NET

Authentication and authorization

Windows authentication and Windows authorization are two terms that are frequently interchanged. However, they do not have the same meaning. Windows authentication permits the recipient to determine the user's identity. Windows authorization determines the resources to which a user may gain access.

Configure Web application for Windows authentication

To configure your Web application for Windows authentication, follow these steps:

  • Create an ASP.NET Web Application named ASPNETWinAuth. By default, theWebForm1.aspx file appears.
  • In the HTML view of WebForm1.aspx, replace the existing code with the following sample code:

    <%=User.Identity.Name%>

  • Click Start, point to Programs, point to Administrative tools, and then click Internet Information Services.
  • The Internet Information Services MMC appears. Expand Computer, and then expand a Web site that uses Windows authentication.
  • Click the ASPNETWinAuth Web site application.
  • On the Action menu, click Properties.
  • In Properties, click the Directory Security tab.
  • Under Anonymous access and authentication control, click Edit.
  • In Authentication Methods, click to select Integrated Windows authentication. Click to clear all other check boxes.
  • Click OK.
  • In Properties, click OK. The ASPNETWinAuth Web application is now configured to accept valid user accounts.

Configure the ASP.NET application

After you configure the IIS Web site for Integrated Windows Authentication, you must configure the ASP.NET application to recognize authenticated users. To do this, you must change the Web.config file. In the Web.config file, locate the <authentication> tag, and then set the mode attribute to Windows, as in the following example:

<authentication mode="Windows" />

Test authentication

To test your Windows authentication setting, follow these steps:

  • In Microsoft Internet Explorer, view the WebForm1.aspx page. This page is located in the Http://Localhost folder. For example:

    http://Localhost/ASPNETWinAuth/WebForm1.aspx

  • Because Integrated Windows Authentication uses the current Windows user information on the client computer for the authentication, it does not immediately prompt the user for a user name and password. However, if the authentication exchange cannot identify the user, a dialog box appears that prompts the user for a Windows user account user name and password.
  • Type a valid user name and password. When the page loads, your user name appears in the following format:

    Domain Name\User Name

Restrict access

In ASP.NET, you set authorization to the application by adding settings in the Web.config file. You can specify which users or groups are permitted to have access to what resources as follows:
To permit all users of an NT Group named Managers to have access to your resources, use the following code:

<configuration>
      <system.web>
        <authorization>
          <allow roles="domainname\Managers" />
          <deny users="*" />
        </authorization>
      </system.web>
    </configuration>

To permit only specific users to have access, use the following code:

<configuration>
      <system.web>
        <authorization>
          <allow users="domainname\user1,domainname\user2,domainname\user3" />
          <deny users="*" />
        </authorization>
      </system.web>
    </configuration>

Note You can specify multiple roles or users by using a comma separated list. Verify that you use the correct case when you specify the configuration file element and the associated attribute values. This code is case sensitive.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides our 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 2012. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows server 2012 Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Write content from ASP.NET to Excel

clock September 27, 2016 20:25 by author Armend

How to Write content from ASP.NET to Excel

The following program shows how to write the GridView content to an Excel file and save to a desired location. Here we are using the FileStream class to write the content to a local system.

FileStream fStream = new FileStream("c:\\data.xls", FileMode.Create);

The following method will confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

 

public override void VerifyRenderingInServerForm(Control control)
  {
  }

Sometimes you will get an exception unless you are not declared the above method in your program the exception shows like :

System.Web.HttpException: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server..

Default.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
    SelectCommand="select * from stores" />
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
    Text="Export to Excel" Width="117px" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="Label1" runat="server" Text="Message : "></asp:Label>
    </form>
</body>
</html>

 

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 :: How to Publishing an ASP.NET 5 Project to a Local IIS Server

clock June 16, 2016 17:45 by author Armend

In this post we will show you how to publishing an ASP.NET 5 project to a local IIS server. Recently I deployed a new ASP.NET 5 web application to a local IIS server. Though there are several online resources available about deployment, I encountered some problems that were difficult to diagnose and fix. In this post I will talk about the general deployment process and the steps I followed for a successful deployment.

ASP.NET 5 applications are meant to be cross-platform. Included in this cross-platform effort is the development of a new, cross-platform web server, named Kestrel. The Kestrel web server can be activated from the command line and can be used on any operating system.
Of course, ASP.NET 5 applications can still be hosted in IIS. But even in this case, the underlying web server will still be Kestrel. The role of IIS is greatly minimized.
In this post we will be deploying a web application using Kestrel as a web host first. Afterwards, we will be deploying to IIS.

Deployment to Kestrel

Let's say that we have an existing ASP.NET 5 application. We can publish the application from the command line. First, navigate to the root web folder of the application (the folder where the project.json file is in). Then, type in the following command:

dnu publish --runtime active -o ..\publish

What this will do is create a new folder named 'publish' alongside the root web folder. Inside this 'publish' folder , there will be three subfolders: 'approot', 'logs', and 'wwwroot'. The 'approot' folder will contain the source files and packages needed by the application. The 'logs' folder will contain any logs that the application emits. The 'wwwroot' folder will contain javascript, html, css files, etc. as well as the web.config file.
Now we can start the Kestrel web server. First, navigate to the 'approot' folder. There will be a file named web.cmd. Start it by typing 'web' from the command line or double-clicking on it from a windows explorer window.

You might notice that a lot of text appears on the command line as soon as the command is run. This is especially true when there are Entity Framework migrations involved. Among the sea of text, the URL of the localhost web server will be displayed, and will look something like this:

Hosting Environment: Production
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Once we find this text, we can just navigate to the appropriate URL using a browser. There we should see the web app up and running.
Congratulations, we have just deployed our ASP.NET 5 web application!
Deployment to IIS
Once we successfully launch the app through Kestrel, we can go for deploying in IIS. We need to do a few things for it to work properly.

  • Use an application pool with No Managed Code as the .NET CLR Version.
  • Create a Login in SQL Server with the login name as IIS APPPOOL\{apppoolname}. This Login should have access to whatever database the web application will use.
  • Create access rights to the 'wwwroot' folder for the user group IIS_IUSRS.

In addition, if we are going to put the application inside IIS Default Web Site and use a virtual directory, we need to modify the Startup.cs to handle this.
The first step is to rename the Configure method to something else, for example Configure1.
Then, we need to create a new Configure method. This would have the same signature as the original Configure method. The implementation would look something like this:

public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.Map("/virtualdirectoryname", (app1) => this.Configure1(app1, env, loggerFactory));
}

So we see that this new Configure method just calls the Configure1 method, taking into account the virtual directory name.
Once all of these are in place, we can go ahead and deploy to IIS using the usual process. We can add a new application in IIS Default Web Site and use the application pool we created earlier (using No Managed Code). The physical path should point to the 'wwwroot' location. The alias should be the same as the one we put in the Configure method in Startup.cs.
Afterwards, just browse to the website and it should all be good!

Conclusion

Although the concept of deployment stayed the same, the process and tools involved for deploying ASP.NET 5 applications has changed. In this post we took a look at how to deploy to the Kestrel web server, then later to IIS. Though it might seem like a long process, most of the steps should only be performed the first time around. Subsequent deployments should be faster and more straightforward.



ASP.NET Hosting - ASPHostPortal.com :: Tips to configure Kestrel URLs in ASP.NET Core RC2

clock June 10, 2016 19:44 by author Armend

How to configure Kestrel URLs in ASP.NET Core RC2

ASP.NET Core is completely decoupled from the web server environment that hosts the application. ASP.NET Core supports hosting in IIS and IIS Express, and self-hosting scenarios using the Kestrel and WebListener HTTP servers. Additionally, developers and third party software vendors can create custom servers to host their ASP.NET Core apps.

Prior to the release of ASP.NET Core RC2 Kestrel would be configured as part of the command bindings in project.json:

"commands": {
  "web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://localhost:60000;http://localhost:60001;"
},

If no URLs were specified, a default binding of http://localhost:5000 would be used.

As of RC2 we have a new unified toolchain (the .NET Core CLI) and ASP.NET Core applications are effectively just .NET Core Console Applications. They have a single entry point where we programatically configure and run the web host:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

Here we're adding support for both Kestrel and IIS hosts via the appropriate extension methods.
When we upgraded SaasKit to RC2 we used the UseUrls extension to configure the URLs Kestrel would bind to:

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://localhost:60000", "http://localhost:60001")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

I didn't really like this approach as we're hard-coding URLs. Fortunately it's still possible to load the Kestrel configuration from an external file.
First create a hosting.json file in the root of your application with your required bindings. Separate multiple URLs with a semi-colon:

{
  "server.urls": "http://localhost:60000;http://localhost:60001"
}

Next update Program.cs to load your hosting configuration, then use the UseConfiguration extension to pass the configuration to the WebHostBuilder:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

If you're launching Kestrel with Visual Studio you may also need to update launchSettings.json with the correct launchUrl:

"RC2HostingDemo": {
  "commandName": "Project",
  "launchBrowser": true,
  "launchUrl": "http://localhost:60000/api/values",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
}

Now the web application will listen on the URLs configured in hosting.json:

Hosting environment: Development
Content root path: C:\Users\ben\Source\RC2HostingDemo\src\RC2HostingDemo
Now listening on: http://localhost:60000
Now listening on: http://localhost:60001
Application started. Press Ctrl+C to shut down.



ASP.NET Hosting - ASPHostPortal.com :: New Ways To Organize Razor Views in ASP.NET Core

clock May 30, 2016 20:50 by author Armend

New Ways To Organize Razor Views in ASP.NET Core

Currently there are many ways to extend or to organize Razor views in ASP.NET Core. Let us start with the new more complex ways. If your are familiar with previous ASP.NET MVC Frameworks you’ll definitely know most. But not almost all of that “old” stuff is still possible in ASP.NET Core MVC. Some of the listed below is completely new in ASP.NET Core. With this post, we’re going to try to write down all options to organize MVC Views in ASP.NET Core.

 

How To Organize Razor Views in ASP.NET Core

1. ViewComponents

This is one of new way to organize Razor views in ASP.NET Core. Sometimes you need to have something like PartialView, but with some more logic behind. In the past there was a way to use ChildActions to render the results of controller actions into a view. In ASP.NET Core, there is a new way (which I already showed in this post about ViewCmponents) with ViewComponents. This are a kind of mini MVC inside MVC, which means they have an own Controller, with an own single action and a view. This ViewComponents are completely independent from your current view, but also can get values passed in from your view. To render a ViewComponent you need to call it like this:

@Component.Invoke("Top10Articles");

2.  TagHelper

This little helpers are extensions of your view, which are looking like real HTML tags. In ASP.NET Core, you should use this TagHelpers instead of the HtmlHelpers because they are more cleaner and easier to use. Another huge benefit is Dependency Injection, which can’t be used with the HtmlHelpers, because the static context of extension methods. TagHelpers are common classes where we can easily inject services via the constructor. A pretty simple example on how a TagHelper could look like:

[TargetElement("hi")]
public class HelloTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "p";
        output.Attributes.Add("id", context.UniqueId);
        output.PreContent.SetContent("Hello ");
        output.PostContent.SetContent(string.Format(", time is now: {0}", 
                DateTime.Now.ToString("HH:mm")));
    }
}

This guy defines a HTML Tag called “hi” and renders a p-tag and the contents and the current Time.
Usage:

<hi>armend</hi>

Result:
<p>Hello armend, time is now: 18:55</p>

ASP.NET Core MVC provides many built in TagHelpers to replace the most used HtmlHelpers. E. g. the ActionLink can now replaced with an Anchor TagHelper:

@Html.ActionLink(“About ��, “About”, “Home”)

The new TagHelper to create a link to an action looks like this:

<a asp-controller=”�� asp-action=”��>About me</a>

The result in both cases is a clean a-Tag with the URL to the about page:

<a href=”/Home/��>About me</a>

As you can see the TagHelpers feel more than HTML and they are easier to use and more readable inside the Views.

3. Dependency Injection

This is the biggest improvement to organize Razor views in ASP.NET Core. Yes, you are able to use DI in your View. Does this really make sense? Doesn’t it mess up my view and doesn’t it completely break with the MVC pattern? (Questions like this are currently asked on StackOverflow and reddit). We think, no. Sure, you need be careful and you should only use it, if it is really needed. This could be a valid scenario: If you create a form to edit a user profile, where the user can add its job position, the country where he lives, his city, and so on. We would prefer not to pass the job positions, the country and the cities from the action to the view. We would prefer only to pass the user profile itself and We only want to handle the user profile in the action. This is why it is pretty useful in this case to inject the services which gives me this look-up data. The action and the ViewModel keeps clean and easy to maintain.
Just register your specific service in the method ConfigureServices in the Startup.cs and use one line of code to inject it into your view:

@inject DiViews.Services.ICountryService CountryService;

Now you are able to use the ContryService in your View to fill a SelectBox with list of countries.

4. Global View Configuration

Last but not least, there is a separate razor file you can use to configure some things globally. Use the _ViewImports.cshtml to configure usings, dependency injections and many more which should be used in all Views.

Conclusion

There are many new ways to extend and organize Razor views in ASP.NET Core. But you are free to decide which feature you want to use to get your problems solved. While there are many programming languages out there for a web developer to choose from, one of the most successful programming language till this date is ASP.NET. It has matured over the years with the latest version, ASP.NET Core, having a number of new features and enhancements. You may already have heard that ASP.NET hosting is offered by several web hosting providers. However, choosing the best cheap ASP.NET hosting isn’t an easy task.

 



ASP.NET Hosting - ASPHostPortal.com :: How to create watermark textbox in ASP.NET

clock October 16, 2015 06:42 by author Dan

Hi Friends, in this article I will explain about Watermark for Username and Password in JavaScript. I already explained in the previous articles about Marquee tag or How to Scroll Text From left to right or How to Move the Text in HTML,C#/VB.NET:Save the generated pdf directly to the server directory folder without user prompt in ASP.NET and How to open PDF File in Adobe Reader, not in Browser in ASP.NET using C#/VB.NET.

We may see Watermark textboxes  in so many sites. Suppose we take the twitter  site in login page and signup page it contains Watermark textboxes. Watermark is not working properly for the password if we take the Textmode as Password(TextMode="Password").For  that i take the extra textbox txtTempPwd and write the code as following.

Take one web page(.aspx page), Copy and Paste the below code in your web page.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Watermark Textboxs for username and Password  Using JavaScript</title>
<script language="javascript" type="text/javascript">
    function WaterMark(objtxt, event) {
        var defaultText = "Username";
        var defaultpwdText = "Password";
        // Condition to check textbox length and event type
        if (objtxt.id == "txtUserName" || objtxt.id == "txtPwd") {
            if (objtxt.value.length == 0 & event.type == "blur") {
                //if condition true then setting text color and default text in textbox
                if (objtxt.id == "txtUserName") {
                    objtxt.style.color = "Gray";
                    objtxt.value = defaultText;
                }
                if (objtxt.id == "txtPwd") {
                    document.getElementById("<%= txtTempPwd.ClientID %>").style.display = "block";
                    objtxt.style.display = "none";
                }
            }
        }
        // Condition to check textbox value and event type
        if ((objtxt.value == defaultText || objtxt.value == defaultpwdText) & event.type == "focus") {
            if (objtxt.id == "txtUserName") {
                objtxt.style.color = "black";
                objtxt.value = "";
            }
            if (objtxt.id == "txtTempPwd") {
                objtxt.style.display = "none";
            document.getElementById("<%= txtPwd.ClientID %>").style.display = "";
                document.getElementById("<%= txtPwd.ClientID %>").focus();
            }
        }
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td><b>UserName:</b></td>
<td>
<asp:TextBox ID="txtUserName" runat="server" Text="Username" Width="150px" ForeColor="Gray" onblur = "WaterMark(this, event);" onfocus = "WaterMark(this, event);" />
</td>
</tr>
<tr>
<td><b>Password:</b></td>
<td>
<asp:TextBox ID="txtTempPwd" Text="Password" runat="server" onfocus="WaterMark(this, event);" Width="150px" ForeColor="Gray" />
<asp:TextBox ID="txtPwd" TextMode="Password" Text="Password" runat="server" Width="150px" Style="display:none" onblur="WaterMark(this, event);"/>
</td>
</tr>
</table>
</form>
</body>
</html>

Then the output like below.

when we click on the textboxes then the text will disappear like below.

Best ASP.NET 4.6 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 :: SQL Split Function to Split an Input String

clock September 28, 2015 06:02 by author Dan

Today, we will explain about SQL Split Function to Split an Input String. Generally when posting an article in a blog, we have to define tags (Like  C#.NET, AJAX, ASP.NET,HTML) upon the article. We usually take these tags in a TextBox with separated them by comma(,). To insert these into database we have two ways to do.

First Method using C# :

Using C# you can split the TextBox items and use a for loop to insert into the database. Code is as follow.
   
string []tags = txtTags.Text.<span class="IL_AD" id="IL_AD10">Trim</span>().Split(',');
 
/* With for loop */
for (int i=0;i<tags.Count ;i++)
{
 /* perform db query with tags[i].ToSting();
}
 
/* with foreach */
foreach (string i in tags)
{
  /* perform db query with i.ToSting();
}

Second SQL Method :

Here in the SQL we pass the whole items of TextBox into SQL function to split it and then insert these into specific table. Lets see how to do this.
   
CREATE FUNCTION SplitText
(   
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT
 
      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END
 
      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)
           
            INSERT INTO @Output(Item)
            <span class="IL_AD" id="IL_AD12">SELECT</span> SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
           
            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END
 
      RETURN
END
GO
 
-- Create a temporary table to insert tags
create #tblTemp
(
Id identity (1,1),
tag nvarchar(50)
)
 
-- Inserting into tmpTable
insert into #tblTemp (temp) values
SELECT Item FROM dbo.SplitText('ASP.NET,C#.NET,ADO.NET,JavaScript', ',') 
-- Seperated by Comma(,). Place any thing according to you.


Execute your SQL batch query to inserting the tags into table.

Best ASP.NET 4.6 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 :: How to Fix ASP.NET Menu Control Cannot Work in Google Chrome

clock May 22, 2015 06:16 by author Dan

Problem

If your website is using ASP.NET Menu Control, the menu part will not work in Google Chrome browser and Apple Safari browser. The look and feel of the main menu is different. Submenu does not show up.

Solution

There is an easy fix for this problem. Just copy and paste the following codes to your page load event of your code behind master page file. You may need to copy it to every page if you do not use master page.

     Partial Class Main
        Inherits System.Web.UI.MasterPage

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Request.UserAgent.IndexOf("AppleWebKit") > 0 Then
                Request.Browser.Adapters.Clear()
            End If
        End Sub
    End Class

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 :: 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 :: How To Show Data In Doughnut Chart Using ASP.NET

clock January 15, 2015 06:49 by author Mark

Doughnut Chart In ASP.Net

Today i will explains about how to show data in doughnut chart. In this article we will learn about the Doughnut Chart of ASP.Net.
what's Donut or Doughnut chart?? Donut or Doughnut chart is just a simple pie chart with a hole inside. You can define hole radius to any size you need, both in percent or pixels. Sometimes we need to show data in a chart like a Doughnut chart, such as to show quarterly data and on, so by considering the preceding requirement and to introduce the ASP.Net Doughnut Chart controls I have decided to write this article.

Let us learn about the ASP.Net chart type Doughnut chart that provides a powerful UI and great design quality. We will learn about these chart type controls step-by-step. All the charts are in the System.Web.UI.DataVisualization.Charting namespace.
The chart data is represented using the following points:

  • X Axis: the horizontal line of the chart termed the X axis
  • Y Axis: the vertical line of the chart termed the Y axis

Now let us learn about the properties of the Doughnut chart. A Doughnut chart type has the following common properties:

  • AlternetText: Sets the alternate text when the image is not available.
  • Annotation: Stores the chart annotations.
  • AntiAliasing: sets a value that determines whether anti-aliasing is used when text and graphics are drawn.
  • BackGradientStyle: sets the orientation for the background gradient for the Chart control. Also determines whether a gradient is used, the default is None.
  • Backcolor: sets the background color for a chart, the default color is White.
  • BackImage: sets the background image for the chart control.
  • BackHatchStyle: sets the hatching style for the chart control, the default is None.
  • Height: Sets the height for the chart control.
  • Width: Sets the width for the chart control.
  • Palette: Sets the style with the color for the chart control, the default style is Chocolate.
  • PaletteCustomColors: Sets the custom color for the chart control.
  • Series: Sets the series collection for the chart control.
  • Legends: Sets the series of legends to the chart.

Now let us show the preceding explanation with a practical example by creating a simple web application.

Step 1: Create the table for the chart data

  • Now before creating the application, let us create a table named QuarterwiseSale in a database from where we show the records in the chart using the following script:

CREATE TABLE [dbo].[QuarterwiseSale](    
    [id] [int] IDENTITY(1,1) NOT NULL,    
    [Quarter] [varchar](50) NULL,    
    [SalesValue] [money] NULL,    
 CONSTRAINT [PK_QuarterwiseSale] PRIMARY KEY CLUSTERED     
    (    
    [id] ASC    
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
    ) ON [PRIMARY]   

  • The table has the following fields (shown in the following image): 
  • Now insert some records using the following script: 

SET IDENTITY_INSERT [dbo].[QuarterwiseSale] ON          
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (1, N'Q1', 100.0000)    
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (2, N'Q2', 50.0000)    
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (3, N'Q3', 150.0000)    
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (4, N'Q4', 200.0000)    
    GO    
    SET IDENTITY_INSERT [dbo].[QuarterwiseSale] OFF    
    GO   

Now the records will look as in the following image:
Now create the Stored Procedure to fetch the records from the database as in the following:

Create Procedure [dbo].[GetSaleData]    
    (    
    @id int=null             
    )    
    as    
    begin    
    Select Quarter,SalesValue from QuarterwiseSale    
    End 
  

I hope you have the same type of table and records as above.

Step: 2 Create Web Application

  • Now create the project using the following:
  • "Start" - "All Programs" - "Microsoft Visual Studio 2013".
  • "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  • Provide the project a name such as UsingDoughnutChart or another as you wish and specify the location.
  • Then right-click on Solution Explorer and select "Add New Item" then select Default.aspx page.
  • Drag and Drop a Chart control from the ToolBox onto the Default.aspx page.
  • Now the Default.aspx source code will be as follows:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>         
    <%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  
        Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head runat="server">  
        <title>Article by Vithal Wadje</title>  
    </head>  
    <body bgcolor="silver">  
        <form id="form1" runat="server">  
        <h4 style="color: Navy;">  
            Article for C#Corner  
        </h4>  
        <asp:Chart ID="Chart1" runat="server" BackColor="0, 0, 64" BackGradientStyle="LeftRight"  
            BorderlineWidth="0" Height="360px" Palette="None" PaletteCustomColors="Maroon"  
            Width="380px" BorderlineColor="64, 0, 64">  
            <Titles>  
                <asp:Title ShadowOffset="10" Name="Items" />  
            </Titles>  
            <Legends>  
                <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default"  
                    LegendStyle="Row" />  
            </Legends>  
            <Series>  
                <asp:Series Name="Default" />  
            </Series>  
            <ChartAreas>  
                <asp:ChartArea Name="ChartArea1" BorderWidth="0" />  
            </ChartAreas>  
        </asp:Chart>  
        </form>  
    </body>  
    </html> 

  • Create a method to bind the chart control. Then open the default.aspx.cs page and create the following function named Bindchart to bind the Chart Control as in the following:

private void Bindchart()  
        {  
            connection();  
            com = new SqlCommand("GetSaleData", con);  
            com.CommandType = CommandType.StoredProcedure;  
            SqlDataAdapter da = new SqlDataAdapter(com);  
            DataSet ds = new DataSet();  
            da.Fill(ds);         
            DataTable ChartData = ds.Tables[0];  
            //storing total rows count to loop on each Record  
            string[] XPointMember = new string[ChartData.Rows.Count];  
            int[] YPointMember = new int[ChartData.Rows.Count];         
            for (int count = 0; count < ChartData.Rows.Count; count++)  
            {  
                //storing Values for X axis  
                XPointMember[count] = ChartData.Rows[count]["Quarter"].ToString();  
                //storing values for Y Axis  
                YPointMember[count] = Convert.ToInt32(ChartData.Rows[count]["SalesValue"]);  
            }  
            //binding chart control  
            Chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember);         
            //Setting width of line  
            Chart1.Series[0].BorderWidth = 10;  
            //setting Chart type   
            Chart1.Series[0].ChartType = SeriesChartType.Doughnut;       
            foreach (Series charts in Chart1.Series)  
            {  
                foreach (DataPoint point in charts.Points)  
                {  
                    switch (point.AxisLabel)  
                    {  
                        case "Q1": point.Color = Color.YellowGreen; break 
                        case "Q2": point.Color = Color.Yellow; break;  
                        case "Q3": point.Color = Color.SpringGreen; break;
                    }  
                    point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);         
                }  
            }           
            //Enabled 3D  
          //  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            con.Close();         
        } 

Note that we have written a small code snippet to provide the different color for each point as in the following:

//To give different color for each point             
    foreach (Series charts in Chart1.Series)      
           {      
               foreach (DataPoint point in charts.Points)      
               {      
                   switch (point.AxisLabel)      
                   {      
                       case "Q1": point.Color = Color.RoyalBlue; break;   
                       case "Q2": point.Color = Color.SaddleBrown; break; 
                       case "Q3": point.Color = Color.SpringGreen; break; 
                   }      
                   point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);                
               }      
           }       

  • Now, call the preceding function on page load as in the following:

protected void Page_Load(object sender, EventArgs e)      
        {      
            if (!IsPostBack)      
            {      
                Bindchart();                 
            }      
        }  
  

  • The entire code of the default.aspx.cs page will look as follows:

      using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Web.UI.WebControls;  
    using System.Data.SqlClient;  
    using System.Configuration;  
    using System.Data;  
    using System.Web.UI.DataVisualization.Charting;  
    using System.Drawing;         
    public partial class _Default : System.Web.UI.Page  
    {  
        private SqlConnection con;  
        private SqlCommand com;  
        private string constr, query;  
        private void connection()  
        {  
            constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
            con = new SqlConnection(constr);  
            con.Open();  
               }  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!IsPostBack)  
            {  
                Bindchart();    
            }  
        }     
        private void Bindchart()  
        {  
            connection();  
            com = new SqlCommand("GetSaleData", con);  
            com.CommandType = CommandType.StoredProcedure;  
            SqlDataAdapter da = new SqlDataAdapter(com);  
            DataSet ds = new DataSet();  
            da.Fill(ds);         
            DataTable ChartData = ds.Tables[0];         
            //storing total rows count to loop on each Record  
            string[] XPointMember = new string[ChartData.Rows.Count];  
            int[] YPointMember = new int[ChartData.Rows.Count];         
            for (int count = 0; count < ChartData.Rows.Count; count++)  
            {  
                //storing Values for X axis  
                XPointMember[count] = ChartData.Rows[count]["Quarter"].ToString();  
                //storing values for Y Axis  
                YPointMember[count] = Convert.ToInt32(ChartData.Rows[count]["SalesValue"]);         
            }  
            //binding chart control  
            Chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember);         
            //Setting width of line  
            Chart1.Series[0].BorderWidth = 10;  
            //setting Chart type   
            Chart1.Series[0].ChartType = SeriesChartType.Doughnut;      
            foreach (Series charts in Chart1.Series)  
            {  
                foreach (DataPoint point in charts.Points)  
                {  
                    switch (point.AxisLabel)  
                    {  
                        case "Q1": point.Color = Color.YellowGreen; break 
                        case "Q2": point.Color = Color.Yellow; break;  
                        case "Q3": point.Color = Color.SpringGreen; break;
                    }  
                    point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);  
                }  
            }    
            //Enabled 3D  
          //  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;  
            con.Close();  
        }  
    } 

We now have the entire logic to bind the chart from the database, let us run the application. The chart will look as follows:

I hope this article work for you.

TOP No#1 Recommended ASP.NET 5 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.



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