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 :: Creating Help Desk Web Application using ASP.NET Core

clock January 17, 2017 05:28 by author Armend

Suppose you work for a small to midsize company that employs 50-100 workers. The Help Desk -- a subsidiary of the Information Services Division -- is in charge of trouble tickets regarding general PC issues such as email, viruses, network issues, etc. Initially, the Help Desk team stored this information in Excel spreadsheets, but as the company has grown, managing these spreadsheets has become tedious and time consuming.

The Help Desk has asked you to devise a more efficient solution that could be developed internally, saving the company money. As you start to think about it, the following requirements are apparent: fields for the submitter's first and last name, as well as their email address. You'll also need combo boxes for indicating ticket severity (low, medium, high), department, status (new, open, resolved), employee working on the issue, as well as an area for comments. Of all the solutions available, creating an internal help desk Web application with ASP.NET is relatively simple.

In the following article, we'll see how to implement these features in an ASP.NET help desk Web application using a database-driven approach,
Creating the JavaScript File
Because creating the JavaScript file is the easiest of the work left, we'll do this next. From the Solution Explorer, follow these steps:

Creating the Help Desk Class

Now that we have our data coming in, we need to be able to record a help desk ticket submission. We need to create an event handler in a class to handle it. Let's first create a help desk class by doing the following:

  •     Right click the project solution.
  •     Choose Add>New Item.
  •     In the Add New Item window, select Class.cs.
  •     In the name text field, type "HelpDesk" and then click Add.

Double click HelpDesk.cs from the Solution Explorer, which will show the empty class as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

We need to import three libraries as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

The first library (System.Data) allows us to work with stored procedures in ADO.NET, the second (System.Configuration) allows us to reference a connection key from configuration file and the last (System.Data.SqlClient) one allows us to connect to SQL Server.


About ASPHostPortal.com:


ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



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 :: 7 Tips for Developing a Secure ASP.NET Web Application

clock December 13, 2016 04:52 by author Armend

7 Tips for Developing a Secure ASP.NET Web Application

As the usage of the internet and the number of web applications over the internet have gone exponentially high there are bad people who continuously work around the clock to hack them. It may be for personal gain or just as an amateur act. Despite the intention of the bad guy the damage caused to the organization hosting the site or its users should be taken into account. As a professional web application developer it is a must to be aware of the best practices to follow in order to make the application more secure. In this article I will be listing and explaining my top 7 tips for developing a secure asp.net application.

Don’t Let Your Users be Victims of Click Jacking

Have you ever thought about someone framing your website onto theirs, making your users to be the victims of click jacking? Yes, the attackers can load your website onto their site in an iframe. They can then skillfully place their transparent controls over your website and fetch the PII information, user credentials, make them perform an unwanted task like exposing their financial information, etc.
In order to prevent that you will have to use a frame busting technique. The following script will not allow your website to be iframed. This can be placed in your master pages.

  •     <script type="text/javascript" language="javascript">
  •         //Check if the top location is same as the current location
  •         if (top.location.hostname != self.location.hostname) {
  •             //If not then set the top to you current
  •             top.location.href = self.location.href;
  •         }
  •     </script>
  • In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
    The header should be added in the global.asax application start event.

    1. protected void Application_Start(object sender, EventArgs e)
    2. {
    3.             HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    4. }
    5.  

     

    In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
    The header should be added in the global.asax application start event.

    1. protected void Application_Start(object sender, EventArgs e)
    2. {
    3.             HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    4. }
    5.  

     

    White List the Request URL

    Though we have many techniques to perform the security preventions inside the application it is most important to prevent the bad data from being entered into your website at the first place. Most attacks happen through the query string values passed through the URL. It is a best security practice to define a common place like an HttpModule to white list the URL, i.e. sanitize the entire URL with a set of white listed characters and drop all the bad ones. It means you will not encourage any other characters apart from a white listed set defined in your application.
    It is important for you to know that black listing is not a foolproof mechanism and it can be broken by the hackers easily.

    Practice of Encoding the Data

    While processing and sending, the data in the response that is fetched from outside the trust boundary should always be encoded. The type of encoding may differ based on the usage of the non-trusted data. For example perform an HtmlEncode for the data that is sent to the client page.

    Label1.Text = Server.HtmlEncode(Request.QueryString["BadValue"]);

     

    Encoding the data will make the XSS scripts inactive and prevent them from being executed. Microsoft has provided the AntiXss library, which provides more sophisticated encoding methods including the JavascriptEncode.

    Using Cookies

    As a web developer you should take utmost care while using cookies, which may open a back door for the hackers to get into your applications. Following are the best practices while using a cookie to store information.
    1. Is your website is hosted under SSL? Then be sure to mark your cookies as secure. This will make them available only in the SSL transmissions.

    1. HttpCookie cookie = new HttpCookie("MySecureCookie");
    2. cookie.Value = "This is a PII information";
    3. cookie.Secure = true;

     

    If your website is not SSL enabled then always encrypt the values using a strong encryption mechanism like AES 256 and then store them in the cookies.

    Secure the Service Calls (WCF / Web Service)

    Are you exposing WCF services through basicHttpBinding? Then think again because the messages transmitted over will be plain text and any intruder will be able to trap the requests and even simulate them easily. Use wsHttpBinding, which will transport the messages in an encrypted format, which makes the life of the intruder hard.
    Though you make lots of protections for your WCF or web services it is a best practice to host the services under an SSL layer.
    Never Deploy the Application with debug=”true”
    It is strongly recommended not to deploy your applications in the production environment with compilation debug=”true” in your web.config. This will result in a big nightmare for performance and security of the application.
    This may leak too much information for the attackers, for example the stack trace in the event of an unhandled exception and the debug trace information. Such exposure of the internals will be good bucks for the attackers.

  • <system.web>
  •         <compilation debug="false" targetFramework="4.0" />
  •     </system.web>
  • Thinking About Turning Off ViewStateMAC?

    Turning off ViewStateMAC will create a security loophole in your asp.net application if you are using Viewstate on your web pages. The intruders will easily be able to intercept, read the 64 bit encoded values and modify them to do some bad things to your website. Having it turned on ensures that the viewstate values are not only encoded but also a cryptographic hash is performed using a secret key.

    1. <pages enableViewStateMac="true"></pages>

     

    I hope this article is useful for the developers who thrive at making their asp.net application an absolutely impossible place for the hackers to deal with.

    Happy reading!

    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 :: Repair Dropdown Boxes in ASP.NET Datagrids

    clock December 6, 2016 07:43 by author Armend

    Introduction

    Today, I will explain Step by Step to Repair Dropdown Boxes in ASP.NET Datagrids. Alright, this issue isn't silverlight, yet I did experience it in my day work. Truth be told, I've experienced it a few times, so I thought I would compose it up so I can discover it once more.

     

    Error

    You compose a page that contains an updatable datagrid, which, when in Editmode, contains a dropdown rundown containing lookup things. The Dropdownbox does not populate, and (later when you get it working) the correct listitem is not chosen.

    Cause

    Since the Dropdownbox down not existing when the page loads, there is nothing to tie.

    Step by Step

    You need to append your occasions to some non-standard page occasions to get it to work. The pertinent piece of the .aspx page is underneath (placed this in your datagrid)

    <asp:TemplateColumn HeaderText=”Tactic Category”>

    <HeaderStyle Font-Size=”Large” Font-Bold=”true” />
    <ItemTemplate>
    <%#DataBinder.Eval(Container.DataItem,”TacticCatName”)%>
    </ItemTemplate>
    <EditItemTemplate>
    <%–Notice the GetCat() routine here as the datasource.–%>
    <asp:DropDownList id=”ddTacticCatList” runat=”server” DataSource=”<%# GetCat() %>” DataTextField=”TacticCatName” DataValueField=”TacticCatID”>
    </asp:DropDownList>
    </EditItemTemplate>

    </asp:TemplateColumn>

    Your code-behind page should look like this (in C#)


    private void MainCode()
    {
    string strID = Request.QueryString["id"].ToString();
    //custom code to get the relevant dataset for the entire datgrid
    DataSet ds = LMR.TacticSubCatList(strID);
    //custom code to bind to the datagrid
    Utility.DGDSNullCheck(ds, dgTacticSubCatList, lblTacticSubCatList, “There are no tactic subcategories in the database at this time.”);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    MainCode();
    }
    }

    protected void dgTacticSubCatList_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    //grab the index
    dgTacticSubCatList.EditItemIndex = e.Item.ItemIndex;
    MainCode();
    }

    protected void dgTacticSubCatList_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    //get the id value of the selected datagrid item
    int intTacticSubCatID = (int)dgTacticSubCatList.DataKeys[(int)e.Item.ItemIndex];

    //this gets our textbox, also in the datagrid
    TextBox EditText = null;
    EditText=(TextBox)e.Item.FindControl(“tbTacticSubCatName”);
    string strEditText = Convert.ToString(EditText.Text);

    //get the value of our dropdown list
    DropDownList dd = (DropDownList)e.Item.FindControl(“ddTacticCatList”);
    string strTacticCatID = dd.SelectedValue.ToString();
    //do our database update
    LMR.TacticSubCatEdit(intTacticSubCatID.ToString(),strTacticCatID,strEditText);
    //reset the datagrid
    dgTacticSubCatList.EditItemIndex = -1;
    //give feedback and rebind
    lblFeedback.Text = “Your changes have been applied.”;
    MainCode();
    }

    protected void dgTacticSubCatList_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    dgTacticSubCatList.EditItemIndex = -1;
    MainCode();
    }
    protected DataTable GetCat()
    {
    //here is where we get the dataset to populate the dropdown list – it does have to go in an independant function
    DataSet ds = LMR.TacticCatList();
    return ds.Tables[0];
    }

    protected void dgTacticSubCatList_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
    if (e.Item.ItemType == ListItemType.EditItem)
    {
    //we set the selcted index in the ItemDataBound event
    string strID = Request.QueryString["id"].ToString();
    string strSubCatID = dgTacticSubCatList.DataKeys[(int)e.Item.ItemIndex].ToString();
    Holder.TacticSubCat tsc = LMR.GetTacticSubCat(strSubCatID);
    DropDownList dd = (DropDownList)e.Item.FindControl(“ddTacticCatList”);
    dd.SelectedIndex =dd.Items.IndexOf(dd.Items.FindByValue(strID));
    }
    }

     

    It's as simple as that. Hopefully this article will be usefull for you.

     

    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 :: Change Startup.cs and wwwroot folder name in ASP.NET Core

    clock November 22, 2016 06:45 by author Armend

    ASP.NET Core runs on conventions. It expects Startup.cs file for starting up the ASP.NET Core application and wwwroot folder for the application’s static contents. But what if you want to change the name of Startup.cs and wwwroot to your choice? Well, that can be done. In this short post, we will see how to change Startup.cs and wwwroot folder name in ASP.NET Core.

     

    Change Startup.cs class name

    You can easily change the startup class name. Open the Startup.cs file and change the startup class name from Startup to “MyAppStartup” (or anything of your choice). And also change the name of the constructor.

    public class MyAppStartup
    {
        public MyAppStartup(IHostingEnvironment env)
        {
           
        }
    }

    Now you need to tell ASP.NET Core about new Startup class name, otherwise application will not start. So open Program.cs file and change the UseStartup() call as follows:

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

    That’s it.

    Change wwwroot folder name

    Earlier, I posted how to rename the wwwroot folder via hosting.json file but that doesn’t seem to work now. To change the name, right on wwwroot folder and rename it to “AppWebRoot” (or anything of your choice).
    Now, open Program.cs file and add highlighted line of code to Main().

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

    That’s it.
    Hope you liked it. Thank you for reading.

    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 publish ASP.NET Core web application via Visual Studio 2015

    clock November 3, 2016 07:04 by author Armend

    How to publish ASP.NET Core web application via Visual Studio 2015

    Create a web app
    From the Visual Studio Start page, tap New Project.
    In the center pane, tap ASP.NET Core Web Application (.NET Core) Create a web app

    In the New ASP.NET Core Web Application dialog, tap Web Application, and then tap OK.

     

    Login to your hosting control panel --> Websites --> Select the target site --> click Show Web Deploy Info. If you have not enable this feature, please enable it first at the same place. You will able to see the web deploy settings there or download the publishing xml configuration file directly.
    And then open your web application with Visual Studio 2015, right click the web application, then click"Publish" to start.
    You can chose Import  with Publish XML and Custom to fill in the deploy info.

    Click Validate Connections to check the deploy info,then you can tap Publish.

    Note:If you get certificate error with publish,please add below code to your PublishProfiles.
    <AllowUntrustedCertificate>True</AllowUntrustedCertificate>

     

    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

    Save



    ASP.NE Core 1.0 Hosting - ASPHostPortal.com :: How to Get Users IP Address in ASP.NET

    clock September 5, 2016 23:20 by author Dan

    Here we will learn how to get users / client IP address in asp.net using c# and vb.net with example or retrieving user's IP address in asp.net using c# and vb.net or how to get IP address of visitors machine in asp.net using c# and vb.net with example.

    Description:

    In previous articles I explained JavaScript Get User IP Address, City, Latitude, Longitude, how to find client machine IP using jquery in asp.net, show users current location in google map using latitude and longitude in asp.net, show google map with latitude & longitude in asp.net and many articles relating to asp.net, c#, vb.net jQuery. Now I will explain how to get users ip address or client IP address of machine in asp.net using c# and vb.net.

    To get user / client ip address of machine in asp.net first create new application in visual studio then open aspx page and write the code as shown following.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Get visitors machine IP in asp.net</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="lblIP" runat="server" Font-Bold="true" Font-Size="XX-Large" ForeColor="#529E00"/>
    </div>
    </form>
    </body>
    </html>


    Now open code behind file and write the code like as shown below

    C# Code

    protected void Page_Load(object sender, EventArgs e)
    {
    string IPAdd = string.Empty;
    IPAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (string.IsNullOrEmpty(IPAdd))
    IPAdd = Request.ServerVariables["REMOTE_ADDR"];
    lblIP.Text = IPAdd;
    }

    VB.NET Code

    Partial Class Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim IPAdd As String = String.Empty
    IPAdd = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If String.IsNullOrEmpty(IPAdd) Then
    IPAdd = Request.ServerVariables("REMOTE_ADDR")
    End If
    lblIP.Text = IPAdd
    End Sub
    End Class


    If you observe above code when users ip address behind the proxies or routers then REMOTE_ADDR will return IP Address of router, not the user’s machine IP because of that first we need to check with HTTP_X_FORWARDED_FOR. In case if users machine IP address behind a proxy server then his machine’s IP Address will appended to Proxy Server’s IP Address.

    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 Running Scripts Pre and Post Publish in ASP.NET Core RC2

    clock August 30, 2016 20:10 by author Armend

    Running Scripts Pre and Post Publish in ASP.NET Core RC2

    This week I ran into an issue when deploying a Service Fabric service where a library file was not being copied to the output directory. Since I am using ASP.NET Core for my API layer in the Service Fabric project, I had to go dig around to figure out how to get the file to copy to the deployment folder during the publishing of the ASP.NET Core application.

    "note that this solution with project.json may change with as ASP.NET Core moves back to .csproj file".

    What I learned is that in ASP.NET Core RC 2 you can add scripts to the prepublish and postpublish events by adding a scripts section to the project.json file. In my case I needed to copy a file to the deployment folder after the rest of the project as built.

    {
      "buildOptions": {
           // ...
        }
      },
      //...

      "scripts": {
        "prepublish": ["<command1>, <command2>"],
        "postpublish": [ "xcopy <pathtofile> %publish:OutputPath%" ]
      }
    }

    Note that you can reference variables like %publish:OutputPath%. You can also supply multiple commands by separating them with a comma. As noted above this currently works in ASP.NET Core RC2 but might change when as we transition back to the .csproj file.

    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 :: Asp.net Export Excel Show/Hide Loading image

    clock August 2, 2016 19:58 by author Armend

    This Tip will explain how to hide the loading gif image after the file is downloaded . It  will be helpful when we are using  Response Object to export the excel or any other file format.

     

    Sometimes while  downloading an excel or any file from an Asp application, it might take some time to Generate the File, the delay  depends on many factors( file size, loops, server bandwidth etc ). So we repesent the File Generation process using a rotating GIF image next to the button.
    But when we are using Response object we wont get the event after the file is downloaded to the browser, in this case it will be difficult to hide the loading gif which is being shown on the screen

    The below steps will guide how to  Show the Gif while Generating and hide it once the file is completly downloaded.

    Hide the GIF after download

    • When the download button is clicked, show the loading gif image using onclicentClick event and CSS properties
    • On the Client click event invoke a Javascript method which Contains a  Setinterval  object that moniters  for our cookie (created in c# Response object).
    • In the Server button click Event Create an HttpCookie and append it to the Respone object.
    • So when the File is downloaded completly the Cookie is added to the Page, Now the SetInterval function will capture the cookie and Hides the Loading Gif image.
    • Note: whenever the download button is clicked, previous cookie has to be deleted.

    Using the code

    protected void btnExportExcel_Click(object sender, EventArgs e)
              {
                DataTable dt = new DataTable();
                dt = GetDataFromDb();
                System.Threading.Thread.Sleep(3000); // for testing purpose to create 3 seconds delay
                //Create a temp GridView
                GridView gv = new GridView();
                gv.AllowPaging = false;
                gv.DataSource = dt;
                gv.DataBind();
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=ExcelReport.xls");
                Response.Charset = "";
                Response.ContentType = "application/vnd.ms-excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                gv.RenderControl(hw);
                // Append cookie
                HttpCookie cookie = new HttpCookie("ExcelDownloadFlag");
                cookie.Value = "Flag";
                cookie.Expires = DateTime.Now.AddDays(1);
                Response.AppendCookie(cookie);
                // end
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }

    HTML/ASPX Code

    <table>
                <tr>
                    <td>
                        <asp:Button Text="Download" ID="btnExportExcel" OnClientClick="jsShowHideProgress();" runat="server" OnClick="btnExportExcel_Click" />
                    </td>
                    <td>
                        <img style="display: none" id="imgloadinggif" src="Images/loading.gif" alt="loading.." />
                    </td>
                </tr>
            </table>

    Javascript Code:

    function jsShowHideProgress() {
        setTimeout(function () { document.getElementById('imgloadinggif').style.display = 'block'; }, 200);
        deleteCookie();

        var timeInterval = 500; // milliseconds (checks the cookie for every half second )

        var loop = setInterval(function () {
            if (IsCookieValid())
            { document.getElementById('imgloadinggif').style.display = 'none'; clearInterval(loop) }

        }, timeInterval);
    }

    // cookies
    function deleteCookie() {
        var cook = getCookie('ExcelDownloadFlag');
        if (cook != "") {
            document.cookie = "ExcelDownloadFlag=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC";
        }
    }

    function IsCookieValid() {
        var cook = getCookie('ExcelDownloadFlag');
        return cook != '';
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    About ASPHostPortal.com:

    ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



    ASP.NET Hosting - ASPHostPortal.com :: Tips To Use BackgroundWorker in C#

    clock July 26, 2016 19:54 by author Armend

    How To Use BackgroundWorker in C#

    BackgroundWorker is the class in System.ComponentModel which is used when you need to do some task on the back-end or in different thread while keeping the UI available to users (not freezing the user) and at the same time, reporting the progress of the same.

    Using the Code

    Backgroundworker has three event handlers which basically takes care of everything one needs to make it work.

    • DoWork - Your actual background work goes in here
    • ProgressChanged - When there is a progress in the background work
    • RunWorkerCompleted - Gets called when background worker has completed the work.

    I have created a sample WPF application which demonstrates how to use the background worker in C#.

    <ProgressBar x:Name="progressbar"
     HorizontalAlignment="Left" Height="14"
     Margin="191,74,0,0" VerticalAlignment="Top"
     Width="133"/>
    <Button x:Name="button" Content="Button"
     HorizontalAlignment="Left"
     Margin="249,97,0,0" VerticalAlignment="Top"
     Width="75" Click="button_Click"/>

    On Window initialization, I am creating a new object of BackgroundWorker and registering the event handlers for the same.

    BackgroundWorker bg;
    public MainWindow()
    {
    InitializeComponent();
    bg = new BackgroundWorker();
    bg.DoWork += Bg_DoWork;
    bg.ProgressChanged += Bg_ProgressChanged;
    bg.RunWorkerCompleted += Bg_RunWorkerCompleted;
    bg.WorkerReportsProgress = true;
    }

    Here is the implementation of all three event handlers.

    private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    MessageBox.Show("Task completed");
    }
    private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    progressbar.Value += 1;
    //label.Content = e.ProgressPercentage;
    }
    private void Bg_DoWork(object sender, DoWorkEventArgs e)
    {
    for (int i = 1; i &amp;lt;= 10; i++)
    {
    Thread.Sleep(1000); //do some task
    bg.ReportProgress(0);
    }
    }

    In order to make this stuff work, you need to trigger the DoWork event and for that, I am using button click event.

    private void button_Click(object sender, RoutedEventArgs e)
       {
               progressbar.Value = 0;
               progressbar.Maximum = 10;
               bg.RunWorkerAsync();
       }

    It is a very basic example of background worker, but it is good to start with. One must be wondering how it is updating the progress bar if it is working in the background.
    Well, the ProgressChanged event handler runs on UI thread whereas DoWork runs on application thread pool. That's why despite running in the background on different thread, it is not freezing the UI and updating the progressbar upon making progress.

     

    Best ASP.NET Core 1.0 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.

     



    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