Category Archives: .net training institute

A Look At The ASP.NET Core Pitfalls

When you intend to redirect after a Post, following the Post-Redirect-Get pattern but your previous view is constructed using a route parameter, then it would be sent to the redirect action too.

A Look At The ASP.NET Core Pitfalls

For instance, you are responding to a request for /Filter/Smartphone, where Smartphone is a route parameter, you Post it to some other controller action and at the end, you redirect to the Index action making use of the RedirectToAction method:

Return this.RedirectToAction(name of(Index));

The browser would issue the GET request for Index but takes the Smartphone route parameter, which is not fine.

The solution is to pass a routeValues parameter to RedirectToAction that do not have any of the possible route parameters. One way to do it is that you can create a dictionary with all action parameters zeroed:

return this.RedirectToAction(nameof(Index), MethodBase.GetCurrentMethod().GetParameters().ToDictionary(x => x.Name, x => (object) null));

The solution to do this automatically lies in the MethodBase.GetCurrentMethod() method. This way, you can surely avoid unwanted route parameters during your next request.

In case you wonder, passing null, a dictionary without object or entries would not work, the only other way is to pass an unknown value with the parameters set to null.

That’s it for now!

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support.

We give a well-structured program for the best Dot Net Course. Among various good institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.

Happy Coding!

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

An Overview Of Model Binding In ASP.NET MVC

ASP.NET MVC provides model binding to get from field values in a view. In several cases, model binding to complex types fulfills the same purpose. If the model type to get from the values is known at the time of development, you can mention a parameter of that type. But this is not the case always. And then you need some programmatic model binding. Programmatic model binding permits you to do model binding at runtime which is based on some condition or logic.

An Overview Of Model Binding In ASP DOT NET MVC

Suppose there is a page that captures details about workers doing a job. The EmployeeID, FirstName, and LastName fields are quite straightforward. The tricky thing is to depend on the selection in the Worker Type dropdown list you need to add the values to two different types. When the Worker Type is Employee you wish to bind the values to Employee object and when the Worker Type is Contract then you want to bind values with the ContractWorker object.

Here, the target type is dependent on the selection in the dropdown list. Let’s see how model binding can be used in such situations.

Firstly you need to create a new ASP.NET MVC project and add two model classes: Employee and ContractWorker. These classes are shown below:

public class Employee

{

public int EmployeeID { get, set; }

public string First Name { get, set; }

public string LastName { get, set; }

}

public class contract worker

{

public int EmployeeID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

}

In the above example, both classes area are almost identical but that’s not necessary.

Index view

Next add a new controller (HomeController) and Index view.

<h1>Enter Worker Details</h1>

<form action=”/home/process” method=”post”>

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

<tr>

<td>Employee ID :</td>

<td><input type=”text” name=”employeeid” /></td>

</tr>

<tr>

<td>First Name :</td>

<td><input type=”text” name=”firstname” /></td>

</tr>

<tr>

<td>Last Name :</td>

<td><input type=”text” name=”lastname” /></td>

</tr>

<tr>

<td>Worker Type :</td>

<td>

<select name=”workerType”>

<option value=”E”>Employee</option>

<option value=”C”>Contract Worker</option>

</select>

</td>

</tr>

<tr>

<td colspan=”2″>

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

</td>

</tr>

</table>

</form>

The Index view has a <form> which submits to Process action as indicated in the action attribute. Although the above markup uses plain HTML tags, you could use HTML helpers.

UpdateModel() method

Now add the Process () action inside the HomeController as shown below:

[HttpPost]

public ActionResult Process(string workerType)

{

if(workerType==”E”)

{

Employee emp = new Employee();

this.UpdateModel(emp);

//do something with emp

}

if (workerType == “C”)

{

ContractWorker worker = new ContractWorker();

this.UpdateModel(worker);

//do something with worker

}

return View(“Index”);

}

The Process()takes a string parameter – workerType. To mention, workerType is a name of the drop-down list on the Index view. This way you can select the Worker Type in the action. Next two if blocks check the value of worker type. If it is E, a new object of Employee is created. This object would be initially empty. To fill various properties of emp object you need to perform the model binding. To get it done, this task UpdateModel() method of the Controller base class is called. The UpdateModel() method accepts the object and tries to model bind it with from the Request.QueryString or Request.Form collections.

Likewise, the other if blocked, fills the ContractWorker object.

Once done, you can use “emp” and worker objects as per the need of your application.

TryUpdateModel() method

Though the application works as expected there is an issue. Execute the application and enter a string in EmployeeID textbox. The call to UpdateModel() will cause an exception:

The codes give an exception since UpdateModel() cannot convert a string to an integer. You can deal this kind of exception with an alternative – TryUpdateModel() method.

The TryUpdateModel() method is very similar to UpdateModel() but it returns true or false rather throwing an exception. That says that the TryUpdateModel() will return true if everything is fine, otherwise, it would return false. So, the job would be to simply check this return value.The following code shows how to do it.

[HttpPost]

Public ActionResult Process(string worker type)

{

bool flag = false;

if(workerType==”E”)

{

Employee emp = new Employee();

flag = this.TryUpdateModel(emp);

if (flag)

{

//do something with emp

}

}

if (workerType == “C”)

{

ContractWorker worker = new ContractWorker();

flag = this.TryUpdateModel(worker);

if (flag)

{

//do something with worker

}

}

return View(“Index”);

}

}

As mentioned, the return value of TryUpdateModel() is kept in flag variable. If the flag is true then only the application specific processing is executed.

If you wish to run the application again and enter some string value in EmplyeeID textbox, then you won’t get any exception.

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through .NET training program; our institute would be of great help and support. We give a well-structured program for the best Dot Net Course. Among various good institutes of dot net training and placement in PuneCRB Tech has developed its own identity.

Happy Coding!

Codes: Google database

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

An Overview Of How To Seed Users And Roles With Code In ASP.NET Core Identity

With the help of ASP.NET Core identity, you can implement authentication and authorization for your web applications. Working with ASP.NET Core Identity, sometimes you have to create a default user accounts and roles in the system. In ASP.NET MVC it can be done in Global.asax and Application_Start event handler. In ASP.NET Core the process different because its application startup process is different.

Seed Users And Roles With Code In ASP DOT NET Core Identity

In case you there is a MyIdentityDbContext, MyIdentityUser and MyIdentityRole classes ready, next your aim is to create a few user accounts and some roles when the application executes for the first time. This is to be done only when those users and roles don’t exist in the database.

Here we shall discuss two ways of putting the data:

  • Using Configure () method
  • Using Main () method

The former method is simple and direct with minimal coding, as you inject objects in other parts of your application, you can inject them into the Configure () method also. The latter approach is complex and needs you to shift the seeding operation to the Main() from Program.cs.

Edit your Configure () method signature as shown below :

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

}

Next can be inserted UserManager and RoleManager into the Configure() method. Hence you can use UserManager to develop user accounts and RoleManager to create roles at the application startup. Instead of directly writing codes inside the Configure() method, it would be isolated in a separate class and then get it from there.

What is necessary is to add a new class called MyIdentityDataInitializer into the project. The following code shows the structure of this class :

public static class MyIdentityDataInitializer

{

public static void SeedData

(UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

}

public static void SeedUsers

(UserManager<MyIdentityUser> userManager)

{

}

public static void SeedRoles

(RoleManager<MyIdentityRole> roleManager)

{

}

}

The MyIdentityDataInitializer class has 3 static methods – SeedRoles(), SeedUsers() and SeedData(). If you want to create both – users and roles – then you would summon SeedData().

Here we shall take a look at the codes that go inside the methods.

The SeedRoles() develops desired default roles in the system and appears like this :

public static void seed rolls

(RoleManager<MyIdentityRole> roleManager)

{

if (!roleManager.RoleExistsAsync

(“NormalUser”).Result)

{

MyIdentityRole role = new MyIdentityRole();

role.Name = “NormalUser”;

role.Description = “Perform normal operations.”;

IdentityResult roleResult = roleManager.

CreateAsync(role).Result;

}

if (!roleManager.RoleExistsAsync

(“Administrator”).Result)

{

MyIdentityRole role = new MyIdentityRole();

role.Name = “Administrator”;

role.Description = “Perform all the operations.”;

IdentityResult roleResult = roleManager.

CreateAsync(role).Result;

}

}

The SeedRoles() method takes in RoleManager as its parameter. Inside, is created two roles in the system – NormalUser and Administrator. You must change the role names and their description as you need.

The SeedUsers() develops desired default user accounts and appears like this :

public static void SeedUsers

(UserManager<MyIdentityUser> userManager)

{

if (userManager.FindByNameAsync

(“user1″).Result == null)

{

MyIdentityUser user = new MyIdentityUser();

user.UserName = “user1″;

user.Email = “user1@localhost”;

user.FullName = “Nancy Davolio”;

user.BirthDate = new DateTime(1960, 1, 1);

IdentityResult result = userManager.CreateAsync

(user, “password_goes_here”).Result;

if (result.Succeeded)

{

userManager.AddToRoleAsync(user,

“NormalUser”).Wait();

}

}

if (userManager.FindByNameAsync

(“user2″).Result == null)

{

MyIdentityUser user = new MyIdentityUser();

user.UserName = “user2″;

user.Email = “user2@localhost”;

user.FullName = “Mark Smith”;

user.BirthDate = new DateTime(1965, 1, 1);

IdentityResult result = userManager.CreateAsync

(user, “password_goes_here”).Result;

if (result.Succeeded)

{

userManager.AddToRoleAsync(user,

“Administrator”).Wait();

}

}

}

The SeedUsers() method accepts a UserManager and develops two users – user1 and user2. It has to be first checked if a user with the same name exists or not. If it doesn’t exist then it has to be created with default values of l, full name, and birth date. The values can be changed as needed.

The SeedUsers() and SeedRoles() do not return any value. But the signature can be changed to return some status of success or failure if you so wish.

The SeedData() basically summons SeedRoles() and SeedUsers() and appears like this :

public static void SeedData

(UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

SeedRoles(roleManager);

SeedUsers(userManager);

}

The SeedData() method accepts a UserManager and a RoleManager. Inside, it summons SeedRoles() and SeedUsers(). Watch out that, SeedRoles() is summoned first because SeedUsers() assigns certain roles to the users being added and those roles must exist in the system before adding the users.

Seeding data in Configure()

And it is time to use the MyIdentityDataInitializer class. Open the Startup class, go to Configure() method and add the following line of code:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

UserManager<MyIdentityUser> userManager,

RoleManager<MyIdentityRole> roleManager)

{

app.UseAuthentication();

MyIdentityDataInitializer.SeedData(userManager, roleManager);

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

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

});

}

After summoning, UseAuthentication() we summon SeedData() on MyIdentityDataInitializer.

Execute the application and see if the users get created in the database or not.

In the previous code are created default users and roles in the Configure() method. You can also do that work in Main() method. The following code shows how the Main() code would look like :

public static void Main(string[] args)

{

var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())

{

var serviceProvider = scope.ServiceProvider;

try

{

var userManager = serviceProvider.

GetRequiredService<UserManager<MyIdentityUser>>();

var roleManager = serviceProvider.

GetRequiredService<RoleManager<MyIdentityRole>>();

MyIdentityDataInitializer.SeedData

(userManager, roleManager);

}

catch

{

}

}

host.Run();

}

Instead of inserting UserManager and RoleManager into Configure() you take them from GetRequiredService() method. The userManager and roleManager objects are next passed on to SeedData() as earlier.

That’s it for now!

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through Dot NET training program; our institute, CRB Tech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among various best institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.

Happy Coding!

Codes: Google database

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

A Way Ahead With .NET Core In Near Future

Now with some advances, you can rely on .NET be it for building a desktop application, a website, a mobile app, or a microservice. Code sharing is now easy because GitHub now provides a unified BCL. You can focus on the attributes and technologies which are specific to user experiences and platforms you target.

Dot-NET-Core-moving-forward

This is how they want to realize the promise: they will provide source and binary compatibility for applications which target the core Base Class Libraries (BCL) across every platform with the same behavior all over. The Base Class Libraries existed in System, mscorlib, System.Data, System.Core, and System.XML and that is not bound to a particular application model and are not connected to a particular OS implementation.

Whether you focus on .NET Core 1.0 surface or the upcoming version of .NET Core with an expanded API, your existing code would continue to work.

Here is mentioned a few examples of the additions that are going to make life easier when you target .NET Core:

  • Reflection would be the same as .NET Framework, no need for GetTypeInfo(), well old.GetType() returns.
  • Types would not miss members who have been removed for clean up reasons (Clone(), Close() vs Dispose(), old APM APIs)
  • Binary serialization would be available again

What it signifies in .NET Core?

Originally, when .NET Core was designed much talk was about modularization and pay for play, meaning one has to consume the disk space for the features that you use. And this still can be realized without compromising heavily on compatibility.

Initially, the plan was to achieve minimum disk space usage and depends on a manual process of dividing the functionality in small libraries.

Timelines and process

The process to extend the API surface of .NET Core would happen after the shipment of .NET Core 1.0 RTM. This way, those who have been following along .NET Core would be able to deploy to production.

One of the first things which will be done is to publish a set of API references listing, which APIs are planned to be brought. They also intend to call out which APIs they don’t plan to bring.

They are also planning to release several updates to .NET Core on NuGet which extends the set of APIs available.

That’s it for now!

If you want to upgrade yourself to the basics and concepts of Dot Net Course and improve through Dot NET training program; our institute would be of great help and support. We give a well-structured program for the best Dot Net Course. Among various good institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.

Happy Coding!

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

An Introduction To Cookies and Session Stored In TempData In ASP.NET Core

People who used TempData in ASP.NET MVC, probably knows that by default TempData is stored in a Session state. This means that the web application must have sessions enabled. Now, the ASP.NET Core 2.0 gives two TempData providers; a Cookie based and a Session State-based. This blog shows how to use both of them in an application in ASP.NET Core.

Cookies-and-Session-Stored-In-TempData-In-ASP-Dot-Net-Core

Cookie-based TempData

By default, ASP.NET Core 2.0 makes use of cookies based TempData provider. This means values of TempData are stored in cookies present in the client’s machine. Since TempData gest stored in cookies you don’t require Session state through the session state middleware. Storing TempData in cookies could be useful in following situations:

The data being stored is small in size.

A web application is a part of a web farm and you don’t need sticky sessions.

Since cookie based TempData is used by default you don’t have to do any configuration to use it. Just store and receive the TempData key-value pairs as you do. An example is given here:

public IActionResult Index1()

{

TempData[“message”] = DateTime.Now;

return View();

}

public IActionResult Index2()

{

return View();

}

The above code highlights two actions – Index1 and Index2 – of HomeController. The Index1 () action stores a date-time stamp in a dictionary of TempData with a key name of the message. The Index1 view offers a hyperlink to direct to the Home/Index2. The Index2 () action gives back Index2 view. The Index2 view reads the TempData and shows the message to the user.

Index1 view is given below:

<h1>Index 1</h1>

@if (TempData.Peek(“message”) == null)

{

<h2>TempData has not been set.</h2>

}

else

{

<h2>TempData has been set.</h2>

}

<br />

<a asp-controller=”home” asp-action=”index2″>

Go to Index2

</a>

As shown the Razor code finds out whether the message has been stored in TempData or not. It does by using Peek () method of TempData. Since Peek() issued, the key won’t be removed from the TempData. And a message gets displayed in the browser mentioning the status of the message key.

An anchor tag helper offers a hyperlink which points to the Index2 () action of HomeController.

When user clicks on the hyperlink given by Index1. The value of message is sent out in the browser. Markup of Index2 is given below.

<h1>Index 2</h1>

<h2>@TempData[“message”]</h2>

<br />

<a asp-controller=”home” asp-action=”index1″>

Go to Index1

</a>

Index2 reads the TempData dictionary and yields the date-time stamp value in the browser. A hyperlink permits the user to go back to the Index1.

How to know that the TempData is really using the cookies. You need to run the application with F12 tools and locate the cookies option.

The cookie value is Base64 encoded. Since cookies are being used to store TempData all the limitations of cookie storage apply like browser support, size etc.

Session State based TempData

Let’s see how to use Session State based TempData and not the cookie based.

Session state based TempData

To allow Session state based TempData storage you must enable sessions using middleware and you also have to change the default provider. The following code shows how to do it.

public void ConfigureServices(IServiceCollection

services)

{

services.AddMvc().AddSessionStateTempDataProvider();

services.AddSession();

}

public void Configure(IApplicationBuilder app,

IHostingEnvironment env)

{

app.UseSession();

app.UseMvcWithDefaultRoute();

}

The ConfigureServices() calls out AddSessionStateTempDataProvider() to alter the default TempData provider to SessionStateTempDataProvider. It also summons AddSession() to allow in-memory session state for the application. The Configure() summons UseSession() to use the session state middleware.

The HomeController and its both the actions, Index1() and Index2() remains unchanged. On running the application, you can see that the final outcome will be same as before. But there won’t be any CookieTempDataProvider cookie. Instead, a Session cookie.

Session state based TempData comes handy when the application is using session state for other reasons.

That’s it for now!

If you want to upgrade yourself to the basics and concepts of Dot Net Course then our institute would be of great help and support in Dot NET training program

We give a well-structured program for the Best Dot Net Course Training. Among various good institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.

Happy Coding!

Code source: Online database

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

Top Web Designing Trends To Watch Out In 2018

From changing web apps to static sites, here we take a look at the trends that developers are expecting to see this year.

Top Web Designing Trends In 2018

From the start of its implementation, the internet is evolving. In its hay days, Mosaic and Netscape Navigator were doing great rounds, and since every New Year brought new ideas, new concepts, and trends, sometimes good, sometimes bad.

Here are the web development trends which are expected to impact globally on the industry in 2018:

Progressive Web Apps

A study showed that mobile apps accounted for 89% of the time spent on our Smartphone. It would be logical that the use of a format which is like a mobile application would be well received by the public.

The progressive web apps are applications which take advantage of the attributes of a browser, with a mobile application interface. This technology has several advantages, like an ability to work offline, virtually no load time, good reliability, and to able receive notifications. They can be designed faster than mobile apps, work for all types of users, and are easier to deploy and maintain.

Chatbots

To remain connected to users is quite essential, be in written or oral conversation software, allows a website to be contacted every day, without continuously maintaining a separate department for customer service. The evolution of chatbots offered new capabilities; they can answer the common questions, redirect users to information or web pages, or also helps in completing a transaction.

Website Notifications

Notifications are the best tools for mobile apps. This kind of communication also works with websites after a user authorizes the notifications. This indulges in greater customer engagement without the added costs of making a mobile app which replaces a website.

User Interfaces in Motion

Interfaces are a major concern for developers since a long time. Even the best designs are useless if the user cannot find what he is looking for. Interfaces help you to use animations or transitions that show certain actions, or important parts.

This technology makes the doorway to a wide range of tailoring, giving a developer several options for designing a very functional and attractive website.

The Release of Flash

Flash has interesting things for websites; it lets developers add animations or other movements. Adobe announced this year that there will no updating or new releases in Flash after 2020. Instead of losing the audience, mainly on the mobile version of a site, you should replace Flash with HTML5, which is rapidly becoming the universal internet format.

One-Page Websites

These sites have a well very long, page. To navigate, simply scroll, or use links to go up and down the page to the desired section.

The biggest advantage is their simplicity. There are no endless menus to explore. And this idea works well on smartphones, where the easiest navigation mode is scrolling. It is an updated solution to simple online requirements, and very inexpensive to develop and host.

Photo Content

A good photo is always significant because this can make things change. Though not a new concept, because since in the age of paper magazines, as well a good photo did matter. But now it is being tried uniquely. A unique photo, with individuality, and also giving sufficient information, will be the success key on the internet in 2018.

Conclusion

Trends are fast changing, as our technologies evolve. These new features can attract and retain customers in a better way. Hence, it’s important to look towards the future for new ideas and inspirations and to stand out from the competition.

With this, we conclude.

If you want to enhance yourself in basics and concepts with Dot Net Course and improve yourself through Dot NET training program; our institute would be of great help and support. We give a well-structured program for the best Dot Net Course. Among several good institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

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

An Introduction To Interception In EF Core

Entity Framework or EF Core is a lightweight, could be extended, and a cross-platform version of the commonly known Entity Framework data access technology.

EF Core is an object-relational mapper (O/RM) that allows .NET developers to work with a database that uses .NET objects. It removes the need for much of the data-access code which developers usually require to write codes. EF Core supports several database engines.

An_Introduction_To_Interception_In_EF_Core

Presently, Entity Framework Core yet does not have all of the attributes provided by pre-Core versions. One of the features is an ability to intercept questions, something which was offered by the IDbCommandInterceptor, IDbCommandTreeInterceptor interfaces.

The EF Core 2.0 has an interception at the SQL level, and you can only get to this in a rather complicated way, via the DiagnosticSource mechanism. Here we shall discuss on how to create a class with two methods, as shown below:

Public class CommandListener

{

[DiagnosticName(“Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting”)]

public void OnCommandExecuting(DbCommand command, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime)

{

}

[DiagnosticName (“Microsoft.EntityFrameworkCore.Database.Command.CommandExecuted”)]

public void OnCommandExecuted(object result, bool async)

{

}

}

You will require the Microsoft.Extensions.DiagnosticAdapter NuGet package to assemble this.

The methods can be hooked to EF Core as shown below:

var listener = ctx.GetService<DiagnosticSource>();

(listener as DiagnosticListener).SubscribeWithAdapter(new CommandListener());

Here, ctx is a DbContext, and it is being tried to access its registered DiagnosticSource service, which is a DiagnosticListener. You need to add a subscriber, and that’s it!

From the OnCommandExecuted method you can summon these methods whatever you choose, as long you keep the [DiagnosticName] features, the result parameter would contain either a scalar, a number or a RelationalDataReader object a sync, and would tell you exactly what version of the method was implemented.

OnCommandExecuting is quite amazing because there you can get an access to the DbCommand which is on how to implement the SQL command and can edit its SQL or parameters.

There are other mechanisms of interception as well, like the IQuerySqlGenerator and IQueryCompiler, to be covered later.

With this, we conclude. Keep coding!

If you want to enhance yourself in basics and concepts with Dot Net Course and improve yourself through Dot NET training program; our institute would be of great help and support.

We give a well-structured program for the best Dot Net Course. Among several good institutes of dot net training and placement in Pune, CRBtech has created a niche for itself.

Code source: Development With A Dot

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

An Overview Of Unit Testing With .NET Core

In this blog on.Net Core, we shall discuss unit testing for user interface (UI). It is a topic very common, and we will see how to do it here.

An_Overview_Of_Unit_Testing_With_Dot_NET_Core

Selenium is a software-testing framework, quite portable and for web applications and there is a .NET port of it. Here we shall use the Selenium.WebDriver package, and one or more of the following, for different browsers:

Selenium.Chrome.WebDriver: for Chrome

Selenium.Firefox.WebDriver: for Firefox

Selenium.WebDriver.MicrosoftWebDriver: for IE and Edge

Selenium gives a “minimum” contract that works over all the browsers.

Here let’s discuss some examples of how it works. Let’s start with instantiating a driver:

using (var driver = (IWebDriver) new ChromeDriver(Environment.CurrentDirectory))

{

//…

}

Take note of the Environment.CurrentDirectory parameter; it marks the path where the driver can find a chromedriver.exe file, or geckodriver.exe for Firefox or MicrosoftWebDriver.exe, in case of IE/Edge. These executables get added automatically by the Nuget packages. If you don’t remove the driver, the window will remain open after the unit test finishes. You also have a choice to Quit at any time.

Let’s now navigate to some page:

driver

.Navigate()

.GoToUrl(“http://www.google.com”);

And get some element from its name:

var elm = driver.FindElement(By.Name(“q”));

Besides the name, you can also search by:

Id: By.Id

CSS class: By.ClassName

CSS selector: By.CssSelector

Tag name: By.TagName

Link text: By.LinkText

Partial link text: By.PartialLinkText

XPath: By.XPath

Once an element is found, its properties can be accessed:

var attr = elm.GetAttribute(“class”);

var css = elm.GetCssValue(“display”);

var prop = elm.GetProperty(“enabled”);

Then we can send it text strokes:

elm.SendKeys(“asp.net core”);

Or click on it:

elm.Click();

It is to be known that, page loading could take some time, so, you can configure the default time of waiting, before doing a GoToUrl:

var timeouts = driver.Manage().Timeouts();

timeouts.ImplicitWait = TimeSpan.FromSeconds(1);

timeouts.PageLoad = TimeSpan.FromSeconds(5);

ImplicitWait is only a time that Selenium awaits before searching an element.

If you have to wait for some period of time, like, till some AJAX request is done with, you can do the following:

var waitForElement = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

var logo = waitForElement.Until(ExpectedConditions.ElementIsVisible(By.Id(“hplogo”)));

The condition is passed on to ExpectedConditions could be one of:

AlertIsPresent

ElementExists

ElementIsVisible

ElementSelectionStateToBe

AlertState

ElementToBeSelected

FrameToBeAvailableAndSwitchToIt

InvisibilityOfElementWithText

PresenceOfAllElementsLocatedBy

StalenessOf

TextToBePresentInElementLocated

TextToBePresentInElementValue

TitleContains

TitleIs

UrlContains

UrlMatches

UrlToBe

VisibilityOfAllElementsLocatedBy

You can see, there are several conditions that you can make use of. If the condition is not met and the timer expires, then the value returned is null.This is nice for your unit tests.

With this, we conclude.

Keep coding!

If you want to enhance yourself in basics and concepts with Dot Net Course and improve yourself through Dot NET training program; our institute, CRBtech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among several good institutes of dot net training and placement in Pune, CRBtech has created a niche for itself.

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

Method To Implement ListBox in Asp.Net MVC

Microsoft developed ASP.NET MVC as a web application framework which implements the model–view–controller or more popularly known as MVC pattern. It happens to be open-source software, besides the ASP.NET Web Forms component.

Method_To_Implement_List_Box_in_Asp_Dot_Net_MVC

In this blog, we shall discuss the process of implementing ListBox in asp.net MVC. Here, table “tblCity” is used for the demo.

For this demo, the “City” entity is used that is created using ADO.NET entity framework.

The first step is to generate a ViewModel class. In asp.net MVC, view models are used as techniques to transfer data between the view and the controller. Give a right click on the “Models” folder, and add a class file bearing name=CitiesViewModel.cs. Copy and paste the below mentioned code. This class will be the Model for the view.

public class CitiesViewModel

{

public IEnumerable<string> SelectedCities { get; set; }

public IEnumerable<SelectListItem> Cities { get; set; }

}

Next, right click on the folder called “Controllers” and then add a “HomeController”. Add the below two namespaces in the “HomeController”

Using MVCDemo.Models;

Using System.Text;

Copy and paste the following code.

[HttpGet]

public ActionResult Index()

{

SampleDBContext db = new SampleDBContext();

List<SelectListItem> listSelectListItems = new List<SelectListItem>();

for each (City city in db.Cities)

{

SelectListItem selectList = new SelectListItem()

{

Text = city.Name,

Value = city.ID.ToString(),

Selected = city.IsSelected

};

listSelectListItems.Add(selectList);

}

CitiesViewModel citiesViewModel = new CitiesViewModel()

{

Cities = listSelectListItems

};

return View(citiesViewModel);

}

[HttpPost]

public string Index(IEnumerable<string> selectedCities)

{

if (selectedCities == null)

{

return “No cities selected”;

}

else

{

StringBuilder sb = new StringBuilder();

sb.Append(“You selected – ” + string.Join(“,”, selectedCities));

return sb.ToString();

}

}

Next give a Right click on the method called “Index” action in “HomeController” and choose “Add View” from the context menu. Set

View Name = Index

View Engine = Razor

Then click “Add”.

Copy and paste the below mentioned code in “Index.cshtml”

@model MVCDemo.Models.CitiesViewModel

@{

ViewBag.Title = “Index”;

}

<div style=”font-family:Arial”>

<h2>Index</h2>

@using (Html.BeginForm())

{

@Html.ListBoxFor(m => m.SelectedCities, Model.Cities, new { size = 4 })

<br />

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

}

</div>

To note that, if you want to select multiple items from the list box, you have to hold down the CTRL Key.

Keep coding!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute, CRBtech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRBtech has created a niche for itself.

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

Understanding Of Models In An MVC Application

In this blog topic, we shall discuss the models in an MVC application.

Let’s understand the models with the help of examples. Suppose it’s an effort to retrieve employee information from the tblEmployee table and exhibit it.

asp dot net mvc

To envelope Employee information, Employee model class must be added to the Models folder. How to do this?

Steps:

1. Right click on “Models” folder > Add > Class

2. Write the name for the class as Employee.cs

3. Click “Add”

Copy and paste the following code in Employee.cs class file.

public class Employee

{

public int EmployeeID { get; set; }

public string Name { get; set; }

public string Gender { get;set; }

public string City { get;set; }

}

Next add EmployeeController class to “Controllers” folder.

Steps:

1. Right click the “Controllers” folder > Add > Controller

2. Use EmployeeController as name

3. Click “Add”

It is to use “Employee” model class EmployeeController. Next, copy and paste this “using” statement in “EmployeeController.cs”

using MVCDemo.Models;

An Index () Action method is created, by default in EmployeeController. Change the name of the function to Details(). Develop an instance of Employee class. Next, you can hard code Employee data in this class. Now EmployeeController should appear as shown below.

public ActionResult Details()

{

Employee employee = new Employee()

{

EmployeeId = 101,

Name = “John”,

Gender = “Male”,

City = “London”

};

return View();

}

Then you have to pass employee model object which was created in EmployeeController to the view, such that it can produce the HTML and send to the client. So you need to add a view.

Steps:

1. Right click on Details() action method and choose “Add View” from the context menu

2. Set

a)View Name = Details

b)View Engine = Razor

c)Select “Create strongly typed view” checkbox

d)From the “Model class” drop-down list, select “Employee (MVCDemo.Models)”

3. Next and finally, click “Add”

Here, Details.cshtml must be added to “Employee” folder. Take a note that “Employee” folder is created automatically and added to “Views” folder.

Copy and paste the below code into Details.cshtml file.

@model MVCDemo.Models.Employee

@{

ViewBag.Title = “Employee Details”;

}

<h2>Employee Details</h2>

<table style=”font-family:Arial”>

<tr>

<td>

Employee ID:

</td>

<td>

@Model.EmployeeId

</td>

</tr>

<tr>

<td>

Name:

</td>

<td>

@Model.Name

</td>

</tr>

<tr>

<td>

Gender:

</td>

<td>

@Model.Gender

</td>

</tr>

<tr>

<td>

City:

</td>

<td>

@Model.City

</td>

</tr>

</table>

Now if you try running the project, and if you go to the following URL, you will get a runtime error saying: Object reference is not set to an instance of an object.

http://localhost/MVCDemo/Employee/Details

And the best way to correct this error is pass “Employee” object to the view. The “return” statement in Details() action method has to be modified as given below:

return View(employee);

Done!

Run the application and go to http://localhost/MVCDemo/Employee/Details.

With this, we conclude. Happy coding!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute, CRBtech Solutions would be of great help and support. We give a well-structured program for the best Dot Net Course. Among many reputed institutes of dot net training and placement in Pune, CRB Tech has created a niche for itself.

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