Posts

Showing posts from October, 2016

Lession 33: C# FileInfo

You have learned how to perform different tasks on physical files using static File class in the previous section. Here, we will use FileInfo class to perform read/write operation on physical files. The FileInfo class provides the same functionality as the static File class but you have more control on read/write operations on files by writing code manually for reading or writing bytes from a file.

Lession 32: Working with Files & Directories

C# provides the following classes to work with the File system. They can be used to access directories, access files, open files for reading or writing, create a new file or move existing files from one location to another, etc.

Lession 31: C# Stream

Image
C# includes following standard IO (Input/Output) classes to read/write from different sources like a file, memory, network, isolated storage, etc. Stream:   System.IO.Stream  is an abstract class that provides standard methods to transfer bytes (read, write, etc.) to the source. It is like a wrapper class to transfer bytes. Classes that need to read/write bytes from a particular source must implement the Stream class. The following classes inherits Stream class to provide functionality to Read/Write bytes from a particular source:

Lession 30: C# Indexer

Image
An Indexer is a special type of property that allows a class or structure to be accessed the same way as array for its internal collection. It is same as property except that it defined with  this  keyword with square bracket and paramters.

Lession 29: C# Hashtable

C# includes Hashtable collection in  System.Collections  namespace, which is similar to generic  Dictionary  collection. The Hashtable collection stores key-value pairs. It optimizes lookups by computing the hash code of each key and stores it in a different bucket internally and then matches the hash code of the specified key at the time of accessing values.

Lession 28: C# Queue

Image
C# includes a Queue collection class in the  System.Collection  namespace. Queue stores the elements in FIFO style (First In First Out), exactly opposite of the  Stack  collection. It contains the elements in the order they were added. Queue collection allows multiple null and duplicate values. Use the Enqueue() method to add values and the Dequeue() method to retrieve the values from the Queue.

Lession 27: C# Stack

Image
C# includes a special type of collection which stores elements in LIFO style(Last In First Out). C# includes a generic and non-generic Stack. Here, you are going to learn about the non-generic stack. Stack allows null value and also duplicate values. It provides a Push() method to add a value and Pop() or Peek() methods to retrieve values.

Lession 26: C# SortedList

Image
The SortedList collection stores key-value pairs in the ascending order of key by default. SortedList class implements IDictionary & ICollection interfaces, so elements can be accessed both by key and index. C# includes two types of SortedList,  generic SortedList  and non-generic SortedList. Here, we will learn about non-generic SortedList.

Lession 25: C# ArrayList

ArrayList is a non-generic type of collection in C#. It can contain elements of any data types. It is similar to an  array , except that it grows automatically as you add items in it. Unlike an array, you don't need to specify the size of ArrayList.

Lession 24: C# Collection

We have learned about an array in the previous section. C# also includes specialized classes that hold many values or objects in a specific series, that are called 'collection'. There are two types of collections available in C#: non-generic collections and  generic collections . We will learn about non-generic collections in this section. Every collection class implements the  IEnumerable  interface so values from the collection can be accessed using a  foreach  loop. The  System.Collections  namespace includes following non-generic collections.

Lession 23: Jagged Array

A jagged array is an array of an array. Jagged arrays store arrays instead of any other data type value directly. A jagged array is initialized with two square brackets [][]. The first bracket specifies the size of an array and the second bracket specifies the dimension of the array which is going to be stored as values. (Remember, jagged array always store an array.) The following jagged array stores a two single dimensional array as a value:

Lession 22: Multi-dimensional Array

Image
We have learned about single dimensional arrays in the previous section. C# also supports multi-dimensional arrays. A multi-dimensional array is a two dimensional series like rows and columns.

Lession 21: C# Array

Image
We have learned that a  variable  can hold only one literal value, for example  int x = 1; . Only one literal value can be assigned to a variable x. Suppose, you want to store 100 different values then it will be cumbersome to create 100 different variables. To overcome this problem, C# introduced an array. An array is a special type of data type which can store fixed number of values sequentially using special syntax. The following image shows how an array stores values sequentially.

Lession 20: StringBuilder

Image
A String is immutable, meaning String cannot be changed once created. For example, new string "Hello World!!" will occupy a memory space on the heap. Now, by changing the initial string "Hello World!!" to "Hello World!! from Tutorials Teacher" will create a new string object on the memory heap instead of modifying the initial string at the same memory address. This behaviour will hinder the performance if the same string changes multiple times by replacing, appending, removing or inserting new strings in the initial string.

Lession 19: Enum in C#

In C#, enum is a value type data type. The enum is used to declare a list of named integer constants. It can be defined using the  enum  keyword directly inside a namespace, class, or structure. The enum is used to give a name to each constant so that the constant integer can be referred using its name.

How to add subdomain for Area in mvc?

I have a web application using asp.net MVC and have multiple Areas: localhost localhost/admin/home/index localhost/tech/home/index How can I add a subdomain for this Areas? example: localhost admin.localhost/home/index admin.tech/home/index

Lession 18: Structure in C#

We have learned class in the previous section. Class is a reference type. C# includes a value type entity, which is called Structure. A structure is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events and nested types. A structure can be defined using the  struct  keyword.

Lession 17: do-while loop

The do-while loop is the same as a 'while' loop except that the block of code will be executed at least once, because it first executes the block of code and then it checks the condition. Syntax: do { //execute code block } while( boolean expression ) As per the syntax above, do-while loop starts with the 'do' keyword followed by a code block and boolean expression with 'while'.

Lession 16: C# while loop

C# includes the while loop to execute a block of code repeatedly. Syntax: While( boolean expression ) { //execute code as long as condition returns true } As per the while loop syntax, the while loop includes a boolean expression as a condition which will return true or false. It executes the code block, as long as the specified conditional expression returns true. Here, the initialization should be done before the loop starts and increment or decrement steps should be inside the loop.

Lession 15: for loop in C#

Image
The  for  keyword indicates a loop in C#. The for loop executes a block of statements repeatedly until the specified condition returns false. for (variable initialization; condition; steps) { //execute this code block as long as condition is satisfied } As per the syntax above, the for loop contains three parts: initialization, conditional expression and steps, which are separated by a semicolon. variable initialization: Declare & initialize a variable here which will be used in conditional expression and steps part. condition: The condition is a boolean expression which will return either true or false. steps: The steps defines the incremental or decremental part Consider the following example of a simple for loop.

Lession 14: switch statement

C# includes another decision making statement called switch. The switch statement executes the code block depending upon the resulted value of an expression. Syntax: switch(expression) { case <value1> // code block break; case <value2> // code block break; case <valueN> // code block break; default // code block break; } As per the syntax above, switch statement contains an expression into brackets. It also includes multiple case labels, where each case represents a particular literal value. The switch cases are seperated by a break keyword which stops the execution of a particular case. Also, the switch can include a default case to execute if no case value satisfies the expression.

Lession 13: Ternary operator "?:"

C# includes a special type of decision making operator '?:' called the ternary operator. Syntax: var result = Boolean conditional expression ? first statement : second statement As you can see in the above syntax, ternary operator includes three parts. First part (before ?) includes conditional expression that returns boolean value true or false. Second part (after ? and before :) contains a statement which will be returned if the conditional expression in the first part evalutes to true. The third part includes another statement which will be returned if the conditional expression returns false.

Lession 12: if statement

C# provides many decision making statements that help the flow of the C# program based on certain logical conditions. C# includes the following decision making statements. if statement if-else statement switch statement Ternary operator :? Here, you will learn about the if statements.

Lession 11: C# Operators

Operator in C# is a special symbol that specifies which operations to perform on operands. For example, in mathematics the plus symbol (+) signifies the sum of the left and right numbers. In the same way, C# has many operators that have different meanings based on the data types of the operands. C# operators usually have one or two operands. Operators that have one operand are called Unary operators.

Lession 10: C# Interface

An interface in C# contains only the declaration of the methods, properties, and events, but not the implementation. It is left to the class that implements the interface by providing implementation for all the members of the interface. Interface makes it easy to maintain a program.

Lession 09: C# Keywords

Image
C# contains reserved words, that have special meaning for the compiler. These reserved words are called "keywords". Keywords cannot be used as a name (identifier) of a variable, class, interface, etc. Keywords in C# are distributed under the following categories:

Lession 08: Value Type and Reference Type

Image
We have learned about the data types in the previous section. In C#, these data types are categorized based on how they store their value in the memory. C# includes following categories of data types: Value type Reference type

Lession 07: Data types in C#

In the previous section, we have seen that a variable must be declared with the data type because C# is a strongly-typed language. For example, string message = "Hello World!!"; string is a data type, message is a variable, and "Hello World!!" is a string value assigned to a variable - message. The data type tells a C# compiler what kind of value a variable can hold. C# includes many in-built data types for different kinds of data, e.g., String, number, float, decimal, etc.

Lession 06: C# Variable

Image
In the  first C# program  section, we declared a variable called "message" as shown below. Example: C# Variable namespace CSharpTutorials { class Program { static void Main( string [] args) { string message = "Hello World!!" ; Console .WriteLine(message); } } }

Lession 05: C# Class

Image
A class is like a blueprint of specific object. In the real world, every object has some color, shape and functionalities. For example, the luxury car Ferrari. Ferrari is an object of the luxury car type. The luxury car is a class that specify certain characteristic like speed, color, shape, interior etc. So any company that makes a car that meet those requirements is an object of the luxury car type. For example, every single car of BMW, lamborghini, cadillac are an object of the class called 'Luxury Car'. Here, 'Luxury Car' is a class and every single physical car is an object of the luxury car class. Likewise, in object oriented programming, a class defines certain properties, fields, events, method etc. A class defines the kinds of data and the functionality their objects will have. A class enables you to create your own custom types by grouping together variables of other types, methods and events. In C#, a class can be defined by using the class keyword.

Lession 04: First C# Program

Image
In the previous section, we have created a console project. Now, let's write simple C# code to understand important building blocks. Every console application starts from the Main() method of Program class. The following example code displays "Hello World!!" on the console.

Lession 03: Setup Developement Environment for C#

Image
C# is used for server side execution for different kind of application like web, window forms or console etc. In order to use C# with your .Net application, you need two things, .NET Framework and IDE (Integrated Development Environment). The .NET Framework: The .NET Framework is a platform where you can write different types of web and desktop based applications. You can use C#, Visual Basic, F# and Jscript to write these applications. If you have the Windows operating system, the .NET framework might already be installed in your PC. Check MSDN to learn about .NET Framework dependencies. Integrated Development Environment (IDE): An IDE is a tool that helps you write your programs. Visual Studio is an IDE provided by Microsoft to write the code in languages such as C#, F#, VisualBasic, etc. Use Visual Studio 2010/2012/2013 based on the C# version you want to work with. You can write C# code with notepad also. Build your C# program using command line tool csc.exe. Visit...

Lession 02: C# Version History

C# is a simple & powerful object-oriented programming language developed by Microsoft. C# has evolved much since its first release in 2002. C# was introduced with .NET Framework 1.0 and the current version of C# is 5.0. The following table lists important features introduced in each version of C#:

How to Get tablename from Generic object ?

You could use the  Type.GetGenericArguments  method for this purpose. var myList = new List<T>(); var myListElementType = myList.GetType().GetGenericArguments().Single(); var nameTable = myListElementType.Name;

Display multiline text in razor

When user wants post data, we are using textarea for input. This data is stored into database and we are retrieving it using razor @Html.DisplayFor(). The Data for textarea is like this (inputed by user) Shall I compare thee to a summer's day?  Thou art more lovely and more temperate: Rough winds do shake the darling buds of May, And summer's lease hath all too short a date:  Sometime too hot the eye of heaven shines, And often is his gold complexion dimm'd; and when we retrieve it using this, <em>@Html.DisplayFor(model => item.inputvalue)</em> but it is displayed as unformated text like below, Shall I compare thee to a summer’s day? Thou art more lovely and more temperate:Rough winds do shake thedarling buds of May,And summer’s lease hath all too short a date: Sometime too hot the eye of heaven shines,And often is his gold complexion dimm’d; How can we format display text? Solution: @Html.Raw(Model.Inputvalue.Replace(Environment.NewLine, "<br...

Lession 01: C# Tutorials

C# is a simple & powerful object-oriented programming language developed by Microsoft. C# can be used to create various types of applications, such as web, windows, console applications or other types of applications using Visual studio. These C# tutorials will help you learn the essentials of C#, from the basic to advance level topics. These tutorials are broken down into sections, where each section contains a number of related topics that are packed with easy to understand explanations, real-world examples, useful tips, informative notes and a "points to remember" section. For Whom? These tutorials are designed for beginners and professionals who want to learn C# step-by-step.

Lession 31: Custom IPrincipal

This article explains a simple tip on how to customized the  IPrincipal  used in ASP.NET MVC4 internet application project template. You can try this tip if you want to attach additional information on the  IPrincipal (Controller.User) for some purposes.

Lession 30: AJAX in ASP.Net MVC

AJAX Helpers in ASP.NET MVC Tutorials x helper of ASP.NET MVC essentially provides Ajax functionality to your web applications. AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. Using Ajax helper you can submit your HTML form using Ajax so that instead of refreshing the entire web page only a part of it can be refreshed. Additionally, you can also render action links that allow you to invoke action methods using Ajax. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc.Ajax namespace.

Lession 29: Rewrite Url MVC5

Understanding URL Rewriting and URL Attribute Routing in ASP.NET MVC (MVC5) with Examples Url Re writing and Routing is how ASP.NET MVC matches a URI to an action. MVC 5 supports a new type of routing, called attribute routing, which is also works in ASP.NET vNext. Attribute routing uses attributes to define routes. Attribute routing provides us more control over the URIs in your web application. The MVC4 or earlier style of routing, which is called convention-based routing, is still fully supported. In fact, the major advantage of MVC5 is that, we can combine both techniques in the same application. In this article I will try to cover the basic features and options of Attribute Routing and Url Rewriting in ASP.NET MVC5.

Lession 28: Area

Image
You have already learned that ASP.NET MVC framework includes separate folders for Model, View and Controller. However, large application can include a large number of controller, views and model classes. So to maintain a large number of views, models and controllers with the default ASP.NET MVC project structure can become unmanageable ASP.NET MVC 2 introduced Area. Area allows us to partition large application into smaller units where each unit contains separate MVC folder structure, same as default MVC folder structure. For example, large enterprise application may have different modules like admin, finance, HR, marketing etc. So an Area can contain separate MVC folder structure for all these modules as shown below.

Lession 27.2: StyleBundle

Image
You have learned how to create a bundle of JavaScript files in the previous section. Here, you will learn how to create a bundle of style sheet files (CSS). ASP.NET MVC API includes  StyleBundle  class that does CSS minification and bundling. StyleBundle is also derived from a Bundle class so it supports same methods as ScriptBundle. As mentioned in the previous section, you should create bundles of script and css files in the RegisterBundles() method of BundleConfig class contained in App_Start -> BundleConfig.cs file.

Lession 27.1: ScriptBundle in ASP.NET MVC

Image
We have learned how bundling technique works in ASP.NET MVC. Here, we will learn how to create a bundle of multiple JavaScript files in one http request. ASP.NET MVC API includes  ScriptBundle  class that does JavaScript minification and bundling. Open App_Start\BundleConfig.cs file in the MVC folders. The BundleConfig.cs file is created by MVC framework by default. You should write your all bundling code in the BundleConfig.RegisterBundles() method. (you can create your own custom class instead of using BundleConfig class, but it is recommended to follow standard practice.) The following code shows a portion of the RegisterBundles method.

Lession 27: Bundling

Image
Bundling and minification techniques were introduced in MVC 4 to improve request load time. Bundling allow us to load the bunch of static files from the server into one http request. The following figure illustrates the bundling techniques:

Lession 26: Action Filters

Image
In the previous section, you learned about filters in MVC. In this section, you will learn about another filter type called  Action Filters  in ASP.NET MVC. Action filter executes before and after an action method executes. Action filter attributes can be applied to an individual action method or to a controller. When action filter applied to controller then it will be applied to all the action methods in that controller. OutputCache is a built-in action filter attribute that can be apply to an action method for which we want to cache the output. For example, output of the following action method will be cached for 100 seconds.

Lession 25: Filters in MVC

Image
In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However, there may be circumstances where you want to execute some logic before or after an action method executes. ASP.NET MVC provides filters for this purpose. ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after an action method executes. Filters can be applied to an action method or controller in a declarative or programmatic way. Declarative means by applying a filter attribute to an action method or controller class and programmatic means by implementing a corresponding interface. MVC provides different types of filters. The following table list filter types, built-in filters for the type and interface which must be implemented to create a custom filter class.

Lession 24: TempData

Image
TempData in ASP.NET MVC can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request. TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects. It is dictionary type which is derived from  TempDataDictionary . You can add a key-value pair in TempData as shown in the below example.

Lession 23: ViewData

Image
ViewData is similar to ViewBag. It is useful in transferring data from Controller to View. ViewData is a dictionary which can contain key-value pairs where each key must be string. The following figure illustrates the ViewData.

Lession 22: ViewBag in ASP.NET MVC

Image
We have learned in the previous section that the model object is used to send data in a razor view. However, there may be some scenario where you want to send a small amount of temporary data to the view. So for this reason, MVC framework includes ViewBag. ViewBag can be useful when you want to transfer temporary data (which is not included in model) from the controller to the view. The viewBag is a  dynamic  type property of ControllerBase class which is the base class of all the controllers. The following figure illustrates the ViewBag.

Lession 21: Partial View

Image
In this section you will learn about partial views in ASP.NET MVC. What is Partial View? Partial view is a reusable view, which can be used as a child view in multiple other views. It eliminates duplicate coding by reusing same partial view in multiple places. You can use the partial view in the layout view, as well as other content views. To start with, let's create a simple partial view for the following navigation bar for demo purposes. We will create a partial view for it, so that we can use the same navigation bar in multiple layout views without rewriting the same code everywhere.

Lession 20: Create Layout View

Image
To create a new layout view in Visual Studio, right click on shared folder -> select Add -> click on New Item.. In the Add New Item dialogue box, select MVC 5 Layout Page (Razor) and give the layout page name as "_myLayoutPage.cshtml" and click  Add .

Lession 19: Layout View

Image
In this section, you will learn about the layout view in ASP.NET MVC. What is Layout view? An application may contain common parts in the UI which remains the same throughout the application such as the logo, header, left navigation bar, right bar or footer section. ASP.NET MVC introduced a Layout view which contains these common UI parts, so that we don't have to write the same code in every page. The layout view is same as the master page of the ASP.NET webform application. For example, an application UI may contain Header, Left menu bar, right bar and footer section that remains same in every page and only the centre section changes dynamically as shown below.

Lession 18.3: ValidationSummary

Image
The ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display custom error messages. The following figure shows how ValidationSummary displays the error messages.

Lession 18.2: ValidationMessageFor

Image
The Html.ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object. ValidationMessageFor() Signature: MvcHtmlString ValidateMessage(Expression<Func<dynamic,TProperty>> expression, string validationMessage, object htmlAttributes) Visit MSDN to know all the  overloads of ValidationMessageFor() method .

Lession 18.1: ValidationMessage

Image
You have learned how to implement validation in a view in the presious section. Here, we will see the HtmlHelper extension method ValidtionMessage in detail. The Html.ValidationMessage() is an extension method, that is a loosely typed method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

Lession 18: Implement Data Validation in MVC

Image
In this section, you will learn how to implement data validations in the ASP.NET MVC application. We have created an Edit view for Student in the previous section. Now, we will implement data validation in the Edit view, which will display validation messages on the click of Save button, as shown below if Student Name or Age is blank.

Lession 17: Create Edit View

Image
We have already created the Index view in the previous section. In this section, we will create the Edit view using a default scaffolding template as shown below. The user can update existing student data using the Edit view.

Lession 16: Model Binding

Image
In this section, you will learn about model binding in MVC framework. To understand the model binding in MVC, first let's see how you can get the http request values in the action method using traditional ASP.NET style. The following figure shows how you can get the values from HttpGET and HttpPOST request by using the Request object directly in the action method.

Lession 15.10: HtmlHelper.Editor

Image
We have seen different HtmlHelper methods used to generated different html elements in the previous sections. ASP.NET MVC also includes a method that generates html input elements based on the datatype. Editor() or EditorFor() extension method generates html elements based on the data type of the model object's property. The following table list the html element created for each data type by Editor() or EditorFor() method.

Lession 15.9: Create Label using HtmlHelper

Learn how to create <label> element using HtmlHelper in razor view in this section. HtmlHelper class includes two extension methods to generate html label : Label() and LabelFor(). We will use following Student model with to demo Label() and LabelFor() method.

Lession 15.8: Create Html String using HtmlHelper

Learn how to create html string literal using HtmlHelper in razor view in this section. HtmlHelper class includes two extension methods to generate html string : Display() and DisplayFor(). We will use the following Student model with the Display() and DisplayFor() method.

Lession 15.7: Create Password field using HtmlHelper

Image
Learn how to generate Password field using HtmlHelper in razor view in this section. HtmlHelper class includes two extension methods to generate a password field (<input type="password">) element in a razor view: Password() and PasswordFor(). We will use following Student model with Password() and PasswordFor() method.

Lession 15.6: Create Hidden field using HtmlHelper

Learn how to generate hidden field using HtmlHelper in razor view in this section. HtmlHelper class includes two extension methods to generate a hidden field (<input type="hidden">) element in a razor view: Hidden() and HiddenFor(). We will use the following Student model with Hidden() and HiddenFor() method.