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 Hosting - HostForLIFE.eu :: How to Steps To Generate Excel Using EPPlus?

clock February 25, 2020 08:01 by author Peter

My work is to create an excel file, which will contain 3 fields: Address, Latitude and longitude.The user will upload an Address in an excel file and after reading the addresses from an excel file, I have to retrieve Latitude and longitude, using Bing MAP API and build another excel file, which can contain Addresses beside the Latitude and longitude of that address and download the new excel file to the user's end.

Create a MVC Application and add EPPLUS from NuGet package manager to your solution.

Now, Add the code to your .cshtml page.

<h2>Upload File</h2> 
 
sing (Html.BeginForm("Upload", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
  { 
      @Html.AntiForgeryToken() 
      @Html.ValidationSummary() 
 
      <div class="form-group"> 
          <input type="file" id="dataFile" name="upload" /> 
      </div> 
 
      <div class="form-group"> 
          <input type="submit" value="Upload" class="btn btn-default" /> 
      </div> 
 
       
  } 


And then, add the code, mentioned below to your controller.

[HttpPost] 
        public ActionResult Upload(HttpPostedFileBase upload) 
        { 
            if (ModelState.IsValid) 
            { 
                if (Path.GetExtension(upload.FileName) == ".xlsx") 
                { 
                    ExcelPackage package = new ExcelPackage(upload.InputStream); 
            //From This part we will read excel file 
                    DataTable dt = ExcelPackageExtensions.ToDataTable(package); 
 
 
                    DataTable dtExcel = new DataTable(); 
                    dtExcel.Columns.Add("Address", typeof(String)); 
                    dtExcel.Columns.Add("LAT", typeof(Double)); 
                    dtExcel.Columns.Add("LONG", typeof(Double)); 
 
                    List<Coordinates> lstCor = new List<Coordinates>(); 
                    for (int i = 0; i < dt.Rows.Count; i++) 
                    { 
                        //Fill the new data Table to generate new excel file 
                    } 
            //This method will generate new excel and download the same 
                    generateExcel(dtExcel);                  
                } 
            } 
            return View(); 
        } 


“ExcelPackageExtensions.ToDataTable(package)” for this create a new class with the name ExcelPackageExtensions and create a static method with the name “ToDataTable()”. The code is mentioned below.

public static class ExcelPackageExtensions 
    { 
        public static DataTable ToDataTable(this ExcelPackage package) 
        { 
            ExcelWorksheet workSheet = package.Workbook.Worksheets.First(); 
            DataTable table = new DataTable(); 
            foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column]) 
            { 
                table.Columns.Add(firstRowCell.Text); 
            } 
 
            for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++) 
            { 
                var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column]; 
                var newRow = table.NewRow(); 
                foreach (var cell in row) 
                { 
                    newRow[cell.Start.Column - 1] = cell.Text; 
                } 
                table.Rows.Add(newRow); 
            } 
            return table; 
        } 
    } 

Now, add the code part to generate and download an Excel file.
[NonAction] 
        public void generateExcel(DataTable Dtvalue) 
        { 
            string excelpath = ""; 
            excelpath = @"C:\Excels\abc.xlsx";//Server.MapPath("~/UploadExcel/" + DateTime.UtcNow.Date.ToString() + ".xlsx"); 
            FileInfo finame = new FileInfo(excelpath); 
            if (System.IO.File.Exists(excelpath)) 
            { 
                System.IO.File.Delete(excelpath); 
            } 
            if (!System.IO.File.Exists(excelpath)) 
            { 
                ExcelPackage excel = new ExcelPackage(finame); 
                var sheetcreate = excel.Workbook.Worksheets.Add(DateTime.UtcNow.Date.ToString()); 
                if (Dtvalue.Rows.Count > 0) 
                { 
                    for (int i = 0; i < Dtvalue.Rows.Count; ) 
                    { 
                        sheetcreate.Cells[i + 1, 1].Value = Dtvalue.Rows[i][0].ToString(); 
                        sheetcreate.Cells[i + 1, 2].Value = Dtvalue.Rows[i][1].ToString(); 
                        sheetcreate.Cells[i + 1, 3].Value = Dtvalue.Rows[i][2].ToString(); 
                        i++; 
                    } 
                } 
                //sheetcreate.Cells[1, 1, 1, 25].Style.Font.Bold = true; 
                //excel.Save(); 
 
                var workSheet = excel.Workbook.Worksheets.Add("Sheet1"); 
                //workSheet.Cells[1, 1].LoadFromCollection(data, true); 
                using (var memoryStream = new MemoryStream()) 
                { 
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
                    Response.AddHeader("content-disposition", "attachment;  filename=Contact.xlsx"); 
                    excel.SaveAs(memoryStream); 
                    memoryStream.WriteTo(Response.OutputStream); 
                    Response.Flush(); 
                    Response.End(); 
                } 
            } 
 
        } 

HostForLIFE.eu ASP.NET Core 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.



European ASP.NET Core Hosting :: Add Custom Parameters In Swagger Using ASP.NET Core 3.1

clock February 18, 2020 10:54 by author Peter

Web APIs have some common parameters in a project, mabybe those paramters should be passed via header or query, etc.For example, there is a Web API url, https://yourdomain.com/api/values, and when we access this Web API, we should add timestamp, nonce and sign three parameters in the query.

It means that the url must be https://yourdomain.com/api/values?timestamp=xxx&nonce=yyy&sign=zzz

Most of the time, we will use Swagger as our document. How can we document those parameters in Swagger without adding them in each action?

Here I will use ASP.NET Core 3.1 to introduce the concept.

How to do this?
Create a new Web API project, and edit the csproj file, add the following content in it.
<ItemGroup> 
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" /> 
</ItemGroup> 
 
<PropertyGroup> 
    <GenerateDocumentationFile>true</GenerateDocumentationFile> 
    <NoWarn>$(NoWarn);1591</NoWarn> 
</PropertyGroup> 


Swashbuckle provides a feature named operation filter that can help us to do that job.

We can add those three additional parameters in our custom operation filter, so that we do not need to add them in each action.

Here is the sample code demonstration.
using Microsoft.AspNetCore.Mvc.Controllers; 
using Microsoft.OpenApi.Models; 
using Swashbuckle.AspNetCore.SwaggerGen; 
using System.Collections.Generic; 
 
public class AddCommonParameOperationFilter : IOperationFilter 

    public void Apply(OpenApiOperation operation, OperationFilterContext context) 
    { 
        if (operation.Parameters == null) operation.Parameters = new List<OpenApiParameter>(); 
 
        var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor; 
 
        if (descriptor != null && !descriptor.ControllerName.StartsWith("Weather")) 
        { 
            operation.Parameters.Add(new OpenApiParameter() 
            { 
                Name = "timestamp", 
                In = ParameterLocation.Query, 
                Description = "The timestamp of now", 
                Required = true 
            }); 
 
            operation.Parameters.Add(new OpenApiParameter() 
            { 
                Name = "nonce", 
                In = ParameterLocation.Query, 
                Description = "The random value", 
                Required = true 
            }); 
 
            operation.Parameters.Add(new OpenApiParameter() 
            { 
                Name = "sign", 
                In = ParameterLocation.Query, 
                Description = "The signature", 
                Required = true 
            }); 
        } 
    } 


NOTE
For showing the difference, we only add those parameters whose controller name does not start with Weather.

By the way, if you have any other parameters or conditions, add them yourself.

Then, we will configure Swagger in Startup class.
public class Startup 

    public void ConfigureServices(IServiceCollection services) 
    { 
        services.AddSwaggerGen(c => 
        { 
            // sepcify our operation filter here. 
            c.OperationFilter<AddCommonParameOperationFilter>(); 
 
            c.SwaggerDoc("v1", new OpenApiInfo 
            { 
                Version = "v1.0.0", 
                Title = $"v1 API", 
                Description = "v1 API", 
                TermsOfService = new Uri("https://www.c-sharpcorner.com/members/catcher-wong"), 
                Contact = new OpenApiContact 
                { 
                    Name = "Catcher Wong", 
                    Email = "[email protected]", 
                }, 
                License = new OpenApiLicense 
                { 
                    Name = "Apache-2.0", 
                    Url = new Uri("https://www.apache.org/licenses/LICENSE-2.0.html") 
                } 
            }); 
        }); 
 
        // other.... 
    } 

 
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
    { 
        app.UseSwagger(c => 
        { 
        }); 
        app.UseSwaggerUI(c => 
        { 
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1 API"); 
        }); 
 
        // other.... 
    } 


Here is the result.


The controller name that doesn't start with `Weather` will contain those three parameters.

This article showed you a sample of how to add custom request parameters in Swagger using ASP.NET Core 3.1 and Swashbuckle.AspNetCore 5.0.0.



European ASP.NET Core Hosting :: Label, TextArea and Image Tag Helper In ASP.NET Core 3.1

clock February 11, 2020 11:55 by author Peter

In this blog, we will discuss 3 tag helpers: Label, Textarea and Image Tag Helper. We will also discuss how to use them in application with an example.

Label Tag Helper: The label tag helper is used for text labels in an application. It renders as an HTML label tag.
Textarea Tag Helper: The Textarea tag helper is used for Textarea of description in the application. It renders as an HTML Textarea tag.
Image Tag Helper: The Image Tag Helper renders as an HTML img tag. It is used to display images in the core applications. It provides cache-busting behavior for static image files. It has scr and asp-append-version which is set to true.

Step 1 Create an ASP.NET web application project in Visual Studio 2019.
Step 2 Create a class employee under the Models folder.
using System.ComponentModel.DataAnnotations; 
 
namespace LabelTextareaImageTagHelper__Demo.Models 

    public class Employee 
    { 
        [Key] 
        public int Id { get; set; } 
 
        [Required] 
        public string Name { get; set; } 
 
        [Required] 
        public string Image { get; set; } 
 
        [Required] 
        [MinLength(10)] 
        [MaxLength(255)] 
        public string Description { get; set; } 
    } 


Step 3 Now open index view from views than Home folder.
Step 4 Add model on top of the view to retrieve property of model class.
@model LabelTextareaImageTagHelper__Demo.Models.Employee  
Step 5 Create images folder in wwwroot folder copy and paste some image to display it on browser.
<div class="form-group"> 
   <label asp-for="Name" class="control-label"></label> 
   <input asp-for="Name" class="form-control" /> 
</div> 

<div class="form-group"> 
   <label asp-for="Image" class="control-label"></label> 
   <img src="~/images/855211650_154321.jpg" asp-append-version="true" height="150" width="150" class="img-thumbnail" /> 
</div> 

<div class="form-group"> 
   <label asp-for="Description" class="control-label"></label> 
   <textarea asp-for="Description" class="form-control"></textarea> 
</div>


This is how it renders in browser:
<textarea class="form-control" data-val="true" data-val-maxlength="The field Description must be a string or array type with a maximum length of '255'." data-val-maxlength-max="255" data-val-minlength="The field Description must be a string or array type with a minimum length of '10'." data-val-minlength-min="10" data-val-required="The Description field is required." id="Description" maxlength="255" name="Description"></textarea> 




European ASP.NET 3.1 Core Hosting :: How to Only Allow Numbers in a Text Box using jQuery?

clock February 4, 2020 11:05 by author Peter

This tutorial explains how to only allow a number in textbox using jQuery.  If you simply add the 'numberonly' class to the text control, then it will only allow numbers.

Code
$(document).ready(function () {   
   
            $('.numberonly').keypress(function (e) {   
   
                var charCode = (e.which) ? e.which : event.keyCode   
   
                if (String.fromCharCode(charCode).match(/[^0-9]/g))   
   
                    return false;                       
   
            });   
   
        });  
 



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