European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Generate Images In ASP.NET Core MVC Using OpenAI

clock March 16, 2023 09:50 by author Peter

Using DALL-E in an ASP.NET Core application involves integrating the OpenAI API into your code. We can generate multiple images based on the given text using DALL-E generate image API endpoint. First, you must develop an OpenAI API key to authorize API use. In this article, I will explain how you can use DALL-E API in the ASP.NET Core MVC application to generate images based on the text.


Agenda for the Article,
    What is OpenAI?
    What is DALL-E?
    How to get OpenAI API Key
    Generating Image In ASP.NET Core MVC

What is OpenAI?
OpenAI is an artificial intelligence research lab that works to develop and grow AI in different fields like medicine, education, sports, information technology, etc. It was founded in 2015. OpenAI conducts research in various areas of AI, including machine learning, natural language processing, robotics, and computer vision. The organization has developed several groundbreaking AI models, including GPT-3, DALL-E, and CLIP. In this article, I will explain the use of the DALL-E. I have also written an article on GPT-3. To know more, please refer to this article.

What is DALL-E?

DALL-E is an artificial intelligence (AI) program developed by OpenAI that generates images from textual descriptions using a transformer-based language model. DALL-E is named after the famous artist Salvador Dali. The program can create highly detailed and complex images of objects, animals, and scenes that do not exist in the real world but also in the real world. It works by learning from a dataset of images and their associated textual descriptions, allowing it to generate fictional and realistic images based on the given textual input. DALL-E is a significant breakthrough in AI image generation and has the potential to revolutionize various industries, including advertising, gaming, and e-commerce.

Generating OpenAI API Key
You need to authorize the API endpoint by passing the API key. To generate an OpenAI API key, follow these steps:

Signup for an OpenAI account. Go to the OpenAI website and create a new account.

Confirm your email address.
Now, Log in to your account and navigate to the 'View API keys' section as given below.

Now, click on 'Create new secret key' as given below.


Store your API key in a secure location, as it will be required to access the OpenAI APIs. You can copy the key and save it for future use. OpenAI has usage and resource limitations for its API, so be sure to check its documentation here for details on usage and pricing.

Generating Image In ASP.NET Core MVC

To generate images in the ASP.NET Core MVC application using DALL-E, you need to follow the below-given steps:
    First, create an ASP.NET Core MVC project. To know more about creating a project, please refer here.
    Add your API key in the appsettings.json file as given below

    //demo key
    "OpenAI_API_KEY": "sk-cF8Dv3n2YtUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"


Add the below-given code for the UI in your Index.cshtml file inside Views>Home>Index.cshtml
<h1 class="display-4">Image Generator</h1>
<!--Image info-->
<input type="text" class="form-control" id="txt" style="width:400px;" placeholder="Image Description" />
<br />
<!--Image Size-->
<select id="size">
    <option selected>256x256</option>
    <option>512x512</option>
</select>
<!--Images Required-->
<input type="number" value="1" placeholder="Images Required" id="quantity" />
<!--Generate button-->
<button id="generate">
    Generate
</button>
<br />
<!--Display image here-->
<div id="Imagedisplay" class="col-md-14 row">
</div>


In the above-given code, you have added a UI for the home page to enter some basic details required for the image, like the information about the image, the number of images required, and the size of the image.

Now you will add a model class ImageInfo.cs inside the Models folder as given below.
public class ImageInfo {
    public string ? ImageText {
        get;
        set;
    }
}
public class RequiredImage {
    public string ? prompt {
        get;
        set;
    }
    public short ? n {
        get;
        set;
    }
    public string ? size {
        get;
        set;
    }
}
public class ImageUrls {
    public string ? url {
        get;
        set;
    }
}
// response handling
public class ResponseModel {
    public long created {
        get;
        set;
    }
    public List < ImageUrls > ? data {
        get;
        set;
    }
}

In the above-given code, You have added ResponseModel class for handling the response and RequiredImage class for the input data about the required image.

Now you will add a controller method inside HomeController.cs as given below.
[HttpPost]
public async Task < IActionResult > GenerateImage([FromBody] RequiredImage obj) {
    string imglink = string.Empty;
    var response = new ResponseModel();
    using(var client = new HttpClient()) {
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", APIKEY);
        var Message = await client.PostAsync("https://api.openai.com/v1/images/generations", new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"));
        if (Message.IsSuccessStatusCode) {
            var content = await Message.Content.ReadAsStringAsync();
            response = JsonConvert.DeserializeObject < ResponseModel > (content);
            imglink = resp.data[0].url.ToString();
        }
    }
    return Json(response);
}


You have added a post-call with the DALL-E API key in the above given code. You have to pass the API key shown above.

The final step is to display the image on the UI using javascript. So you have to add the below-given code inside wwwroot>js>site.js.
$(document).ready(() => {
    $('#generate').click(function() {
        var info = {};
        info.n = parseInt($('#quantity').val());
        info.prompt = $('#txt').val();
        info.size = $('#size').find(":selected").val();
        $.ajax({
            url: '/Home/GenerateImage',
            method: 'post',
            contentType: 'application/json',
            data: JSON.stringify(info)
        }).done(function(data) {
            $.each(data.data, function() {
                $('#Imagedisplay').append('<div class="col-md-5" style="padding-top:12px">' + '<img class="p-12" src = "' + this.url + '"/>' + '</div>');
            });
        });
    });
});


Output

Conclusion
OpenAI provides us with lots and lots of use for artificial intelligence. AI has become a part of our daily life nowadays. ChatGPT and DALL-E are all advanced and great examples of AI. To generate an image, you need two things. First, the OpenAI APOI key and second DALL-E API endpoint. Pass the API key in the header and freely use that endpoint.

Thank You, and Stay Tuned for More.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Using MVC 6 And AngularJS 2 With .NET Core

clock March 8, 2023 07:22 by author Peter

Overview on ASP.NET

Let’s differentiate both.

.NET Framework

  • Developed and run on Windows platform only.
  • Built on the .NET Framework runtime.
  • Supported (MVC, Web API & SignalR) Dependency Injection (DI).
  • MVC & Web API Controller are separated.

.Net Core

  • Open Source.
  • Developed & run on Cross Platform.
  • Built on the .NET Core runtime & also on .NET Framework.
  • Facility of dynamic compilation.
  • Built in Dependency Injection (DI).
  • MVC & Web API Controller are unified, Inherited from same base class.
  • Smart tooling (Bower, NPM, Grunt & Gulp).
  • Command-line tools.


Start with .NET Core 1.0
Let’s create a new project with Visual Studio 2015 > File > New > Project.

Choose empty template and click OK.


Visual Studio will create a new project of ASP.NET Core empty project.

We will now explore all initial files one by one.

Explore Initial Template

Those marked from Solution Explorer are going to be explored, one by one.

First of all, we know about program.cs file. Let’s concentrate on it.

Program.cs: Here, we have sample piece of code. Let’s get explanation.
    namespace CoreMVCAngular  
    {  
        public class Program   
        {  
            public static void Main(string[] args) {  
                var host = new WebHostBuilder().UseKestrel().UseContentRoot(Directory.GetCurrentDirectory()).UseIISIntegration().UseStartup < Startup > ().Build();  
                host.Run();  
            }  
        }  
    }  


.UseKestrel() : Define the Web Server. ASP.NET Core supports hosting in IIS and IIS Express.

HTTP servers
    Microsoft.AspNetCore.Server.Kestrel (cross-platform)
    Microsoft.AspNetCore.Server.WebListener (Windows-only)

.UseContentRoot(Directory.GetCurrentDirectory()) : Application base path that specifies the path to the root directory of the Application.
.UseIISIntegration() : For hosting in IIS and IIS Express.
.UseStartup<Startup>() : Specifies the Startup class.
.Build() : Build the IWebHost, which will host the app & manage incoming HTTP requests.

Startup.cs
This is the entry point of every .NET Core Application. It provides services, that the Application required.
    namespace CoreMVCAngular   
    {  
        public class Startup   
        {  
            // This method gets called by the runtime. Use this method to add services to the container.  
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940  
            public void ConfigureServices(IServiceCollection services) {}  
                // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {}  
        }  
    }  


As you can see, there are two methods; one is ConfigureServices & another is Configure. In Configure method, three parameters are specified.

IApplicationBuilder defines a class, which provides the mechanisms to configure an Application's request.

We can add MVC (middleware) to the request pipeline by using “Use” extension method. Later, we will use it.
ConfigureServices is an extension method, which is configured to use the several services.

Project.json: This is where our Application dependencies are listed i.e by name & version. This file also manages runtime, compilation settings.

Dependencies: All Application dependencies can add new dependencies, if required, intellisense will help up to include with the name & version.

After saving changes, it will automatically restore the dependencies from NuGet.


Here, the code snippet is changed.
    "dependencies": {  
    "Microsoft.NETCore.App": {  
    "version": "1.0.0",  
    "type": "platform"  
    },  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",  
      
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",  
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",  
    "Microsoft.Extensions.Logging.Console": "1.0.0",  
    "Microsoft.AspNetCore.Mvc": "1.0.0"  
    },  


To uninstall, go to Solution explorer > right click on package > Uninstall package.


Tools: This section manages and lists command line tools. We can see IISIntegration.Tools is added by default, which is a tool that contains dotnet publish iis command for publishing the Application on IIS.
    "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  
    },  


Frameworks: As we can see, initially our app is running on the .NET Core platform by default with the runtime.
    “netcoreapp1 .0”.  
    "frameworks": {  
        "netcoreapp1.0": {  
            "imports": ["dotnet5.6", "portable-net45+win8"]  
        }  
    },
 

Build Options: Options, which are passed to the compiler while building the Application.
    "buildOptions": {  
        "emitEntryPoint": true,  
        "preserveCompilationContext": true  
    },  


RuntimeOptions: Manage Server garbage collection at Application runtime.
    "runtimeOptions": {  
        "configProperties": {  
            "System.GC.Server": true  
        }  
    },  


PublishOptions: This defines the file/folder to include/exclude to/from the output folder, while publishing the Application.
    "publishOptions": {  
        "include": ["wwwroot", "web.config"]  
    },  


Scripts: Scripts is an object type, which specifies that scripts run during building or publishing the Application.
    "scripts": {  
        "postpublish": ["dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"]  
    }  


Add MVC6
It’s time to add MVC6. In .NET Core 1.0 MVC & Web API are unified, and become a single class, which inherits from the same base class.

Let’s add MVC Service to our Application. Open project.json to add new dependencies in it. In dependencies section, add two dependencies.
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0"


Click Save.

It will start restoring the packages automatically.


Now let’s add MVC (midleware) to request pipeline in Config method at startup class.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {  
        loggerFactory.AddConsole();  
        if (env.IsDevelopment()) {  
            app.UseDeveloperExceptionPage();  
        }  
        //app.UseStaticFiles();  
        app.UseMvc(routes => {  
            routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
        });  
    }  


In ConfigureServices method, we need to add framework Service. We have added services.AddMvc();
    public void ConfigureServices(IServiceCollection services) {  
        services.AddMvc();  
    }  

MVC Folder Structure

Let’s add MVC folder structure to our sample Application. We have added view files in the views folder & MVC controller in Controllers folder like old MVC Application.

Here, you may notice that there is a new file in the views folder “_ViewImports.cshtml”. This file is responsible for setting up the namespaces, which can be accessed by the views in the project, which was previously done by the Web.config file in the views folder.

We are almost done. Let’s modify our view content with welcome message. Now, run the Application. You can see welcome message appears in the home page.

Output

AngularJS2
AngularJS2 is a modern Client end JavaScript Framework for the Application development. This JavaScript framework is totally new & written, based on TypeScript.

We will follow the steps, given below, to learn, how we install it to our Application,
    Manage Client-side Dependencies
    Use Package Manager (NPM).
    Use Task Runner.
    Bootstrapping using Type Script.

Client-side Dependencies: We need to add a JSON config file for Node Package Manager(NPM). Click add > New Item > Client- Side > npm Configuration File and click OK.


Open our newly added npm config file and modify the initial settings.

Package.json
    {  
        "version": "1.0.0",  
        "name": "asp.net",  
        "private": true,  
        "Dependencies": {  
            "angular2": "2.0.0-beta.9",  
            "systemjs": "0.19.24",  
            "es6-shim": "^0.33.3",  
            "rxjs": "5.0.0-beta.2"  
        },  
        "devDependencies": {  
            "gulp": "3.8.11",  
            "gulp-concat": "2.5.2",  
            "gulp-cssmin": "0.1.7",  
            "gulp-uglify": "1.2.0",  
            "rimraf": "2.2.8"  
        }  
    }  

In the dependencies section, we need to add AngularJS2 with other dependencies and they are for:
    Es6-shim is a library, which provides compatibility on old environment.
    Rxjs provides more modular file structure in a variety of formats.
    SystemJS enables System.import TypeScript files directly.

As you can see, there are two different type objects; one is dependencies, which are used for the production purposes & the other one is devDependencies for development related things, like gulp is to run different tasks.

Click save. It will restore automatically. Here, we have all our required packages in the Dependencies section.


In this application we have added another package manager called Bower, Click add > New Item > Client- Side > Bower Configuration File then click Ok.

Comparing with NPM,
Bower:
    Manage html, css, js component
    Load minimal resources
    Load with flat dependencies

NPM:
    Install dependencies recursively
    Load nested dependencies
    Manage NodeJS module

Open the config file then add required dependencies in dependencies secction with specific version.

Save the JSON file after edit, it will automatically restore that package in our project. Here you can see we have added Jquery & Bootstrap package with Bower package manager.

Now, let’s add a gulp configuration file to run the task. Click Add > New Item > Client-Side. Select gulp JSON file to include.

 

Gulp.json
    /*
    This file in the main entry point for defining Gulp tasks and using Gulp plugins.
    Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
    */  
    "use strict";  
    var gulp = require("gulp");  
    var root_path = {  
        webroot: "./wwwroot/"  
    };  
    //library source  
    root_path.nmSrc = "./node_modules/";  
    //library destination  
    root_path.package_lib = root_path.webroot + "lib-npm/";  
    gulp.task("copy-systemjs", function() {  
        return gulp.src(root_path.nmSrc + '/systemjs/dist/**/*.*', {  
            base: root_path.nmSrc + '/systemjs/dist/'  
        }).pipe(gulp.dest(root_path.package_lib + '/systemjs/'));  
    });  
    gulp.task("copy-angular2", function() {  
        return gulp.src(root_path.nmSrc + '/angular2/bundles/**/*.js', {  
            base: root_path.nmSrc + '/angular2/bundles/'  
        }).pipe(gulp.dest(root_path.package_lib + '/angular2/'));  
    });  
    gulp.task("copy-es6-shim", function() {  
        return gulp.src(root_path.nmSrc + '/es6-shim/es6-sh*', {  
            base: root_path.nmSrc + '/es6-shim/'  
        }).pipe(gulp.dest(root_path.package_lib + '/es6-shim/'));  
    });  
    gulp.task("copy-rxjs", function() {  
        return gulp.src(root_path.nmSrc + '/rxjs/bundles/*.*', {  
            base: root_path.nmSrc + '/rxjs/bundles/'  
        }).pipe(gulp.dest(root_path.package_lib + '/rxjs/'));  
    });  
    gulp.task("copy-all", ["copy-rxjs", 'copy-angular2', 'copy-systemjs', 'copy-es6-shim']);  


To run the task, right click on Gulp.json file to reload.

Right click on copy-all & click run.

Task run & finish.

In Solution Explorer, all the required packages are copied. We also need to put the type definitions for es6-shim(typing folder), without this, it will cause error - "Cannot find name 'Promise'".

Bootstrapping with TypeScript

tsConfig.json
    {  
        "compilerOptions": {  
            "noImplicitAny": false,  
            "noEmitOnError": true,  
            "removeComments": false,  
            "sourceMap": true,  
            "target": "es5",  
            //add this to compile app component  
            "emitDecoratorMetadata": true,  
            "experimentalDecorators": true,  
            "module": "system",  
            "moduleResolution": "node"  
        },  
        "exclude": ["node_modules", "wwwroot/lib"]  
    }  


noImplicitAny : Raise an error on the expressions and declarations with an implied ‘any’ type.
noEmitOnError : Do not emit outputs, if any errors were reported.
Target : Specify ECMAScript target version: ‘es5’ (default), ‘es5’, or ‘es6’.
experimentalDecorators : Enables an experimental support for ES7 decorators.

Create an app folder for .ts file in wwwroot folder.


In Solution Explorer, you may add the files, given below.

In main.ts code snippet, bootstrap AngularJS with importing the component.

    import {bootstrap} from 'angular2/platform/browser';  
    import {AppComponent} from './app.component';  
    import {enableProdMode} from 'angular2/core';  
      
    enableProdMode();  
    bootstrap(AppComponent);  


Component: imports the Component function from Angular 2 library; use of import, app component class can be imported from other component.
import {Component} from 'angular2/core';

    @Component({  
        selector: 'core-app',  
        template: '<h3>Welcome to .NET Core 1.0 + MVC6 + Angular 2</h3>'  
    })  
    export class AppComponent {}  


MVC View: It’s time to update our layout & linkup the library.


Now, we will add the reference to our layout page.
    <!DOCTYPE html>  
    <html>  
      
    <head>  
        <meta name="viewport" content="width=device-width" />  
        <title>@ViewBag.Title</title>  
        <script src="~/lib-npm/es6-shim/es6-shim.js"></script>  
        <script src="~/lib-npm/angular2/angular2-polyfills.js"></script>  
        <script src="~/lib-npm/systemjs/system.src.js"></script>  
        <script src="~/lib-npm/rxjs/Rx.js"></script>  
        <script src="~/lib-npm/angular2/angular2.js"></script>  
    </head>  
      
    <body>  
        <div> @RenderBody() </div> @RenderSection("scripts", required: false) </body>  
      
    </html> Index.cshtml @{ ViewData["Title"] = "Home Page"; }  
    <core-app>  
        <div>  
            <p><img src="~/img/ajax_small.gif" /> Please wait ...</p>  
        </div>  
    </core-app> @section Scripts {  
    <script>  
        System.config({  
            packages: {  
                'app': {  
                    defaultExtension: 'js'  
                }  
            },  
        });  
        System.import('app/main').then(null, console.error.bind(console));  
    </script> }  


One more thing to do is to enable the static file serving. Add this line to startup config method.
app.UseStaticFiles();

Build & run application

Finally, build & run the Application.

Here, we can see our app is working with AngularJS2.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Generate QR Code In ASP.NET Core MVC

clock January 24, 2023 10:16 by author Peter

In this article, we are going to create an ASP.Net Core MVC application that generates QR Code for different purposes like Email, Website, Bookmark Websites, SMS, WhatsApp, etc. For this, we are going to use NuGet package called QRCoder.

About QRCoder NuGet Package
QRCoder is a simple library, written in C#.NET, which enables you to create QR codes. It hasn't any dependencies on other libraries and is available as .NET Framework and .NET Core PCL version on NuGet.

QRCoder provides many types of QR Codes but in this article, I will use only the following types.

    URL
    Bookmark Website
    Send SMS
    Send WhatsApp Message
    Compose Email
    Connect To WIFI

Create ASP.Net Core MVC project.

Step 1
Open Visual Studio and click on Create New Project.

Step 2
Select ASP.NET CORE Web App (Model-View-Controller) Template as shown in the below image and click on next button.

Step 3
Configure your project by specifying the name of the project and the location where you want to save your project.

Step 4
Select the version of the .Net Core framework you want to use and click on create button.
Add New Controller

Step 1
Right Click on Controller Folder then click on Add then Controller.

Step 2
Select MVC Empty Controller. And give a name whatever you want here I gave QRCode.


Add NuGet Package
Step 1
Right click on your project and then click on Manage NuGet Packages.

Step 2
Search for QRCoder in browse tab.

Step 3
Click on the install button and it will install in your project.

Create a new Model Class
For transferring data from controller to view and view to controller we have to use model class.

Step 1

For creating a model right click on the Model folder and click on Add then class.

Step 2
Give a suitable name for your class, Here I gave QRCodeModel.

Step 3
Create required properties in your class. As you can see in the below code I have created different properties for different types of QR Codes.
public class QRCodeModel {
    public int QRCodeType {
        get;
        set;
    }
    public string QRImageURL {
        get;
        set;
    }
    //for bookmark qr code
    public string BookmarkTitle {
        get;
        set;
    }
    public string BookmarkURL {
        get;
        set;
    }
    // for email qr codes
    public string ReceiverEmailAddress {
        get;
        set;
    }
    public string EmailSubject {
        get;
        set;
    }
    public string EmailMessage {
        get;
        set;
    }
    //for sms qr codes
    public string SMSPhoneNumber {
        get;
        set;
    }
    public string SMSBody {
        get;
        set;
    }
    //for website
    public string WebsiteURL {
        get;
        set;
    }
    // for whatsapp qr message code
    public string WhatsAppNumber {
        get;
        set;
    }
    public string WhatsAppMessage {
        get;
        set;
    }
    // for wifi qr code
    public string WIFIName {
        get;
        set;
    }
    public string WIFIPassword {
        get;
        set;
    }
}


Design View

Step 1
Create an action method in your controller as you want. Here I used the index action method.

Step 2

Right-click on the action method and click on Add View to add a new view.

Step 3
Return the model from the controller which you have created. If you want to pass some extra data you can pass it. Here as you see in the below code I just created object of model and pass that model to view.
public IActionResult Index() {
    QRCodeModel model = new QRCodeModel();
    return View(model);
}


Step 4
Design your view as per your requirements.
@model QRCodeModel
@{
    ViewData["Title"] = "Generate QR Code";
}

<form asp-action="Index">

    <div class="row mt-2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Select QR Code Type</label>
            <select asp-for="QRCodeType" id="QRCodeType" class="form-control" onchange="onQRCodeTypeChange()">
                <option value="1">Website</option>
                <option value="2">Bookmark URL</option>
                <option value="3">SMS</option>
                <option value="4">WhatsApp</option>
                <option value="5">Email</option>
                <option value="6">WIFI</option>
            </select>
        </div>
    </div>

    <!--  Website  -->
    <div class="row mt-2 hideDiv" id="DIV1">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Enter your website URL</label>
            <input autocomplete="off" type="url" asp-for="WebsiteURL" class="form-control" />
        </div>
    </div>

    <!-- Book Mark URL   -->
    <div class="row mt-2 hideDiv" id="DIV2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Enter your URL</label>
            <input type="url" asp-for="BookmarkURL" class="form-control" autocomplete="off" />
        </div>
    </div>

    <!--  SMS  -->
    <div id="DIV3" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Phone Number with country code(eg. +91)</label>
                <input type="text" asp-for="SMSPhoneNumber" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter your Message</label>
                <textarea asp-for="SMSBody" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--  Whats App Message  -->
    <div id="DIV4" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WhatsApp Number with country code(eg. +91)</label>
                <input type="text" asp-for="WhatsAppNumber" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter your Message</label>
                <textarea asp-for="WhatsAppMessage" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--  Compose Email  -->
    <div id="DIV5" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Receive's Email Address</label>
                <input type="text" asp-for="ReceiverEmailAddress" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Email Subject</label>
                <input type="text" asp-for="EmailSubject" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Email Message</label>
                <textarea asp-for="EmailMessage" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--   WIFI   -->
    <div id="DIV6" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WIFI Name</label>
                <input type="text" asp-for="WIFIName" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WIFI Password</label>
                <input type="text" asp-for="WIFIPassword" class="form-control" autocomplete="off" />
            </div>
        </div>
    </div>

    <div class="row mt-2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <button type="submit" class="btn btn-primary">Generate</button>
            <button type="reset" class="btn btn-secondary">Reset</button>
        </div>
    </div>

    @if (!string.IsNullOrEmpty(Model.QRImageURL))
    {
        <div class="row mt-2" id="qrCodeImage">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <img height="250" width="250" src="@Model.QRImageURL" />
            </div>
        </div>
    }

</form>

@section Scripts{

    <script>
        $(document).ready(function () {
            $("#QRCodeType").trigger("change");
        });

        function onQRCodeTypeChange() {
            let qrcodeType = $("#QRCodeType").val();
            $(".hideDiv").hide();
            $("#DIV" + qrcodeType).show();
        }
    </script>
}


Code Explanation
As you can see in the above HTML code I created inputs as per my properties.

Here I add drop-down for QR Code type and based on that type I show and hide DIV of codes.
<div class="row mt-2">
  <div class="col-lg-6 col-md-6 col-sm-12">
    <label>Select QR Code Type</label>
    <select asp-for="QRCodeType" id="QRCodeType" class="form-control" onchange="onQRCodeTypeChange()">
      <option value="1">Website</option>
      <option value="2">Bookmark URL</option>
      <option value="3">SMS</option>
      <option value="4">WhatsApp</option>
      <option value="5">Email</option>
      <option value="6">WIFI</option>
    </select>
  </div>
</div>

For different types of QR Codes, I have created different div and gave an id to that div same as I gave the value in dropdown. Also gave same class name to all div.

At bottom, there are two buttons for submitting and resetting page.

Below button, there is an image that shows QR Code Image when the view return from controller after generating QR Code. Here we directly pass QR Code Image as base64 string instead of saving image and then show it on view side.
@if (!string.IsNullOrEmpty(Model.QRImageURL))
{
    <div class="row mt-2" id="qrCodeImage">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <img height="250" width="250" src="@Model.QRImageURL" />
        </div>
    </div>
}


At last, there is JavaScript code in the Scripts section which contain a function called onQRCodeTypeChange which gets value of QR Code Type drop-down then hide all the divs and only show which has id same as drop down value.
function onQRCodeTypeChange() {
    let qrcodeType = $("#QRCodeType").val();
    $(".hideDiv").hide();
    $("#DIV" + qrcodeType).show();
}


On the document ready event I triggered the change event of QR Code type drop-down.
$(document).ready(function() {
    $("#QRCodeType").trigger("change");
});

Code for Generate QR Code
Create post action method in your controller to post data from form. In this method, we are going to generate QR Code as per its type.
[HttpPost]
public IActionResult Index(QRCodeModel model) {
    Payload payload = null;
    switch (model.QRCodeType) {
        case 1: // website url
            payload = new Url(model.WebsiteURL);
            break;
        case 2: // bookmark url
            payload = new Bookmark(model.BookmarkURL, model.BookmarkURL);
            break;
        case 3: // compose sms
            payload = new SMS(model.SMSPhoneNumber, model.SMSBody);
            break;
        case 4: // compose whatsapp message
            payload = new WhatsAppMessage(model.WhatsAppNumber, model.WhatsAppMessage);
            break;
        case 5: //compose email
            payload = new Mail(model.ReceiverEmailAddress, model.EmailSubject, model.EmailMessage);
            break;
        case 6: // wifi qr code
            payload = new WiFi(model.WIFIName, model.WIFIPassword, WiFi.Authentication.WPA);
            break;
    }
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeData qrCodeData = qrGenerator.CreateQrCode(payload);
    QRCode qrCode = new QRCode(qrCodeData);
    var qrCodeAsBitmap = qrCode.GetGraphic(20);
    // use this when you want to show your logo in middle of QR Code and change color of qr code
    //Bitmap logoImage = new Bitmap(@"wwwroot/img/Virat-Kohli.jpg");
    //var qrCodeAsBitmap = qrCode.GetGraphic(20, Color.Black, Color.Red, logoImage);
    string base64String = Convert.ToBase64String(BitmapToByteArray(qrCodeAsBitmap));
    model.QRImageURL = "data:image/png;base64," + base64String;
    return View("Index", model);
}
private byte[] BitmapToByteArray(Bitmap bitmap) {
    using(MemoryStream ms = new MemoryStream()) {
        bitmap.Save(ms, ImageFormat.Png);
        return ms.ToArray();
    }
}

Step 1
Create a new object of QRCodeGenerator class.
QRCodeGenerator qrGenerator = new QRCodeGenerator();

Step 2

Call the CreateQrCode method using this object and pass payload in its constructor. Payload is an object of PayloadGenerator.Payload type. There are different payload types as per QR Code types. We will discuss different types of payload later in this article.
QRCodeData qrCodeData = qrGenerator.CreateQrCode(payload);

Step 3
Create object of QRCode type and Pass QR Data object to its constructor.
QRCode qrCode = new QRCode(qrCodeData);

Step 4
Call GetGraphic method of this QR Code object which take one integer parameter which define pixels per module.
var qrCodeAsBitmap = qrCode.GetGraphic(20);

There are also some overloaded methods using which you can change the color of QR Code and also set logo in QR Code.
// use this when you want to show your logo in middle of QR Code and change color of qr code
Bitmap logoImage = new Bitmap(@"wwwroot/img/Peter.jpg");
var qrCodeAsBitmap = qrCode.GetGraphic(20, Color.Black, Color.Red, logoImage);

Step 5
GetGraphic method return bitmap image as return type. You can save this image in your local path but here I convert this bitmap image to byte array and then convert this byte array to base64 string which I’m going to bind in QRImageURL property and pass it to the view so user can view this QR Code.
string base64String = Convert.ToBase64String(BitmapToByteArray(qrCodeAsBitmap));
model.QRImageURL = "data:image/png;base64," + base64String;

For converting bitmap to byte first convert it to memory stream and then get byte array from this stream in user define method BitmapToByteArray. As you can see in below code.
private byte[] BitmapToByteArray(Bitmap bitmap) {
    using(MemoryStream ms = new MemoryStream()) {
        bitmap.Save(ms, ImageFormat.Png);
        return ms.ToArray();
    }
}


Step 6
Return view data after generating QR Code so user can see Generated QR Code in their browser.
Followings are different payload type which is used in this article.
Payload payload = null;

URL Payload
To generate QR Code that opens URL or any Website QRCoder provider payload type of URL class.

This class takes one argument in its constructor which is URL of website.
payload = new Url(model.WebsiteURL);

Bookmark Payload
To generate QR Code for bookmark type we have to Use Bookmark payload.
Bookmark class’s constructor takes two parameters first is the URL of the website and second is the title of the bookmark.
payload = new Bookmark(model.BookmarkURL, model.BookmarkURL);

SMS Payload

To generate QR Code for composing SMS we have to pass payload of SMS type. QR Code provider SMS class for this type of payload.

SMS class’s constructor takes two parameters first is phone number to whom you want to send the SMS and the second is the message you want to send. Message parameter s optional you can only pass phone number to it.
payload = new SMS(model.SMSPhoneNumber, model.SMSBody);

WhatsApp Message Payload
To generate QR Code that send WhatsApp message we have to pass WhatsAppMessage payload. QRCoder provides WhatsAppMessage class to generate payload.
WhatsAppMessage provides two overloaded methods one only takes one parameter which is message only and second takes two parameter WhatsApp number and message both.
payload = new WhatsAppMessage(model.WhatsAppNumber, model.WhatsAppMessage);

Mail Payload
To generate QR Code which compose email we have to use MAIL payload.

Mail class’s constructor does not required any parameter. It’s all parameters are by default set to null. But here we are going to pass receiver email address, Subject, and body of mail.
payload = new Mail(model.ReceiverEmailAddress, model.EmailSubject, model.EmailMessage);

WiFi Payload
To generate QR Code which connect to WIFI we have to pass data in WIFI payload.
WiFi class’s constructor takes three required parameter wifi name, wifi password, and authentication mode (WEP, WPA, nopass). You can pass any theme but mostly WPA is used in all wifi so here I by default set it.
payload = new WiFi(model.WIFIName, model.WIFIPassword, WiFi.Authentication.WPA);



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Folder Structure Of ASP.NET Core MVC 6.0 Project

clock January 20, 2023 06:25 by author Peter

In this article, I am going to explain to you, the default folder structure of an ASP.NET Core MVC 6.0 web application and describe the purpose of each folder. In my previous article, we created an empty ASP.NET Core MVC 6.0 Project and the structure of the project as shown in the following image.

Let’s start exploring each folder and file that exists in the Project Structure for easy understanding.

Project Folder Structure Description
The details of the default project structure can be seen in the solution explorer, it displays all the projects related to a single solution.


.csproj File

Double click on the project name in Solution Explorer to open .csproj file in the editor. Right-click on the project and then click on Edit Project File in order to edit the .csproj file. As shown in the following image.

Once clicked on Edit Project File, .csproj file will be opened in Visual Studio as shown below.

As you can see the project’s SDK is Microsoft.NET.Sdk.Web. The target framework is net6.0 indicating that we are using .NET 6. Notice the Nullable and ImplicitUsings elements.
The <Nullable> elements decide the project wide behaviour of Nullable of Nullable reference types. The value of enable indicates that the Nullable reference types are enabled for the project.

The < ImplicitUsings > element can be used to enable or disable. When < ImplicitUsings > is set to enable, certain namespaces are implicitly imported for you.

Connected Services
It contains the details about all the service references added to the project. A new service can be added here, for example, if you want to add access to Cloud Storage of Azure Storage you can add the service here. As shown in the following image.

Dependencies
The Dependencies node contains all the references of the NuGet packages used in the project. Here the Frameworks node contains reference two most important dotnet core runtime and asp.net core runtime libraries. Project contains all the installed server-side NuGet packages, as shown below.


Properties
Properties folder contains a launchSettings.json file, which containing all the information required to lunch the application. Configuration details about what action to perform when the application is executed and contains details like IIS settings, application URLs, authentication, SSL port details, etc.

 

WWWroot
This is the webroot folder and all the static files required by the project are stored and served from here. The webroot folder contains a sub-folder to categorize the static file types, like all the Cascading Stylesheet files, are stored in the CSS folder, all the javascript files are stored in the js folder and the external libraries like bootstrap, jquery are kept in the library folder.

Generally, there should be separate folders for the different types of static files such as JavaScript, CSS, Images, library scripts, etc. in the wwwroot folder as shown below.

Controllers
Controller handles all the incoming requests. All the controllers needed for the project are stored here. Controllers are responsible for handling end user interaction, manipulating the model and choose a view to display the UI. Each controller class inherits a Controller class or ControllerBase class. Each controller class has “Controller” as a suffix on the class name, for example, the default “HomeController.cs” file can be found here. As shown below.

Models
A Model represents the data of the application and a ViewModel represents data that will be displayed in the UI. The models folder contains all the domain or entity classes. Please note user can add folders of his choice to create logical grouping in the project.

Views
A view represents the user interface that displays ViewModel or Model data and can provide an option to let the user modify them. Mostly a folder in name of the controller is created and all the views related to it are stored in it. Here HomeController related view Index.cshtml and Privacy.cshtml is stored in Home folder and all the shared view across the application is kept in Shared folder. Under this shared folder there are _Layout.cshtml, _ValidationScriptsPartial.cshtml and Error.cshtml view files. There are two more view files, _ViewImports.cshtml and _ViewStart.cshtml under the view folder.

appsettings.json
This file contains the application settings, for example, configuration details like logging details, database connection details.


Program.CS
This class is the entry point of the web application. It builts the host and executes the run method.

I hope the article helped you to understand ASP.NET Core MVC 6.0 Project Structure.

Conclusion
In this article we explained, the folder structure of ASP.NET Core MVC 6.0 application. I hope this article is useful to understand.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Pass Data Across Views In .NET MVC

clock January 10, 2023 06:17 by author Peter

In previous articles, we discussed both View Variables in ASP.NET MVC and View Variables in ASP.NET Core MVC, respectively.  Although each has some distinctive points, both share a lot of common features. In this article, we will discuss something new: pass data across views. We will also summarize some common or important shared features for various vew variables.


A: Brief Summary of ViewData
We will start our discussion from ViewData, but most or all features are the same for other MVC View Variables. The ASP.NET Core also has the same features. So, we will discuss ViewData in the most, and have the last part to see the extension to other View variables.

A - 1: MVC Data Passing Techniques
This is a different approach to summarize the MVC Data Passing Techniques from Data Passing Techniques in ASP.NET Core (dotnettricks.com). We will not repeat the conclusion here, but we can go to the page to learn the different approaches or understanding.

B: Type of ViewData
We have discussed ViewData, ViewBag, TempData, Session type features. They are all the Type of Dictionary:

Where the difference between ViewBag and ViewData:


Besides ViewBag, all other View Variables need to be cast before using. We define a ViewData named "book": as type BookModel with data such as Id = 1:


When we retrieve data, we have to cast the data back to the data type. Otherwise, we will get an error message:


After casting:

C: Pass Data into _Layout.cshtml Page by ViewData
The _layout.cshtml is a shared page by other specific views. It belongs to no Controller or Action, or we can say it belongs to every Controller or Action when the related view is using _layout.cshtml. Therefore, we can pass data into Layout either from the Controller or Action view, which uses the _layout.cshtml, such as, if we have a Contact Us Action:

Or, we can define the ViewData from the Contact Us View:

Both ways will pass the data into Layout page:

Notes
1, We usually introduce the Layout into View by the code in the View as below:

2, in some cases, if we want to make the Layout page(s) dynamic, we can assign the layout to the view through Controller/Action:

3, A related important shared concept for MVC, _Viewstat.cshtml

D: Pass Data into _Layout.cshtml Page by Other View Variables
The same is true for other MVC View Variables, such as ViewBag, TempData, and absolutely Session variable:


Pass TempData to Layout:

Pass ViewData to Layout:

Pass ViewBag to Layout:

This article discussed using ASP.NET MVC ViewData to pass data into Layout View through either Controller or View.  The features are available or the same as other View Variables in ASP.NET MVC, and the same is true for ASP.NET Core MVC.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: CRUD Operation With Dapper Using ASP.NET Core 6 MVC

clock December 6, 2022 08:03 by author Peter

In this article will learn CURD (Create, Update, Read and Delete) operation which is common for most web applications. Here will understand SQL Database, Dapper Micro-ORM (Object Relation Mapper) along with repository pattern using ASP.NET Core 6 MVC.


What is Dapper?
Dapper is a micro ORM or it is a simple object mapper framework that helps to map the native query output to a domain class.
Creating a New Project in Visual Studio 2022

Start Visual Studio software and select Create a new project.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.

In the Configure your new project dialog, enter CURDWithDapperCore6MVC_Demo for Project name. It's important to name the project CURDWithDapperCore6MVC_Demo. The capitalization needs to match each namespace when code is copied. Select Next.

In the Additional information dialog, select .NET 6.0 (Long-term support). Select Create

The Visual Studio project 2022 will now generate the structure for the selected application. In this example, we are using ASP.Net MVC so we can create a controller to write the code, or so we can use the existing controller. There you can enter the code and build/run the application.
Install the Dapper, Microsoft.Data.SqlClient Library through NuGet Package Manager

The Visual Studio software provides the NuGet Package manager option to install the package directly to the solution.

In Visual Studio Select Tools > NuGet Package Manager > Manage NuGet Packages for the solution. The below screenshot shows how to open the NuGet Package Manager.

Search for the specific package Dapper, Microsoft.Data.SqlClient using the search box on the upper left. Select a package from the list to display its information, enable the Install button and a version-selection drop-down, as shown in the below screenshot. The NuGet package will be installed for your project and reference will be added, as seen in the screenshot below.

In the above image, we can see the list of the related search items. We need to select the required option to install the package to the solution.

Add Connection String
In solution explorer select a file appsettings.json double click on this file to open "Add" connection string as shown below.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=Companies-DB;Integrated Security=True;Pooling=False;Encrypt=false"
  }
}


Add Models class
Right-click the Models folder > Add > Class. Name the file Company.cs
using System.ComponentModel.DataAnnotations;

namespace CURDWithDapperCore6MVC_Demo.Models
{
    public class Company
    {
        public int Id { get; set; }
        [Display(Name ="Company Name")]
        public string CompanyName { get; set; }

        [Display(Name = "Company Address")]
        public string CompanyAddress { get; set; }

        public string Country { get; set; }

        [Display(Name = "Glassdoor Rating")]
        public int GlassdoorRating { get; set; }
    }
}


Add DBContext Folder and DapperContext Class
Right click on Project in Solution Explorer>Add New>New Folder. Rename this folder to DBContext. Now right click on DBContext folder > Add> New Item> C# class name this class DapperContext.

using Microsoft.Data.SqlClient;
using System.Data;

namespace CURDWithDapperCore6MVC_Demo.DBContext
{
    public class DapperContext
    {
        private readonly IConfiguration _configuration;
        private readonly string _connectionString;
        public DapperContext(IConfiguration configuration)
        {
            _configuration = configuration;
            _connectionString = _configuration.GetConnectionString("DefaultConnection");
        }
        public IDbConnection CreateConnection() => new SqlConnection(_connectionString);
    }
}


Add Repositories Folder and ICompanyRepository Interface

Right click on Project in Solution Explorer>Add New>New Folder. Rename this folder to Repositories. Now right click on DBContext folder > Add> New Item>C# Interface and name this interface ICompanyRepository.
using CURDWithDapperCore6MVC_Demo.Models;

namespace CURDWithDapperCore6MVC_Demo.Repositories
{
    public interface ICompanyRepository
    {
        Task<IEnumerable<Company>> GetCompanies();
        Task<Company> GetCompany(int? id);
        Task CreateCompany(Company company);
        Task UpdateCompany(int id, Company company);
        Task DeleteCompany(int id);
    }
}


Add Company Repository class to Implement Interface

Right click on Repositories Add> New Item>C# class and name this class to CompanyRepository.
using CURDWithDapperCore6MVC_Demo.DBContext;
using CURDWithDapperCore6MVC_Demo.Models;
using Dapper;
using System.Data;

namespace CURDWithDapperCore6MVC_Demo.Repositories
{
    public class CompanyRepository : ICompanyRepository
    {
        private readonly DapperContext context;

        public CompanyRepository(DapperContext context)
        {
            this.context = context;
        }

        public async Task<IEnumerable<Company>> GetCompanies()
        {
            var query = "SELECT * FROM Companies";

            using (var connection = context.CreateConnection())
            {
                var companies = await connection.QueryAsync<Company>(query);
                return companies.ToList();
            }
        }

        public async Task<Company> GetCompany(int? id)
        {
            var query = "SELECT * FROM Companies WHERE Id = @Id";

            using (var connection = context.CreateConnection())
            {
                var company = await connection.QuerySingleOrDefaultAsync<Company>(query, new { id });
                return company;
            }
        }

        public async Task CreateCompany(Company company)
        {
            var query = "INSERT INTO Companies (CompanyName, CompanyAddress, Country,GlassdoorRating) VALUES (@CompanyName, @CompanyAddress, @Country, @GlassdoorRating)";

            var parameters = new DynamicParameters();
            parameters.Add("Name", company.CompanyName, DbType.String);
            parameters.Add("Address", company.CompanyAddress, DbType.String);
            parameters.Add("Country", company.Country, DbType.String);
            parameters.Add("Country", company.GlassdoorRating, DbType.Int32);

            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, parameters);
            }
        }

        public async Task UpdateCompany(int id, Company company)
        {
            var query = "INSERT INTO Companies (CompanyName, CompanyAddress, Country,GlassdoorRating) VALUES (@CompanyName, @CompanyAddress, @Country, @GlassdoorRating WHERE Id = @Id)";
            var parameters = new DynamicParameters();
            parameters.Add("Name", company.CompanyName, DbType.String);
            parameters.Add("Address", company.CompanyAddress, DbType.String);
            parameters.Add("Country", company.Country, DbType.String);
            parameters.Add("Country", company.GlassdoorRating, DbType.Int32);
            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, parameters);
            }
        }
        public async Task DeleteCompany(int id)
        {

            var query = "DELETE FROM Companies WHERE Id = @Id";
            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, new { id });
            }
        }
    }
}

Add a controller
In Solution Explorer, right-click Controllers > Add > Controller.
In the Add New Scaffolded Item dialog box, select MVC Controller – MVC Controller with read/write actions > Add.
In the Add New Item - Companies dialog, enter CompaniesController.cs and select Add.
Replace the contents of Controllers/ CompaniesController.cs with the following code:

Add a view

Right-click on the Action in CompaniesController, and then Add View.
In the Add New Scaffolded Item dialog:
    Select Razor View Select Add
    View Name: Index
    Template: List
    Model Class: Company
    Select Add

Replace the contents of the Views/Companies/Index.cshtml Razor view file with the following:
@model IEnumerable<CURDWithDapperCore6MVC_Demo.Models.Company>

@{
    ViewData["Title"] = "Index";
}

<h2 class="text-capilization text-center">List of Companies</h2>

<p>
    <a asp-action="Create" class="btn btn-primary"> <i class="fa-solid fa-circle-plus"></i> Add New</a>
</p>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Id)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CompanyName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CompanyAddress)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Country)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GlassdoorRating)
            </th>
            <th>Action(s)</th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyAddress)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Country)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.GlassdoorRating)
            </td>
            <td>
                 <a href="@Url.Action("Details",new { id=item.Id})" class="btn btn-sm btn-primary"><i class="fa-solid fa-eye"></i></a>
                 <a href="@Url.Action("Edit",new { id=item.Id})" class="btn btn-sm btn-info"><i class="fa-solid fa-pen-to-square"></i></a>
                 <a href="@Url.Action("Delete",new { id=item.Id})" class="btn btn-sm btn-danger"><i class="fa-solid fa-trash"></i></a>
            </td>
        </tr>
}
    </tbody>
</table>

Note: Similarly Add all action view like Details, Create, Edit and Delete
Now its time to build and run your application Ctrl+F5

 

The above article has taught us. How we can use dapper with repository pattern. Dapper is Micro ORM whereas Entity Framework is ORM. Dapper is faster than entity framework. Hope you enjoyed the article. Happy Coding.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Working With Areas In MVC

clock November 30, 2022 07:27 by author Peter

The primary purpose of areas in MVC is to separate and manage Model, View, Controller, Themes and routing registration file into separate sections. In other words, areas serve as a technique for dividing and managing a large Application into well managed smaller modules with the separate M-V-C in each module.


Why to use areas in MVC Application?
If you are building a CRM Application for a small Educational Consultancy with multiple business units such as Registration on Arrival, Information Gathering by Receptionist, Updates by Consular, Documentation Management, Interview Preparation, Billing, and Report Generation by different departments etc. Each of these units have their own logical components views, controllers and models. In this scenario, you can use ASP.NET MVC areas to physically partition the business components in the same project.

It is also possible that we can have large projects that uses MVC, then we need to split the Application into smaller units called areas that isolates the larger MVC Application into smaller functional groupings. A MVC Application can contain several MVC structures (areas).

Areas are the small functional units with its own set of Model, View and Controller

    MVC Application can have any number of areas.
    Each area has its own controllers, models and views.
    Areas are put under separate folders called areas.

Today, we will be creating a new ASP.NET MVC Application and define a new area inside the project.

Creating new MVC Application


Step 1
Open Visual Studio.

Step 2
Create an ASP.NET Web Application with MVC template, as shown below.

Step 3
In Solution Explorer, right-click on the project and click Add. Select areas to add an area.

Step 4
Enter the name for the area, such as "Consular" or “SuperAdmin”.

Adding Controller for Area
Now, let’s add a controller in Area.

Step 1
Right-click on the Controller in your article area to add a controller.

Step 2
Select "MVC 5 Empty Controller.


Step 3
Provide controller name as "ManageInterviewController”. Now, your Area folder should look, as shown below.

Adding Views for Area
We have successfully added a controller for our area. Now, let’s add a view for the area.

Step 1
Right-click on the "Index" method of ManageInterviewConsular Controller and click on Add View.

Step 2
Enter the view name and select Layout page.

Step 3
Generate some content in the View of Index method, as shown below.


Index g (table table-hover table-bordered table-responsive" >Time< /tr>Kathmandu< /tr> " "picture_x0020_6"="">
 
Area Registration
Step 1
Open the "Global.asax" file.

Step 2
Add the code given below in your Application_Start() method.

AreaRegistration.RegisterAllAreas();


Till here, we have successfully added an area. Inside Area is the one, where we have added aController and a View for Index method.
Now, let’s add a link in Navbar of an Application to navigate to the view, which we created just now.

Step 1
Open the project view Layout file.

Step 2
Modify the <ul> </ul> in the layout file, as shown in the code given below.

Step 3
Debug the Application and open List Interview link, as shown below.

Let’s notice the URL
As highlighted, to invoke the controller of the area, we need to use

Baseurl/Areaname/Controller/{actionname}




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Single Sign-On Using ASP.NET MVC And ASP.NET Core

clock November 21, 2022 07:28 by author Peter

What is single sign-on (SSO)?
Users must authenticate themselves to access pages protected by a web application, and if a user accesses multiple web applications, they must be authenticated. You must log in to each application separately.

Single Sign-on using ASP.NET MVC and ASP.NET CORE
Interested in using single sign-on (SSO) for your ASP.NET MVC app? You're in the right place. There are many reasons to use SSO for custom apps owned by the same organization.

    Improved user experience.
    Reduce development time.
    Improved security.

These are all good reasons.

Another thing I like about SSO is that it allows me to update large code bases in small increments instead of all at once.

As? Suppose you want to migrate an app written in ASP.NET MVC 5 to ASP.NET Core MVC. Instead of rewriting everything at once, you can migrate one service at a time. By implementing SSO between two apps, you can effectively connect the two apps as if they were one app.

This tutorial simulates such a scenario by implementing his SSO in an MVC 5 app and a .NET Core app. Along the way, you'll also learn about the differences in how the two platforms implement authentication.

Find the ASP.NET MVC 5 App

Access an existing MVC 5 app from GitHub instead of building a project from scratch. Clone or download this project (https://github.com/oktadev/aspnet-mvc-crud-example) and open the solution in Visual Studio.

Web.config file has some app settings used by programmers to configure authentication with the Open ID Connect server provided by Okta:
<add key="okta:ClientId" value="{yourClientId}" />
<add key="okta:ClientSecret" value="{yourClientSecret}" />
<add key="okta:OktaDomain" value="https://{yourOktaDomain}" />


For this tutorial, you'll need to switch these values ​​to your own Okta instance. Sign in to your Okta domain if you already have an account, or sign up for a forever free developer account if you don't already have one.

After signing in to Okta, register your client application.

    Click Applications on the top menu.
    Click Add Application.
    Select Web and click Next.
    Enter SSO MVC 5 for Name.
    For the Grant type allowed check the Implicit (Hybrid) checkbox
    And last click on DONE

The application has been created, but we still need to add something. Select Edit and add http://localhost:8080/Account/PostLogout to the logout redirect URI list and click Save.

On the next screen, you will see a summary of your settings. Under the General Settings section, you will see the Client Credentials section. Update the SSO settings in Web.config with your client ID and client secret. Next, go to the main page of your Okta dashboard, copy the organization URL shown in the top left corner, and paste it into Okta.

OktaDomain app settings in Web.config.

At this point, you should be able to run your app and sign in and out using OpenID Connect. If you're interested, take a look at Startup.cs to see how the authentication middleware is configured.

Find the ASP.NET Core App

Now that you're using Okta to log into your MVC 5 app, adding SSO to your second app is trivial.

First, download or clone this .NET Core app from GitHub.(https://github.com/oktadeveloper/okta-aspnetcore22-crud-example) If opening in Visual Studio, change the debug target from IIS Express to LiveMusicFinder.

This will run your app through the Kestrel web server on port 5001 (for https).

Go back to your Okta admin panel and register this application.
    click on Applications at top of the menu
    Then click on Add Application
    And select Web and click Next
    Enter SSO Core MVC for the Name
    Replace Base URIs with https://localhost:5001/
    Replace Login redirect URIs with https://localhost:5001/authorization-code/callback
    Click Done

Once complete, you'll be taken to the General Settings tab of the app. In this tab, click the Edit button and add an entry to the Signout Redirect URI as https://localhost:5001/signout/callback.

Then click Save.

Copy the Client ID and Client Secret from the Client Credentials section of the next page and update your application's appsettings.json file.
"Okta": {
  "ClientId": "{yourClientId}",
  "ClientSecret": "{yourClientSecret}",
  "OktaDomain": "https://{yourOktaDomain}",
  "PostLogoutRedirectUri": "https://localhost:5001/"
},


While editing the settings, update the OktaDomain settings to match what you entered in your MVC 5 app's Web.config. Also change the PostLogoutRedirectUri to https//local host:5001/.

That's really it. When you sign in to either app, click the Sign In link in the other app to automatically sign you in without prompting for your password.

(If you're inexplicably testing this using Internet Explorer and Visual Studio's auto-launch feature, make sure you're opening her second app in a tab in her window in the first browser. . Each browser window is isolated from the others due to Visual Studio's habit of launching IE.)
How single sign-on works in ASP.NET MVC 5 and ASP.NET Core

We've seen how easy it is to enable SSO in two ASP.NET apps, but what's really going on behind the scenes to make it work?

Suppose you first navigate to App 1 and click Sign In. App 1 redirects to Okta IdP (Identity Provider) where it signs in. When you log in, a cookie from Okta's domain is set in your browser. This cookie keeps you logged into Okta. Okta then returns to App 1 with the token it uses to complete the sign-in process. At this point, her cookie is also set on the App 1 domain. Here's a diagram to explain the states:


Then open app 2 in another tab in the same browser. Click Sign In and you will be redirected back to the Okta IdP. However, this time we still have a valid cookie, so we are already logged into the IdP. So instead of showing a login screen, Okta simply redirects to App 2 with the token needed to complete the local login process. A cookie is set on the domain of app 2 and you can log in from anywhere.

Note that Single sign-out_ is not supported by Okta as of this writing. When you log out of App 1, the cookies in App 1 are deleted and a quick call is made to the Okta IdP, which deletes the cookies. However, the App 2 cookie remains and you remain signed in to App 2 until you click Sign Out or the cookie expires. The default expiration is 30 days.
Explain ASP.NET OpenID Connect Flow

As you may have noticed, when I set up the configuration for my MVC 5 app I had to check the box to enable the implicit (hybrid) grant type, but not for .NET Core apps was.

When the OpenID Connect middleware was written for his MVC 5 years ago (long time ago in the software world), the OpenID Connect hybrid flow was implemented. This flow requires the IdP to pass an authorization code and ID token to the MVC 5 app submission. When redirecting the user to your app.

When the OpenID Connect middleware was written for .NET Core, it implemented a more secure authorization code flow. In this case the IdP should only return an authorization code and the middleware should get the ID token via a backchannel request to his IdP. This means that the ID token is not exposed to browsers. Note that if you pass sensitive information in an ID token, in MVC 5 this token will be returned to your app via the browser. This is not a problem when enabling SSO for him for .NET Core apps.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Generating An Excel File Through A List Of Objects In ASP.NET MVC

clock October 10, 2022 09:21 by author Peter

Today I will show you how to generate an excel file from a list of objects in C#. To do this, several plugins allow you to do this work in a global way. In this work, I will try to create a very simple and generic method to generate an excel file from a list of objects whatever their nature.


Step 1
Create a new ASP.NET MVC project.

Give a name to this project. for example "ExcelGeneratingApp".

Choose the MVC type.

Step 2

Create a class "ExcelLib.cs" in the models folder of the application.

Step 3

Add "ClosedXML" library from Nuget Package Manager.

Add class named "Employee.cs" for example.
using System.ComponentModel;
namespace ExcelGeneratingApp.Models
{
public class Employee
{
[DisplayName("Identity number")]
public int ID { get; set; }
[DisplayName("Full name")]
public string Name { get; set; }
[DisplayName("Age")]
public int Age { get; set; }
[DisplayName("Salary")]
public float Salary { get; set; }
[DisplayName("Department name")]
public string Department { get; set; }

}
}


​Add an "addHeader" method to "ExcelLib.cs" class. This method allows to add and style header of the table in excel file.
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace ExcelGeneratingApp.Models
{
public class ExcelLib
{
// Default Constructor.
public ExcelLib() { }
// Method for adding Header and Title of the table containing List of object values.
public IXLWorksheet addHeader(XLWorkbook wb, List<Object> objs, string title,  string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Sheet initialisation.
var ws = wb.Worksheets.Add("nomDeLaListe").SetTabColor(XLColor.UaBlue);
// font choice.
ws.Style.Font.FontName = fontFamily;
ws.Style.Font.SetFontSize(13);
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Style.Alignment.WrapText = true;
Object obj = objs.FirstOrDefault();
// Add the model fields to the header of the excel file.
int totalOfFields = obj.GetType().GetProperties().Length; // number of fields in the object.
int numberOfFields = 0;
// Adding the title of table in excel file.
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Value = title;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Style.Fill.BackgroundColor = XLColor.FromHtml(color); ;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.Bold = true;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontColor = XLColor.WhiteSmoke;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontSize = 18;
//Looping all propeties of the object.
foreach (var prop in obj.GetType().GetProperties())
{
        var displayNameAttribute = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false);
        string displayName = prop.Name;
        if (displayNameAttribute.Count() != 0)
        {
            displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
        }
        numberOfFields++;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Value = displayName;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        ws.Column(totalOfFields - numberOfFields + 4).Width = 30;
        ws.Column(totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
}
ws.Range(ws.Cell(5, 4), ws.Cell(5, totalOfFields + 3)).SetAutoFilter();
return ws;
}
}
}


Then add "addBody" method to the "ExcelLib.cs" class.
This method allows to add the list of objects "objs" content to the table in excel file.
It merges the cells of the first column containing the same values.
public IXLWorksheet addBody(IXLWorksheet ws, List<Object> objs)
{
int numberOfFields = 0;
int numberOfRecords = 0;
Object obj = objs.FirstOrDefault();
int totalOfFields = obj.GetType().GetProperties().Length;
string previousValue = "";
int indexOfPreviousValue = 0;

foreach (var item in objs.ToList())
{
  numberOfFields = 0;
  Type myType = item.GetType();
  IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

  foreach (PropertyInfo prop in props)
  {
      object propValue = prop.GetValue(item, null);

      numberOfFields++;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Value = propValue;

      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Font.Bold = true;

      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;

      if (numberOfFields == 1 && numberOfRecords == 0)
      {
          previousValue = propValue.ToString();
      }
      else
      {
          if (numberOfFields == 1)
          {
              if (previousValue == propValue.ToString())
              {
                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Value = propValue.ToString();

                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                  indexOfPreviousValue++;
              }
              else
              {
                  previousValue = propValue.ToString();
                  indexOfPreviousValue = 0;
              }
          }

      }


  }
  numberOfRecords++;
}

return ws;
}


Then add a "Generate" method for generating the excel file.
public void Generate(List<Object> objs, string title, string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Workbook creation.
using (XLWorkbook wb = new XLWorkbook())
{
        var ws = addHeader(wb, objs, title);
            ws = addBody(ws, objs);
            wb.SaveAs("C://TestExcelGen.xlsx");
}
}

Step 4
To test this method, we will add some code to the Home controller.
public ActionResult Index()
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { ID = 100 ,Name="PETER", Age=32,Salary=12000,Department="INFO"}) ;
employees.Add(new Employee() { ID = 200 ,Name="SCOTT", Age=24,Salary=10000,Department="CIVIL"}) ;
employees.Add(new Employee() { ID = 300 ,Name="ADAM", Age=20,Salary=11000,Department="INDUS"}) ;
employees.Add(new Employee() { ID = 400 ,Name="ETHAN", Age=21,Salary=9000,Department="INFO"}) ;
ExcelLib excel = new ExcelLib();

excel.Generate(employees.Cast<object>().ToList(), "List of employees");

return View();
}

The full ExcelLib.cs content:
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;

namespace ExcelGeneratingApp.Models
{
public class ExcelLib
{
// Default Constructor.
public ExcelLib() { }
// Method for adding Header and Title of the table containing List of object values.
public IXLWorksheet addHeader(XLWorkbook wb, List<Object> objs, string title,  string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Sheet initialisation.
var ws = wb.Worksheets.Add("nomDeLaListe").SetTabColor(XLColor.UaBlue);
// font choice.
ws.Style.Font.FontName = fontFamily;
ws.Style.Font.SetFontSize(13);
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Style.Alignment.WrapText = true;
Object obj = objs.FirstOrDefault();
// Add the model fields to the header of the excel file.
int totalOfFields = obj.GetType().GetProperties().Length; // number of fields in the object.
int numberOfFields = 0;
// Adding the title of table in excel file.
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Value = title;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Style.Fill.BackgroundColor = XLColor.FromHtml(color); ;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.Bold = true;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontColor = XLColor.WhiteSmoke;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontSize = 18;
//Looping all propeties of the object.
foreach (var prop in obj.GetType().GetProperties())
{
        var displayNameAttribute = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false);
        string displayName = prop.Name;
        if (displayNameAttribute.Count() != 0)
        {
            displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
        }
        numberOfFields++;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Value = displayName;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        ws.Column(totalOfFields - numberOfFields + 4).Width = 30;
        ws.Column(totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
}
ws.Range(ws.Cell(5, 4), ws.Cell(5, totalOfFields + 3)).SetAutoFilter();
return ws;
}
public IXLWorksheet addBody(IXLWorksheet ws, List<Object> objs)
{
int numberOfFields = 0;
int numberOfRecords = 0;
Object obj = objs.FirstOrDefault();
int totalOfFields = obj.GetType().GetProperties().Length;
string previousValue = "";
int indexOfPreviousValue = 0;

foreach (var item in objs.ToList())
{
    numberOfFields = 0;
    Type myType = item.GetType();
    IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

    foreach (PropertyInfo prop in props)
    {
        object propValue = prop.GetValue(item, null);
        numberOfFields++;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Value = propValue;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;

        if (numberOfFields == 1 && numberOfRecords == 0)
        {
            previousValue = propValue.ToString();
        }
        else
        {
            if (numberOfFields == 1)
            {
                if (previousValue == propValue.ToString())
                {
                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Value = propValue.ToString();

                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    indexOfPreviousValue++;
                }
                else
                {
                    previousValue = propValue.ToString();
                    indexOfPreviousValue = 0;
                }
            }
        }
    }
    numberOfRecords++;
}
return ws;
}
public void Generate(List<Object> objs, string title, string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Workbook creation.
using (XLWorkbook wb = new XLWorkbook())
{
        var ws = addHeader(wb, objs, title);
            ws = addBody(ws, objs);
            wb.SaveAs("C://TestExcelGen.xlsx");
}
}
}
}

NB: You can download all project source code from my github page.

Conclusion
I think the procedure is very clear with snapshots. If you have found any mistake in concept, please do comment. Your comments will make me perfect in the future.
Thanks for reading.

 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Pass Data Across Views In .NET MVC

clock September 30, 2022 09:46 by author Peter

In this article, we will discuss something new: pass data across views. We will also summarize some common or important shared features for various vew variables.

Brief Summary of ViewData
We will start our discussion from ViewData, but most or all features are the same for other MVC View Variables. The ASP.NET Core also has the same features. So, we will discuss ViewData in the most, and have the last part to see the extension to other View variables.


Type of ViewData
We have discussed ViewData, ViewBag, TempData, Session type features. They are all the Type of Dictionary:

Where the difference between ViewBag and ViewData:

Besides ViewBag, all other View Variables need to be cast before using. We define a ViewData named "book": as type BookModel with data such as Id = 1:


When we retrieve data, we have to cast the data back to the data type. Otherwise, we will get an error message:

After casting:

Pass Data into _Layout.cshtml Page by ViewData
The _layout.cshtml is a shared page by other specific views. It belongs to no Controller or Action, or we can say it belongs to every Controller or Action when the related view is using _layout.cshtml. Therefore, we can pass data into Layout either from the Controller or Action view, that uses the _layout.cshtml, such as, if we have a Contact Us Action:

Or, we can define the ViewData from the Contact Us View:

Both ways will pass the data into Layout page:

Notes
1, We usually introduce the Layout into View by the code in the View as below:

2, in some cases, if we want to make the Layout page(s) dynamic, we can assign the layout to the view through Controller/Action:

3, A related important shared concept for MVC, _Viewstat.cshtml


Pass Data into _Layout.cshtml Page by Other View Variables
The same is true for other MVC View Variables, such as ViewBag, TempData, and absolutely Session variable:


Pass TempData to Layout:

Pass ViewData to Layout:

Pass ViewBag to Layout:

This article discussed using ASP.NET MVC ViewData to pass data into Layout View through either Controller or View.  The features are available or the same as other View Variables in ASP.NET MVC, and the same is true for ASP.NET Core MVC.



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