Asp.Net 5 – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Build, Rebuild & Clean Solution: A fact /build-rebuild-clean-solution-a-fact/ /build-rebuild-clean-solution-a-fact/#respond Fri, 22 Apr 2016 12:15:32 +0000 /?p=607 Why This?

Just out of curiosity, thought of why Build, Rebuild & Clean Solution in Visual Studio IDE. Earlier, thought use any one of them, i.e. Build & Rebuild, they do the same! but still thought of going through few resources and get the differences and I was staggered to find that I was wrong. 😀
This is a very simple and basic fact, which every developer using VS should be aware of. I wanted to be aware of this before some one questions me the same. I will be discussing their work and describing each as an Agent.

Discuss Facts!

7
Lets first discuss about Build Solution

Build Solution

:-
‘Ctrl + Shift + B’
The short cut above to build a solution. Now what this Build agent does in the background!
The Build Agent
1
This agent of the VS IDE does an incremental build. If you build your solution once, with some files changed, then it will build only those files which you have changed, without touching the files that are not even touched by you. 😛
Moreover, if you are building the Solution once and then again doing a build, it will not again build the solution actually, as the agent finds no files that are changed!
We see the build result on the output window in the IDE.
Lets see a pictorial difference.
4
As you see in the above image, the dll of the project gets re-generated, as a file was modified under that project. Since, my solution has a single project, so it creates the dll of that only.
5
In the above image as we hit the Build, the Build is succeeded but shows ‘0 succeeded’ i.e. there were no files modified, for which it did not create any dll.
8

Re-Build Solution

2
This agent is the master of all. This is the combination of Clean & Build.
9
This does not check or bother if there are any changed/modified files, it will always do a clean and build the solution or the specific project. This will recompile and regenerate the dlls inside the bin folder.

Clean Solution

3
The clean Madam, cleans and removes all the dlls created inside the bin folder. The procedure she follows is simple, just remove the Dlls related to the project or related to the entire solution from the bin folder.
Before Clean the bin folder has all the dlls:
10
After the clean when the clean succeeds, all the dlls are removed by the clean agent.
11

When to use what

To be honest, we can use any of them, I prefer a Clean first and then a Build. What do you?
When we

  • Rebuild a Solution with 2-3 projects, then the Re-build agent cleans the project 1 and then builds the project 1. Similarly, cleans project 2 and builds project 2 and so on.
  • When we clean and then build a solution, then the Clean agent first removes all the dlls for each project and then the build agent generates the project dlls at once.

Thus I have shared a simple tip and know how fact which might be handy and mandate as we are a
Visual Studio developer!

]]>
/build-rebuild-clean-solution-a-fact/feed/ 0
The Forms and Web Api Bridge /the-forms-and-web-api-bridge/ /the-forms-and-web-api-bridge/#respond Sun, 10 Apr 2016 14:44:27 +0000 /?p=584 Introduction

Recently, a scenario arose in which we had interact to a Web API from either a windows service or windows forms application. The logic and implementation seems easy once you are aware of the proceedings. I would be sharing this article for all those who wonder how! This is what my solution was to resolve this requirement. The implementation and the code is simple, but only a copy paste would not help unless we know what the keywords are and what they are meant for here. So let’s see:

Get Started

Before I start, the basic requirement would be a windows form and a web api project. So, the readers should know how to create a windows form and a web api application as a prerequisite. I will be sharing the Windows Forms application, which will ping the API we set via the url. As we know the medium of interaction or the bridge is HttpClient
According to MSDN:

Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

As the above definition suggests, the HttpClient class helps send HTTP requests and also get back the responses from the API resource we have provided. (Not only API, this article focuses on API). Thus, HttpClient is our bridge here.
I have created a windows forms application, which will post some values to the API on click of a button and also get back the response from the API. Lets have a look at the code:

private async void button1_Click(object sender, EventArgs e)
        {          
            string value = "After Test Post API (Result From API)"; //This value is sent to the API and again returned the same from it
            var text = await DataReceivedHandler(value);
            txtOutput.Text = text.Result;            
        }
     

        private static async Task DataReceivedHandler(string value)
        {
              using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var url = new Uri("https://localhost:54640/api/values?value="); //Change the Url to the Host (This is the default Values APi Controller)
                var result = await client.PostAsJsonAsync(url, value);
                if (result.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    return await Task.Delay(200)
                                .ContinueWith(t => "Hello");
                }
                string testResult = await result.Content.ReadAsStringAsync();
                return testResult;
            }
        }

I am using async method here, to post the values to the API and also awaiting for the result/response from the API.
Snippet explanation
The default headers, the kind of media types we are sending may it be application/xml, application/xhtml+xml,or text/html. So for each request, we are clearing the headers and then annotating the media type we would be sending through the request.
Then, we are setting and formatting the url to the API, with the query string that needs to be passed.
Then we are posting to the API through the client object, using PostAsJsonAsyc. It is an async method which awaits internally for the response and gets back to the thread once the task is completed.
Then, we check for the response message status code, incase it is a failure (404/any other) or a success(200|OK).
If it is a success, through IsSuccessStatusCode (200|OK), then we are reading again asynchronously the string using ReadAsStringAsync() and finally returning the result from this method block.
This is actually the entire simple flow that flows through in the snippet and how we connect to the API using the bridge.

Conclusion

Here I have shown you how to post values to any API. This can be handy when you are using serial port values to be sent from any machine form client machine to your application hosted on other servers or even cloud. I hope this logic helps!
If any suggestion or better implementation logic, i would love to learn. 🙂

]]>
/the-forms-and-web-api-bridge/feed/ 0
Overview of MVC6 & Deploy application to Azure /overview-of-mvc6-deploy-application-to-azure/ /overview-of-mvc6-deploy-application-to-azure/#respond Sat, 02 Apr 2016 19:04:35 +0000 /?p=558 Introduction

With an anticipation and hope, this article would be an interesting and effective somehow. This article will be covering the Asp.Net 5’s MVC6 Welcome application. a brief about the all new concepts of MVC6 and the new structure it beholds. Then we create our first Welcome application and then have a walk through of the new Azure Portal and deploy our first web application.
Collage

The above image is all that we will be covering in our article.

Get Started

A perfect blend of cloud and web application is what Asp.Net 5 is intended for. Asp.Net 5 is now being called off as .NET core is what that stands out today. It is a framework with open source & cross platform for building cloud based web applications. Here Azure comes integrated to the Visual Studio applications. Web applications either can be deployed to cloud or be running on On-premise. .Net core is available on Visual Studio 2015 build. You can download the community edition of the Visual Studio which is actually free. 🙂
Community Edition Download. Give a try for sure!
.Net 5 core contains a small optimized run time environment called “CoreCLR” One more important point to note is, .Net Core is opensource and the progress can be updated on Github. They have the code exposed and the build can be tracked easily. .Net core is said to contain a set of libraries known as “CoreFx”. Below are the links to the Github. Just have a look:

Another important benefit is termed as “Portability”. What this means is, we can package and deploy the Core CLR which can in turn help you eliminate the dependency on the installed version of .Net framework. Multiple application running on different versions of CLR can be set ups well. This is the magic the team wanted to result out, which is great!
With .NET 5 and VS 2015 comes MVC6 into picture. Microsoft builds are moving faster than the world! 😀
When I first looked at the structure of the Solution when i added a new MVC project, I was like What!!
thinkzoo
Where is Global.asax.cs? Where is Web.config, App_Start?. Did I download the correct files and selected the correct template. These sort of questions were flickering in my mind. When ran the application it ran successfully as well. Strange!!

Let’s have a small trip into the MVC6

Unified MVC Controllers

MVC6, the merger, the blend of three frameworks, i.e. MVC, Web API2 & Web Pages. Previous versions of MVC, while adding a new template would prompt to check whether we want Web API along with MVC. Here we select the MVC project and we get the opportunity to work with API as well.
In previous versions there were two base controller classes, separate for normal controller and also for the Api controller, i.e. ApiController

public class TestController: Controller {

}

public class ApiTestController ; ApiController {

}

In earlier version as shown above, the controller base class were from System.Web.MVC.Controller and for API, System.Web.Http.ApiController. But in MVC6 it is only one, i.e. Microsoft.AspNet.Mvc.Controller.

Different style of HTML helpers

In MVC6 there comes a new title termed as Tag Helpers. They make life much more simpler. How! We will get to know once we see the code snippet.
For normal web pages, as we know the HTML helpers are defined within the System.Web.WebPages.Html under System.Web.WebPages
, whereas in MVC6, it is under the System.Web.MVC assembly..
The HTML helpers which we used to use in Razor or ASPX, were quite difficult for normal HTML developers to understand (suppose designers). Now i MVC6 that has been simplifies using the Tag Helpers.

@using (Html.BeginForm())
{
        @Html.LabelFor(m => p.EmpName, "Employee Name:")
        @Html.TextBoxFor(m => p.EmpName)
        
        <input type="submit" value="Create" />
}

But in MVC6 ,

@model AzureDemoProject.Models.Employee
@addtaghelper "Microsoft.AspNet.Mvc.TagHelpers" 
<form method="post">
<div><label>Employee Name:</label> <input type="text" /></div>
<input type="submit" value="Save" />

</form>

Now the second snippet looks more like HTML friendly and also a bit simple.
Mr. Damian Edwards, has posted the source code on Github which has examples of Tag Helpers. Please go through for better live understanding
Git Hub Tag Helpers Download and play around.

Support for Grunt, NPM & Bower

These are the latest trending front end development tools. These are quite new to me as well, 😛 but will be learning and posting articles on these as well in coming days. Stay tuned!!
Ok branding apart, 😉 lets have a brief idea on what these are.
gnpmbower
Bower:-This is a client side item added by default to MVC6 project. If not added, then Right click on the project-> Add->New Item
->Installed(Client Side)-> Bower.json
. You can find then the file is already installed. The file is inside the wwwroot->lib->bootsrap->bower.json. As you open up the file, you can find the client side tool packages added to the project and their versions. Thus, we got to know that the bower is a client side package manager which is used to add the front-end packages like bootstrap, jQuery, angular, etc.
Grunt:-In MVC6 project when we add, we can find the gulpfile.js, this is kind of an alternative to the Grunt as both perform the same kind of functions. The operations they perform is minification, cleaning, concatenation, etc. of both js & css files.
NPM:- Node Package Manager is present under the project with the name project.json. This holds the dependencies and their versions required by the web application we have set up.

"dependencies": {
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
  },
 "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }

As we can see in the above snippet, which is just a part of the project.json file. This is to show the default dependencies added to the project and the pre publish scripts mentioned. When we suppose add a new dependency, suppose I try and add System.Linq, it will list up the Nuget package as intellisense and then we add the version which also comes under the intellisense. Like below image:
projectjson
Then after hitting Ctrl+S, the restoring of the references packages starts.
restor
Then we see the references added. For more information on the project.json file and its contents, please visit the below link:
Project.json
Integration to Cloud & optimized: This is another major boost feature added to MVC6 application. Now it comes integrated to the cloud with Microsoft Azure and also the optimizing and monitoring tool provided by Azure, i.e. Application Insights.
We will have a walk through of adding the cloud Web application and then a brief on Application insights as well.
Boosted Dependency Injection: Now MVC6 application has in built and integrated dependency injection facility. There is no more need for the packages like, Ninject, Unity, Structure Map3 and all. The code for the configuration setting for the dependency injection is added inside the StartUp.cs class file as below:

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext(options =&gt;
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
                .AddEntityFrameworkStores()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            //Dependency Injection as well
            services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
            services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;();
        }

The we normally inject the services into the constructor of the controllers. Is’nt that great!!
appsettings.json: As we know there is no Web.config file in our application, but we need to have a place where we have the settings required by the application at all stages. This is this place. In MVC6, they have had a upper hand over the JSON than the XML. 😛
The connection strings, the other app settings file we used to add inside the Web.config will now be contained here, that to in Json format. An example like below:

"Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-AzureWebAppDemo-XXXXXXXXXXXXXXXXXXX-XXX;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  }

global.json: This is a separate folder named Solution Items. here is the global.json file, which contains the solutions’s project references and their dependencies as well. Loos like below:

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-rc1-update1"
  }
}

The appsettings is initialized into the project in the Startup.cs file as below:

var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

The App_Start which had the RouteConfig.cs file also goes missing. In MVC is present inside the Startup.cs file as below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
               app.UseMvc(routes =&gt;
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Thus, lets have a look at the entry point of the application:

// Entry point for the application.
        public static void Main(string[] args) =&gt; WebApplication.Run(args);

Another nice feature is the segregation of the Models & View Models. The Model now only will deal with the Db Entities and the context, where as the ViewModel will deal with the model classes which are required in the View binding.
This was just a brief about MVC6, more information and application building will be shown in the upcoming articles on MVC6. Now lets jump start the deployment to azure.

done

Head start Deployment

Now lets discuss creating a new MVC6 project from VS 2015 and then deploying to Azure, mostly I will pictorially explain you which will help understand better.

    • Step 1: Create a brand new project from the Visual Studio 2015 templates. Select the cloud directly and then the Web project as we will be deploying our application to azure.
      1
    • Step 2: Then after giving name for the project, another window will prompt which will ask for the Microsoft Azure configurations. Web App Name, which will actually be the URL for the application after hosted on cloud.
      Then asks for the Application Service under which the application will be registered and deployed.
      Region is another important factor which might come handy in the performance of the application. Thus, we select East Asia here.
      If asked for the Database server and the application required we add a new database server or use any existing database. We skip for now the database integration.
      2
    • Step 3: After setting up, we land in creating our first web application and the structure is like below:
      3
    • Step 4: Lets have a look at project structure which gets created.
    • 4
    • Step 5: Lets now publish and deploy our web application. Right click on the project and click ‘Publish’. We then see a window pop up like below:8
    • Step 6: This will now create an Application Service(Webservice) on Azure portal and also deploy our Web Application as a new Website. The status can be seen under Azure Activity :
      10 1112
      The above images are the over all status and the name of the publish package that got deployed.
    • Step 7: Then navigate to the Azure portal, already notifications would be highlighted to let you know that web site is now hosted and you can browse.
      15
      The status app type and the app status will update in a few minutes.

    Conclusion

    Thus, once the website is hosted on Azure, we can browse and run our application and share with anyone to navigate through our application. We came to know in this article how easy it is to deploy to cloud in the latest builds, making the lives of developers much easier. I will be sharing and covering the Application Insights in the next article which will follow this up. I hope this has helped in learning some facts about MVC6 and please post your feedback. Application Insights– upcoming. 🙂

    References

    MVC6
    MVC6 Features

    ]]> /overview-of-mvc6-deploy-application-to-azure/feed/ 0