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 :: 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.



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use OnClick and OnClientClick events to Prevent Double Clicking on your ASP.Net Buttons

clock December 9, 2014 04:46 by author Dan

While ASP.NET gives a great validator set of controls, now and then you have to "move your own" so to talk when making your controls. What's more, on the off chance that you have some AJAX preparing with your buttons in the background (for instance, sparing a record in a popup window) you run the danger of having "twofold spares" happening when the client clicks on the button and nothing happens instantly.

Having battled with this issue myself recently, it took somewhat more work than expected to get this to work legitimately. Here's the manner by which you get everything to play pleasantly together.

The first step is to wire up your code behind occasion that does your handling. In case you're doing this in C# you setup your Onclick occasion:

<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />

In case you're doing this in Vb.net, there's no compelling reason to utilize the Onclick value as a part of your button, you can go straight to the code behind, make your strategy name, and utilize the Handles pivotal word, pointing out your buttons click occasion:

Protected Void Sub btnSave_Click Handles btnSave.Click
' Code here
End Sub

The next step is to do our validation using Javascript (we’re using jQuery in here).

function validatePage()
{
    var check = true;

    // Check only simple textbox for now
    if ($("#txtImportant").val() == '') check = false;

    if (!check)
    {
       alert('Missing data. Please complete');
       return false;
    }
    else
    {
       $("#MainContent_btnSave").val('Processing...');
       $("#MainContent_btnSave").attr("disabled", true);
       return true;
    }
}

There are several vital notes to this capacity. The main is not to overlook that Asp.net as a matter of course likes to help particularly name your server controls, subsequently the "Maincontent_" prefix on our spare button. You can utilize the Clientidmode property in the event that you have to get around this. The following is that we keep the client from twofold clicking the spare catch by handicapping the catch and transforming its content to say "Handling… " Finally, we just debilitate the button if the acceptance succeeds. This keeps us from needing to handicap and re-empower the button focused around the results. Strangely it likewise verifies that our return value in the HTML component forms accurately, which was likely one of the greatest glitches I ran crosswise over amid this process.

Presently we have to wire up the Javascript handling. To do this, we utilize the Onclientclick technique that is accessible for most .Net server controls. While taking a gander at our code above looks clear enough (return false to prematurely end the script or valid to proceed with the post back) we do need to change our rationale somewhat. Having a "return genuine" explanation doesn't let the button proceed with its post back, it will make it quit handling (very nearly the same as a return false summon). Rather, we let our rationale just prematurely end if our acceptance fizzled:

<asp:Button ID="btnSave" runat="server"
            Text="Save"
            OnClick="btnSave_Click"
            OnClientClick="if (!validatePage()) {return false;}" />

At long last, following we're overriding the HTML onclick occasion on the control (on account of the Oncilentclick property) that regardless of the possibility that your acceptance strategy succeeds, the code behind system won't shoot. To work around this, we utilize the Usesubmitbehavior property of the button control and set it to false. What this does is attaches the suitable __dopostback call after our Javascript code. The last code for your button resembles this:

<asp:Button ID="btnSave" runat="server"
            Text="Save"
            OnClick="btnSave_Click"
            OnClientClick="if (!validatePage()) {return false;}"
            UseSubmitBehavior="false" />

That is all there is to it. Presently when you click on the button, if the acceptance falls flat, you'll get the caution box. Something else, the button will get to be crippled with a "handling" message and your code behind strategy will run.



ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Implement a Simple Captcha in C# .NET

clock December 1, 2014 06:07 by author Mark

Implement a simple captcha in C# .NET

  • Create a page with name “Captcha.aspx
  • Place the following html code in body part of the page

IMG height="30" alt="" src=BuildCaptcha.aspx width="80">
asp:TextBox runat="Server" ID="txtCaptcha">
    <asp:Button runat="Server" ID="btnSubmit"
     OnClick="btnSubmit_Click"
       Text="Submit" />
     On “btnSubmit_Click” place the following code
         if (Page.IsValid && (txtCaptcha.Text.ToString() ==
         Session["RandomStr"].ToString()))
           {
             Response.Write("Code verification Successful");
           }
    else
{
  Response.Write( "Please enter info correctly");
}

  • Include the following code in “BuildCaptcha.aspx"

Bitmap objBMP = new Bitmap(60, 20);
Graphics objGraphics = Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Wheat);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
  //' Configure font to use for text
      Font objFont = new Font("Arial", 8, FontStyle.Italic);
      string randomStr = "";
      char[] myArray = new char[5];
      int x;
   //That is to create the random # and add it to our string
     Random autoRand = new Random();
     for (x = 0; x < 5; x++)
{
  myArray[x] = System.Convert.ToChar(autoRand.Next(65,90));
  randomStr += (myArray[x].ToString());
}
     //This is to add the string to session, to be compared later
       Session.Add("RandomStr", randomStr);
    //' Write out the text
       objGraphics.DrawString(randomStr, objFont, Brushes.Red, 3, 3);
    //' Set the content type and return the image
  Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();

There you go you can test the page with captcha. Happy Programming Laughing



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Add Multiple Files Utilizing ASP.NET 4.5

clock November 28, 2014 05:07 by author Ben

In earlier versions of ASP.NET (edition under ASP.NET 4.5), we didn't have any inbuilt functionality to add several files at the same time. ASP.NET FileUpload handle permits uploading just one file in a time. Alternate answers to add numerous files are third party controls like Telerik or Devexpress. We can also use various jQuery Plugin like Uploadify to attain comparable performance.


In ASP.NET 4.5, we can add multiple documents simultaneously making use of ASP.NET FileUpload control. In ASP.NET 4.5, FileUpload Control support HTML5 several attribute.

Under are the steps to add numerous information utilizing ASP.NET 4.5 :

  1. In Visual Studio 2012, In Visual Studio 2012, create a new website using .Net 4.5 framework.
  2. Add a new web form (for example FileUpload.aspx) in newly created website.
  3. In code-beside file of FileUpload.aspx, write following code for FileUpload Control:

<asp:fileupload AllowMultiple="true" id="MultipleFileUpload" runat="server">
</asp:fileupload>

In above code, I have set AllowMultiple property of FileUpload Control to true.

Add one button to upload multiple files using FileUpload Control on button click.

<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

Write below code on button click event handler.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (MultipleFileUpload.HasFiles)
        {
            StringBuilder UploadedFileNames = new StringBuilder();

            foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
            {
                string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Files/"), FileName));
                UploadedFileNames.AppendFormat("{0}<br />", FileName);
            }
            Response.Write("Uploaded Files are : <br/>" + UploadedFileNames);
        }
    }

On button click, I am checking for multiple files and saving those files into Files folder of web application.
Compile source code and run the website application.

 

I had selected five images to upload. Once I had clicked on Upload button, all five images were uploaded successfully in Files folder.



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