Tag Archives: .net jobs

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

How C# 7.1 Is Different?

With C#, Microsoft has been always some major releases: with a lot of features up, and less frequent release. They went ahead than routinely, omitting the conventional “.0″ when they talked about C# 6.0!

C# 7.1

In the C# 7.0, they are trying something innovative. Tools like Visual Studio upgrade in a frequent mode and they left no reason why the C# couldn’t also be updated more frequently. Hence this time, they are embracing a notion of “point releases”; minor versions of C# with quite useful but smaller language features and with shorter intervals. This indicates that you don’t need to wait for a long time to make some additional value to ship, but also it becomes easy to align a C# release with the shipping of related features, e.g. in.NET.

It is a fact that upgrading to a newer version of programming language every time could be a hassle in an organization and is not the way for everyone. Visual Studio 2017 allows you to decide whether to take the latest or only to the major (“.0″) versions of C#. You can choose your own rhythm.

The first point release

In August of 2017 Microsoft shipped the first point release of C# and named as C# 7.1, and its main purpose is to get practice with point releases, without too many dependencies on accompanying technology to make things complicated.

C# 7.1 is a small release with just a few and well-chosen new language attributes but in the minor range. It’s supported by VS 2017, starting with Update 15.3.

Let’s take a look! There is a program which uses the three C# 7.1 features that are being covered here, and a number of the recent C# 7.0 ones.

using System.Linq;

using System.Threading;

using System.Threading.Tasks;

using static System.Console;

class Program

{

static async Task Main(string[] args)

{

var results = Enumerable.Range(1, 40)

.Select(input => (input, task: FibonacciAsync(input)))

.ToArray();

for each (var tuple in results)

{

WriteLine($”Fib {tuple.input} = {await tuple.task}”);

}

}

private static Task<int> FibonacciAsync(int n, CancellationToken token = default)

{

return Task.Run(() => Fib(n).curr, token);

(int curr, int prev) Fib(int i)

{

if (i is 0) return (1, 0);

var (c, p) = Fib(i – 1);

return (c + p, c);

}

}

}

view raw

cs7.1-Example.cs hosted with by GitHub

It figures out the first 40 Fibonacci numbers in parallel on the thread pool and prints them out in order.

Here let’s take a look at C# 7.1 features used here.

Async Main

The Main entry point method can return a Task or a Task<int>. And as a result, execution will wait for the returned task to complete, before shutting down the program.

The main purpose is to make the Main method async, which you can do as well:

static async Task Main(string[] args)

This makes you wait for the Main method, which you couldn’t do before.

WriteLine($”Fib {tuple.input} = {await tuple.task}”);

Previously what you need to do was that, first you’d create an async helper method, for instance, MainAsync, with all the logic in. Then you can write this cryptic Main method:

static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();

Now you can asynce the Main method and the compiler would rewrite it for you.

Inferred tuple element names

In lambda expression in the query:

input => (input, task: FibonacciAsync(input))

Only a tuple is created, and give a name, task, for the second element. And a few lines later you are able to say

WriteLine($”Fib {tuple.input} = {await tuple.task}”);

To access the first element with the name tuple.input.

Default literals

With an expected type for a default expression, you can omit the mention of the type, as done for the CancellationToken in the signature of the FibonacciAsync method:

Private static Task<int> FibonacciAsync(int n, CancellationToken token = default)

This prevents a repetition of type names or typing the longer ones which are already given by context.

Microsoft is already working on C# 7.2, and also the features intended for their next major release.

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

Ways To Configure log4net For .NET Core

We start with the mention that the log4net team published new NuGet packages which support.NETStandard 1.3, which says it must work with .NET Core. This article is to discuss updates for log4net support.

Ways To Configure log4net For Dot NET Core

To start with: Configure() log4net

To add a reference to the log4net NuGet package is no problem. If you worked previously with log4net for any amount of time, you know that you must add codes for configuring it.

XmlConfigurator.Configure() needs some parameters that we didn’t usually provide in the past.

Configuration Workaround: Load It Manually

This log4net is good enough to load its configuration from a web.config or log4net.config file. In .NET Core, it doesn’t appear to know how.

It makes sense that this can’t read from a web.config/app.config because they don’t exist in .NET Core.

But, it doesn’t automatically try to read a log4net.config file. To mention, NLog does the same thing. You need to configure manually as in .NET Core.

With little little reverse dtudying, you will know how to load the log4net.config file and configure log4net.

var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

XmlConfigurator.Configure(logRepository, new FileInfo(“log4net.config”));

You can get this to work with a .NET Core app targeting both netcoreapp1.0 and net452. Sum up that to your Program.cs as the first thing your code does.

There is a mention about some limitations with the current 2.0.7 version of log4net. Hopefully, there will be some more developments.

Now with this, we conclude. We hope this was of help to you.

If you want to enhance yourself in Dot Net Course and improve yourself then our institute, CRB Tech Solutions would be of great help and support.

They offer a well-structured program for the best Dot Net Training course. Among many reputed institutes of dot net training and placement in Pune. Keep 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

Tips To Increase Visual Studio Editor Window Space Rapidly

Today under the topic for dot net coding tips and tricks, we shall discuss how to maximise the Visual Studio window space faster.

Tips To Increase Visual Studio Editor Window Space Rapidly

 

Many of you must like to prefer that, right? To bestow more screen space in Visual Studio to the editor window as possible.

At times doing the same on full-screen mode might not be that easy or your requirement, because getting to several tool windows — Solution Explorer, for example — isn’t certain.

Here we share Dot Net tips to bring back the tool panes to the windows layout, after hiding them by one click.

If you want to get the maximum space for your editor’s window without giving up the VS window, then go to Windows menu and select the option, Auto Hide All. That choice will collapse all of your tool panes: Solution Explorer, the Properties List, the toolbox, and all the related things will collapse into the sides of the Visual Studio, providing you a maximum editing space inside the Visual Studio.

You can definitely bring back the tool panes when you need them by a single click, but there is no “auto un-hide all” option; so you have to bring back every tool pane, individually.

In Visual Studio 2015, there was an alternative to bring back each tool page one-by-one. To make use of this, you need to first set up your “preferred” layout of tool panes. Next, assign this Windows layout a name and save it by visiting the Window menu and by selecting Save Window Layout.

With your preferred, saved the layout, after applying Auto Hide All; you can go back to the tool panes of your choice by selecting Window | Apply Window Layout | <your layout name> from the menu drop down list.

To mention, the earlier versions of Visual Studio did not have any option to save Windows layouts but only kept in memory, the layouts for 4 fixed modes: Design, Debug, Full Screen, and File.

Now with this, we conclude our today’s blog under dot net tips and tricks. We hope this was of help to you.

Keep coding!!

To be successful in yours .Net career, try to enhance your skill set in Dot Net Course and improve yourself through Dot NET training programs. In this reference our institute i.e. CRB Tech Solutions Pune could be of great help and support for you.

Stay connected to this space for more technical blogs and updates related to the world of Dot Net.

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

Why You Need To Add An Error Handler To Your ASP.NET MVC Controller

Today we shall discuss error handling under the topic of dot net tips and tricks.

Need_To_Add_An_Error_Handler_To_Your_ASP_DOT_NET_MVC_Controller

An error handler is significant in order to avoid future problems. There isn’t anything like an “unhandled error” — if your code causes an error outside of a Try…Catch block, then the error will come up through several ASP.NET and .NET Framework error handlers. An “unhandled error” is actually another form of an error that you couldn’t handle.

Here we share Dot Net tips to avoid an error from bubbling up in future.

In ASP.NET MVC you could handle lots of errors by inserting an error handler inside your Controller: You need to add a OnException method to your Controller. The code will be implored each time there is an “unhandled error” in the Controller.

It’s an easy way to add the method: In your Controller, you need to type Overrides (in Visual Basic) or override (in C#), next press the Tab key to get a list of override methods, pick OnException from the drop down list, and again press the Tab key. Visual Studio will write the structure of the method for you.

The version for Visual Basic will as shown below:

Protected Overrides Sub OnException(filter context As ExceptionContext)

End Sub

Your method then sends an ExceptionContext object whose Exception property will give you access to all of the information telling what went wrong. Within the OnException method, you can do anything you want about the error which appears specific to the Controller. If you don’t take any further action, the error will keep coming up to the ASP.NET error handler.

And if you are willing to finish by making use of RedirectToRouteResult method built into the Controller to send the user an error page of your choice then you must stop that process, by which the error pops out. You can do with this line:

filter context.ExceptionHandled = True

This sets the ExceptionContext object’s ExceptionHandled property to True.

Now with this, we conclude. We hope this was of help to you. Keep looking into this space for more blogs on dot net coding tips and tricks.

Keep coding!! 

To be successful in yours .Net career, try to enhance your skill set and improve yourself through Dot NET training programs. In this reference, CRB Tech Solutions, Pune could be of great help and support for you.

Stay connected to this space for more technical blogs and updates related to the world of Dot Net.

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

Final Features Of .NET Standard 2.0

The .NET Standard is a specification of the entire API’s that a .NET platform needs to implement in order to form a .NET platform. The standard is an open source, and you can find every different version and API’s in the same place.

Final Features Of .NET Standard 2.0

Now the .NET Standard 2.0 is with its final look. Microsoft has announced this and said that users can create .NET Standard 2.0 libraries and NuGet packages as well, but the company has suggested making use of .NET Core Preview 2 as it has several necessary enhancements to make your experience better.

Extra ordinary features of .NET Standard 2.0 as suggested by Microsoft:

Bigger API Surface

With doubled set of available APIs from 13k in .NET Standard 1.6 to 32k in version 2.0. will make it easier to port current codes to .NET Standard, and also to any .NET implementation of .NET Standard, like .NET Core 2.0 and the next version of UWP.

.NET Framework mode of compatibility

Majority of NuGet packages targets .NET Framework. Many projects are being blocked at present from moving to .NET Standard because all their dependencies are not targeting .NET Standard. Hence the need of compatibility mode that permits .NET Standard projects to depend on libraries of .NET Framework as if they were made for .NET Standard. It has been found that about 70% of NuGet packages on nuget.org are API compatible with .NET Standard 2.0, hence practically, it unblocks several projects.

Broad platform support

This will be supported on the below mentioned platforms:

.NET Framework 4.6.1

.NET Core 2.0

Mono 5.4

Xamarin.iOS 10.14

Xamarin.Mac 3.8

Xamarin.Android 7.5

Besides this, the company also told about the prerequisite tools for using .NET Standard 2.0. You need the latest versions of the following tools :

.NET Core SDK : Microsoft recommended to install .NET Core 2.0 Preview 2. This includes CLI as well.

Visual Studio: Users For this, you have to install Visual Studio 2017 15.3 which is the latest version of VS. For Mac users, the latest version of Visual Studio for Mac is perfect.

For more details, you can visit Microsoft site or read their release documents.

Now with this, we conclude. We hope this was of help to you.

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

Stay connected with us for your technical up-gradation and to remain updated with all the happenings in the world of Dot Net.

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

3 Aspects Every ASP.Net Developers Must Know

With several options to design web applications in MS ecosystem like ASP.Net MVC, ASP.Net Web Forms, Single Page Applications. From the start of ASP.Net it supported ASP.Net Web Forms and even today enterprises develop many of web applications using them. The web forms help you create faster web applications.

3 Aspects Every ASP.Net Developers Must Know

But it envelops the underlying technology i.e. HTTP totally.

If you know the basics, you must know how to summon javascript from your code behind codes in ASP.Net Code.

In this article, we covered 3 basic things which every ASP.Net developer must know while using ASP.Net Web Forms

1.The nature of HTTP and Request-Response pattern:

All web applications are created using ASP.Net use HTTP protocol or its secured versions. You can consider HTTPS as using HHTP safely. HTTPS makes use of Secure Socket Layer (SSL) and encrypts your data. But, HTTPS still use HTTP.

HTTP is a no state protocol which follows a response/request pattern i.e., the user requests a resource and the web server sends the resource.

The web server never keeps any state of the previous requests. If the user requests for the same resource, the web server will respond as if the request was made for the first time. There are several ways to maintain the state in a web application. ViewState is one such way. Here all the data is coded in a hidden field and sent to the client and hence the state can be maintained between requests.

There are several other ways available to maintain the state which would be discussed later. For the time being, it is for your information that even though HTTP is stateless, there are certain options to maintain the state.

2. Role of CSS, HTML,Javascript, ASPX page in ASP.Net web application

Your browser can only understand HTML, CSS, javascript . So the web technology must be converted to technology based code to HTML, CSS and JS.

HTML provides the layout of the web page.

CSS or Cascading style sheet will help you in putting styles to elements on the page.

Javascript is to process the elements at client side without hitting the server. Javascript is used only for validation, to handle the user input, to change the style of some element based on data or user input etc…

When a user reaches out for the ASP.Net web page, these are the sequence of events that occur:

User reaches out the web page

The request is sent to the server where the web application is hosted. The web server carries forward the request to ASP.Net because the requested resource is of aspx page.

Net converts ASP.Net code into CSS, HTML and JS

The changed document is sent back to the user and the user gets the web page via the browser.

3. Differences between client side and server side

The ASP.Net server controls are changed into HTML elements at server side and the changed HTML parts are sent to the browser. To mention, javascript works only on HTML parts, and you must know the HTML element of ASP.Net server control that you are making use of to have the attributes changed.

Now we conclude. Keep coding!!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute CRB Tech Solutions would be of great help and support. We offer well structured program for the Best Dot Net Training course.

Stay connected to with us for your technical up-gradation and to remain updated with all the happenings in the world of .Net.

Continue reading

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

The Use Of Validation Groups Inside ASP.NET User Controls

What does Validation groups do? Well, they permit you to validate data entry controls in the groups. Server controls like validation controls, Button and TextBox have ValidationGroup attributes that have a string value.

The Use Of Validation Groups Inside ASP.NET User Controls

All the server controls which have the same ValidationGroup value acts as a single validation group. Validation groups are necessary when you want to analyze only a small set of controls from several controls housed on a Web Form. Using validation groups is very easy and straight. But if you have a validation group inside a user control and there are many control instances on a Web Form you come across some problems.

To understand in details let’s develop a simple user control.

The Web Form has two instances of a user control – TestUC.ascx. The user control has a TextBox, a RequiredFieldValidator and a Button. The codes of the user control is shared below:

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server”

ControlToValidate=”TextBox1″ ErrorMessage=”*” Font-Bold=”True”

Font-Size=”30px” ForeColor=”Red”>*</asp:RequiredFieldValidator>

<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”Submit” />

<br />

<br />

<asp:Label ID=”Label1″ runat=”server” Font-Bold=”True” ForeColor=”Red”></asp:Label>

The Web Form has two instances of TestUC.ascx as mentioned below:

<%@ Page Language=”C#” … %>

<%@ Register Src=”~/TestUC.ascx” TagPrefix=”uc1″ TagName=”TestUC” %>

<!DOCTYPE html>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head runat=”server”>

<title></title>

</head>

<body>

<form id=”form1″ runat=”server”>

<uc1:TestUC runat=”server” id=”TestUC1″ />

<br />

<uc1:TestUC runat=”server” id=”TestUC2″ />

</form>

</body>

</html>

If you put the ValidationGroup property of TextBox1, RequiredFieldValidator1 and Button1 to some string (e.g. VG) and then carry out the Web Form you will find that once getting clicked either of the Submit buttons, both the RequiredFieldValidatior controls display an error.

This behavior though not expected but occurs as both the instances of the user control using same ValidationGroup value.

To remove this problem you can take two approaches:

Provide a different and unique ValidationGroup value to the user control from the Web Form

Produce a unique value for ValidationGroup inside the user control

The first solution needs creation of a property (e.g. ValidationGroup) in user control. This attribute will accept a unique string value for the ValidationGroup and will assign to all the other necessary server controls. This is how the property can be developed:

public string ValidationGroup

{

get

{

return Button1.ValidationGroup;

}

set

{

Button1.ValidationGroup = value;

TextBox1.ValidationGroup = value;

RequiredFieldValidator1.ValidationGroup = value;

}

}

As shown, the set block of ValidationGroup attribute assign the given value to the ValidationGroup of Button1, TextBox1 and RequiredFieldValidator1.Once the ValidationGroup property is developed you can set it from the Web Form as given below:

<form id=”form1″ runat=”server”>

<uc1:TestUC runat=”server” id=”TestUC1″ ValidationGroup=”Group1″ />

<br />

<uc1:TestUC runat=”server” id=”TestUC2″ ValidationGroup=”Group2″ />

</form>

The ValidationGroup property of TestUC1 and TestUC2 is set to different and unique values. Now each user controls will work as per expectations.

In the next approach mentioned above you can auto-generate ValidationGroup value within the user control itself. The following code tells you how:

protected void Page_Load(object sender, EventArgs e)

{

if(!IsPostBack)

{

string vgId = Guid.NewGuid().ToString();

Button1.ValidationGroup = vgId;

TextBox1.ValidationGroup = vgId;

RequiredFieldValidator1.ValidationGroup = vgId;

}

}

The above code reveals the Page_Load event handler of the user control. The Page_Load event handler develops a new Guid using Guid.NewGuid() method. Next it sets ValidationGroup property of Button1, TextBox1 and RequiredFieldValidaror1 to this Guid string. Thus, every example of user control gets a unique ValidationGroup value and the Web Form woks as expected.

That’s it for now! Keep coding!!

If you want to enhance yourself in Dot Net Course and improve yourself through Dot NET training program; our institute would be of great help and support. We offer well structured program for the Best Dot Net Course

Stay connected to CRB Tech for your technical up-gradation and to remain updated with all the happenings in the world of Dot Net.

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