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 4.8 Hosting - HostForLIFE.eu :: Use Distinct And FirstOrDefault Clauses In .NET Using linq.js

clock September 10, 2019 12:37 by author Peter

In this version, I will tell you about using Let us see how to use Distinct() and FirstOrDefault() clauses with the help of linq.js in .NET Web Application. It's useful to write simple LINQ queries from Entityframework to client side with LinqJS.

It’s better for validating data at the client side.
Improves performance of the application.

Let’s see one by one,
Distinct() function is different here.

C#.NET Code
    var FirstNameCollection = myDataArray.Select(x => x.FirstName).Distinct(); 
LinqJS Code
    // Retrieves non-duplicate FirstName values. 
    var FirstNameCollection = Enumerable.From(myDataArray).Distinct(function(x) { 
        return x.FirstName; 
    }).Select(function(FName) { 
        return FName; 
    }).ToArray(); 
The FirstOrDefault() function is nearly similar.

C#.NET Code
    public class cmbMonthOfWeek { 
        public string cmbMonth { 
            get; 
            set; 
        } 
        public int Id { 
            get; 
            set; 
        } 
    } 
    List < cmbMonthOfWeek > weekInfo = new List < cmbMonthOfWeek > (); 
    weekInfo.Add(new cmbMonthOfWeek { 
        cmbMonth = "First week", Id = 0 
    }); 
    weekInfo.Add(new cmbMonthOfWeek { 
        cmbMonth = "Second week", Id = 1 
    }); 
    weekInfo.Add(new cmbMonthOfWeek { 
        cmbMonth = "Third week", Id = 2 
    }); 
    weekInfo.Add(new cmbMonthOfWeek { 
        cmbMonth = "Fourth week", Id = 3 
    }); 
    var defaultWeekData = (from p in weekInfo where p.Id == 1 select p).FirstOrDefault();
Note

Here in defaultWeekData, you will get cmbMonth = "Second week".

LinqJS Code
    $scope.cmbMonthOfWeek = [{ 
        "cmbMonth": "First week", 
        "Id": 0 
    }, { 
        "cmbMonth": "Second week", 
        "Id": 1 
    }, { 
        "cmbMonth": "Third week", 
        "Id": 2 
    }, { 
        "cmbMonth": "Fourth week", 
        "Id": 3 
    }, ]; 
    var defaultWeekData = Enumerable.From($scope.cmbMonthOfWeek).Where(function(x) { 
        return x.Id == 1 
    }).FirstOrDefault();  Distinct And FirstOrDefault Clauses In .NET Using linq.js

HostForLIFE.eu ASP.NET 4.8 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 Hosting HostForLIFE.eu :: Centralized Exception Handling Without Using Try Catch Block In .Net Core 2.2 Web API

clock September 3, 2019 12:00 by author Peter

Rather than writing try catch block for each method, throwing exceptions manually and handling them, here we will use the power of .Net Core middleware to handle the exceptions at one single place, so that when an exception occurs anywhere in the code, the appropriate action can be taken. We will use UseExceptionHandler extension method that will add a middleware to the pipeline, and it will catch exceptions, log them, reset the request path, and re-execute the request if response has not already started.

Developer can customize the response format as well.

To achive this in .NetCore 2.2, this code snippet is very simple and it's just a matter of adding a few lines in your Startup.cs.

Simply go in Configure method and add the below code,
if (env.IsDevelopment()) {  
    app.UseDeveloperExceptionPage();  
} else {  
    app.UseExceptionHandler(errorApp => errorApp.Run(async context => {  
        // use Exception handler path feature to catch the exception details   
        var exceptionHandlerPathFeature = context.Features.Get < IExceptionHandlerPathFeature > ();  
        // log errors using above exceptionHandlerPathFeature object   
        Console.WriteLine(exceptionHandlerPathFeature ? .Error);  
        // Write a custom response message to API Users   
        context.Response.StatusCode = "500";  
        // Set a response format    
        context.Response.ContentType = "application/json";  
        await context.Response.WriteAsync("Some error occured.");  
    }));  
}  


The Console.WriteLine() is for demonstration purposes only. Here a developer can log the exceptions using any tool/package getting used in their project.

When any exceptions are thrown in the application this code will be executed and will produce the desired custom response in non-development environments (as in a development env we are using UseDeveloperExceptionPage() as a middleware).

HostForLIFE.eu ASP.NET 4.8 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET 4.8 Hosting HostForLIFE.eu :: Fix Error on System.Web.UI.ViewStateException

clock August 27, 2019 12:38 by author Peter

In this post, I will tell you about fix System.Web.UI.ViewStateException: Invalid viewstate or System.Web.HttpException: The client disconnected exception Response.IsClientConnected Property ASP.NET 4.8.What is HttpResponse.IsClientConnected Property: HttpResponse.IsClientConnected used to gets a quality demonstrating whether the customer is still joined with the server.

The accompanying illustration utilizes the IsClientConnected property to check whether the customer that is asking for the page remains connected to the server. IfIsClientConnected is genuine, the code calls the  Redirect  technique, and the client will see an alternate page. In the event that IsClientConnected is false, then the code calls the End system and all page handling is ended.

 

And here is code that I used:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Fix System.Web.UI.ViewStateException
    </title></head>
<body>
    <form id="form1" runat="server">
    <div>Welcome</div>
    </form>
</body>
</html>

C#
public partial class ClientDisconnected : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Check whether the browser(client) remains connected to the server
        if (Response.IsClientConnected)
        {
            // if  browser connected, redirect to the Main.aspx page
            Response.Redirect("~/Main.aspx");
        }
        else
        {
            //if browser is not connected,terminate all response processing.
            Response.End();
        }
    }
}


VB.NET
Public Partial Class ClientDisconnected
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        'Check whether the browser(client) remains connected to the server
        If Response.IsClientConnected Then
            ' if  browser connected, redirect to the Main.aspx page
            Response.Redirect("~/Main.aspx")
        Else
            'if browser is not connected,terminate all response processing.
            Response.[End]()
        End If
    End Sub
End Class

HostForLIFE.eu ASP.NET 4.8 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET Core Hosting :: Rotate Ads Without Refreshing the Page Using AdRotator in ASP.NET

clock August 20, 2019 12:18 by author Peter

This article explains the concept of the AdRotator control without the user refreshing the page and rotates the ads on a certain time interval. This article also gives a tip to fetch ad information from an XML file. The AdRotator Control presents ad images each time a user enters or refreshes a webpage. When the ads are clicked, it will navigate to a new web location. However the ads are rotated only when the user refreshes the page. In this article, we will explore how you can easily rotate ads at regular intervals, without the user refreshing the page. First of all start Visual Studio .NET And make a new ASP.NET web site using Visual Studio 2010.
 
Now you have to create a web site.
Go to Visual Studio 2010
New-> Select a website application
Click OK

Now add a new page to the website.

    Go to the Solution Explorer
    Right-click on the Project name
    Select add new item
    Add new web page and give it a name
    Click OK

We create an images folder in the application which contains some images to rotate in the AdRotator control. Now add a XML file. To do so, right-click the App_Data folder > Add New Item > 'XML File' > Rename it to adXMLFile.xml and click Add. Put this code in the .XML File.

    <?xml version="1.0" encoding="utf-8" ?> 
    <Advertisements> 
    <Ad> 
    <ImageUrl>~/Images/image1.gif</ImageUrl> 
    <NavigateUrl>http://www.c-sharpcorner.com/</NavigateUrl> 
    <AlternateText>C-sharpcorner Home Page</AlternateText> 
    <Impressions>3</Impressions> 
    <Keyword>small</Keyword> 
    </Ad> 
    <Ad> 
    <ImageUrl>~/images/forest_wood.JPG</ImageUrl> 
    <NavigateUrl>http://www.c-sharpcorner.com/</NavigateUrl> 
    <AlternateText>C-sharpcorner Home Page</AlternateText> 
    <Impressions>2</Impressions> 
    <Keyword>small</Keyword> 
    </Ad> 
    <Ad> 
    <ImageUrl>~/images/image2.gif</ImageUrl> 
    <Width>300</Width> 
    <Height>50</Height> 
    <NavigateUrl>http://www.c-sharpcorner.com/</NavigateUrl> 
    <AlternateText>C-sharpcorner Home Page</AlternateText> 
    <Impressions>3</Impressions> 
    <Keyword>small</Keyword> 
    </Ad> 
    </Advertisements> 


XML file elements

  • Here is a list and a description of the <Ad> tag items.
  • ImageUrl - The URL of the image to display.
  • NavigateUrl - The URL where the page will go after AdRotator image is clicked.
  • AlternateText - Text to display if the image is unavailable.
  • Keyword - Category of the ad, which can be used to filter for specific ads.
  • Impressions - Frequency of ad to be displayed. This number is used when you want some ads to be displayed more frequently than others.
  • Height - Height of the ad in pixels.
  • Width - Width of the ad in pixel.

Now drag and drop an AdRotator control from the toolbox to the .aspx and bind it to the advertisement file. To bind the AdRotator to our XML file, we will make use of the "AdvertisementFile" property of the AdRotator control as shown below:
    <asp:AdRotator 
    id="AdRotator1" 
    AdvertisementFile="~/adXMLFile.xml" 
    KeywordFilter="small" 
    Runat="server" /> 


To rotate the ads without refreshing the page, we will add some AJAX code to the page.
    <Triggers> 
    <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /> 
    </Triggers> 


The .aspx code will be as shown below.
 
Now drag and drop an UpdatePanel and add an AdRotator control into it. The DataList code looks like this:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="adrotator.aspx.cs" Inherits="adrotator" %> 
    <!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> 
    </head> 
    <body> 
    <form id="form1" runat="server"> 
    <div> 
    <asp:ScriptManager ID="ScriptManager1" runat="server" /> 
    <asp:Timer ID="Timer1" Interval="1000" runat="server" /> 
    <asp:UpdatePanel ID="up1" runat="server"> 
    <Triggers> 
    <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /> 
    </Triggers> 
    <ContentTemplate> 
    <asp:AdRotator ID="AdRotator1" AdvertisementFile="~/adXMLFile.xml" KeywordFilter="small" 
    runat="server" /> 
    </ContentTemplate> 
    </asp:UpdatePanel> 
    </div> 
    </form> 
    </body> 
    </html> 


Now run the application and test it. The AdRotator control rotates the ads without the user refreshing the page and rotates the ads on a certain time interval



European ASP.NET Core Hosting :: Session Wrapper Design Pattern For ASP.NET Core

clock August 14, 2019 11:11 by author Peter

In this article, we will learn to access the Session data in a Typed manner by getting IntelliSense support. We learned how to use Session in ASP.NET Core. In this article, we'll learn about Session Wrapper design pattern to ease the access of Session. In short, we'll make our access of session "Typed". Also, we may apply any validation or constraint in this wrapper class.

Step 1 - Create a Session Manager class

In this example, we are going to store two items in Session (i.e. ID & LoginName).
We are injecting IHttpContextAccessor so that we can access the Session variable.
We are creating properties which are actually accessing Session variable and returning the data or writing the data to Session.
We have added one helping property "IsLoggedIn" which is using other properties to make a decision. We may have more such helping/wrapper properties.
using Microsoft.AspNetCore.Http;

public class SessionManager 

    private readonly ISession _session; 
    private const String ID_KEY = "_ID"; 
    private const String LOGIN_KEY = "_LoginName"; 
    public SessionManager(IHttpContextAccessor httpContextAccessor) 
    { 
        _session = httpContextAccessor.HttpContext.Session; 
    } 

    public int ID 
    { 
        get 
        { 
            var v = _session.GetInt32(ID_KEY); 
            if (v.HasValue) 
                return v.Value; 
            else 
                return 0; 
        } 
        set 
        { 
            _session.SetInt32(ID_KEY, value); 
        } 
    } 
    public String LoginName 
    { 
        get 
        { 
            return _session.GetString(LOGIN_KEY); 
        } 
        set 
        { 
            _session.SetString(LOGIN_KEY, value); 
        } 
    } 
    public Boolean IsLoggedIn 
    { 
        get 
        { 
            if (ID > 0) 
                return true; 
            else 
                return false; 
        } 
    } 
}
 

Step 2
Registering IHttpContextAccessor and SessionManager in Startup file.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
services.AddScoped<SessionManager>(); 


Step 3
Injecting SessionManager in your classes. Here is an example of Controller class but in the same way, it can be injected in non-controller classes too.
private readonly SessionManager _sessionManager; 
public HomeController(SessionManager sessionManager) 

  _sessionManager = sessionManager; 


Step 4
Using SessionManager to access Session Data,
_sessionManager.ID = 1; 
_sessionManager.LoginName = dto.Login; 

if(_sessionManager.IsLoggedIn == true) 

ViewBag.Login = _sessionManager.LoginName; 
return View(); 


Conclusion
This wrapper pattern helps using Session without worrying about KeyNames & Makes access easier. It also helps you apply different conditioning and constraints in a wrapper class.

 



ASP.NET 4.8 Hosting - HostForLIFE.eu :: How to Steps To Generate Excel Using EPPlus?

clock August 6, 2019 12:39 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 4.8 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 :: Dynamically Check And Uncheck Checkbox Based On DB Value In Gridview

clock July 23, 2019 12:23 by author Peter

This code will help the developers to check and uncheck the gridview checkbox based on the value from the database.
Create a GridView with checkbox.

<asp:GridView ID="Gridview" runat="server" Font-Size="8pt" 
        PageSize="200" Width="880px" AutoGenerateColumns="False"> 
        <Columns> 
            <asp:TemplateField> 
                <HeaderTemplate> 
                    <asp:CheckBox ID="chkHeader" Text="Select All" runat="server" /> 
                </HeaderTemplate> 
                <ItemTemplate> 
                    <asp:CheckBox ID="chkChild" runat="server"  Checked='<%# Eval("PROCESSED").ToString().Equals("1") %>' Enabled='<%# !Eval("PROCESSED").ToString().Equals("1") %>'/> 
                </ItemTemplate> 
            </asp:TemplateField>            
        </Columns> 
    </asp:GridView> 


Get the data from the database, the field from the database to check the checkbox should be 1 or 0.

DB Table data

PROCESSED (HEADER)
1
1
0

DataField "PROCESSED" should be 1 or 0 (boolean),

Checked='<%# Eval("PROCESSED").ToString().Equals("1") %>' 

The above GridView code will check the checkbox if the value from the PROCESSED field in DB is 1 else if the PROCESSED value is other than 1 the checkbox will be unchecked,

Enabled='<%# !Eval("PROCESSED").ToString().Equals("1") %>' 

This code will help us to enable or disable the text box. In the above mentioned code, if the PROCESSED is 1, checkbox will be disabled else the checkboc will be enable.

HostForLIFE.eu ASP.NET 4.8 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 :: A Quick And Simple Look Into .NET Core And Comparison To .NET Standard

clock July 16, 2019 11:54 by author Peter
First, as Microsoft simply described, .NET Core is an open-source, general-purpose development platform maintained by Microsoft and the .NET community on GitHub. .NET is cross-platform which supports Windows, macOS, and Linux and can be used to implement devices, cloud, and IoT applications. Historically, the .NET Framework had only worked on Windows devices. The Xamarin and Mono projects worked to bring .NET to mobile devices, macOS, and Linux. .NET Core provides a standard base library that can now be used across Windows, Linux, macOS, and mobile devices, still via Xamarin.

.NET Core has multiple characteristics such as cross-platform programming for Windows, Linux, MacOS, as well as consistency across architectures. It runs your code with the same behavior on multiple architectures, including x64, x86, and ARM. .NET Core provides flexible deployment, can be included in your app or installed side-by-side such as user-wide or system-wide installations, and can be used with Docker containers.

.NET Core makes it simpler for developers to build microservice architecture systems promptly. As such, systems include several independent and dynamic microservices, the developers can focus on specific microservices. .NET Core enables programmers to develop custom microservices by using varying programming languages, technologies, and frameworks. Likewise, the developers can build a robust system by combining multiple microservices flawlessly.

PROGRAMMING LANGUAGE SUPPORT
From a programming point of view C#, Visual Basic, and F# languages can be used to write applications and libraries for .NET Core. Additionally, with .NET Core 3.0 C# 8.0 will be supported. Currently, VB.NET compiles and runs on .NET Core, but the separate Visual Basic Runtime is not implemented. Microsoft announced that .NET Core 3 would include the Visual Basic Runtime.

GENERAL SUPPORTED FEATURES
.NET Core supports four cross-platform scenarios: ASP.NET Core web apps, command-line apps, libraries, and Universal Windows Platform apps. However, it does not presently apply Windows Forms or WPF which render the standard GUI for desktop software on Windows. Also, .NET Core 3 supports desktop technologies WinForms, WPF and UWP. Besides these, .NET Core supports the use of NuGet packages. Differently than before like .NET Framework, which is serviced using Windows Update, .NET Core depends on its package manager to get updates.

.NET Core consists of CoreCLR, a whole runtime implementation of the Common Language Runtime, which created at Microsoft as the virtual machine for handling execution of .NET programs and includes a just-in-time compiler called RyuJIT. Moreover, .NET Core also contains CoreRT, the .NET Native runtime enhanced to be integrated into AOT compiled native binaries.

.NET Core also includes CoreFX, which is a partial branch of .NET Framework standard libraries. While .NET Core shares a subset of .NET Framework APIs and comes with its own API that is not a subset of .NET Framework. Also, a variant of the .NET Core library is used for UWP.

.NET Core's command-line interface provides an execution entry point for operating systems and gives developer services similar compilation and package management.

Use .NET Core when

  • You want to build cross-platform applications
  • If the new application (web or service) needs to run on multiple platforms- Windows, Linux, macOS, choose .NET Core over .NET Framework. Visual Studio Code and third-party editors such as Sublime, Emacs, VI support .NET Core for cross-platform development.
  • The need is to build high-performance and scalable systems
  • When a performance-oriented and scalable system is on the list, it is better to prefer .NET Core over the .NET Framework. Reason being, .NET Core offers high-performance server runtime for Linux and Windows Server.
  • When you are using microservices or Docker containers
  • For applications or services that use microservices or Docker containers, opting .NET Core makes more sense. Reasons include,
    • .NET Core facilitates mixing microservices or services developed with Ruby, Java, .NET Framework, or other monolithic technologies.
    • Containers usually work in conjugation with microservices architecture. With .NET Framework, there is a limitation to work with Windows containers only. Moreover, while creating and deploying a container, the image size is smaller with .NET Core vs .NET Framework.
  • You need side-by-side .NET versions per application
  • For applications that may have a dependency on different versions of .NET for installation, opt for .NET Core. .NET Core offers side by side installation of multiple versions for .NET Core runtime on the same machine.

Use the .NET Framework when:

  • The app is using .NET technologies that are not available for .NET Core.
  • Several .NET technologies are not available for .NET Core. For example, ASP.NET web pages applications or workflow related services (WCF Data Services, Windows Workflow Foundation) are not included in. NET Core.
  • The existing app uses a platform that .NET Core does not support.
  • Some of the Microsoft or third-party services/platforms do not offer support to .NET Core. For example, Azure’s Service Fabric Stateful Reliable Services programming model does not support .NET Core and is available for.NET Framework.

Finally, the .NET Framework supports Windows and web applications. .NET Core is the new open-source and cross-platform framework to build applications for all operating systems including Windows, Mac, and Linux. .NET Core supports UWP and ASP.NET Core only.

HostForLIFE.eu ASP.NET 4.8 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 :: Register And Use Multiple Implementations Of A Dependency In ASP.NET Core Dependency Injection

clock July 12, 2019 12:13 by author Peter

There can be situations where you need to register multiple implementations of the same dependency for your applications. For example, if you want to add features to your application without changing the existing code, a good way to do it is to add a new implementation for that. Your application needs to be written in a certain way to do this correctly. We have a really simple example that demonstrates this in this article. But when you eventually need to do this, ASP.Net Core built-in Dependency Injection providers capabilities to achieve this. In this article, we will look at how to do this with an example.
Registering Multiple Implementations of a Dependency

As an example, let’s take an online e-commerce website. This site gives Discounts to the customers on certain occasions and when certain conditions are met. I have an interface called IDiscount where it defines a discount and the logic to calculate it. For each type of discount, you want to provide in your e-commerce application, you can have an implementation of the IDiscount interface. Then I have an interface called IDiscountProcessor where the implementation of this interface handles calling all the implementations of IDiscount to calculate the final discount for a given Order.

You have a couple of ways to register multiple implementations of a dependency in ASP.Net Core. One way is to just use the provided extension methods on IServiceCollection to register your implementations with the desired lifetime.
    services.AddScoped<IDiscountProcessor, OrderDiscountProcessor>(); 
    services.AddScoped<IDiscount, SeasonalDiscount>(); 
    services.AddScoped<IDiscount, LargeOrderDiscount>(); 
    services.AddScoped<IDiscount, ThreeOrModeDiscount>();  


Here, I have registered the OrderDiscountProcessor implementation of IDiscountProcessor and 3 implementations of IDiscount interface.

This will work fine when we eventually resolve all the implementations of IDiscount interface we can calculate the total discount. But the problem comes when you have multiple registrations of the same implementation. For example, let’s say one of the developers accidentally registered SeasonalDiscount implementation twice. What will happen is that the Seasonal discount will be applied twice for all the orders, costing the organization money.

A better way of registering multiple implementations is to use TryAddEnumerable extension method given in the Microsoft.Extensions.DependencyInjection.Extensions namespace. This will not register any duplicate implementations making multiple implementation registration safe. The registration is a bit different where you need to use ServiceDescriptors to register the dependency. The modified implementation looks like this.
    services.AddScoped<IDiscountProcessor, OrderDiscountProcessor>(); 
    services.TryAddEnumerable(new[] 
    { 
        ServiceDescriptor.Scoped<IDiscount, SeasonalDiscount>(), 
        ServiceDescriptor.Scoped<IDiscount, LargeOrderDiscount>(), 
        ServiceDescriptor.Scoped<IDiscount, ThreeOrModeDiscount>() 
    }); 


Injecting and Using Multiple Implementations of a Dependency

Once your implementations are registered with the Dependency Injection container, they are ready to be used. To inject all the registered implementations, you need to use IEnumerable<> of the implementation type in your constructor. So, your constructor would look something like this. This is our OrderDiscountProcessor implementation.
    public class OrderDiscountProcessor : IDiscountProcessor 
    { 
        private readonly IEnumerable<IDiscount> _discounts; 
     
        public OrderDiscountProcessor(IEnumerable<IDiscount> discounts) 
        { 
            _discounts = discounts; 
        } 
        // ... 
    } 


Here I am injecting IEnumerable<IDiscount> where it injects all the registered implementations to my class. Then in my ProcessDiscount() method I can use the implementations like this.
    public (double, List<string>) ProcessDiscount(OrderViewModel order) 
    { 
        var discountDiscroptoons = new List<string>(); 
        var totalDiscount = 0.0; 
     
        foreach (var discount in _discounts) 
        { 
            var addedDiscount = discount.CalculateDiscount(order); 
            if (addedDiscount > 0) 
            { 
                 discountDiscroptoons.Add(discount.Description); 
            } 
            totalDiscount += addedDiscount; 
        } 
     
        return (totalDiscount, discountDiscroptoons); 
     } 


I can now iterate through all the implementations of IDiscount interface and call its CalculateDiscount() method to calculate the discount for the given Order.

Note that you can only use IEnumerable<> for your injections of multiple implementations. Any other type like IList<>, ICollection<> will not work in this case.
Summary

In this article, we looked into the process of how to register multiple implementations of the same dependency in ASP.NET Core and how to use these dependencies in our classes by injecting them. The simple sample application used to demonstrate this usage is available for download with this article or you can find the source code on GitHub under the following repository

HostForLIFE.eu ASP.NET 4.8 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.5 Hosting - HostForLIFE.eu :: How to Read a Remote WEB Page in ASP.NET C#?

clock July 2, 2019 12:16 by author Peter

In this tutorial, let me show you how to Read a Remote WEB Page in ASP.NET C#. Below is my aspx:

    <%@ 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> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div> 
            <asp:Label ID="lblResponse" runat="server"></asp:Label></div> 
        </form> 
    </body> 
    </html> 

Now my aspx.cs is:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Net; 
    using System.IO; 
     
    public partial class _Default : System.Web.UI.Page 
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            string URLResponse = GetHtmlPage("http://www.google.com"); 
            lblResponse.Text = URLResponse; 
        } 
     
        static string GetHtmlPage(string strURL) 
        { 
     
            String strResult; 
            WebResponse objResponse; 
            WebRequest objRequest = HttpWebRequest.Create(strURL); 
            objResponse = objRequest.GetResponse(); 
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) 
            { 
                strResult = sr.ReadToEnd(); 
                sr.Close(); 
            } 
            return strResult; 
        } 
    } 


Here I am reading http://www.google.com and showing response in a label:

 


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

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in