How To Access Identity And HttpContext Info Using Dependency Injection In .NET Core

If you use .NET Core, then you know that Dependency Injection is quite important in this ecosystem. Grateful to them, the development team made it significantly easy to use.

One common scenario that you must have seen arise from its time of release, is:

“How could I inject Identity or User information via D.I. in .NET Core?”

This could be a common use case for systems that need identity information for server-level transactions (e.g. when you create a new entity, you might want to know who performed this action or likewise if you wanted to audit who approached a particular record in your system).

This blog will cover implementing such services that you can use or extend within your applications; which you have probably tried already, but didn’t work.

The most common place that you’ll see developers go to reach out the current user might be as simple as the User.Identity property that is exposed from the HttpContext. However, if you are reading this blog, sure that you have attempted something like this:

//Exampleofacontroller

publicFooController(FooContextcontext)

{

//Injectingyourdatacontext(acommon-usecase)

_context=context;

//Attemptingtoresolvethecurrentuser

_user=HttpContext.User?.Identity?.Name;

}

You’ll find that the actual HttpContext doesn’t exist within the constructor for the Controller.

So, to actually access anything within the HttpContext, you will need to inject it. To mention, that isn’t difficult.

Build a Service to Inject the HttpContext

For D.I. to work, you will need to vreate a service that can inject the HttpContext that we need in the pipeline so that we can access the properties of it.

You can do this by designing a simple class that already injects that information, behind the scenes through a IHttpContextAccessor object, as given below.

publicclassUserResolverService

{

privatereadonlyIHttpContextAccessor_context;

publicUserResolverService(IHttpContextAccessorcontext)

{

_context=context;

}

publicstringGetUser()

{

returnawait_context.HttpContext.User?.Identity?.Name;

}

}

What this will do is inject the HttpContext object from a request into this UserResolverService, which will store the context and expose a method called GetUser() that will return the current name of the user.

This could be used within a repository if you required to store the username that was accessing a particular record.

publicclassFooRepository:IFooRepository

{

privateFooContext_context;

privatestring_currentUser;

publicFooRepository(FooContextcontext,UserResolverServiceuserService)

{

_context=context;

_currentUser=userService.GetUser();

}

publicvoidDoWork()

{

varwidget=newWidget(){

Id=42,

Title=”TheAnswer”,

Author=”Deepthought”,

CreatedBy=_currentUser

};

_context.Widgets.Add(widget);

_context.SaveChanges();

}

} And, that it is basically.


How To Extend the Service

If you have some additional properties that existed on the ApplicationUserobject, then you might need to extend this service to pass along the entire object itself.

Doing this would require a very minor change, as you would simply need to inject your UserManager object into this new service.

publicclassUserResolverService

{

privatereadonlyIHttpContextAccessor_context;

privatereadonlyUserManager<ApplicationUser>_userManager;

publicUserResolverService(IHttpContextAccessorcontext,UserManager<ApplicationUser>userManager)

{

_context=context;

_userManager=userManager;

}

publicasyncTask<ApplicationUser>GetUser()

{

returnawait_userManager.FindByEmailAsync(_context.HttpContext.User?.Identity?.Name);

}

}

This is definitely just a beginning point for developing a service that upgrads the existing context, but hopefully it will increaseyour interest in creating your own services to pass around.

Since .NET Core is a cross-platform tool, you should think about looking into both of them.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimisation and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Command Line Interface Tools In .NET Core

CLI or Command Line Interface is a new cross-platform tool for developing .NET Core applications. It is also a basic tool because it is a primary layer on which other tools like IDE build the application and run it.

CLI tools are available in DEB packages for Ubuntu and MSI bundles for Windows. This installer will install the tool and setup the environment required to run CLI tool. There are availabilities of multiple versions of CLI tools installed on a single machine.

All CLI commands are run from command prompt. The CLI command mainly has three parts -

  1. The driver
  2. Command
  3. Command Argument

Driver

The verb “.net” is used as driver. The following two are the main responsibilities.

  • Execute IL (Intermediate Language) code
  • Execute the Command

The driver finds the version of the tool that we want to use. If the specified version of CLI tool is unavailable, driver uses the latest version of the tools. The driver starts to execute the command once the tool version is found.

Command

It is the action which needs to be performed by the driver.


Arguments

They are passed with the command. The arguments are helpers of the command and they provide user input to the command

Built-in supported Commands

Following commands are installed during installation.

  • new
  • restore
  • run
  • build
  • test
  • publish
  • pack

CLI tool gives the way to import more commands on the basis of need in project. You can add our own command as well.

“.net” commands

The .net is a generic driver for the CLI tool and is used to run the command-line commands. The .net is itself used as command; and with this command, it has the following options.
 

 Options  Description
 –version   Display current version of the CLI tool
 -v or –verbose  Does verbose output
 –info  Display details about the CLI tool like name and version of the OS, SHA-1 information etc.
 –help or-h  Display short help and list down current supported command


E.g.

Run the following commands in command window

>dotnet –version
>dotnet –info
>dotnet –v
>dotnet –help

“.net new” command

It is used for developing new .NET core project. It provides nicer way to initialize a valid .NET Core project and sample source code. When we run this command, two main files will be created – Program.cs and Project.json. We can edit these files as per our need.

Syntax

.net new [arguments/options]
 

 Options  Description
 -l Or –lang  Develop specified language project in present directory. Currently it ables to create C# and F# project
  -tor –type  Develop specified type of project in current directory. The supported values are console, web, lib and xunittest


E.g.
I have run the following commands in command window.

>dotnet new
>dotnet new -l F#
>dotnet new – t web

“.net restore” command

This is used to restore the dependencies to the project. It uses NuGet to restore dependencies which are mentioned in project.json file.

The configuration file “NuGet.config” provides the feeds where packages are located. When you installed CLI tools, by default one feed is present. You could specify more feeds by creating your own NuGet.config file in the project directory.

Syntax

.net restore [arguments/options]

 Options   Description
 -s Or –source [Source]  Specifies a source during the operation to restore. This will override all sources specified by nuget.config files.
 –packages [DIR]   Makes directory to restored packages placed in.
 –disable-parallel  Disable restoring multiple projects in parallel.
 -f Or –fallbacksource [FEED]  Specifies a fallback source which could be used in restore operation if main source can’t be restored.
 –configfile [FILE]  Specify the configuration of file NuGet.config that is used to perform restore operation.
 –verbosity [LEVEL]  Specifies which level of logging to use. Available options are Debug, Verbose, Information, Minimal, Warning and Error.


E.g.
I have run the following commands in command window.

>dotnet restore -s “D:\packages”
>dotnet restore –packages “Mypackages”

“.net build” command

It builds a project and its dependencies. It develops multiple source files from the project and its dependencies into binary and binary are in IL (Intermediate Language) and it has a DLL extension. This command needs lock file to be present in current directory, it means that we must run “.net restore” command prior to building a command.

Syntax

>.net build [arguments/options]

 Options   Description
 -o Or –output [DIR]  Build binaries are placed into specific directory.
 -b Or –build-base-path [DIR]  Temporary outputs are desugned in specified directory.
 -f Or –framework [FRAMEWORK]   Build compiles for the specific folder.
 -c Or –configuration [Debug|Release]   Defines build configuration. Default value of configuration is “Debug”.
 -r Or –runtime [RUNTIME_IDENTIFIER]  Defines target runtime to build.
 –version-suffix [VERSION_SUFFIX]  It defines what would be replaced with the version field in to the project.json file.
 –build-profile   It defines the incremental safety check which user needs to turn on automatically incremental compilation.
 –no-incremental  This will ensure the build as unsafe for incremental build. It turns off incremental compilation and forces rebuild of project dependency graph
 –no-dependencies   Only build the root project and ignore the build reference project.


E.g.
I have run the following commands in command window

>dotnet build
>dotnet build -c release
>dotnet build –no-dependencies

“.net run” command

This command is used to run our application from the source code. The main responsibilities are to compile source code, produce output program and run this program. This command depends on “.net build” command to build source code. The build command writes the output files in “bin” folder. It also develops this folder if it does not exist. The “obj” folder is used to write temporary files.

Syntax

.net run [arguments/options]

 Options   Description
 -f Or –framework [framework identifier]   Run the application under mentioned framework
 -c Or –configuration [Debug|Release]  Use the mentioned configuration when publishing application. The default value of configuration is “debug”
 -p Or –project [Path]  This command runs project specified in Path argument. It by default takes current directory if path is not specified.


E.g.
I have run the following commands in command window

>dotnet run
>dotnet run -c release
>dotnet run -p “C:\CoreAppTest”

“.net test” command

It runs unit test case under the configured test runner. Unit tests are class library type projects which have dependencies of unit test frameworks like xUnit or NUnit. The project.json file must contain the information about the test runner.

Following is sample project.json file.

 Options  Description
  - [project]  It decides the path of the project. By default it looks into current directory.
 -c Or –configuration[Debug|Release]  Use the mentioned configuration when test application. The default value of configuration is “release”
 -o Or –output [DIR]   Binaries are found in specified directory.
 -b Or –build-base-path [DIR]  Temporary outputs put in specified folder.
 -f Or –framework[FRAMEWORK]  Specify the version of the framework used for test binaries.
 -r Or –runtime [RUNTIME_IDENTIFIER]   Define the target runtime to test.
 –no-build   It does not build project prior to running test.
 –parentProcessId   It used by IDE to specify process ID.
 –port   It used by IDE to define a port number for listen for a connection


“.net publish” command

This compiles the application and publishes the application with the project dependencies (specified in project.json file) and puts it into specified folder.

 Options   Description
 - [project]  It defines the path of the project. By default it looks into current directory.
 -c Or –configuration [Debug|Release]  Use the configuration when to publish application. The default value of configuration is “debug”
 -o Or –output [DIR]  Binaries are found in to specified directory. Default path:
./bin/[configuration]/[framework]/ for portable applications
./bin/[configuration]/[framework]/[runtime] for self-contained applications.
 
-b Or –build-base-path [DIR]
 
Temporary outputs put in specified folder.
 -f Or –framework [FRAMEWORK]  Define the version of the framework used for publishing the application
 -r Or –runtime [RUNTIME_IDENTIFIER]  Define the target runtime to publish the application.
 –version-suffix [VERSION_SUFFIX]  It defines what must be replaced with the version field in to the project.json file.


E.g.
I have run the following commands in command window,

>dotnet publish
>dotnet publish -c release

“.net pack” commands

It packs your code into the NuGet package. This command builds your project and creates NuGet packages and as a result of this; you have two packages with nupkg extension. One contains the code and the other contains debug symbols.

 Options  Description
 - [project]  It can be either path of project directory or project.json file.
 -c Or –configuration [Debug|Release]  Use the configuration when developing the application. The default value of configuration is “debug”.
 -o Or –output [DIR]  Create packages in the specified directory
 –build-base-path [DIR]  Temporary outputs placed in specified folder.
 –no-build  It will skip build the application while creating pack.
 –version-suffix [VERSION_SUFFIX]   It defines what would be replaced with the version field in to the project.json file.


E.g.

Run the following commands in command window.

>dotnet pack

Summary

The .NET Core is supporting CLI. Using CLI, you can perform various tasks, like creating application, buildong application, publishing the application from command prompt. The higher-level tools like IDE also use this CLI internally, so you can get the same behaviour as with IDE in command prompt.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Continuous Integration In Kentico CMS

Definition of Kentico

Kentico CMS is a web content management system (WCMS) for developing websites, online stores, intranets, and Web 2.0 community sites. This utilizes ASP.NET and Microsoft Sql Server. Kentico permits development via its portal engine or using VS. Kentico is also compatible with Microsoft Windows Azure Platfrom.

Versions

Included in Kentico 9.

Why CI?

Kentico’s Continuous Integration module, mixed with Source Control, provides you an ability to move development coding and data changes automatically from Development through QA, Staging to Production. It supports the synchronization of work between programmers and the developing teams with the same workflow; by permiting them to store code and data in a file system, give them to Source Control, and import them back into a different Kentico installation within a few seconds.

It supports all operations, from the developing and updating of objects to their erase, and synchronizes the changes locally before storing them in a Source Control.

The system stores the XML files containing the serialized data of objects in the project’s CMS\App_Data\CIRepository folder.

Application

Enable CI

  • Open the Continuous integration application in the Kentico administration interface.
  • Select the Enable continuous integration checkbox.
  • Click Save.

Storing the CI files in a custom location

  • Develop a junction point
    mklink /J SitePath\Kentico\CMS\App_Data\CIRepository ExternalFolderPath
  • Use a custom storage provider
    StorageHelper.UseLocalFileSystemForPath(“~/App_Data/CIRepository”, @”C:\ExternalSourceControl”);

By Default CI will include all objects in the serialization. But you can include/exclude some objects by choice.

Including/Excluding objects from CI

By editing your application’s repository.config file that is present under CMS\App_Data\CIRepository folder.

  1. <IncludedObjectTypes>
  2. <ObjectType>cms.webpart</ObjectType>
  3. <ObjectType>cms.webpartcategory</ObjectType>
  4. </IncludedObjectTypes>
  5. <ExcludedObjectTypes>
  6. <ObjectType>cms.webpartlayout</ObjectType>
  7. </ExcludedObjectTypes>

Excluding individual objects

  1. <ObjectFilters>
  2. <ExcludedCodeNamesObjectType=”cms.settingskey”>CMSSMTPServerPassword;CMSStagingServicePassword</ExcludedCodeNames>
  3. </ObjectFilters>
  4. <ObjectFilters>
  5. <ExcludedCodeNamesObjectType=”cms.webpart”>test%</ExcludedCodeNames>
  6. <ExcludedCodeNamesObjectType=”cms.document”>/Testing/%</ExcludedCodeNames>
  7. </ObjectFilters>

Running CI

  • Open the CI application in the Kentico administration interface.
  • Click Serialize all objects.

It will develop XML Files under CIRepository folder.

Restoring CI files to the database

Open Command Prompt using Admin rights
Move on to the CMS\bin folder of your Kentico project and run ContinuousIntegration.exe from the command line with the -r parameter.

ContinuousIntegration.exe -r

Thus restore all the db changes using xml files.

N.B.

The CI functionality is only integrated to use on development instances and has its negative effect on site performance. Do not leave CI enabled for live production site.

What is best about it?

The user interface and layout is user friendly and easy to navigate. Without much training many people can edit and change pages without much trouble. Much of the editing you can do feels like Word and it has similar icons and styles that you can select.

Moreover if you want to go into depth then there is adequate for more advanced users to get into so it is a good all round system for all levels of users.

Limitations

Sometimes it is hard to embed certain files into some of the articles produced.

Recommendations

If you are finding an easy-to-use and user friendly CMS then Kentico is for you. You don’t need a lot of training and it is easy to edit, design and update your web-pages

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Mobile applications using Microsoft Mobile Internet Toolkit (MMIT)

Explain The Working Of.NET Mobile

Sequence of steps for execution of MMIT application:

– A mobile client make requests for a webpage
– The request travels via internet
– The request reaches IIS on the server
– .NET Framework handles the request and processes it
– ASP.NET compiles the page
– MMIT takes care of mobile device specific needs
– Page is sent to the client.

What are the components required to develop mobile applications with .NET Mobile.


Windows 2000/2003/2008R2 server with IIS
ASP.NET Framework
MMIT
IE 6 or more
A WAP based simulator for testing.

To develop a mobile web application with ASP.NET is quite easy.

The only difference are the tags of the form i.e.

Normal ASP.NET Webpage

<asp:Form runat=”server”>
<asp:Label runat=”server”>Hello World</asp:Label>
</asp:Form>

For Mobile

<%@ Register TagPrefix=”mob” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>
<mob:Form runat=”server”>
<mob:Label runat=”server”>Hello World</mob:Label>
</mob:Form>

MMIT takes care of all the mobile device requirements. Thus, the developer is free from such concerns

NET Mobile example with explanation.

Example:

<%@ Page Inherits=”System.Web.UI.MobileControls.MyPage” %>
<%@ Register TagPrefix=”mob” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>
<mob:Form runat=”server”>
<mob:Label runat=”server”>Hello World</mob:Label>
</mob:Form>

This is similar to a conventional ASP.NET webpage. The only difference being the tag mob which uses the System.Web.UI.MobileControls library.

Output for a WAP Enabled Mobile device:

<?xml version=’1.0’?>
<!DOCTYPE wml PUBLIC ‘-//WAPFORUM//DTD WML 1.1//EN’ ‘http://www.wapforum.org/DTD/wml_1.1.xml’>
<wml>
<card>
<p>Hello World</p>
</card>
</wml>

Output for a Pocket PC:

<html>
<body>
<form id=”ctrl1″ name=”ctrl1″ method=”post” action=”example.aspx”>
<div>Hello World</div>
</form>
</body>
</html>

Describe .NET Mobile Emulators.

Applications built could be tested and viewed using a variety of emulators.

Using Browser: This detect the browser, hence can be tested using the standard browsers like IE6.

Openwave: Most commonly used browser for Internet-enabled mobile phones.

Nokia Mobile Internet Toolkit: This enables testing for a variety of Nokia phones/devices.

Windows Mobile Development Platform: A Microsoft platform used to test applications for Windows Mobile O/s

Net Mobile Pages vs. ordinary .NET web page

.NET Mobile pages are similar to ordinary .NET Webpages.

<%@ Page Inherits=”System.Web.UI.MobileControls.MyPage” %>

<%@ Register TagPrefix=”mob” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>
<mob:Form runat=”server”>
<mob:Label runat=”server”>Hello World</mob:Label>
</mob:Form>


The only difference is the tag mob which uses the System.Web.UI.MobileControls library instead of the asp tag.

Describe .Net Mobile Forms

.NET Mobile Forms are specialized Web forms which could work on various mobile devices. Each Mobile Page must have at least one mobile form. A single mobile form can encapsulate multiple mobile controls in it. Compared to ASP.NET, a single mobile page can consist of multiple mobile forms.

<mob:Form id=”form1” runat=”server”>
<mob:Label id=”lbl1” runat=”server”>Hello World</mob:Label>
</mob:Form>
<mob:Form id=”form2” runat=”server”>
<mob:Label id=”lbl2” runat=”server”>Hello World2</mob:Label>
</mob:Form>

Explain .Net Mobile automatic paging.

- supports automatic paging for a number of mobile devices.

– Paging is handled differently for different controls.

– A method of writing data and reading it from secondary storage.

– Does memory management for a computer’s operating system.

– Helps more efficient and faster use of storage.

Explain <Mobile:Link> element .NET Mobile with example.

The <Mobile:Link> element enables a user to navigate between 2 forms in a page.

Example:

<%@ Page Inherits= “System.Web.UI.MobileControls.MobilePage”%>
<%@ Register TagPrefix=”Mobile” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>

<Mobile:Form id=”form1″ runat=”server”>
<Mobile:Label runat=”server”>Hello World1
</Mobile:Label>
<Mobile:Link runat=”server” NavigateURL=”#form2″>Form2
</Mobile:Link>
</Mobile:Form>

<Mobile:Form id=”form2″ runat=”server”>
<Mobile:Label runat=”server”>Hello World2
</Mobile:Label>
<Mobile:Link runat=”server” NavigateURL=”#form1″>Form1
</Mobile:Link>
</Mobile:Form>

Explain .NET Mobile controls attributes.

- Build web pages for several types of mobile devices instead of specific ones.
– permit creation of user controls with events
– Offer same attributes as ASP.NET Pages and server controls along with support to work with several devices.
– Permit customizing the output for a specific device by adding a new adapter for the control.
– Can develop new controls which can use inheritance or composition.

Describe .NET Mobile Events.

.NET mobile controls expose events which are device independent. They have an object model with programmable properties, methods and events.

Example:

<%@ Page Inherits=”System.Web.UI.MobileControls.MobilePage”%>
<%@ Register TagPrefix=”Mobile” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>

<script runat=”server”>
string age;

private void AgeClick(Object sender, EventArgs e)
{
age=text1.Text;
ActiveForm=Form2;
}
private void Form2_Activate(Object sender, EventArgs e)
{
message.Text=”You are ” + age + ” years old”;
}

</script>

<Mobile:Form id=”form1″ runat=”server”>
<Mobile:Label runat=”server”>Age?</Mobile:Label>
<Mobile:TextBox runat=”server” id=”text1″ />
<Mobile:Command runat=”server” OnClick=”AgeClick” Text=”Submit” />
</Mobile:Form>

<Mobile:Form id=”form2″ runat=”server” OnActivate=”Form2_Activate”>
<Mobile:Label runat=”server” id=”message” />
</Mobile:Form>

Describe .NET Mobile Input controls.

Input controls:

– To collect input from the mobile user.

TextBox control:

– It is a most common input control.

– TextBox control is perfect for simple user input like names, numbers, identification and keywords.

TextView control:

– It is used for larger amounts of input.

– It allows long multi-line input like the one you need for SMS or other messages.

– .NET provides a variety of input controls to enable interaction form the user.

Numeric input:

– The TextBox has a numeric attribute which, if set to true or false specifies whether the TextBox should accept only numeric values.

Password input:

– The TextBox has a password attribute which, when set to true or false it specifies that the textbox should be treated as a password field.

– It will be hide the input by displaying stars(*) in the TextBox as the user types in the textbox field.

Example:

<%@ Page Inherits= “System.Web.UI.MobileControls.MobilePage”%>
<%@ Register TagPrefix=”Mobile” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>

<script runat=”server”>

private void Page2(Object Sender, EventArgs e)
{
If (Page.IsValid)
{
ActiveForm=f2;
text2.Text=”You are ” + age.text + ” years old”;
}
}

</script>

<Mobile:Form id=”f1″ runat=”server”>
<Mobile:CompareValidator runat=”server” ControlToValidate=”txtage” Type=”Integer” ValueToCompare=”12″ Operator=”GreaterThanEqual”> You must be at least 12
</Mobile:CompareValidator>

<Mobile:Label runat=”server”>What is your Age?</Mobile:Label>
<Mobile:TextBox id=”txtage” runat=”server” />
<Mobile:Command OnClick=”Page2″ runat=”server”>Submit</Mobile:Command>
</Mobile:Form>

<Mobile:Form id=”f2″ runat=”server”>
<Mobile:Label id=”text2″ runat=”server” />
</Mobile:Form>


– This will display a message if the user input is less than 12.

Describe TextBox and TextView controls of .NET Mobile.

- .NET provides a variety of input controls to enable interaction with the user:

TextBox control:

– It is a most common input control.
– TextBox control is perfect for simple user input like names, numbers, identification and keywords.
– The TextBox control in .NET mobile application is used to display a single line of text.

TextView control:

– It is used for larger amounts of input.
– It allows long multi-line input like the one you need for SMS or other messages.
– The TextView control is used to display multiple lines of text.
– The text property of the TextView control also accepts HTML tags to specify formatting of the text in the control.

NET Mobile Input Validation. Explain with an example

Validation controls are used to validate an input control. They provide a message if the validation fails on the control. By default validation is applied on the command event of an input control. One can disable this by setting the input control’s causes validation property to false.

Example:

<%@ Page Inherits= “System.Web.UI.MobileControls.MobilePage”%>
<%@ Register TagPrefix=”Mobile” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>

<script runat=”server”>

private void Page2(Object Sender, EventArgs e)
{
If (Page.IsValid)
{
ActiveForm=f2;
text2.Text=”You are ” + age.text + ” years old”;
}
}
</script>

<Mobile:Form id=”f1″ runat=”server”>
<Mobile:CompareValidator runat=”server” ControlToValidate=”txtage” Type=”Integer” ValueToCompare=”12″ Operator=”GreaterThanEqual”> You must be at least 12</Mobile:CompareValidator>

<Mobile:Label runat=”server”>What is your Age?</Mobile:Label>
<Mobile:TextBox id=”txtage” runat=”server” />
<Mobile:Command OnClick=”Page2″ runat=”server”>Submit</Mobile:Command>
</Mobile:Form>

<Mobile:Form id=”f2″ runat=”server”>
<Mobile:Label id=”text2″ runat=”server” />
</Mobile:Form>


This will display a message if the user input is less than 12

NET Mobile Lists. Explain with an example.

There are 2 types of lists:

– The selectionlist control supports drop down lists, check boxes and also radio buttons.

– The list control supports selection from a list or menu. It has a display and a value property.

Example: Display price of a car selected by user.

<script runat=”server”>

private void Show_Price(Object sender, ListCommandEventArgs e)
{

text1.Text=e.ListItem.Text + “=” + e.ListItem.Value;
ActiveForm=f2;
}
</script>

<Mobile:Form id=”f1″ runat=”server”>
<Mobile:List runat=”server” OnItemCommand=”Show_PriceList”>
<Item text=”Camry” value=”$25,000″ />
<Item text=”Audi” value=”$32,000″ />
<Item text=”BMW” value=”$54,000″ />
</Mobile:List>
</Mobile:Form>

<Mobile:Form id=”f2″ runat=”server”>
<Mobile:Label runat=”server” id=”text1″ />
</Mobile:Form>

.NET Mobile SelectionList Control. Explain with an example.

The selectionlist control supports drop down lists, check boxes and also radio buttons.

Example: Allow user to select a car

<%@ Page Inherits= “System.Web.UI.MobileControls.MobilePage”%>

<%@ Register TagPrefix=”Mobile” Namespace=”System.Web.UI.MobileControls” Assembly=”System.Web.Mobile” %>

<script runat=”server”>
private void Car_Click(Object sender, EventArgs e)
{
ActiveForm=f2;
t1.text=cars.Selection.Value;
}
</script>
<Mobile:Form id=”f1″ runat=”server”>
<Mobile:SelectionList runat=”server” id=”cars” >
<Item Text=”Camry” Value=”$25,000″ />
<Item Text=”Audi” Value=”$32,000″ />
<Item Text=”BMW” Value=”$54,000″ />
</Mobile:SelectionList>
<Mobile:Command runat=”server” OnClick=”Car_Click” Text=”Submit” />
</Mobile:Form>
<Mobile:Form id=”f2″ runat=”server”>
<Mobile:Label id=”t1″ runat=”server” />
</Mobile:Form>

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

ASP.NET Core – Old Solution Structure Vs. New Solution Structure

In the previous three segments of the series (MVC 6 and EF 7 Application) we developed a simple database driven application that shows a list of customers and also allows you to edit the customer details. Though the application is working as expected, it relies on the local instances of the NorthwindDbContext. We concluded an article where we discussed the use of Dependency Injection (DI) attributes of MVC 6 to inject the NorthwindDbContext into the controller class.

Here we talk about the old solution vs new solution structure of ASP.Net Core

A reader who is new to ASP.NET Core, often ask a question -

Even on following your instructions to create a working example based on old articles. After creating the project his solution explorer looks different from that of the screen shots. Why is it so? Did I missing something?

Well. That’s mainly because of a simple setting. But it is always wise to know why things are happening in the way they shouldn’t. So, in this blog post I am discussing why you see two different solution structures in VS 2015.

Solution Structure – ASP.NET MVC 5 Style

Let’s develop a new ASP.NET MVC 5 project using Visual Studio 2015.

Open Visual Studio 2015 and select File > New > Project. This will open a new project dialog.

Take notice of the dialog carefully. Specifically note the following:

  • Project name is Project1
  • Solution name is Solution1
  • Create directory for solution checkbox is checked

Notice that under the Demos folder you have Solution1 folder because you selected the “Create directory for solution” checkbox. Inside, you have Project1 folder that has all the project specific files and folders.

Now, create a new project again but this time unchecks the “Create directory for solution” checkbox.

This time Project2 folder gets created directly inside Demos folder. There is no separate folder for solution as you unchecked the “Create directory for solution” checkbox.

Solution Structure – ASP.NET Core Style

Next create a new ASP.NET Core project by checking the “Create directory for solution” checkbox.

This time project name is Project3 and solution name is Solution3. This time your solution explorer would look different.

That’s bit different! See the following differences:

  • There are two top level folders – Solution Items and src.
  • Solution Items contains global.json file.
  • Src folder contains the project – Project3.

Now try putting another project to the same solution by right clicking on Solution3 (this process will remain the same as before). After adding the new project your Solution Explorer will resemble this:

Thus all the projects belonging to a solution are located inside the Src folder. The physical folder structure will look like this:

You might ask – Why this structure?

That’s because this structure closely resembles the GitHub project layout. Since ASP.NET Core extremely uses OSS, the new solution structure copies what people using repositories such as GitHub are familiar with.

You are not limited to these two folders. You can, for instance, create Tests folder to store unit testing related things and Documentation folder to store documentation files.

Now you might ask – Could I continue using the older solution structure in ASP.NET Core too?

The answer is yes. You can do that. Simply uncheck the “Create directory for solution” checkbox while designing a project and you will have a solution with older and familiar structure.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Creating an ASP.NET Mobile Web Application

Visual Studio .NET 2003

With ASP.NET, the New Project dialog box in Microsoft VS .NET shows two ASP.NET Mobile Designer project types:

  • Mobile Web Application template: Visual C# Projects
  • Mobile Web Application template: Visual Basic Projects

These application templates provide the basic file references and forms for the specified language. Selecting a template creates and opens the specified project in Visual Studio .NET.

The following walkthrough takes you through the basic steps necessary to create a mobile Web application using the designer.

To create a new ASP.NET mobile Web application

In VS, develop a new Visual C# or Visual Basic mobile Web application project.

  1. ] From the File menu, select New, and then click Project.
  2. ] In the New Project dialog box, do the following:
    1. In the Project Types pane, select either Visual Basic Projects or Visual C# Projects.
    2. In the Templates pane, click Mobile Web Application.
    3. In the Name box, type a name for your project. This would also be the name of the project solution.
    4. In the Location box, enter the URL (including http://) of the Web server where you want to develop the project.

Note : This software must be installed on the Web server: Internet Information Services (IIS) version 5.0 or later and the Microsoft .NET Framework.

  1. ] The programmer develops a new mobile Web Forms page called MobileWebForm1. It also creates the following project files:
    • MobileWebForm1.aspx. File format for the ASP.NET Web Forms pages. This has the declarative format of the ASP.NET mobile controls.
    • MobileWebForm1.aspx.cs or MobileWebForm1.aspx.vb. This contain the code for handling events and performing other tasks.
    • AssemblyInfo.cs or AssemblyInfo.vb. This has a set of features that provide information about the assembly created by the project.
    • Global.asax and Global.asax.cs or Global.asax.vb. This has code for responding to application-level events raised by ASP.NET or by HttpModules. These files are known as the ASP.NET application files.
    • web.config. They have settings specific to the application.

The Solution Explorer shows the files and resources in your application. Use this window to view, add, remove, and rename the listed files.

The application wizard develops an initial form. It brings controls from the Mobile Web Forms tab of the Toolbox onto the form. You could add as many controls as necessary.

Note : The Mobile Web Forms tab of the Toolbox is available only when you are in Design view of the designer.

Edit properties in the Properties window.

Repeat the steps 3 and 4 until the design for your Web application is complete.

Handling Events

Like Web Forms controls, they controls on mobile Web Forms, and can raise various events; for example, a Command control can raise a Click event. Controls provide default events and nondefault events. A control’s default event is most common event raised for that type of control. For example, the Click event is a Command control’s default event. All other events that the control supports are nondefault events.

The code to handle the event is executed on the server. When an user clicks a Command control, the page is posted to the server and then the event information is screened. If your application has an event handler corresponding to the event, the event handler is called upon. When the event handler finishes, the application sends the page back to the browser with any changes made by the event handler.

All controls provide Init, Load, PreRender, and Unload events. They also support more events specific to their respective purposes.

To create a default event handler for a control

  1. After placing the control on the form, double-click the control.

The Web Forms designer opens the code-behind file for the current page and creates skeleton methods for handling the control’s default events. For the Command control, the code looks like the following.

Visual Basic

Private Sub Command1_Click(ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Command1.Click

End Sub

// C#

private void Command1_Click(object sender, System.EventArgs e)

{

}

  1. Program code in the control’s event handler methods that the application can call when the events occur. For the Command control, your code might look similar to the following.
  2. Visual Basic
  3. Private Sub Command1_Click(ByVal sender as System.Object, ByVal e as System.EventArgs)Handles Command1.Click
  4. Command1.Text = “Hello, Web Forms!”
  5. End Sub
  6. // C#
  7. private void Command1_Click(Object sender, System.EventArgs e)
  8. {
  9. Command1.Text = “Hello, Web Forms!”;
  10. }

To create a nondefault event handler in Visual Basic

  1. ] Open the code-behind page for the mobile Web Forms page by clicking Code on the View menu in Visual Studio .NET.
  2. ] From the Class Name list, select the control to which you want to add the event handler.
  3. ] From the Method Name drop-down list, choose the event for which you want to add the event handler.

Note : The Code Editor automatically inserts the appropriate event-handling method into the code-behind page and positions the insertion point within the method.

  1. ] Add an appropriate code to the event handler.

To create a nondefault event handler in Visual C#

  1. ] In Design view, select the control to which you want to add the event handler.
  2. ] In the Properties window, click the Events button (). The window shows a list of all the events for the selected control.
  3. ] Double-click the method name for which you want to create an event handler.

Note : The Code Editor opens the code-behind page and inserts the appropriate event-handling method into the code-behind class. It also positions the insertion point within the method.

  1. ] Add the appropriate code to the event handler.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Preparation For ASP.NET 5 – Part 1 (Less and Sass)

It is often said that .NET are not comfortable with the new environment for a variety of reasons. One of the reasons is they didn’t use the following much talked about technologies: Less, Sass, npm, Gulp, Grunt, Bower, OWIN.

Not all developers remain updated with the cutting edge technologies. Many companies use an old fashioned way of doing the things and their developers might not get chance to work with these kinds of technologies at all. In this article series we will explain the basics of all these technologies as well as major ASP.NET vNext changes you must be aware of. This article is for the beginners in the technologies mentioned above as well as in ASP.NET vNext.

To begin with, the first part tells something about Less and Sass. So, let’s start.

Old vs. modern way of creating ASP.NET applications

Let’s outline the tasks that many simple web applications follow. They mainly don’t use the above technologies. They are done mostly with what comes with the default installation of .NET, VS and web standards.

The traditional way of developing ASP.NET applications is as follows:

  • You create an ASP.NET web application project in VS.
  • You write application specific server side code. This could be done either with web forms or with MVC.
  • You might refer .NET framework assemblies and custom components using References folder in the Solution Explorer.
  • You might install some NuGet packages using options in the Solution Explorer.
  • You could add JavaScript libraries such as jQuery or AngularJS to your project.
  • Create JavaScript files required by your application.
  • Create CSS style sheets for your application.
  • You might do some unit testing for your application.
  • Finally, deploy your application on the server.

Many modern, big applications use this approach to produce a better code-base and to manage it better.

  • Create an ASP.NET web application project in VS.
  • Program application specific server side code. This can be done either with web forms or with MVC.
  • You might refer .NET framework assemblies and custom the components using References folder in the Solution Explorer.
  • You might install some NuGet packages using “Manage NuGet Packages” options in the Solution Explorer.
  • You use some client side package manager such as npm and Bower to grab the JavaScript libraries such as jQuery and AngularJS.
  • You create JavaScript files needed by your application using plain JavaScript and / or TypeScript or CoffeeScript.
  • You compile your TypeScript or CoffeeScript into plain JavaScript.
  • You create style sheets using some CSS pre-processor such as Less and Sass.
  • You compile the Less and Sass files into plain CSS.
  • You minify all the JavaScript and CSS files you created so far using some automated build tool such as Gulp or Grunt.
  • You do unit testing of your application.
  • You tweak the configuration file (JSON format, more on this in later parts) to adjust settings such as connection string.
  • Finally, you deploy the application on the server or in cloud.

As a first instalment we shall discuss the basics of Less and Sass.

Basics of Less and Sass

To create CSS style sheets and attach them to web pages is a common task one must do. Although this task is straight and simple it has troubles of its own. Consider the following style rules:

h1{

color: #0026ff;

font-family: Arial;

font-size: 20px;

}

h2 {

color: #0026ff;

font-family: Arial;

font-size: 16px;

}

The official Less website lesscss.org defines Less like this:

“Less is a CSS pre-processor, meaning that it extends the CSS language, adding features that allow variables, mixins, functions and many other techniques that allow you to make CSS that is more maintainable, themable and extendable.”

The official Sass website sass-lang.com says :

“Sass lets you use features that don’t exist in CSS yet like variables, nesting, mixins, inheritance and other nifty goodies.”

Installing and using Less

Firstly go to Node.js website and install Node Package Manager on your machine. Then open the Command Prompt and set the following command:

npm install -g less

Less will get installed on your machine. Once installed you can use Less compiler to compile Less code to plain CSS.

Next, design an empty ASP.NET MVC project in VS and add a LESS style sheet to it.

Notice that Less files are stored with .less extension. Instead of using this template you can also add a text file manually and save it with .less extension.

Then add the following “code” to the Less style sheet:

@textSize:20px;

@fontName: Arial;

h1{

color:blue;

font-family:@fontName;

font-size:@textSize;

}

The above code declares two Less variables – @textSize and @fontName – and also stores some values in them.

Browsers won’t understand .less files unless you compile them to plain CSS. To do so you need to invoke Less compiler as follows:

$ lessc StyleSheet1.less > StyleSheet1.css

The Less command line compiler – lessc – takes two things. The .less file name and the .css file name where the result of compilation is to be stored. If you invoke the above command successfully StyleSheet1.css will contain something like this:

h1 {

color: blue;

font-family: Arial;

font-size: 20px;

}

This is plain old CSS!

Now you can add a <link> reference to StyleSheet1.css in all the ASP.NET web forms or MVC views.

Installing and using Sass

Sass works on similar lines as Less but there with a few differences. Install Ruby on your development machine. You can do so by visiting Ruby Installer website. Once installed you need to invoke Command Prompt as before and issue the following command.

Gem install sass

This will install Sass on your machine.

Next, add a text file to your Visual Studio project and name it – StyleSheet2.scss

Note that there are two syntax variations for Sass. One uses file extension of .sass and the other uses file extension of .scss. The later is the newer syntax and hence is recommended.

Now add the following “code” to the .scss file:

$textSize:20px;

$fontName: Arial;

h1{

color:blue;

font-family:$fontName;

font-size:$textSize;

}

As you can see, the syntax is quite similar but uses $ instead of @ for variable names.

To compile this Sass code to plain CSS, open Command Prompt and issue this command:

sass –watch “C:\Demos\StyleSheet2.scss”

This will compile the Sass code and create StyleSheet2.css file for you. If you open the .css file you should something like this:

h1 {

color: blue;

font-family: Arial;

font-size: 20px;

}

/*# sourceMappingURL=stylesheet2.css.map */

You can now refer the StyleSheet2.css file in your web forms or views.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

MVC 6 and EF 7 Application (Dependency Injection)

Part 3

In Part 1 and Part 2 of the series we developed a simple database driven application that shows a list of customers and also allows you to edit the customer details. Though the application is working as expected, it relies on the local instances of the NorthwindDbContext. In this article we will use the Dependency Injection (DI) attributes of MVC 6 to inject the NorthwindDbContext into the controller class.

Let’s start!

We shall do with the same project in the VS and open the Startup class in the IDE. Edit the ConfigureServices() method of the Startup class as shown below:

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

services.AddEntityFramework()

.AddSqlServer()

.AddDbContext<NorthwindDbContext>

(options => options.UseSqlServer

(AppSettings.ConnectionString));

}

Do note the bold letter code. The AddDbContext() method is changed at the end of the AddSqlServer() method call. The AddDbContext() is a generic method that permits you to specify the type of the DbContext that you wish to inject into the controllers. Moreover, you can also point the database connection string while adding the DbContext. In this case the AppSettings.ConnectionString property holds the database connection string and is passed to the UseSqlServer() method.

Now open the NorthwindDbContext class and remove the OnConfiguring() overridden method completely.

public class NorthwindDbContext:DbContext

{

public DbSet<Customer> Customers { get; set; }

// no more OnConfiguring() method

}

We do this because connection string is being supplied from the ConfigureServices() method.

Finally, open the HomeController and add a public constructor to it as mentioned below:

public class HomeController : Controller

{

private NorthwindDbContext db;

private CustomerRepository repository;

public HomeController(NorthwindDbContext context)

{

this.db = context;

this.repository = repository;

}

}

The HomeController class announces a NorthwindDbContext variable at the top. This variable is assigned in the constructor. The constructor takes a parameter of type NorthwindDbContext. This parameter will be supplied by the DI framework of MVC 6.

Next you have to modify the actions to use this class level variable instead of locally instantiating a DbContext. So, remove the using blocks from the existing code. The modified actions are shown below:

public IActionResult Index()

{

List<Customer> data = db.Customers.ToList();

return View(data);

}

public IActionResult Edit(string id)

{

Customer data = db.Customers.Where(i =>

i.CustomerID == id).SingleOrDefault();

var query = (from c in db.Customers

orderby c.Country ascending

select new SelectListItem()

{ Text = c.Country, Value

= c.Country }).Distinct();

List<SelectListItem> countries = query.ToList();

ViewBag.Countries = countries;

return View(data);

}

public IActionResult Save(Customer obj)

{

var query = (from c in db.Customers

orderby c.Country ascending

select new SelectListItem()

{ Text = c.Country, Value =

c.Country }).Distinct();

List<SelectListItem> countries = query.ToList();

ViewBag.Countries = countries;

if (ModelState.IsValid)

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

}

return View(“Edit”, obj);

Run the application.You will find that the DI framework supplies an instance of NorthwindDbContext configured to use the specified connection string.

Now let’s go ahead and use a repository for the database operations.

So add CustomerRepository class in the Classes folder and write 5 methods – SelectAll(), SelectByID(), Insert(), Update() and Delete(); as mentioned below:

public class CustomerRepository

{

public NorthwindDbContext Context {get; private set;}

public CustomerRepository(NorthwindDbContext context)

{

this.Context = context;

}

public List<Customer> SelectAll()

{

return Context.Customers.ToList();

}

public Customer SelectByID(string id)

{

return Context.Customers.Where(i =>

i.CustomerID == id).SingleOrDefault();

}

public void Insert(Customer obj)

{

Context.Entry(obj).State = EntityState.Added;

Context.SaveChanges();

}

public void Update(Customer obj)

{

Context.Entry(obj).State = EntityState.Modified;

Context.SaveChanges();

}

public void Delete(string id)

{

Customer obj = Context.Customers.Where(i =>

i.CustomerID == id).SingleOrDefault();

Context.Entry(obj).State = EntityState.Deleted;

Context.SaveChanges();

}

}

The CustomerRepository class uses all the logic to perform CRUD operations on the Customers table. Take note that the CustomerRepository doesn’t create any local instance of NorthwindDbContext class. We do this because we want the DI framework to inject the DbContext in the repository just as it did for the controller. The received instance is stored in a public Context property. The Context property has private setter so that the DbContext can’t be assigned from outside, at the same time allowing access to the DI supplied instance.

Once the CustomerRepository is ready you need to register it with the DI framework. This can be done as follows:

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

services.AddEntityFramework()

.AddSqlServer()

.AddDbContext<NorthwindDbContext>

(options => options.UseSqlServer

(AppSettings.ConnectionString));

services.AddScoped<CustomerRepository>();

}

Notice the code marked in bold letters. It makes use of the AddScoped() generic method to register CustomerRepository class with the DI framework. The AddScope() develops an object instance. So, next CustomerRepository could be injected into the controller class.

Although the above class doesn’t do that, you could create a repository interface and then implement that interface on the repository class. If your repository is based on some interface you can also specify the interface in the AddScoped() generic method. For example:

services.AddScoped<ICustomerRepository, CustomerRepository>();

The following code tells how the injected repository instance could be used.

public class HomeController : Controller

{

private CustomerRepository repository;

public HomeController(CustomerRepository repository)

{

this.repository = repository;

}

}

This code must look familiar to you because you used it while injecting the NorthwindDbContext. But, you declare a variable of type CustomerRepository and assign it in the constructor.

Once injected you can make use the CustomerRepository in all the actions instead of using the DbContext directly. The following code shows the modified actions of the HomeController.

public IActionResult Index()

{

List<Customer> data = repository.SelectAll();

return View(data);

}

public IActionResult Edit(string id)

{

Customer data = repository.SelectByID(id);

var query = (from c in repository.Context.Customers

orderby c.Country ascending

select new SelectListItem()

{ Text = c.Country, Value = c.Country })

.Distinct();

List<SelectListItem> countries = query.ToList();

ViewBag.Countries = countries;

return View(data);

}

public IActionResult Save(Customer obj)

{

var query = (from c in repository.Context.Customers

orderby c.Country ascending

select new SelectListItem()

{ Text = c.Country, Value = c.Country })

.Distinct();

List<SelectListItem> countries = query.ToList();

ViewBag.Countries = countries;

if (ModelState.IsValid)

{

repository.Update(obj);

}

return View(“Edit”, obj);

The above code creates List of SelectListItem objects by writing a query using the Context property. You can add some methods in the repository that returned the desired countries. Run the application again. If everything is fine, you can see the customer list and will be able to change the customer details.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

First MVC 6 and EF 7 Application (using Tag Helpers)

Part 2

In Part 1 of this series we created and configured a basic project using ASP.NET MVC 6. Though the project runs as per expectations and gives a message in the browser, it isn’t yet database driven. In this blog we will add database support to the project in the following ways:

  • By displaying a list of customers from the Northwind database
  • Permit modifications of existing customers
  • Give basic validation capabilities

As a result, the page will display a list of customers from the Customers table of the Northwind database. Each table row has an Edit link. By clicking on the Edit link that will take you to the Edit view such that the customer details can be modified.

Once you edit the details and click the Save button the changes are saved in the database. In case there are any errors they are displayed on the page.

Let’s stasrt with development!

Let’s recall the same project that we created in Part 1 and add Customer class to the Models folder by using the Add New Items dialog. The complete code of this class is shown below:

[Table(“Customers”)]

public class Customer

{

[Required]

[StringLength(5)]

public string CustomerID { get; set; }

[Required]

public string CompanyName { get; set; }

[Required]

public string ContactName { get; set; }

[Required]

public string Country { get; set; }

}

The Customer class is added to the Customers table using the [Table] feature and contains 4 public properties namely CustomerID, CompanyName, ContactName and Country. Basic validations like [Required] and [StringLength] are also added to these properties.

Then add NorthwindDbContext class to the Classes folder and write the following code to it.

public class NorthwindDbContext:DbContext

{

public DbSet<Customer> Customers { get; set; }

protected override void OnConfiguring

(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer(AppSettings.ConnectionString);

}

}

The NorthwindDbContext class represents the data context and hence inherits from the DbContext base class. It consists of a single DbSet – Customers. Notice how the OnConfiguring() method has been overridden to specify the database connection string.

The overridden OnConfiguring() method supplies optionsBuilder parameter. The UseSqlServer() method accepts a d-base connection string. Remember that we stored the database connection string in the ConnectionString static property of the AppSettings class during startup of the application.

Next modify the Index() action of the HomeController as shown below:

public IActionResult Index()

{

using (NorthwindDbContext db = new NorthwindDbContext())

{

List<Customer> data = db.Customers.ToList();

return View(data);

}

}

The Index() action instantiates the NorthwindDbContext and brings all the customers in the form of a List. This List is given to the Index view as its model.

Now, open the Index view and modify it as shown below:

@model List<MVC6Demo.Models.Customer>

<html>

<head>

<title>My First MVC 6 Application</title>

</head>

<body>

<h1>List of Customers</h1>

<table border=”1″ cellpadding=”10″>

@foreach (var item in Model)

{

<tr>

<td>@item.CustomerID</td>

<td>@item.CompanyName</td>

<td><a asp-action=”Edit”

asp-controller=”Home”

asp-route-id=”@item.CustomerID”>

Edit</a></td>

</tr>

}

</table>

</body>

</html>

The Index view displays a list of customers in a table. This code is quite same to MVC 5.x except the Edit link. In MVC 5.x you use ActionLink() HTML helper to render hyperlinks. The above code uses an anchor Tag Helper to achieve the same. The asp-action and asp-controller features points to the action method and the controller. The asp-route-id attribute specifies the ID route parameter to a CustomerID. This way the Edit links will take this form:

/home/edit/ALFKI

To get the Tag Helper intellisense you must add _ViewImports.cshtml file to the Views folder (you can do that using Add New Items dialog). Once added place the following code in it:

@addTagHelper “*, Microsoft.AspNet.Mvc.TagHelpers”

The @addTagHelper directive tells the framework to use Tag Helpers from the specified assembly. You will now get various tag helper related attributes in the Visual Studio intellisense.

Ok. Next, add Edit() action to the HomeController as shown below:

public IActionResult Edit(string id)

{

using (NorthwindDbContext db = new NorthwindDbContext())

{

Customer data = db.Customers.Where(i =>

i.CustomerID == id).SingleOrDefault();

var query = (from c in db.Customers

orderby c.Country ascending

select new SelectListItem()

{ Text = c.Country, Value = c.Country })

.Distinct();

List<SelectListItem> countries = query.ToList();

ViewBag.Countries = countries;

return View(data);

}

}

The Edit action gets a CustomerID as its parameter. Inside, the code brings a Customer matching the supplied ID and sends it to the Edit view. The Edit view needs a list of countries for the Country column. So, a List of SelectListItem (Microsoft.AspNet.Mvc.Rendering namespace) is developed and filled with unique countries from the Customers table. This List is sent to the view through the Countries ViewBag property.

Then add Edit view under Views/Home folder and key-in the following markup in it:

@model MVC6Demo.Models.Customer

<html>

<head>

<title>My First MVC 6 Application</title>

<style>

.field-validation-error

{

color:red;

}

.validation-summary-errors

{

color:red;

}

</style>

</head>

<body>

<h1>Edit Customer</h1>

<form asp-controller=”Home” asp-action=”Save” method=”post”>

<table border=”1″ cellpadding=”10″>

<tr>

<td>

<label asp-for=”CustomerID”>Customer ID :</label>

</td>

<td>

<input asp-for=”CustomerID” readonly=”readonly” />

<span asp-validation-for=”CustomerID”></span>

</td>

</tr>

<tr>

<td>

<label asp-for=”CompanyName”>Company Name :</label>

</td>

<td>

<input asp-for=”CompanyName” />

<span asp-validation-for=”CompanyName”></span>

</td>

</tr>

<tr>

<td>

<label asp-for=”ContactName”>Contact Name :</label>

</td>

<td>

<input asp-for=”ContactName” />

<span asp-validation-for=”ContactName”></span>

</td>

</tr>

<tr>

<td>

<label asp-for=”Country”>Country :</label>

</td>

<td>

<select asp-for=”Country”

asp-items=”@ViewBag.Countries”></select>

<span asp-validation-for=”Country”></span>

</td>

</tr>

<tr>

<td colspan=”2″>

<input type=”submit” value=”Save” />

</td>

</tr>

</table>

</form>

<div asp-validation-summary=”ValidationSummary.All”></div>

<br />

<a asp-action=”Index” asp-controller=”Home”>Go Back</a>

</body>

</html>

The above markup uses the following Tag Helpers:

  • form
  • label
  • input
  • select
  • field validation and validation summary

The asp-action and asp-controller features of the form tag helper are set to Save and Home respectively. This way the form will be POSTed to the Save() action of the HomeController. The asp-for attribute of the label and the input tag helpers specify a model property that is bound with the label and the input field respectively. The asp-items feature of the select tag helper specify that the <option> elements be generated from the Countries ViewBag property.

The field level validations are displayed by adding <span> elements and setting their asp-validation-for attribute to the appropriate model property. This way the model validation errors will be displayed in the <span> elements. The validation summary is displayed in a <div> element by setting its asp-validation-summary attribute to ValidationSummary.All. The look and feel of the validation tag helpers is controlled through CSS classes – .field-validation-error and .validation-summary-errors (see top of the markup).

Now add Save() action to the HomeController and write the following code to it:

public IActionResult Save(Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

var query = (from c in db.Customers

orderby c.Country ascending

select new SelectListItem()

{ Text = c.Country, Value = c.Country }).Distinct();

List<SelectListItem> countries = query.ToList();

ViewBag.Countries = countries;

if (ModelState.IsValid)

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

}

return View(“Edit”, obj);

}

}

The code that fills the Countries ViewBag property is similar to before. Then the code finds whether the ModelState is valid using the IsValid property. If the model state is valid the modified Customer details are saved to the database. This is done by setting the State property to Modified and then calling SaveChanges() method.

That’s done! Run the application and check if the customer details could be edited successfully.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

First MVC 6 and EF 7 Application (with Empty Project Template)

Part 1

If you are one of that techie who is tracking the progress of ASP.NET 5, you probably know that RC 1 of ASP.NET 5 is available now. This article explains how a simple MVC 6 application could be developed from ground up by using an Empty Project Template. This article is based on the following software:

  • Visual Studio 2015

  • ASP.NET 5 RC 1

  • Entity Framework 7 RC 1

Before you start you need to ensure that you have installed them correctly before you proceed further.

Let’s start here!

Open VS 2015 and select File—–New—-Project menu option. In the New Project dialog choose ASP.NET Web Application, give some project name and click OK button.

In the project template dialog, select Empty under ASP.NET 5 Preview Templates section.

Next, open Project.json file in the VS editor. The Project.json file is a JSON file and contains the entire project configuration like project dependencies, target frameworks and much more. For this example, you have to add some NuGet packages required to develop and run the application. You can enhance project dependencies in two ways:

  • Right click on the References node and choose Manage NuGet Packages. This is very similar to MVC 5.x projects. Once added the NuGet package entries are automatically added to the Project.json file.

  • Add NuGet package dependencies in the Project.json file.

Let’s make use of the later approach.

We won’t go into every minute details of each and every package in this article. It is sufficient to mention that:

  • Microsoft.AspNet.Mvc is the core MVC 6 package

  • Microsoft.AspNet.Mvc.TagHelpers contains tag helpers (discussed later)

  • EntityFramework.MicrosoftSqlServer provides Entity Framework 7 support

Then, right click on the project and choose Add > New Item to open the Add New Item dialog.

Select ASP.NET Configuration File from the list, name it AppSettings.json and click on Add to add the file to project root folder.

The AppSettings.json file has the entire application specific configuration. There is a difference between Project.json and AppSettings.json. The former stores project configuration that is necessary to compile and run the project. The later stores application configuration utilized in the code.

Next you have to add four folders under the project root namely Models, Views, Controllers and Classes. The purpose of the first three is quite obvious. The Classes folder will store other classes required in the application such as a DbContext class. You can give any other name to this folder.

Then add a class called AppSettings in the Classes folder and write the following code:

public class AppSettings

{

public static string ConnectionString { get; set; }

}

The AppSettings class has a single static property – ConnectionString – that intends to hold the database

connection string. This property is taken from the Startup class as discussed recently. Once assigned you can reach out the database connection string from anywhere in the application.

Now open Startup.cs file. The code from the Startup class is implored whenever the application runs. You will find that the Startup class has two methods – ConfigureServices() and Configure(). Both of them have special meaning to the framework and hence their name must remain unchanged.

Edit the Startup file to include a few namespaces and a public constructor.

using Microsoft.AspNet.Hosting;

using Microsoft.Dnx.Runtime;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.PlatformAbstractions;

using Microsoft.Data.Entity;

using MVC6Demo.Classes;

namespace WebApplication1

{

public class Startup

{

public Startup(IHostingEnvironment env,

IApplicationEnvironment app)

{

}

public void ConfigureServices(IServiceCollection services)

{

}

public void Configure(IApplicationBuilder app)

{

}

}

}

Take note of the namespaces at the top. They are needed by the code that you will fill in these methods sooner. Also take note that the constructor accepts two parameters: IHostingEnvironment and IApplicationEnvironment. These 3 methods are executed by the framework in the same order – Startup(), ConfigureServices() and Configure().

Next, add the following code to the Startup() constructor.

public Startup(IHostingEnvironment env,

IApplicationEnvironment app)

{

ConfigurationBuilder builder = new ConfigurationBuilder();

builder.SetBasePath(app.ApplicationBasePath);

builder.AddJsonFile(“appsettings.json”);

IConfigurationRoot config = builder.Build();

AppSettings.ConnectionString = config.Get<string>

(“Data:DefaultConnection:ConnectionString”);

}

The Startup constructor mainly reads the AppSettings.json file and stores the database connection string into the AppSettings class. The ConfigurationBuilder class is responsible for reading and loading the configuration information. The SetBasePath() method sets the base path where the configuration file(s) is located. The ApplicationBasePath means the physical path of the project’s root folder.

The AddJsonFile() adds AppSettings.json file to the list of configuration files to be processed. You can have multiple configuration files per project. The Build() method reads the configuration and returns it as an instance of IConfigurationRoot.

To read it, you can use Get<T>() method on the IConfigurationRoot object. Now the database connection string could be accessed from anywhere in the application in typed manner.

Then modify the ConfigureServices() method as shown below:

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

services.AddEntityFramework().AddSqlServer();

}

The ConfigureServices() method specifies the features that are available to your application. In this case your application is made available the services of the MVC framework and the Entity Framework.

Now modify the Configure() method as shown below:

public void Configure(IApplicationBuilder app)

{

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}/{action=Index}/{id?}”);

});

}

The Configure() method tells the framework that you want to use static files feature and MVC features. The static files feature allows you to access static files such as .htm and .html. If you don’t specify this feature and attempt to access the static files you will get an error. Of course, if you don’t need this feature you can skip this line.

The UseMvc() call is important because it not only tells the framework that your application is using MVC but also configures the routing system.

Ok. Now add HomeController to the Controllers folder using the Add New Item dialog. The default HomeController looks like this:

public class HomeController : Controller

{

public IActionResult Index()

{

ViewBag.Message = “Hello from MVC 6!”;

return View();

}

}

Notice that the Index() action returns IActionResult. The Index() action is quite straightforward and simply sets Message property on the ViewBag.

Then add Home subfolder under Views folder. Right click on the Home folder and open the Add New Item dialog again to add Index view to the project.

Add the following HTML markup to the Index view.

<html>

<head>

<title>My First MVC 6 Application</title>

</head>

<body>

<h1>@ViewBag.Message</h1>

</body>

</html>

The Index view simply outputs the Message ViewBag property on the response stream.

Run the application by pressing F5.

We conclude for now. Keep coding!!

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr