ASP.NET MVC – Project Items

ASP.NET MVC – Project Items

/App_Data

This folder contains private data such as XML Files or databases if you are using SQL Server Express, SQLite, or other file based repositories.

IIS web server will not server any other the contains from this folder.

/App_Start

This folder has core configuration settings about the project, including route definitions, filters and content bundles.

/Areas

Areas is a way to partition large application into smaller pieces.

/bin

Bin consists of the compiled assembly of MVC application along with any referenced assemblies that are not in the GAC.

/Content

This folder holds the content for CSS files and images.

/Controllers

This folder contains all the controllers.

/Models

This folder has all the view model and domain model classes.

/Scripts

This directory holds the JavaScript libraries.

/Views

This directory holds the views and partial views, grouped by the controller name. The web.config file prevents the views to be served by IIS. It must be rendered by action methods in controller class.

/View/Shared

This directory holds layouts and views which are not specific to a single controller.

/Views/Web.config

It contains the configuration required to make views work with ASP.NET and prevents views from being served by IIS and the namespaces imported into views by default.

/Global.asax

This is the global ASP.NET application class. Its code-behind class (Global.asax.cs) is the place to register routing configuration, as well as set up any code to run on application initialization or shutdown, or when unhandled exceptions occur.

/Web.config

This is the configuration file for the application.

Happy Days!!

Live as if you were to die tomorrow. Learn as if you were to live forever.. -Mahatma Gandhi

ASP.NET MVC – Controllers

Controllers

The controller is responsible for the request made by the browser, each request is mapped to a particular controller.

The controller can return a view or redirect to another controller.

The controller is just a class derived from the base System.Web.Mvc.Controller class.

Controller Actions

Action is a method on a controller which gets called when you enter a URL in the browser address.

A controller action needs to be a public method of a controller class.

Controller action methods cannot be overloaded.

Action Results

A controller returns an action result in response to the browser request.

ViewResult – Represents HTML and markup.

EmptyResult – Represents no result.

RedirectResult – Represents a redirection to a new URL.

JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.

JavaScriptResult – Represents a JavaScript script.

ContentResult – Represents a text result.

FileContentResult – Represents a downloadable file (with the binary content).

FilePathResult – Represents a downloadable file (with a path).

FileStreamResult – Represents a downloadable file (with a file stream).

An action result is not passed directly instead the following is passed:

View – Returns a ViewResult action result.

namespace MvcApplication1.Controllers
{
    public class BookController : Controller
    {
        public ActionResult Index()
        {
            // Add action logic here
            return View();
        }
    }
}

Redirect – Returns a RedirectResult action result.

RedirectToAction – Returns a RedirectToRouteResult action result.

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class CustomerController : Controller
    {
        public ActionResult Details(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Index");

            return View();
        }
    }
}

RedirectToRoute – Returns a RedirectToRouteResult action result.

Json – Returns a JsonResult action result.

JavaScriptResult – Returns a JavaScriptResult.

Content – Returns a ContentResult action result.

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class StatusController : Controller
    {
        public ActionResult Index()
        {
            return Content("Hello World!");
        }
    }
}

File – Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.

HttpUnauthorizedResult – forces the user to login.

 

Live as if you were to die tomorrow. Learn as if you were to live forever.. -Mahatma Gandhi

C# – Working with Excel

Working with Excel

Library

Include

using Excel = Microsoft.Office.Interop.Excel

Instantiating the excel application class

Excel.Application excelApp = new Excel.Application();

To make the object visible

excelApp.Visible = true; //false to turnoff visibility

Add a workbook

Excel.Workbook openExcel = excelApp.Workbooks.Add(Type.Missing);

or to add an existing excel file

var path = @"C:\\excel.xlsx";
Excel.Workbook openExcel = excelApp.Workbooks.Open(path);

To add blank sheets

Excel.Sheets sheets = openExcel.Worksheets;
Excel._Worksheet worksheet = (Excel.Worksheet)sheets.Add(Type.Missing);

To select active sheet

Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

or To select sheet by name

Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.Worksheets[sheetname];

Writing to the cell

workSheet.Cells[1, "A"] = "Fund";

Set the column width

workSheet.Columns.ColumnWidth = 18;

Using get_Range and format header

Excel.Range headerColumnRange = workSheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
headerColumnRange.WrapText = true;
headerColumnRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

Name of the worksheet

workSheet.Name = name.Substring(0, len);

Format cells

workSheet.Cells[startCell, strAlpha].NumberFormat = "0.00";

Autofit columns

workSheet.Columns.AutoFit();

Save

openExcel.Save();

SaveAs .xlsx

openExcel.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
    Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Excel.XlSaveConflictResolution.xlUserResolution, true, 
    Missing.Value, Missing.Value, Missing.Value);

Close excel

openExcel.Close();

Copy or Cloning

foreach(Worksheet sheet in workBook.Worksheets)
{
    var newbook = app.Workbooks.Add(1);
    sheet.Copy(newbook.Sheets[1]);

    newbook.SaveAs(FileDropLocation + "\\" + sheet.Name);
    newbook.Close();
}

workBook.Close();

Delete worksheet

workSheet.Worksheets[2].Delete();

Border

Microsoft.Office.Interop.Excel.Borders border = celLrangE.Borders;  
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;  
border.Weight = 2d; 

C# – LINQ to read XML

LINQ to read XML

Loading the XML File

XElement and XDocument derive from XContainer.

1. XElement class

Reads the XML elements (attributes and children)

Implements IXmlSerializable.

XElement xelement = XElement.Load(file);
IEnumerable employees = xelement.Elements();
//Read the entire XML
foreach(var employee in employees)
{
	Console.WriteLine("Reading Employee: == " + employee);
}

2. XDocument class

Reads the entire XMl document.

Reads from the single root element.

XDocument xdocument = XDocument.Load(file);
IEnumerable employees = xdocument.Elements();
foreach(var employee in employees)
{
     Console.WriteLine("Reading Employee: == " + employee);
}

Reading the Single Element

foreach(var employee in employees)
{
     Console.WriteLine("Reading Employee: == " + employee.Element("Name").Value);
}

Reading Multiple Elements

foreach(var employee in employees)
{
Console.WriteLine("Reading Employee: {0} == {1}", employee.Element("Name").Value, employee.Element("EmpId").Value);
}

Filter Elements

XElement xelement = XElement.Load(file);
var name = from nm in xelement.Elements("Employee")
    where (string)nm.Element("Sex") == "Female"
    select nm;

    Console.WriteLine("Information about Female Employees");
    foreach(XElement x in name)
    {
	Console.WriteLine(x);
    }

Filter Element within another Element

XElement xelement = XElement.Load(file);
var addresses = from address in xelement.Elements("Employee")
	where (string)address.Element("Address").Element("City") == "Alta"
	select address;

Console.WriteLine("Information about Employees in Alta City");
foreach(XElement x in addresses)
{
	Console.WriteLine(x);
}

Find Nested Elements using Descendants

XElement xelement = XElement.Load(file);
Console.WriteLine("List of all Zip codes");
foreach(XElement x in xelement.Descendants("Zip"))
{
    Console.WriteLine((string)x);
}

Sorting Elements

XElement xelement = XElement.Load(file);
IEnumerable codes = from code in xelement.Elements("Employee")
	let zip = (string)code.Element("Address").Element("Zip")
        orderby zip
	select zip;
Console.WriteLine("List and Sort all Zip Codes");
			 
foreach (string zp in codes)
	Console.WriteLine(zp);

C# – LinkedList

LinkedList

LinkedList<T> is a generic doubly linked list.

Doubly linked list is a chain of nodes in which each references the node before, the node after and the actual element.

Benefit – element can always be inserted efficiently anywhere in the list, since it just involves creating a new node and updating a few references.

Implements IEnumerable<T> and ICollection<T>.

LinkedList<T> supports copying to an array for indexed processing and obtaining an enumerator to support foreach statement.

public sealed class LinkedListNode
{
	public LinkedList List { get; }
	public LinkedListNode Next { get; }
	public LinkedListNode Previous { get; }
	public T Value { get; set; }
}
var tune = new LinkedList();
tune.AddFirst ("do");                           tune.Dump(); // do
tune.AddLast ("so");                            tune.Dump(); // do - so

tune.AddAfter (tune.First, "re");               tune.Dump(); // do - re- so
tune.AddAfter (tune.First.Next, "mi");          tune.Dump(); // do - re - mi- so
tune.AddBefore (tune.Last, "fa");               tune.Dump(); // do - re - mi - fa- so

tune.RemoveFirst();                             tune.Dump(); // re - mi - fa - so
tune.RemoveLast();                              tune.Dump(); // re - mi - fa

LinkedListNode miNode = tune.Find ("mi");
tune.Remove (miNode);                           tune.Dump(); // re - fa
tune.AddFirst (miNode);                         tune.Dump(); // mi- re - fa

C# – IReadOnlyList

IReadOnlyList<T>

Low version of IList<T> which provides only readonly view of list.

public interface IReadOnlyList<out T> : IEnumerable<T>, IEnumerable
{
	int Count { get; }
	T this[int index] { get; }
}

C# – IList

IList<T> and IList

IList<T>

Standard interface for collection indexable by position.

Functionality inherited from ICollection<T> and IEnumerable<T>.

Provides the ability to read or write an element by position.

public interface IList : ICollection, IEnumerable, IEnumerable
{
	T this [int index] { get; set; }
	int IndexOf (T item);
	void Insert (int index, T item);
	void RemoveAt (int index);
}

IndexOf – performs liner search, returns -1 if item not found.

Insert – inserts at specified index.

RemoveAt – removes at specified index.

IList

public interface IList : ICollection, IEnumerable
{
object this [int index] { get; set }
bool IsFixedSize { get; }
bool IsReadOnly { get; }
int Add (object value);
void Clear();
bool Contains (object value);
int IndexOf (object value);
void Insert (int index, object value);
void Remove (object value);
void RemoveAt (int index);
}

Add – returns an integer index of the newly added item.

C# – ICollection

ICollection<T> and ICollection

ICollection<T> is the standard interface for countable collections of objects.

It provides the ability to determine the size of a collection (Count).

If the collection is writable you can also Add, Remove and Clear items from the collection.

Collection can be traversed via foreach statement since it extends IEnumerable.

Methods and Properties

Contains – determine whether an item exists in the collection.

ToArray – copy the collection into an array.

IsReadOnly – determine whether the collection is read-only.

Count-size of the collection.

Add– add item to the collection.

Remove– remove item from collection.

Clear– clear collection.

Generic Collection

public interface ICollection<T> : IEnumerable<T>, IEnumerable
{
	int Count { get; }
	
	bool Contains (T item);
	void CopyTo (T[] array, int arrayIndex);
	bool IsReadOnly { get; }

	void Add(T item);
	bool Remove (T item);
	void Clear();
}

Non Generic Collection

public interface ICollection : IEnumerable
{
	int Count { get; }
	bool IsSynchronized { get; }
	object SyncRoot { get; }
	void CopyTo (Array array, int index);
}

The interface is implemented in conjunction with either IList or IDictionary.

C# – IEnumerable and IEnumerator

IEnumerable and IEnumerator

Related Article

IEnumerator Interface

Elements in a collection are enumerated in a forward manner only.

public interface IEnumerator
{
	bool MoveNext();
	object Current { get; }
	void Reset();
}

MoveNext – advances the current element to the next position or returns false if there are no more elements in the collection.

Current – returns the element at the current position.

Reset – moves back to the start of the collection.

Collections do not implement enumerators, instead they provide enumerators via the interface IEnumerable.

public interface IEnumerable
{
	IEnumerable GetEnumerator();
}

IEnumerable

Provides flexibility in that the iteration logic can be farmed off to another class.

Several consumers can enumerate the collection at once without interfering with each other.

IEnumerable can be thought of as IEnumeratorProvider.

string s = "Hello";

// Because string implements IEnumerable, we can call GetEnumerator():
IEnumerator rator = s.GetEnumerator();

while (rator.MoveNext())
{
	char c = (char) rator.Current;
	Console.Write (c + ".");
}

Console.WriteLine();

// Equivalent to:

foreach (char c in s)
	Console.Write (c + ".");

IEnumerable<T> and IEnumerator<T>

IEnumerator and IEnumerable are nearly always implemented in conjunction with their extended generic versions.

public interface IEnumerator : IEnumerator, IDisposable
{
	T Current { get; }
}

public interface IEnumerable : IEnumerable
{
	IEnumerator GetEnumerator();
}

By defining typed version of Current and GetEnumerator, these interfaces strengthen static type safety and avoid the boxing overhead.

Arrays automatically implement IEnumerable<T>.

IEnumerable<T> and IDisposable

IEnumerator<T> inherits from IDisposable.

This allows enumerators to hold references to resources such as database connections to ensure that those resources are released when enumeration is complete.

foreach (var element in somethingEnumerable) { ... }

translates into:

using ( var rator = somethingEnumerable.GetEnumerator())
	while (rator.MoveNext())
	{
		var element = rator.Current;
		...
	}

The using block ensures disposal.

IEnumerable s = "Hello";

using (var rator = s.GetEnumerator())
	while (rator.MoveNext())
	{
		char c = (char) rator.Current;
		Console.Write (c + ".");
	}

Non Generic Interface

void Main()
{
   Count("the quick brown fox".Split());
}

public static int Count(IEnumerable e)
{
   int count = 0;
   foreach (object element in e)
   {
      var subCollection = element as IEnumerable;
      if (subCollection != null)
          count += Count (subCollection);
      else
          count++;
   }
   return count;
}

IEnumerable or IEnumerable<T> can be implemented for one of the reasons:

  • To support the foreach statement.
  • To inter-operate with anything expecting a standard collections.
  • To meet the requirements of a more sophisticated collection interface.
  • To support collection initializers.

To implement IEnumerable/IEnumerable<T>:

  • If class is wrapping another collection, return the wrapped collection’s enumerator
  • Using the iterator yield return
  • By instantiating your own implementation

Using Iterator

void Main()
{
	foreach (int element in new MyCollection())
		Console.WriteLine (element);
}

public class MyCollection : IEnumerable
{
	int[] data = { 1, 2, 3 };
	
	public IEnumerator GetEnumerator()
	{
		foreach (int i in data)
			yield return i;
	}
}

Using Iterator using Generic

void Main()
{
	foreach (int element in new MyGenCollection())
		Console.WriteLine (element);
}

public class MyGenCollection : IEnumerable<int>
{
	int[] data = { 1, 2, 3 };

	public IEnumerator GetEnumerator()
	{
		foreach (int i in data)
			yield return i;
	}

	IEnumerator IEnumerable.GetEnumerator()     // Explicit implementation
	{                                           // keeps it hidden.
		return GetEnumerator();
	}
}

Using Iterator Method

The yield statement allows for an easier variation. Instead of writing a class the iteration logic can be moved into a method returning a generic IEnumerable<T> and let the compiler take care of the rest.

void Main()
{
	foreach (int i in Test.GetSomeIntegers())
		Console.WriteLine (i);
}

public class Test
{
	public static IEnumerable  GetSomeIntegers()
	{
		yield return 1;
		yield return 2;
		yield return 3;
	}
}