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 2.2.1 Hosting - HostForLIFE.eu :: How .NET Is A Multilingual Framework?

clock November 13, 2018 08:18 by author Peter

An application is said to be multilingual if it can be deployed in many different languages. With .NET, all of the languages including Visual Basic, .NET, C#, and J# compile to a common Intermediate language (IL). This makes all languages interoperable. Microsoft has created Java bytecode, which is a low-level language with a simple syntax, which can be very quickly translated into native machine code.

CLR
.NET Framework is a multilingual application because of CLR.CLR is the key of .NET Framework. The code running under the control of the CLR is often termed as managed code.The main task of CLR is to convert compiled code into the native code. .NET Framework has one or more compilers; for e.g., VB .NET, C#, C++, JScript or any third party compiler such as COBOL.

Anyone of these compilers will convert your source code into Microsoft Intermediate Language (MSIL). The main reason for .NET to be multilingual is that you can compile your code from IL and this compiled code will be interoperable with the code that has been compiled to IL from another language.

It simply means that you can create pages in different languages (like C#, VB .NET, J# etc.) and once all of these pages are compiled they all can be used in a single application. Let us understand this point clearly with an example.

Let us consider a situation where a customer needs an application to be ready in 20 days. For completing the application in 20 days we want 30 developers who all know the specific language but we have 15 developers who know C# and 15 developers who know VB .NET. In this situation, if we don’t use .NET then we need to hire 15 more developers of C# or VB .NET which is a difficult and costly solution. Now, if we use .NET then we can use C# and VB .NET language in the same application. This is possible because once C# code is compiled from IL it becomes interoperable with VB .NET code which is compiled from IL.


Then JIT (Just In Time) of CLR converts this MSIL code into native code using metadata which is then executed by OS.

CLR stands for common language runtime. Common language runtime provides other services like memory management, thread management, remoting, and other security such as CTS and CLS. CLR is a layer between an operating system and .NET language, which uses CTS and CLS to create code.

CTS
CTS stands for the common type system. CTS defines rules that common language runtime follows when we are declaring, using and managing type. CTS deals with the data type. .NET supports many languages and every language has its own data type. One language cannot understand data types of another language. For example: When we are creating an application in C#, we have int and when we are creating an application in VB .NET, we have an integer. Here CTS comes into play --  after the compilation, CTS converts int and integer into the int32 structure.

CLS
CLS stands for common language specification. CLS is a subset of CTS and it declares all the rules and restrictions that all languages under .NET Framework must follow. The language which follows these rules is known as CLS compliant. For example, we can use multiple inheritances in c++ but when we use the same code in C# it creates a problem because C# does not support multiple inheritances. Therefore, CLS restricts multiple inheritances for all language. One other rule is that you cannot have a member with the same name and a different case.

In C# add() and Add() are different because it is case sensitive but a problem arises when we use this code in VB .NET because it is not case-sensitive and it considers add() and Add() as the same.

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: QRCode with Footer Text

clock November 6, 2018 11:09 by author Peter

Recently, I was working with a library which helps to generate barcode within images, the open source library is called ZXing (http://zxingnet.codeplex.com/). Its a free library with lots of great features and even supports QRCode generation. The only missing feature I came across was of writing a Barcode Text below the generated image. I reached out ZXing support team, here they replied to my thread.
http://zxingnet.codeplex.com/discussions/452290

Implementing such functionality in an html page was not that a big task.

Anyway here I came up with a solution. Hope this helps you..
<div style="border: 1px double black;width:50%;text-align:center;" id="PrintBarcode"> 
<div><asp:Image ID="imgBarcode" runat="server" /></div> 
<div style="margin-top:-10px;"><asp:Label ID="lblTexttoDisplay" runat="server"></asp:Label></div> 
</div><br /> 
<a ID="PrintMe" runat="server" Text="Print" onclick=""></a> 
<script type="text/javascript"> 
function PrintMe() 
{    
var popupWin = window.open('', '_blank', 'width=0,height=0,directories=0,fullscreen=0,location=0,menubar=0, 
 
                     resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0'); 
popupWin.document.open(); 
var divToPrint = document.getElementById('PrintBarcode'); 
popupWin.document.write('<html><body onload="window.print();this.close();"> 
 
          <div style="border: 0px double black;width:50%;text-align:center;">' + divToPrint.innerHTML + '</div></html>'); 

</script> 

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: ASP.NET Core Sample Website - Calculator

clock November 1, 2018 08:36 by author Peter

In this article, I will be explaining how to create a simple Web Calculator using .NET Core.

What is ASP.NET Core and why do we use it?

  • Easy to develop Web Pages as well as Web APIs.
  • Integration of modern frameworks and development workflows.
  • Easy to integrate with Azure.
  • Natural dependency injection support.
  • Large hosting variety, like on IIS, Apache, Docker, or self-host in your own process.
  • A wide range of tools that simplifies web development.
  • Multi-platform, so you may build and run on Windows, macOS, and Linux.
  • Open-source and with a powerful community.

We are using a single controller with two Action Results - one for the first HttpGet and another to calculate the operation on the server side. Here is the code.
public class HomeController : Controller 

    [HttpGet] 
    public IActionResult Index() 
    { 
        return View(); 
    } 
 
    [HttpPost] 
    public IActionResult Index( Operation model ) 
    { 
        if ( model.OperationType == OperationType.Addition ) 
            model.Result = model.NumberA + model.NumberB; 
        return View( model ); 
    } 


This is the View,
@model Operation 
<form asp-controller="Home" asp-action="Index" method="post" > 
    <div class="form-group"> 
        <div class="row"> 
            <label asp-for="NumberA" class="col-lg-2"></label> 
            <input type="number" asp-for="NumberA" class="col-lg-2" /> 
        </div> 
        <div class="row"> 
            <label asp-for="NumberB" class="col-lg-2"></label> 
            <input type="number" asp-for="NumberB" class="col-lg-2" /> 
        </div> 
        <div class="row"> 
            <label asp-for="OperationType" class="col-lg-2"></label> 
            <select asp-for="OperationType" class="col-lg-2" asp-items="Html.GetEnumSelectList<OperationType>()"> 
                <option selected="selected" value="">Select</option> 
            </select> 
        </div> 
        <div class="row"> 
            <label asp-for="Result" class="col-lg-2"></label> 
            <input type="number" disabled="disabled" class="col-lg-2" asp-for="Result" /> 
        </div> 
        <div class="row"> 
            <input type="submit" value="Submit" asp-action="Index" /> 
        </div> 
    </div> 
</form> 


View Result in the browser.


This is the model used in here.

public class Operation 

    [Display( Name = "First Number" )] 
    public double NumberA { get; set; } 
 
    [Display( Name = "Second Number" )] 
    public double NumberB { get; set; } 
 
    [Display( Name = "Result" )] 
    public double Result { get; set; } 
 
    [Display( Name = "Operation" )] 
    public OperationType OperationType { get; set; } 


public enum OperationType 

    Addition, 
    Multiplication, 
    Division, 
    Subtraction 


Right now, only addition is implemented.

You can implement multiplication, division, and subtraction as well. I will publish these methods in my next article.

Congratulations, you have successfully created your Web Calculator using .NET Core.

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: Google Custom Searching In ASP.NET

clock October 23, 2018 11:28 by author Peter
In many huge contented websites it is very difficult to find some information like any link, page, text etc. So, they use a textbox where visitor types his keyword to search. There are couple of ways to create it like, to search the content from database, crawler. But if you don't have such things then we use Google Custom Search. In Google Custom Search, we create account in Google and provide the domain information to Google and then Google generates some codes which are used inside our web application. If we use the Google Custom Search codes in our application, then Google searches the content from your website. It is available in cost-free and paid also. In cost-free there will be some advertisement of Google.

Let's take a look how to create it.
 
Creating Account in Google Custom Search
 
To create Google Custom Search account use the following link
http://www.google.com/cse/

Click above link to create Google Custom Search.

At the end of this process you will receive some codes generated by Google and you have to keep it for use inside web application. Here is code given Google for my own domain hostforlife.eu.
<scriptsrc="http://www.gmodules.com/ig/ifr?url=http://www.google.com/cse/api/014464787619631746113/cse/67a_iw-duna/gadget&synd=open&w=250&h=100&title=hostforlife.eu+Search&border=%23ffffff%7C0px%2C1px+solid+%23998899%7C0px%2C1px+solid+%23aa99aa%7C0px%2C2px+solid+%23bbaabb%7C0px%2C2px+solid+%23ccbbcc&output=js"></script>  

And I have used it inside the <div> tag in web page, as shown below
<div>    
     <scriptsrcscriptsrc="http://www.gmodules.com/ig/ifr?url=http://www.google.com/cse/api/014464787619631746113/cse/67a_iw-duna/gadget&synd=open&w=250&h=100&title=hostforlife.eu+Search&border=%23ffffff%7C0px%2C1px+solid+%23998899%7C0px%2C1px+solid+%23aa99aa%7C0px%2C2px+solid+%23bbaabb%7C0px%2C2px+solid+%23ccbbcc&output=js"></script>    
  </div>   

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: How To Use An Area In ASP.NET Core?

clock October 16, 2018 11:40 by author Peter

In order to include an Area in an ASP.NET Core app, first we need to include a conventional route in the Startup.cs file (It's best to place it before any non-area route).

In Startup.cs, configure the method.
    app.UseMvc(routes =>  
    {  
        routes.MapRoute("areaRoute", "{area:exists}/{controller=Admin}/{action=Index}/{id?}");  
        routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
    });   


Then, make a folder named Areas in the app root and make another directory named Admin inside the former. Inside the admin folder, create the following folders (ViewComponent is optional).

Now, we will create a Controller inside the Controllers folder named AdminController.
Now, in order for that to work, you'll need to create Views for all actions that return one. The hierarchy for Views is just like what you have in a non-area Views folder.

Now, you should be good to go!

Question - What if I want to have another Controller inside my Area?

Answer -
Just add another Controller beside AdminController and make sure the routes are like the following,
    [Area("Admin")]  
    [Route("admin/[controller]")]  
    public class ProductsController: Controller {  
        publicProductsController() {  
                //  
            }  
            [Route("{page:int?}")]  
        publicIActionResult Index() {  
            returnView();  
        }  
    }   


The important part is [Route("admin/[controller]")]. With that, you can keep the style of routing to admin /controller/ action/.

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: End-To-End Testing Of Your Web Applications With Canopy

clock October 9, 2018 09:07 by author Peter

Why Is Canopy Stabilization Layer Built on Top of Selenium?
One of the most crucial concepts of Canopy is reliability - when performing an action the framework tries, during the time span specified via elementTimeout or compareTimeout or pageTimeout, before failing. This improves the experience of writing tests.
Expressiveness

The syntax looks pretty self-explanatory:
    "Bio should contain twitter link" &&& fun _ ->      
        url "https://github.com/
peter"      
        ".user-profile-bio" == "https://twitter.com/
peter

F#
In one of my previous articles, I have already expressed my opinion regarding power and expressiveness of F#.
Writing More Tests

To start, just create a console application, install nuget package canopy and create tests in Program.fs like below:
    open canopy.configuration 
    open canopy.runner.classic 
    open System 
    open canopy.classic 
     
    //set path for chrome direver explicitly 
   chromeDir <- "C:\\" 
    start chrome 
     
    "Left bottom repostitory should be stationwalk.server" &&& fun _ -> 
        //visit the following url 
        url "https://github.com/
peter
        //get 4th child of the following selector 
        let repo = nth 4 ".pinned-repo-item" 
        //get element with the following selector inside repo element 
        let firstRepoCaption = repo |> someElementWithin ".js-repo" 
        match firstRepoCaption with     
        | Some caption -> read caption == "stationwalk.server" //if found read element caption  
                                                               //and compare it 
        | None _ -> failwith "Element not found" //if none element found throw an exception 
     
    "Left bottom repostitory should be stationwalk.client" &&& fun _ -> 
        url "https://github.com/
peter
        let repo = nth 5 ".pinned-repo-item" 
        let firstRepoCaption = repo |> someElementWithin ".js-repo" 
        match firstRepoCaption with 
        | Some caption -> read caption == "stationwalk.client" 
        | None _ -> failwith "Element not found" 
     
    "Bio should contain twitter link" &&& fun _ -> 
        url "https://github.com/
peter" 
        ".user-profile-bio" == "https://twitter.com/peter" 
     
    run() 
     
    printfn "Press any key to exit..." 
    Console.ReadKey() |> ignore 
     
    quit() 


Accessing IWebDriver
If you've ever written tests with Selenium using C#, you might be aware of IWebDriver interface which you still might use for some advanced configuration. For example, let's say we want to run our tests with a browser opened fullscreen. Then we can add the following function to our Program.fs file
    let maximizeBrowser (browser : IWebDriver) =     
      browser.Manage().Window.Maximize() 


Accessing IWebElement
Most of canopy's assertions, i.e., == accept as a parameter either a string which can be css or xpath selector or instance of IWebElement type which again might be already familiar to you if you've ever written selenium tests using C#. So let's say we want to upload something into file upload control.
    let uploadFile fullFilePath = 
      (element "input[type='file']").SendKeys(fullFilePath) 


Splitting Up Big File
Patterns which I've practiced to keep test project maintainable include extracting selectors into page modules and moving tests to separate files.

Let's revisit our github example by moving out selectors into the separate module:
    module GithubProfilePage 
     
    let pinnedRepository = ".pinned-repo-item" 
    let bio = ".user-profile-bio" 


Now we can reference them in the test which we'll move into a separate module too:
    module GithubProfileTests 
     
    open canopy.runner.classic 
    open canopy.classic 
     
    let all() = 
        context "Github page tests" 
     
        "Left bottom repostitory should be staionwalk.server" &&& fun _ -> 
            url "https://github.com/peter" 
            let repo = nth 4 GithubProfilePage.pinnedRepository 
            let firstRepoCaption = repo |> someElementWithin ".js-repo" 
            match firstRepoCaption with 
            | Some caption -> read caption == "stationwalk.server" 
            | None _ -> failwith "Element not found" 
     
        "Right bottom repostitory should be staionwalk.client" &&& fun _ -> 
            url "https://github.com/
peter
            let repo = nth 5 GithubProfilePage.pinnedRepository 
            let firstRepoCaption = repo |> someElementWithin ".js-repo" 
            match firstRepoCaption with 
            | Some caption -> read caption == "stationwalk.client" 
            | None _ -> failwith "Element not found" 
     
        "Bio should contain twitter link" &&& fun _ -> 
            url "https://github.com/peter" 
            GithubProfilePage.bio == "https://twitter.com/peter" 


Our Program.fs will look like this:
    open canopy.configuration 
    open canopy.runner.classic 
    open System 
    open canopy.classic 
     
    chromeDir <- "C:\\" 
    start chrome 
     
    GithubProfileTests.all() 
     
    run() 
     
    printfn "Press any key to exit..." 
    Console.ReadKey() |> ignore 
     
    quit() 


Running Test in Parallel
Recently, Canopy had a major upgrade from 1.x to 2.x and one of the great new features is the ability to run tests in parallel.

Let's revisit our example by using this ability:
    module GithubProfileTests 
     
    open canopy.parallell.functions 
    open canopy.types 
    open prunner 
     
    let all() =   
        "Left bottom repostitory should be stationwalk.server" &&& fun _ -> 
            let browser = start Chrome         
            url "https://github.com/
peter" browser 
            let repo = nth 4 GithubProfilePage.pinnedRepository browser 
            let firstRepoCaption = someElementWithin ".js-repo" repo browser 
            match firstRepoCaption with 
            | Some caption -> equals (read caption browser) "stationwalk.server" browser 
            | None _ -> failwith "Element not found" 
     
        "Right bottom repostitory should be stationwalk.client" &&& fun _ -> 
            let browser = start Chrome         
            url "https://github.com/
peter" browser 
            let repo = nth 5 GithubProfilePage.pinnedRepository browser 
            let firstRepoCaption = someElementWithin ".js-repo" repo browser 
            match firstRepoCaption with 
            | Some caption -> equals (read caption browser) "stationwalk.client" browser 
            | None _ -> failwith "Element not found" 
     
        "Bio should contain twitter link" &&& fun _ -> 
            let browser = start Chrome         
            url "https://github.com/
peter" browser 
            equals GithubProfilePage.bio "https://twitter.com/
peter" browser 

The key trick to follow here is that each test operates now with its own copy of browser and assertions are now taken from open canopy.parallel.functions to accept browser as an argument.

Headless Testing
Testing in a headless browser seems to be the new black now. Although I don't share the sentiment, I still can assure you that testing in headless browsers is supported by Canopy. You can run your tests in headless Chrome as follows:
let browser = start ChromeHeadless 

I hope this article has convinced you that Canopy is a robust and easy to use framework which can be used in building end-to-end testing layers of your application.

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: System.Diagnostics Useful Actions

clock October 2, 2018 09:51 by author Peter

The namespace System.Diagnostics provides a set of attributes and classes to interact with the system process, event managers, performance counts etc. This namespace can help us too in debugging jobs.

Let’s review the useful actions inside System.Diagnostics namespace.

DebuggerDisplay Attribute
DebuggerDisplay attribute drives the string format with debug screen, which shows the value of: class, properties or fields.

For this same task, it is best known override ToString method, but use DebbugerDisplay attribute is a better choice, because this does not modify the data structure as it only interacts with Visual Studio debbuger screen. Override ToString method for only this purpose can give problems because many actions in .NET takes this value for default, for example bindings in WPF.

This attribute supports delegates, properties, fields and assamblies.

Example
[System.Diagnostics.DebuggerDisplay("{ID} - {Model}- {Manufacturer} - {ProductionDate}")] 
public class Car 

    public int      ID             { get; set; } 
    public string   Model        { get; set; } 
    public string   Manufacturer   { get; set; } 
    public DateTime ProductionDate { get; set; } 
}  



DebuggerHidden Attribute
DebuggerHidden attribute prevents the compiler from stopping in constructors, methods, properties and indexers declarations.
In mentioning this later, my comment might sound lightweight, but in the practice, this can save time push key F11 in debugging.

Example
[System.Diagnostics.DebuggerHidden] 
public static List<Car> GetData() 

    var result = new List<Car>() 
    { 
        new Car{ ID = 1, Manufacturer = "Ford",   Model = "Mustang", ProductionDate = DateTime.Today }, 
        new Car{ ID = 2, Manufacturer = "Nissan", Model = "Micra"  , ProductionDate = DateTime.Today } 
    }; 
 
    return result; 
}  


Debugger.Launch

Occasionally, we can’t debug the code of a library, Service etc. because it is not accessible or we can’t add project to our solution. In this case, we can use the Debugger.Launch() method and Visual Studio opens a debug Window and we can debug its code.

When executed, the line Systen.Diagnostics.Debbuger.Launch() opens a MessageBox with the instance of Visual Studio Debugger Options.

In this window, we can choose, if we open a new stance of Visual Studio (all versions) or if we re-use an existing instance. We can debug the code, as shown below.

Conditional Attribute
Conditional attribute allows us to indicate a condition to the methods so that the compiler executes or does not execute its content. We can use it with the precompiler sentences as DEBUG.
static void Main(string[] args) 

 
    DebugMethod(); 
 
 
    Console.Read(); 

 
[System.Diagnostics.Conditional("DEBUG")] 
public static void DebugMethod() 

    Console.WriteLine("Execute Debug Method"); 
}  


It will only run if the solutions configurations are debugged.

The condition doesn’t exist for RELEASE, therefore we will use a define Directives.
Define Directives is another way to use System.Diagnostics.Conditional,
#define RELEASE_MODE 
 
using System; 
namespace SystemDiagnosticsUsefulActions 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            ReleaseMethod(); 
 
            Console.Read(); 
        } 
 
        [System.Diagnostics.Conditional("RELEASE_MODE")] 
        public static void ReleaseMethod() 
        { 
            Console.WriteLine("Execute Release Method"); 
        } 
 
    } 
 
}  


These are the useful tips and traps of System.Diagnostics. They become very practical in many cases and I hope you find them useful.

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: Insert Data using Uploading Excel file and upload image and set water mark

clock September 28, 2018 11:17 by author Peter

In this blog, I will show you how to Insert Data using Uploading Excel file and upload image and set water mark. Let's write the code below.

Demo.aspx
<body> 
    <form id="form1" runat="server"> 
        <div> 
            <table> 
                <tr> 
                    <td> 
                        <asp:FileUpload ID ="fu" runat ="server" /> 
                    </td> 
                    <td> 
                        <asp:Button ID ="btnupload" runat ="server" Text="Upload File" 
onclick="btnupload_Click" /> 
                    </td> 
                </tr> 
            </table> 
        </div> 
    </form> 
</body> 


Demo.aspx .cs
DataTable dt = new DataTable(); 
 
protected void btnupload_Click(object sender, EventArgs e) 

    if (fu.HasFile) 
    { 
        if (fu.PostedFile.ContentType == "application/vnd.ms-excel" || fu.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") 
        { 
            string fileName = Path.Combine(Server.MapPath("~/localization"), Guid.NewGuid().ToString() + Path.GetExtension(fu.PostedFile.FileName)); 
            fu.PostedFile.SaveAs(fileName); 
 
            string conString = ""; 
            string ext = Path.GetExtension(fu.PostedFile.FileName); 
            if (ext.ToLower() == ".xls") 
            { 
                conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; 
            }  
            else if (ext.ToLower() == ".xlsx")  
            { 
                conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; 
            } 
            string query = "Select * from [Sheet1$]"; 
            OleDbConnection con = new OleDbConnection(conString); 
            OleDbDataAdapter data = new OleDbDataAdapter(query, con); 
            data.Fill(dt); 
            int i = 0; 
            //File_Upload file = new File_Upload(); 
            for (i = 0; i < dt.Rows.Count; i++) 
            { 
                string name = dt.Rows[i]["name"].ToString(); 
                string email = dt.Rows[i]["email"].ToString(); 
                string pass = dt.Rows[i]["Password"].ToString(); 
                string mobile = dt.Rows[i]["mobile"].ToString(); 
                string state = dt.Rows[i]["state"].ToString(); 
                string city = dt.Rows[i]["city"].ToString(); 
                string photo = dt.Rows[i]["Photo"].ToString(); 
 
                string[] pathArr = photo.Split('\\'); 
                string[] fileArr = pathArr.Last().Split('.'); 
                string fName = fileArr[0].ToString(); 
                Random rnd = new Random(); 
                string fn = fName + "_" + rnd.Next(111, 999) + "_" + rnd.Next(111, 999) + ".jpg"; 
                string path = "~/photo/" + fn; 
                string pat = Server.MapPath(path); 
                Wattermark w = new Wattermark(); 
                Dal odal = new Dal(); 
                System.Drawing.Image image = System.Drawing.Image.FromFile(photo); 
                Graphics graphics = Graphics.FromImage(image); 
                Font font = new Font("Times New Roman", 42.0f); 
                PointF point = new PointF(10, 10); 
                graphics.DrawString("Tusharsangani", font, Brushes.Red, point); 
                image.Save(pat); 
                odal.fetch("insert into Registeruser (name,E_id,password,mobile,state,city,photo) values('" + name + "','" + email + "','" + pass + "','" + mobile + "','" + state + "','" + city + "','" + path + "')"); 
            } 
        } 
    }  
    else  
    { 
 
    } 

HostForLIFE.eu ASP.NET Core 2.2.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 2.2.1 Hosting - HostForLIFE.eu :: Random Password In C#

clock September 26, 2018 11:14 by author Peter

A random password is a combination of characters, numbers, and special characters. We can generate a random password by combining random numbers and random strings.
Generate A Random Password In C# And .NET Core. The code snippet in this article is an example of how to generate random numbers and random strings and combine them to create a random password using C# and .NET Core.

The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value. The Random class has three public methods - Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0.

Generate a random number
The following code in Listing 1 returns a random number.
// Generate a random number 
Random random = new Random(); 
// Any random integer  
int num = random.Next(); 


Generate a random string
The following code snippet in Listing 2 generates a random string with a given size. The second parameter of the RandomString method is used for setting if the string is a lowercase string.
// Generate a random string with a given size and case.  
// If second parameter is true, the return string is lowercase 
public string RandomString(int size, bool lowerCase) 

    StringBuilder builder = new StringBuilder(); 
    Random random = new Random(); 
    char ch; 
    for (int i = 0; i < size; i++) 
    { 
        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); 
        builder.Append(ch); 
    } 
    if (lowerCase) 
        return builder.ToString().ToLower(); 
    return builder.ToString(); 


Creating a random password
A random password can simply be a combination of a random string and a random number. To make it more complex, you can even add special characters and mix it up.
For us, we will combine the two methods - RandomNumber and RandomString.

The following code snippet in Listing 3 generates a password of length 10 with first 4 letters lowercase, next 4 letters numbers, and the last 2 letters as uppercase.
// Generate a random password of a given length (optional) 
public string RandomPassword(int size = 0) 

    StringBuilder builder = new StringBuilder(); 
    builder.Append(RandomString(4, true)); 
    builder.Append(RandomNumber(1000, 9999)); 
    builder.Append(RandomString(2, false)); 
    return builder.ToString(); 


All of the above functionality is listed here in Listing 4. Create a .NET Core Console app in Visual Studio and use this code.
using System; 
using System.Text; 
 
class RandomNumberSample 

    static void Main(string[] args) 
    { 
        // Generate a random number 
        Random random = new Random(); 
        // Any random integer  
        int num = random.Next(); 
 
        // A random number below 100 
        int randomLessThan100 = random.Next(100); 
        Console.WriteLine(randomLessThan100); 
 
        // A random number within a range 
        int randomBetween100And500 = random.Next(100, 500); 
        Console.WriteLine(randomBetween100And500); 
 
        // Use other methods  
        RandomNumberGenerator generator = new RandomNumberGenerator(); 
        int rand = generator.RandomNumber(5, 100); 
        Console.WriteLine($"Random number between 5 and 100 is {rand}"); 
 
        string str = generator.RandomString(10, false); 
        Console.WriteLine($"Random string of 10 chars is {str}"); 
 
        string pass = generator.RandomPassword(); 
        Console.WriteLine($"Random password {pass}"); 
 
        Console.ReadKey(); 
    } 

 
public class RandomNumberGenerator 

    // Generate a random number between two numbers   
    public int RandomNumber(int min, int max) 
    { 
        Random random = new Random(); 
        return random.Next(min, max); 
    } 
 
// Generate a random string with a given size and case.  
// If second parameter is true, the return string is lowercase 
public string RandomString(int size, bool lowerCase) 

    StringBuilder builder = new StringBuilder(); 
    Random random = new Random(); 
    char ch; 
    for (int i = 0; i < size; i++) 
    { 
        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); 
        builder.Append(ch); 
    } 
    if (lowerCase) 
        return builder.ToString().ToLower(); 
    return builder.ToString(); 

 
    // Generate a random password of a given length (optional) 
    public string RandomPassword(int size = 0) 
    { 
        StringBuilder builder = new StringBuilder(); 
        builder.Append(RandomString(4, true)); 
        builder.Append(RandomNumber(1000, 9999)); 
        builder.Append(RandomString(2, false)); 
        return builder.ToString(); 
    } 


The random string and random password looks like Figure 1.
Generate A Random Password In C# And .NET Core


Random password with given characters

Now, let’s say, you want to create a password that allows some specific characters only. The following code snippet in Listing 5 has a string of valid characters. The code uses this string to pick one character at a time for the password and stops at the given length. The default length of the password is 15.

private static string CreateRandomPassword(int length = 15) 

    // Create a string of characters, numbers, special characters that allowed in the password 
    string validChars = "A[email protected]#$%^&*?_-"; 
    Random random = new Random(); 
 
    // Select one random character at a time from the string 
    // and create an array of chars 
    char[] chars = new char[length]; 
    for (int i = 0; i < length; i++) 
    { 
        chars[i] = validChars[random.Next(0, validChars.Length)]; 
    } 
    return new string(chars); 


Note
You can modify validChars string with the characters you allowed in the password.
Listing 6 is the complete program written in .NET Core.

using System; 
class Program 

    static void Main(string[] args) 
    {  
        Console.WriteLine(CreateRandomPassword()); 
        Console.WriteLine(CreateRandomPassword(10)); 
        Console.WriteLine(CreateRandomPassword(30)); 
 
        Console.WriteLine(CreateRandomPasswordWithRandomLength()); 
 
        Console.ReadKey(); 
    } 
 
 
    // Default size of random password is 15 
    private static string CreateRandomPassword(int length = 15) 
    { 
        // Create a string of characters, numbers, special characters that allowed in the password 
        string validChars = "[email protected]#$%^&*?_-"; 
        Random random = new Random(); 
 
        // Select one random character at a time from the string 
        // and create an array of chars 
        char[] chars = new char[length]; 
        for (int i = 0; i < length; i++) 
        { 
            chars[i] = validChars[random.Next(0, validChars.Length)]; 
        } 
        return new string(chars); 
    } 
 
    private static string CreateRandomPasswordWithRandomLength() 
    { 
        // Create a string of characters, numbers, special characters that allowed in the password 
        string validChars = "[email protected]#$%^&*?_-"; 
        Random random = new Random(); 
 
        // Minimum size 8. Max size is number of all allowed chars. 
        int size = random.Next(8, validChars.Length); 
 
        // Select one random character at a time from the string 
        // and create an array of chars 
        char[] chars = new char[size]; 
        for (int i = 0; i < size; i++) 
        { 
            chars[i] = validChars[random.Next(0, validChars.Length)]; 
        } 
        return new string(chars); 
    } 

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: Start Using HTTP Handlers In ASP.NET

clock September 19, 2018 11:48 by author Peter

First, let me explain the main purpose of using HTTPHandler. Sometimes you need to handle a specific request separately using a different method from that of a normal request. This article will explain HTTP Handler in a simple way. Let’s begin:
How can you handle any incoming HTTP request with a path “AllUsers/User.gif” by returning “Hello From HTTP Handler”.

  • Create a class file --  it could be MyHttpHandler.cs
  • Let MyHttpHandler class inherit from IhttpHandler Interface.
  • In MyHttpHandler class, implement all the methods which are found in IhttpHandler Interface.

You should do the following,
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
namespace MyProject { 
    public class MyHttpHandler: IHttpHandler { 
        public bool IsReusable { 
            get { 
                return true; 
            } 
        } 
        public void ProcessRequest(HttpContext context) { 
            HttpResponse response = context.Response; 
            response.Write("Hello From Http Handler"); 
        } 
    } 


The next step is to register the http handler in the web.config,

<httpHandlers> 
   <add verb="*" path="AllUsers/User.gif" type="MyProject.MyHttpHandler,MyProject"/> 
</httpHandlers> 


The above code (point 4) should be added as a child of <system.web>

That's all. Now HTTP Handler is ready

Section2
When using HTTP Handler with either MVC or WEB API, you will get the following error:


Because each MVC and WEB API are using routing to access methods within the controller, they will search the path and find that it is not found. To solve this problem you have two choices:

The first one is,

  • Create a class file --  it could be MyRouteHandler.cs
  • Let MyRouteHandlerclass inherit from IRouteHandlerInterface.
  • In MyRouteHandler class, implement all the methods which are found in IRouteHandlerInterface and return the MyHttpHandlerwhich are created in the previous section.

You should do the following,
public class MyRouteHandler: IRouteHandler { 
    public IHttpHandler GetHttpHandler(RequestContext requestContext) { 
        return new MyHttpHandler(); 
    } 


In RouteConfig class which is related to MVC and WEP API and responsible for requests routing, add the following line code to RegisterRoutes method and before the Default MapRoute.
routes.Add(new Route("AllUsers/User.gif", new MyRouteHandler())); 

Drop the HTTP Handler registration from web.config, since calling HTTP Handler will be from RegisterRoutes method.

The Second Solution Is:

Let us go back to section 1. It is a straightforward solution: In RouteConfig class which is related to MVC and WEP API and responsible for requests routing, add the following line of code to the RegisterRoutes method and before the Default MapRoute.
routes.IgnoreRoute("AllUsers/User.gif"); 

That's it.

Note
If you want to Handle all HTTP requests which have a specific extentaion such as gif you can using the following in web.config.
<httpHandlers> 
   <add verb="*" path="*.gif" type="MyProject.MyHttpHandler,MyProject"/> 
</httpHandlers> 

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