European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Create Login Form In ASP.NET?

clock March 9, 2017 07:58 by author Peter

In this tutorial, I will show you how to create login form in ASP.NET core. You can easily implement this concept anywhere in .NET applications. I have used some controls to build the login form in a .NET application.

  •  Text Box
  •  Label and Button

Please follow these steps to make this application.
Step 1
First, open your Visual Studio -> File -> New -> Website -> ASP.NET Empty website and click OK. Now, open Solution Explorer and go to Add New Item -> Web form -> click Add.

Step 2
Now, make a Login page like the one given below.
.aspx or design page (front-end)
    <html xmlns="http://www.w3.org/1999/xhtml">  
      
    <head runat="server">  
        <title>Login Form</title>  
    </head>  
      
    <body>  
        <form id="form1" runat="server">  
            <div>  
                <table>  
                    <tr>  
                        <td> Username: </td>  
                        <td>  
                            <asp:TextBox ID="txtUserName" runat="server" />  
                            <asp:RequiredFieldValidator ID="rfvUser" ErrorMessage="Please enter Username" ControlToValidate="txtUserName" runat="server" /> </td>  
                    </tr>  
                    <tr>  
                        <td> Password: </td>  
                        <td>  
                            <asp:TextBox ID="txtPWD" runat="server" TextMode="Password" />  
                            <asp:RequiredFieldValidator ID="rfvPWD" runat="server" ControlToValidate="txtPWD" ErrorMessage="Please enter Password" /> </td>  
                    </tr>  
                    <tr>  
                        <td> </td>  
                        <td>  
                            <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> </td>  
                    </tr>  
                </table>  
            </div>  
        </form>  
    </body>  
      
    </html>  


Now, create an event for click button, such as -  onclick="<>".
    onclick="btnSubmit_Click"  

So, our button tag will be like <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />. And in login.aspx.cs page, we need to write the following code.

C# Code --Code behind(Aspx.cs)
    using System;  
    using System.Data;  
    using System.Data.SqlClient;  
    using System.Configuration;  


After adding the namespaces, write the following code in code behind.
    protected void btnSubmit_Click(object sender, EventArgs e) {  
        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);  
        con.Open();  
        SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName =@username and Password=@password", con);  
        cmd.Parameters.AddWithValue("@username", txtUserName.Text);  
        cmd.Parameters.AddWithValue("@password", txtPWD.Text);  
        SqlDataAdapter da = new SqlDataAdapter(cmd);  
        DataTable dt = new DataTable();  
        da.Fill(dt);  
        if (dt.Rows.Count > 0) {  
            Response.Redirect("Details.aspx");  
        } else {  
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");  
        }  
    }  


Now, for connecting it with the database, write the database connection string like the following.

Web Config
    <connectionStrings>  
        <add name="dbconnection" connectionString="Data Source=BrajeshKr;Integrated Security=true;Initial Catalog=MyDB" /> </connectionStrings>

That's it. Now, our Login page is ready to be executed. You can download the code for this application and run that on your Visual Studio.

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How To Drag And Upload Multiple Image Files In ASP.NET?

clock January 25, 2017 08:20 by author Peter

In this tutorial, I will show you How To Drag And Upload Multiple Image Files In ASP.NET. First, I create a blank ASP.NET WebForm Project. And then, right click on the Project ==>select NuGet Package Manager ==> Select DropZone and Download it.

Design a WebForm having a file upload control.
    <head runat="server"> 
        <title></title> 
        <script src="scripts/dropzone/dropzone.min.js"></script> 
        <link href="scripts/dropzone/basic.min.css" rel="stylesheet" /> 
        <link href="scripts/dropzone/dropzone.css" rel="stylesheet" /> 
          
        <script src="scripts/ai.0.15.0-build58334.min.js"></script> 
    </head> 
    <body> 
        <form id="form1" runat="server" class="dropzone"> 
            <div> 
                <div class="fallback"> 
                    <asp:FileUpload ID="file" runat="server" AllowMultiple="true" /> 
                </div> 
            </div> 
        </form> 
    </body> 
    </html> 


Write the following code in the code behind(.cs) file.
    protected void Page_Load(object sender, EventArgs e) 
           { 
               foreach (string s in Request.Files) 
               { 
                   HttpPostedFile file = Request.Files[s]; 
     
                   int fileSizeInBytes = file.ContentLength; 
                   string fileName = file.FileName; 
                   string fileExtension = ""; 
     
                   if (!string.IsNullOrEmpty(fileName)) 
                       fileExtension = Path.GetExtension(fileName); 
     
                   // IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory 
                   // string savedFileName = Path.Combine(@"..\Files\", Guid.NewGuid().ToString() + fileExtension); 
                  string savepath = Path.Combine(Request.PhysicalApplicationPath, "Files"); 
                   string savefile = Path.Combine(savepath, file.FileName); 
                   file.SaveAs(savefile); 
               } 
           } 


Run the project and select multiple files and drag to the box.

Drag and drop all the images to the box. It will upload the images and save them to your local folder (here in Files Folder).

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: Implement .NET Core CSV WriterImplement .NET Core CSV Writer

clock January 18, 2017 07:56 by author Peter

Today, I will explain you about how to implement Generic CSV Writer which may take an input from any list and return a CSV string or write to a certain file, if specified. Although, this is a generic C# implementation and can be used in any .NET Framework supporting generics. Yet, we are going to discuss this with .NET Core. We are going to use .NET Core Console Application which is in continuation to Welcome to .NET Core Console Application.

Add new Class in DotNetCore.ConsoleApplication
We are going to add a new class CsvWriter in DotNetCore.ConsoleApplication.

  • Open existing solution in Visual Studio 2015.
  • Now, add a new class CsvWriter.cs.

        Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.

        Name it CsvWriter.cs.
        Click OK button.

  • Add CsvWriter implementation.


        Write<T> (IList<T> list, bool includeHeader = true).
        Creates and returns the generated CSV.
        Write<T> (IList<T> list, string fileName, bool includeHeader = true)
        Creates and returns the generated CSV and saves the generated CSV to the specified path.
        CreateCsvHeaderLine
        Creates CSV header line, if includeHeader is set true.
        CreateCsvLine<T>(T item, PropertyInfo[] properties).
        Creates a CSV line for the given type of the object.
        CreateCsvLine(IList<string> list).
        Creates a CSV line for the given list of the string by joining them, demarcated by comma.

        CreateCsvItem
        Adds the provided value item to the processed list, used to create CSV line.

        CreateCsvStringListItem
        Adds the provided string list as a single item to the processed list, which is used to create CSV line.

        CreateCsvStringArrayItem
        Adds the provided string array as a single item to the processed list, which is used to create CSV line.

        CreateCsvStringItem
        Adds the provided string value item to the processed list, used to create CSV line.

        ProcessStringEscapeSequence
        Processes the provided data to handle double quotes and comma value. If we do not apply escape sequences, they can corrupt the data.

        WriteFile
        Writes the generated CSV data to the file.

ConsoleApplication
    public class CsvWriter { 
        privateconst string DELIMITER = ","; 
     
        public string Write < T > (IList < T > list, bool includeHeader = true) { 
            StringBuildersb = new StringBuilder(); 
     
            Type type = typeof(T); 
     
            PropertyInfo[] properties = type.GetProperties(); 
     
            if (includeHeader) { 
                sb.AppendLine(this.CreateCsvHeaderLine(properties)); 
            } 
     
            foreach(var item in list) { 
                sb.AppendLine(this.CreateCsvLine(item, properties)); 
            } 
     
            returnsb.ToString(); 
        } 
     
        public string Write < T > (IList < T > list, string fileName, bool includeHeader = true) { 
            string csv = this.Write(list, includeHeader); 
     
            this.WriteFile(fileName, csv); 
     
            return csv; 
        } 
     
        private string CreateCsvHeaderLine(PropertyInfo[] properties) { 
            List < string > propertyValues = new List < string > (); 
     
            foreach(var prop in properties) { 
                stringstringformatString = string.Empty; 
                string value = prop.Name; 
     
                var attribute = prop.GetCustomAttribute(typeof(DisplayAttribute)); 
                if (attribute != null) { 
                    value = (attribute as DisplayAttribute).Name; 
                } 
     
                this.CreateCsvStringItem(propertyValues, value); 
            } 
     
            returnthis.CreateCsvLine(propertyValues); 
        } 
     
        private string CreateCsvLine < T > (T item, PropertyInfo[] properties) { 
            List < string > propertyValues = new List < string > (); 
     
            foreach(var prop in properties) { 
                stringstringformatString = string.Empty; 
                object value = prop.GetValue(item, null); 
     
                if (prop.PropertyType == typeof(string)) { 
                    this.CreateCsvStringItem(propertyValues, value); 
                } else if (prop.PropertyType == typeof(string[])) { 
                    this.CreateCsvStringArrayItem(propertyValues, value); 
                } else if (prop.PropertyType == typeof(List < string > )) { 
                    this.CreateCsvStringListItem(propertyValues, value); 
                } else { 
                    this.CreateCsvItem(propertyValues, value); 
                } 
            } 
     
            returnthis.CreateCsvLine(propertyValues); 
        } 
     
        private string CreateCsvLine(IList < string > list) { 
            returnstring.Join(CsvWriter.DELIMITER, list); 
        } 
     
        private void CreateCsvItem(List < string > propertyValues, object value) { 
            if (value != null) { 
                propertyValues.Add(value.ToString()); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private void CreateCsvStringListItem(List < string > propertyValues, object value) { 
            string formatString = "\"{0}\""; 
            if (value != null) { 
                value = this.CreateCsvLine((List < string > ) value); 
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value))); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private void CreateCsvStringArrayItem(List < string > propertyValues, object value) { 
            string formatString = "\"{0}\""; 
            if (value != null) { 
                value = this.CreateCsvLine(((string[]) value).ToList()); 
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value))); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private void CreateCsvStringItem(List < string > propertyValues, object value) { 
            string formatString = "\"{0}\""; 
            if (value != null) { 
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value))); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private string ProcessStringEscapeSequence(object value) { 
            returnvalue.ToString().Replace("\"", "\"\""); 
        } 
     
        public bool WriteFile(string fileName, string csv) { 
            boolfileCreated = false; 
     
            if (!string.IsNullOrWhiteSpace(fileName)) { 
                File.WriteAllText(fileName, csv); 
     
                fileCreated = true; 
            } 
     
            returnfileCreated; 
        } 
    } 


Add Test Model Class in DotNetCore.ConsoleApplication
We are going to add a new class TestVM in DotNetCore.ConsoleApplication.

  • Open the existing Solution in Visual Studio 2015
  • Now, add a new class TestVM.cs.

        Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.
        Name it TestVM.cs.
        Click OK button.

  • Add TestVM implementation.
  • Update Program.cs to initialize List<TestVM> with the dummy data and call CsvWriter.

    public class TestVM { 
        [Display(Name = "Test Id")] 
        publicintTestId { 
            get; 
            set; 
        } 
        [Display(Name = "Name")] 
        public string TestName { 
            get; 
            set; 
        } 
    } 
     
    public class Program { 
        public static void Main(string[] args) { 
            Console.WriteLine("Welcome to .NET Core Console Application"); 
            List < TestVM > tests = new List < TestVM > { 
                newTestVM { 
                    TestId = 1, TestName = "Bill Gates" 
                }, 
                newTestVM { 
                    TestId = 2, TestName = "Warren Buffett" 
                }, 
                newTestVM { 
                    TestId = 3, TestName = "Amancio Ortega" 
                }, 
                newTestVM { 
                    TestId = 4, TestName = "Carlos Slim Helu" 
                } 
            }; 
            stringstringfileName = string.Format("{0}\\test.csv", System.AppContext.BaseDirectory); 
            CsvWritercsvWriter = new CsvWriter(); 
            csvWriter.Write(tests, fileName, true); 
            Console.WriteLine("{0} has been created.", fileName); 
            Console.ReadKey(); 
        } 
    } 

Run Application in Debug Mode

  • Press F5 or Debug Menu >> Start Debugging or Start Console Application button on the toolbar to start the Application in the debugging mode. It will start an Application Console in the debug mode.
  • It will generate test.csv at given path. Therefore at C:\ASP.NET Core\CSV Writer\DotNetCore\ConsoleApplication.NetCore\bin\Debug\netcoreapp1.0.

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Create Multi Step Form In ASP.NET?

clock January 11, 2017 07:18 by author Peter

In this post, I will tell you about how to create multi step form in ASP.NET. Multiview will be used to display the content on the tap of Tab. 

To show tab on the top, we will use Menu control. Thus, let's go and Add menu control from toolbox. I have given the Horizontal orientation, so that Tab will display horizontally. 
<asp:Menu 
           ID="menuTabs" 
           Orientation="Horizontal" 
           Width="100%" 
           runat="server"> 
           <Items> 
               <asp:MenuItem Text="Employee Info" Value="0" Selected="true"/> 
               <asp:MenuItem Text="Contact Info" Value="1" /> 
               <asp:MenuItem Text="Salary Info" Value="2" /> 
           </Items> 
</asp:Menu>
 

To display the content for each tab, we will use Multiview control. I have given a property Selected="true" for Employee Info, so that when a page is launched, it will display the content of Employee Info.
<asp:MultiView ID="multiviewEmployee" 
                      runat="server" ActiveViewIndex="0"> 

</asp:MultiView> 


Next step is to add view inside Multiview. As I have three menu items, I need to add three views inside Multiview.
<asp:MultiView ID="multiviewEmployee" 
                       runat="server" ActiveViewIndex="0"> 
              <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
               <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
               <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
</asp:MultiView> 
 

ActiveViewIndex= "0" will display first view after page is launched. Now, we will open corresponding view, when it is clicked on menu items. For it, we need to handle OnMenuItemClick event of Menu control. Hence, add it in your code and it will look, as mentioned below.
<asp:Menu 
  ID="menuTabs" 
  Orientation="Horizontal" 
  Width="100%" 
  runat="server" 
  OnMenuItemClick="menuTabs_MenuItemClick"> 
  <Items> 
      <asp:MenuItem Text="Employee Info" Value="0" Selected="true"/> 
      <asp:MenuItem Text="Contact Info" Value="1" /> 
      <asp:MenuItem Text="Salary Info" Value="2" /> 
  </Items> 
</asp:Menu> 


In CS page, assign the value of menu item to multiview .
protected void menuTabs_MenuItemClick(object sender, MenuEventArgs e) 
    { 
        Menu menuTabs = sender as Menu; 
        MultiView multiTabs = this.FindControl("multiviewEmployee") as MultiView; 
        multiTabs.ActiveViewIndex = Int32.Parse(menuTabs.SelectedValue); 
         
    } 


Now, it's none. Your tab structure is ready. Full code for ASPX is mentioned below.
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<style> 
    .viewCSS { 
        border: solid 2px black; 
        padding: 20px; 
    } 


    #menuTabs a.static.selected { 
        border-bottom-color: red; 
        border-bottom-style: solid; 
        border-bottom-width: 3px; 
        color: red; 
    } 
</style> 
</head> 
<body> 
<form id="form1" runat="server" style="width: 100%"> 
    <div style="width: 100%; margin-left: 20px; margin-top: 50px; margin-right: 20px;"> 

        <asp:Menu 
            ID="menuTabs" 
            Orientation="Horizontal" 
            Width="100%" 
            runat="server" 
            OnMenuItemClick="menuTabs_MenuItemClick"> 
            <Items> 
                <asp:MenuItem Text="Employee Info" Value="0" Selected="true" /> 
                <asp:MenuItem Text="Contact Info" Value="1" /> 
                <asp:MenuItem Text="Salary Info" Value="2" /> 
            </Items> 
        </asp:Menu> 
        <asp:MultiView ID="multiviewEmployee" 
            runat="server" ActiveViewIndex="0"> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">First Name</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Last Name</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Address</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Mobile</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Hire Date</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Salary</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 

        </asp:MultiView> 
    </div> 
</form> 
</body> 
</html> 


I Hope it works for you!

 

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How To Change app.config Data in ASP.NET?

clock January 4, 2017 08:20 by author Peter

In this post, I will tell you about How To Change app.config Data in ASP.NET. Please write the following code to change app.config data at runtime.
    private static void SetSetting(string key, string value) 
           { 
               Configuration configuration = 
                   ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
               configuration.AppSettings.Settings[key].Value = value; 
               configuration.Save(ConfigurationSaveMode.Full, true); 
               ConfigurationManager.RefreshSection("appSettings"); 
           } 


The code given below is used to fetch app.config data.
    private static string GetSetting(string key) 
            { 
                return ConfigurationManager.AppSettings[key]; 
            } 


App.config file

Key is lang and value is English.
 
Output

We get the "lang" value as English, this value is fetched from App.config file.

Modify App.config value at runtime.


Code
    public Form1() 
    { 
        InitializeComponent();  
        string objAppConfigValue = GetSetting("lang"); 
        SetSetting("lang", "Tamil"); 
        string objModifiedAppConfigValue = GetSetting("lang"); 
        
    } 

    private static string GetSetting(string key) 
    { 
        return ConfigurationManager.AppSettings[key]; 
    } 

    private static void SetSetting(string key, string value) 
    { 
        Configuration configuration = 
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
        configuration.AppSettings.Settings[key].Value = value; 
        configuration.Save(ConfigurationSaveMode.Full, true); 
        ConfigurationManager.RefreshSection("appSettings"); 
    } 



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Create Circular Progress Bar Dynamically In ASP.NET?

clock December 21, 2016 08:20 by author Peter

In this post, let me explain you about Create Circular Progress Bar Dynamically In ASP.NET. For it, we will take a div and apply style to make it circular.

<div id="circularProgess" class="circularprogress background" runat="server"> 
          <div id="ProgressText" class="overlay" runat="server"></div> 
</div> 


Add the style, mentioned below.
<style> 
    .background { 
        background-image: linear-gradient(<%= Val1 %>, <%= ColorCode %> 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0)), linear-gradient(<%= Val2 %>, #AC2D36 50%, #ffffff 50%, #ffffff); 
    } 
 
    /* -------------------------------------
     * Bar container
     * ------------------------------------- */ 
    .circularprogress { 
        float: left; 
        margin-left: 50px; 
        margin-top: 30px; 
        position: relative; 
        width: 180px; 
        height: 180px; 
        border-radius: 50%; 
    } 
 
        /* -------------------------------------
         * Optional centered circle w/text
         * ------------------------------------- */ 
        .circularprogress .overlay { 
            position: absolute; 
            width: 130px; 
            height: 110px; 
            color: white; 
            background-color: #CF5760; 
            border-radius: 50%; 
            margin-left: 25px; 
            margin-top: 23px; 
            text-align: center; 
            line-height: 90px; 
            font-size: 35px; 
            padding-top: 20px; 
        } 
</style> 

In the background style, I have added val1 and val2, where I will assign from .cs page, so we can make a dynamic circular progress bar. Add the properties and methods, mentioned below in .cs file.
private string val1 = "90deg"; 
 
       public string Val1 
       { 
           get { return val1; } 
           set { val1 = value; } 
       } 
 
       private string val2 = "90deg"; 
 
       public string Val2 
       { 
           get { return val2; } 
           set { val2 = value; } 
       } 
 
       private string colorCode = "#ffffff"; 
 
       public string ColorCode 
       { 
           get { return colorCode; } 
           set { colorCode = value; } 
       } 
 
       protected void Page_Load(object sender, EventArgs e) 
       { 
           ProgressText.InnerText = "0%"; 
           CalculateActiveUsersAngle(75); 
       } 
 
       private void CalculateActiveUsersAngle(int TotalUser) 
       { 
           //int TotalUser = 50; 
 
           if (TotalUser == 0) 
           { 
               Val2 = "90deg"; 
               Val1 = "90deg"; 
               ColorCode = "#ffffff"; 
           } 
           else if (TotalUser < 50 && TotalUser > 0) 
           { 
               double percentageOfWholeAngle = 360 * (Convert.ToDouble(TotalUser) / 100); 
               Val2 = (90 + percentageOfWholeAngle).ToString() + "deg"; 
               Val1 = "90deg"; 
               ColorCode = "#ffffff"; 
           } 
           else if (TotalUser > 50 && TotalUser < 100) 
           { 
               double percentage = 360 * (Convert.ToDouble(TotalUser) / 100); 
               Val1 = (percentage - 270).ToString() + "deg"; 
               Val2 = "270deg"; 
               ColorCode = "#AC2D36"; 
           } 
           else if (TotalUser == 50) 
           { 
               Val1 = "-90deg"; 
               Val2 = "270deg"; 
               ColorCode = "#AC2D36"; 
           } 
           else if (TotalUser >= 100) 
           { 
               Val1 = "90deg"; 
               Val2 = "270deg"; 
               ColorCode = "#AC2D36"; 
           } 
 
           ProgressText.InnerText = TotalUser + "%"; 
 
       } 


CalculateActiveUsersAngle() method will calculate and show the exact angle .You can assign the angle if you want to CalculateActiveUsersAngle() method. For this example, I have assigned 75, so circular progress will display 75% on the radial. And here is the output:

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Get IP Address In ASP.NET?

clock December 14, 2016 08:07 by author Peter

In this post, I will tell you how to Get IP Address In ASP.NET. An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing. Its role has been characterized as follows: "A name indicates what we seek. An address indicates where it is. A route indicates how to get there.”

There are two versions of IP address, earlier Version of IP address is IPv4 contains IP address as 32 bit number, and then because of growth of internet new version of IP is developed named IPv6 which takes 128 bit to store the IP Address.

There are different ways to get IP Address of visitor of the websites.

First method of getting IP Address is using “HTTP_X_FORWARDED_FOR” and “REMOTE_ADDR”. Where, “X_FORWARDED_FOR” is HTTP header field for identifying originating IP Address of the client who connected to internet and “REMOTE_ADDR” Returns the IP address of the remote machine.

Code to get IP Address using Method 1:

Second method of getting IP address is using built in functionality of ASP.NET. Here we use Request property of Page Class which gets the object of HttpRequest class for the requested page. HttpRequest is sealed class which enables ASP.NET to read the HTTP values sent by client machine during the web request. We access the UserHostAddress property of HttpRequest class to get the IP Address of the visitor.

Code to get IP Address using Method 2:

Default.aspx

Call above both method in Page_Load event, as soon as page will load you will get output like this.

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: Using Highchart In ASP.NET

clock December 8, 2016 08:56 by author Peter

In this post, will tell you how to use Highchart in ASP.NET. Highchart in ASP.NET is purely a JavaScript and jQuery based API which can create interactive charts for representing the data. Highchart is a client-side API and it is flexible for use on different kinds of web browsers.

And here is the feature of highchart:

  • Compatible: Highchart works on all kinds of browsers.
  • Highchart is free for non-commercial purposes.
  • Different types of charts are available.
  • We can easily integrate it with .NET.

Types of Charts

Highcharts support different types of charts, such as:

  • Gauges
  • Basic Area chart
  • Bar chart
  • Column chart
  • Line chart
  • Pie chart
  • Polar chart
  • Range series

How it works

  • Download this dll and add to your project:
  • Download and add JavaScript to your project:
  • Chart Creation
  • Chart Output

Step 1

  • Download this dll to add to your project or install NET Highcharts.
  • You can follow the below steps.

Step 2
Download Highcharts and add reference of the JavaScript in your page or master page:
Add the below script
        <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> 
        <script src="../../Scripts/highcharts.js" type="text/javascript"></script> 

Step 3

Chart Creation

Below code 
        for Mvc 
        public ActionResult Index() { 
                DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart").SetXAxis(new XAxis { 
                        Categories = new [] { 
                            "Jan", 
                            "Feb", 
                            "Mar", 
                            "Apr", 
                            "May", 
                            "Jun", 
                            "Jul", 
                            "Aug", 
                            "Sep", 
                            "Oct", 
                            "Nov", 
                            Dec " }  
                        }).SetSeries(new Series { 
                        Data = new Data(new object[] { 
                            29.9, 
                            71.5, 
                            106.4, 
                            129.2, 
                            144.0, 
                            176.0, 
                            135.6, 
                            148.5, 
                            216.4, 
                            .1, 
                            95.6, 
                            54.4 
                        }) 
                    }); 
                    return View(chart); 
                } 
                Below Code 
                for Asp.net 
                protected void Page_Load(object sender, EventArgs e) { 
                    DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart").SetXAxis(new XAxis { 
                        Categories = new [] { 
                            "Jan", 
                            "Feb", 
                            "Mar", 
                            "Apr", 
                            "May", 
                            "Jun", 
                            "Jul", 
                            "Aug", 
                            "Sep", 
                            "Oct", 
                            "Nov", 
                            "Dec" 
                        } 
                    }).SetSeries(new Series { 
                        Data = new Data(new object[] { 
                            29.9, 
                            71.5, 
                            106.4, 
                            129.2, 
                            144.0, 
                            176.0, 
                            135.6, 
                            148.5, 
                            216.4, 
                            194.1, 
                            95.6, 
                            54.4 
                        }) 
                    }); 
                    ltrChart.Text = chart.ToHtmlString(); 
                } 
    HTML Code
        For Mvc 
        @model DotNet.Highcharts.Highcharts 
        @(Model) 
        For Asp.net < asp: Content ID = "BodyContent" 
        runat = "server" 
        ContentPlaceHolderID = "MainContent" > < asp: Literal ID = "ltrChart" 
        runat = "server" > < /asp:Literal>  < /asp:Content> 


Step 4

We get the output like the below image.

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Built-In Logging In .NET Core?

clock November 30, 2016 08:19 by author Peter

In this post, I will show you how to Built-In Logging In .NET Core. For an application, logging is very important to keep track of that application and keep it error-free.

In .NET Core, we don't need any third party logging; instead, we can use built-in logging whenever we want. This is very efficient in terms of code and performance. Now, develope a new .NET Core application and name it.

Step 1: Go to Package mManager View-->Other Windows--> Package manager Console  -->

Install-Package Microsoft.Extensions.Logging

Add Logging
Once  the extension's installed, we can add logging by adding ILogger<T> (custom logging) or ILoggerFactory. If we want to use ILoggerFactory, then we must create it using CreateLogger, to use logging add logging services under ConfigureServices. Moreover, we can use built-in logging with the other loggings (like Nlog) with very minimal code.
services.AddLogging(); 

Startup.cs
public class Startup 
    { 
        public Startup(IHostingEnvironment env) 
        { 
            var builder = new ConfigurationBuilder() 
                .SetBasePath(env.ContentRootPath) 
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
                .AddEnvironmentVariables(); 
            Configuration = builder.Build(); 
        } 
 
        public IConfigurationRoot Configuration { get; } 
 
        // This method gets called by the runtime. Use this method to add services to the container. 
        public void ConfigureServices(IServiceCollection services) 
        { 
            // Add framework services. 
            services.AddMvc(); 
            services.AddLogging(); 
        } 
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
        { 
            loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
            loggerFactory.AddDebug(); 
 
            if (env.IsDevelopment()) 
            { 
                app.UseDeveloperExceptionPage(); 
                app.UseBrowserLink(); 
            } 
            else 
            { 
                app.UseExceptionHandler("/Home/Error"); 
            } 
 
            app.UseStaticFiles(); 
 
            app.UseMvc(routes => 
            { 
                routes.MapRoute( 
                    name: "default", 
                    template: "{controller=Home}/{action=Index}/{id?}"); 
            }); 
        } 
    } 

ILoggerFactory: We can use  ILoggerFactory. For this, we must use CreateLogger.

_logger = Mylogger.CreateLogger(typeof(HomeController)); 

HomeController.cs
public class HomeController : Controller 
    { 
        private ILogger _logger; 
 
        public HomeController(ILoggerFactory Mylogger) 
        { 
            _logger = Mylogger.CreateLogger(typeof(HomeController)); 
        } 
 
        public IActionResult Index() 
        { 
            return View(); 
        } 
 
        public IActionResult About() 
        { 
            try 
            { 
                ViewData["Message"] = "Your application description page."; 
                _logger.LogInformation("About Page has been Accessed"); 
                return View(); 
            } 
            catch (System.Exception ex) 
            { 
                _logger.LogError("About: " + ex.Message); 
                throw; 
            } 
        } 
 
        public IActionResult Contact() 
        { 
            try 
            { 
                ViewData["Message"] = "Your contact page."; 
                _logger.LogInformation("Contact Page has been Accessed"); 
                return View(); 
            } 
            catch (System.Exception ex) 
            { 
                _logger.LogError("Contact: " + ex.Message); 
                throw; 
            } 
        } 
 
        public IActionResult Error() 
        { 
            return View(); 
        } 
    } 


Run and Test

LogLevel: We can add logging level by adding the level we want in appsettings.json.Trace

  • Debug
  • Information
  • Warning
  • Error
  • Application failure or crashes         


ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: Uploading File Without PostBack In ASP.NET

clock November 9, 2016 08:55 by author Peter

In this post, you will learn how to upload a file without PostBack in ASP.NET. My main focus to write this blog is that, if you work with file upload control, the page requires full PostBack and if your file upload control is inside the update panel, you must specify your submit button in trigger, as shown below.

 <Triggers> 
    <asp:PostBackTrigger ControlID=""/> 
 </Triggers> 


This also causes the full PostBack problem. To remove this problem, use "Handler" in ASP. NET C#.

UploadFile.ashx Code

 using System; 
 using System.Web; 
 using System.IO; 
 using System.Web.SessionState; 
 public class UploadFile: IHttpHandler, IRequiresSessionState { 
     public void ProcessRequest(HttpContext context) { 
         string filedata = string.Empty; 
         if (context.Request.Files.Count > 0) { 
             HttpFileCollection files = context.Request.Files; 
             for (int i = 0; i < files.Count; i++) { 
                 HttpPostedFile file = files[i]; 
                 if (Path.GetExtension(file.FileName).ToLower() != ".jpg" && 
                     Path.GetExtension(file.FileName).ToLower() != ".png" && 
                     Path.GetExtension(file.FileName).ToLower() != ".gif" && 
                     Path.GetExtension(file.FileName).ToLower() != ".jpeg" && 
                     Path.GetExtension(file.FileName).ToLower() != ".pdf" 
                 ) { 
                     context.Response.ContentType = "text/plain"; 
                     context.Response.Write("Only jpg, png , gif, .jpeg, .pdf are allowed.!"); 
                     return; 
                 } 
                 decimal size = Math.Round(((decimal) file.ContentLength / (decimal) 1024), 2); 
                 if (size > 2048) { 
                     context.Response.ContentType = "text/plain"; 
                     context.Response.Write("File size should not exceed 2 MB.!"); 
                     return; 
                 } 
                 string fname; 
                 if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { 
                     string[] testfiles = file.FileName.Split(new char[] { 
                         '\\' 
                     }); 
                     fname = testfiles[testfiles.Length - 1]; 
                 } else { 
                     fname = file.FileName; 
                 } 
                 //here UploadFile is define my folder name , where files will be store. 
                 string uploaddir = System.Configuration.ConfigurationManager.AppSettings["UploadFile"]; 
                 filedata = Guid.NewGuid() + fname; 
                 fname = Path.Combine(context.Server.MapPath("~/" + uploaddir + "/"), filedata); 
                 file.SaveAs(fname); 
             } 
         } 
         context.Response.ContentType = "text/plain"; 
         context.Response.Write("File Uploaded Successfully:" + filedata + "!"); 
         //if you want to use file path in aspx.cs page , then assign it in to session 
         context.Session["PathImage"] = filedata; 
     } 
     public bool IsReusable { 
         get { 
             return false; 
         } 
     } 
 } 


web.config code

 <?xml version="1.0"?> 
 <!-- 
 For more information on how to configure your ASP.NET application, please visit 
 http://go.microsoft.com/fwlink/?LinkId=169433 
 --> 
 <configuration> 
     <system.web> 
         <compilation debug="true" targetFramework="4.0" /> 
     </system.web> 
     <appSettings> 
         <add key="Upload" value="UploadFile" /> 
     </appSettings> 
 </configuration> 


Default.aspx code

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
     <!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></title> 
         <%-- Should have internet connection for loading this file other wise inherit own js file for supporting js library--%> 
             <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
             <script type="text/javascript"> 
                 function onupload() { 
                     $(function() { 
                         var fileUpload = $('#<%=FileUpload.ClientID%>').get(0); 
                         var files = fileUpload.files; 
                         var test = new FormData(); 
                         for (var i = 0; i < files.length; i++) { 
                             test.append(files[i].name, files[i]); 
                         } 
                         $.ajax({ 
                             url: "UploadFile.ashx", 
                             type: "POST", 
                             contentType: false, 
                             processData: false, 
                             data: test, 
                             success: function(result) { 
                                 if (result.split(':')[0] = "File Uploaded Successfully") { 
                                     document.getElementById("<%=lbl_smsg.ClientID%>").innerText = result.split(':')[0]; 
                                 } else { 
                                     document.getElementById("<%=lbl_emsg.ClientID%>").innerText = result; 
                                 } 
                             }, 
                             error: function(err) { 
                                 alert(err.statusText); 
                             } 
                         }); 
                     }) 
                 } 
             </script> 
     </head> 
  
     <body> 
         <form id="form1" runat="server"> 
             <asp:ScriptManager ID="scmain" runat="server"></asp:ScriptManager> 
             <asp:UpdatePanel ID="upmain" runat="server"> 
                 <ContentTemplate> 
                     <fieldset> 
                         <legend>Upload File WithOut PostBack inside Update Panel</legend> 
                         <asp:FileUpload ID="FileUpload" runat="server" /> 
                         <input type="button" id="btnUpload" value="Upload Files" onclick="onupload();" /> 
                         <asp:Label ID="lbl_emsg" runat="server" ForeColor="Red"></asp:Label> 
                         <asp:Label ID="lbl_smsg" runat="server" ForeColor="Green"></asp:Label> 
                     </fieldset> 
                 </ContentTemplate> 
             </asp:UpdatePanel> 
         </form> 
     </body> 
  
     </html> 


Default.aspx code.cs code

 using System; 
 using System.Collections.Generic; 
 using System.Linq; 
 using System.Web; 
 using System.Web.UI; 
 using System.Web.UI.WebControls; 
 public partial class _Default: System.Web.UI.Page 
 { 
     protected void Page_Load(object sender, EventArgs e) {} 
 } 

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in