Rss Feed Like Us on facebook Google Plus
Showing posts with label C Sharp. Show all posts
Showing posts with label C Sharp. Show all posts

June 4, 2013

Generate Excel to Export Data using Datatable

Generate Excel is a Major Feature which is used frequently in Web Applications as well as
in Console Applications. So i am going to present an article about generating excel with MS-Excel installed on and without MS-Excel installed on target computer.

Problem with Excel Automation
The technique that is most frequently used to transfer data to an Excel workbooks is Automation. With Automation, you can call methods and properties that are specific to Excel tasks, but this solution has many drawbacks. Some of them are described in the Microsoft Knowledge Base. Additionally, you have to manage the lifetime of the temporary Excel files(.xls) created on the server. Also, it is slow, because Excel runs in a separate process.


  • You can generate excel without MS-Office installed on target computer..
  • You Can Export Data Table data to created Excel

class GenerateExcel
 
{
//  This function will Genereate Excel without MS-Office installed on target computer
 public void CreateExcel(string fileName)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
                Console.WriteLine("** Excel Deleted ***");
            }
            if (!File.Exists(fileName))
            {
                FileStream stream = new FileStream(filename, FileMode.OpenOrCreate); 
                stream.Close();
                Console.WriteLine("** Excel Created ***");
            }
        }
  
        public void createExcelwithMSOffice(string fileName)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
                Console.WriteLine("** Excel Deleted ***");
                swlog.WriteLine("***  Excel Exists....Excel Deleted.....  ***");
            }
            if (!File.Exists(fileName))
            {
                Application xl = null;
                _Workbook wb = null;
                object misValue = System.Reflection.Missing.Value;
 
                xl = new Application();
                xl.SheetsInNewWorkbook = 1;
                wb = (_Workbook)(xl.Workbooks.Add(Missing.Value));
                wb.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                wb.Close(true, misValue, misValue);
                Console.WriteLine("** Excel Created ***");
                swlog.WriteLine("***    New Excel Created     ***");
            }
        }
 
 //  This function will export Datatable Data to Created Excel......

        public void ExportToSpreadsheet(System.Data.DataTable table, string name)
        {
            StreamWriter sw = null;
            sw = new StreamWriter(name);
            string ColValue;
            string ColName = "";
            if (table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    ColName = table.Columns[i].ColumnName.ToString() + "\t";
                    sw.Write(ColName);
                }
                sw.WriteLine("\t");
                foreach (DataRow row in table.Rows)
                {
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        ColName = table.Columns[i].ColumnName.ToString();
                        ColValue = row[i].ToString();
                        ColValue = ColValue.ToString().Replace(",", string.Empty) + "\t";
                        ColValue = ColValue.ToString().Replace(Environment.NewLine, " ");
                        ColValue = ColValue.ToString().Replace("\n", " ");
                        //ColValue = ColValue.ToString().Replace(" ", "");
                        ColValue = ColValue.ToString().Replace("-Select-;", "");
                        if (table.Columns[i].DataType.Name == "Boolean")
                        {
                            ColValue = ColValue.ToString().Replace("True", "Yes");
                            ColValue = ColValue.ToString().Replace("False", "No");
                        }
                        sw.Write(ColValue);
                    }
                    sw.WriteLine("\t");
                }
                sw.Close();
                Console.WriteLine("** Data Exported to Excel ***");
            }
            else
            {
                Console.WriteLine("** No Data to Export in Excel ***");
                Environment.Exit(0);
            }
        }
}

Calling the functions..


class Program
    {
        static void Main(string[] args)
        {
           System.Data.DataTable dt = new DataTable();
           GenerateExcel oexcel = new GenerateExcel ();
           string filename=@"C:\demo.xls";
           oexcel.CreateExcel(filename);
           oexcel.ExportToSpreadsheet(dt,filename);
         }
    } 
I hope this article gives you a head start in working with Excel files from .NET and C#.
Read More

February 23, 2012

Top 10 Most Popular Programming Language

The knowledge of a handful of programming languages could come to be a lifesaver to many a programmer, especially since most languages that were popular 10 years ago are not as viable as they are now.

But there are many developers who have earned their worth simply by knowing the right programming language at the right time, simply because they had solid skills that were profitable while the language was popular.

Here are some languages though, which stayed popular through the years, and prove to give young developers a jumpstart to their careers, and always are a bonus to add to any developer’s resume, as compiled by TIOBE software, a coding standards company.

1. Java

What is it?
 An object-oriented programming language developed in the late 1990s by James Gosling and colleagues at Sun Microsystems.

Why is it important?
This “beautiful” programming language is central for any non-Microsoft developer, i.e. any developer who focuses on the non-.NET experience. It is mostly derived from C and C++ but has a more basic object model. It ranked first on TIOBE’s list of most popular programming languages.

2. C

What is it?
C, a general purpose programming language built by Dennis Ritchie when he was a part of Bell Telephone labs, is the bass of C++ and other programming languages. It was built to work with the Unix operating system.

Why is it important?
C is one of the most widely used programming languages of all time, and ranked second on the list. “Learning C is crucial. Once you learn C, making the jump to Java or C# is fairly easy, because a lot of the syntax is common. Also, a lot of C syntax is used in scripting languages,” Wayne Duqaine, director of Software Development at Grandview Systems, of Sebastopol, Calif., told eWEEK.
 
3. C#

What is it?
This general-purpose programming language developed by Microsoft evolved from C and C++ as a part of the software company’s .NET initiative.

Why is it important?
This language is an essential part of the .NET framework, so developers who use Microsoft heavily will find it critical, according to Duqaine.

4. C++

What is it?
C++ is a general purpose multi-paradigm spanning compiled language that has both high-level and low-level languages’ features. It was started as an enhancement to the C programming language, Bjarne Stroustrup in 1979.

Why is it important?
It is one of the most popular programming languages, winning fourth place on the list, with application domains including systems software, application software, server and client applications, and entertainment software such as video games.  The language has also greatly influenced many other popular programming languages, such as C# and Java.

5. Objective-C
 
What is it?
This object-oriented programming language created first by Brad Cox and Tom Love at their company Stepstone in the early 1980s, adds Smalltalk-like messaging to the C programming language.

Why is it important?
This language is most used on the Apple iOS and Mac OS X. Objective-C is the principal language used for Apple's Cocoa API as well.

6. PHP

What is it?
This language is especially suited for Web development because of it easy embedding into HTML pages. It is an open-source, server-side, cross-platform, interpretive HTML scripting language

Why is it important?
It is a popular language, ranking sixth on TIOBE’s list. "High-speed scripting with caching, augmented with compiled code plug-ins (such as can be done with Perl and PHP) is where the future is. Building Web apps from scratch using C or COBOL is going the way of the dinosaur," said Duquaine, according to eWEEK’s report.

7. (Visual) Basic

What is it?
This is an event-driven programming language which is implemented on Microsoft’s .Net framework.

Why is it important?
This language ranked as the seventh most popular language on TIOBE’s list, probably because it was designed by Microsoft to be easy to learn and use. According to Tim Huckaby, CEO of San Diego-based software engineering company CEO Interknowlogy.com, “It is currently dominating in adoption and that is where all the work is,” as in eWEEK’s report.

 8. Python

What is it?

This is an event-driven programming language which is extensively used by Google because of its simplicity. It is managed by the Python Software Foundation.

Why is it important?

Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to combine "remarkable power with very clear syntax", and its standard library is large and comprehensive.

It is releases on 4 September 2011, 6 months ago.It is developed by Python Software Foundation.

9. Perl

What is it?
Being a high-level programming language, its emphasis lies in code readability and clear syntax. It combines Object-oriented and functional programming styles, and is often used as a scripting language. Perl is an open-source language used widely to process text through CGI programs.


Why is it important?
Perl’s efficiency in processing of piles of text has ranked it ninth in terms of programming language popularity. It is used extensively to write Web server programs for a variety of tasks. “Learning some form of scripting language, such as Perl or PHP is critical if you are doing Web apps," told Wayne Duqaine, director of Software Development at Grandview Systems, of Sebastopol, Calif., in a talk with eWEEK.

10. JavaScript

What is it?
JavaScript is an object-oriented scripting language that is smaller than Java. Being a client-side language, it runs in the web browser on the client-side with a simplified set of commands, easier code and no need for compilation.

Why is it important?

JavaScript is simple to learn and is the tenth most widely used programming language. It is used in millions of web pages to authenticate forms, detect browsers and improve design, and it is easier to run these functions as it is embedded into HTML.
Read More

February 18, 2012

6 Important .Net Concepts

Stack, heap, Value types, reference types, boxing and Unboxing.
 
This article will explain 6 important concepts Stack , heap , value types , reference types , boxing and unboxing. This article starts first explaining what happens internally when you declare a variable and then it moves ahead to explain 2 important concepts stack and heap. Article then talks about reference types and value types and clarifies some of the important fundamentals around them.

Finally the article concludes by demonstrating how performance is hampered due to boxing and unboxing with a sample code.

What goes inside when you declare a variable?

When you declare a variable in a .Net application, it allocates some chunk of memory in to the RAM. This memory has 3 things first the name of the variable, second data type of the variable and finally the value of the variable.

That was a simple explanation of what happens in the memory, but depending on what kind of data type your variable is allocated on that type of memory. There are two types of memory allocation stack memory and heap memory. In the coming sections we will try to understand these two types of memory in more details.

Stack and Heap

In order to understand stack and heap, let’s understand what actually happens in the below code internally.

public void Method1()
{
// Line 1
int i=4;

// Line 2
int y=2;

//Line 3
class1 cls1 = new class1();
}
 
It’s a 3 line code so let’s understand line by line how things execute internally.

Line 1:- When this line is executed compiler allocates a small amount of memory in to memory type called as stack. Stack is responsible of keeping track of running memory needed in your application.

Line 2:- Now the execution moves to the next step. As the name says stack it stacks this memory allocation on the top of the first memory allocation. You can think about stack as series of compartment or boxes put on top of each other.

Memory allocation and de-allocation is done using LIFO (Last in first out) logic. In other words memory is allocated and de-allocated at only one end of the memory i.e. top of the stack.

Line 3:- In line 3 we have a created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called as ‘Heap’. ‘Heap’ does not track running memory it’s just pile of objects which can reached at any moment of time. Heap is used for dynamic memory allocation.

One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword it allocates on "HEAP".

Exiting the method (The fun):- Now finally the execution control starts exiting the method. When it passes the end control it clears all the memory variables which are assigned on stack. In other words all variables which are related to ‘int’ data type are de-allocated in ‘LIFO’ fashion from the stack.

The BIG catch – It did not de-allocate the heap memory. This memory will be later de-allocated by “GARBAGE COLLECTOR”.
Now many of our developer friends must be wondering why two types of memory, can’t we just allocate everything on just one memory type and we are done.

If you look closely primitive data types are not complex, they hold single values like ‘int i = 0’. Object data types are complex, they reference other objects or other primitive data types. In other words they hold reference to other multiple values and each one of them must be stored in memory. Object types need dynamic memory while primitive needs static type memory. If the requirement is of dynamic memory it’s allocated on a heap or else it goes on a stack.

Value types and reference types

Now that we have understood the concept of ‘Stack’ and ‘Heap’ it’s time to understand the concept of value types and reference types.

Value types are types which hold both data and the memory on the same location. While a reference type has a pointer which points to the memory location.

Below is a simple integer data type with name ‘i’ whose value is assigned to an other integer data type with name ‘j’. Both these memory values are allocated on the stack.

When we assign the ‘int’ value to the other ‘int’ value it creates a complete different copy. In other word if you change either of them the other does not change. These kinds of data types are called as ‘Value types’.
When we create an object and when we assign one object to the other object, they both point to the same memory location as show in the below code snippet. So when we assign ‘obj’ to ‘obj1’ they both point to the same memory location.

In other words if we change one of them the other object is also affected this is termed as ‘Reference types’.

So which data types are ref type and value type?

In .NET depending on data types the variable is either assigned on the stack or on the heap. ‘String’ and ‘Objects’ are reference types and any other .NET primitive data types are assigned on the stack. Below figure explains the same in a more detail manner.

Boxing and Unboxing

WOW, you have given so much knowledge, so what’s the use of it in actual programming. One of the biggest implications is to understand the performance hit which is incurred due to data moving from stack to heap and vice versa.

Consider the below code snippet. When we move a value type to reference type the data is moved from the stack to the heap. When we move reference type to a value type the data is moved from the heap to the stack.

This movement of data from the heap to stack and vice-versa creates a performance hit.

When the data moves from value types to reference types its termed as ‘Boxing’ and the vice versa is termed as ‘UnBoxing’.
If you compile the above code and see the same in ILDASM you can see in the IL code how ‘boxing’ and ‘unboxing’ looks, below figure demonstrates the same.

Performance implication of Boxing and unboxing

In order to see how the performance is impacted we ran the below two functions 10,000 times. One function has boxing and the other function is simple. We used a stop watch object to monitor the time taken.

The boxing function was executed in 3542 MS while without boxing the code was executed in 2477 MS. In other words try to avoid boxing and unboxing. In project you always need boxing and unboxing , use it when it’s absolutely necessary.

With the same article the sample code is attached which demonstrates this performance implication.
Currently I have not put a source code for unboxing but the same hold true for the same. You can write the same and experiment it by using stopwatch class.
Read More

February 17, 2012

“Razor” – a new view engine for ASP.NET MVC


One of the things my team has been working on has been a new view engine option for ASP.NET.

ASP.NET MVC has always supported the concept of “view engines” – which are the pluggable modules that implement different template syntax options.  The “default” view engine for ASP.NET MVC today uses the same .aspx/.ascx/.master file templates as ASP.NET Web Forms.  Other popular ASP.NET MVC view engines used today include Spark and NHaml.

The new view-engine option we’ve been working on is optimized around HTML generation using a code-focused templating approach. The codename for this new view engine is “Razor”, and we’ll be shipping the first public beta of it shortly.

Design Goals


We had several design goals in mind as we prototyped and evaluated “Razor”:
  • Compact, Expressive, and Fluid: Razor minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.
  • Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of concepts. You use all your existing language and HTML skills.
  • Is not a new language: We consciously chose not to create a new imperative language with Razor. Instead we wanted to enable developers to use their existing C#/VB (or other) language skills with Razor, and deliver a template markup syntax that enables an awesome HTML construction workflow with your language of choice.
  • Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old text editor (notepad works great).
  • Has great Intellisense: While Razor has been designed to not require a specific tool or code editor, it will have awesome statement completion support within Visual Studio. We’ll be updating Visual Studio 2010 and Visual Web Developer 2010 to have full editor intellisense for it.
  • Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).
We’ve spent the last few months building applications with it and doing lots of usability studies of it with a variety of volunteers (including several groups of non-.NET web developers). The feedback so far from people using it has been really great.

Choice and Flexibility

One of the best things about ASP.NET is that most things in it are pluggable. If you find something doesn’t work the way you want it to, you can swap it out for something else.
The next release of ASP.NET MVC will include a new “Add->View” dialog that makes it easy for you to choose the syntax you want to use when you create a new view template file.  It will allow you to easily select any of of the available view engines you have installed on your machine – giving you the choice to use whichever view approach feels most natural to you:
AddView9
Razor will be one of the view engine options we ship built-into ASP.NET MVC.  All view helper methods and programming model features will be available with both Razor and the .ASPX view engine. 
You’ll also be able to mix and match view templates written using multiple view-engines within a single application or site.  For example, you could write some views using .aspx files, some with .cshtml or .vbhtml files (the file-extensions for Razor files – C# and VB respectively), and some with Spark or NHaml.  You can also have a view template using one view-engine use a partial view template written in another.  You’ll have full choice and flexibility.

Hello World Sample with Razor

Razor enables you to start with static HTML (or any textual content) and then make it dynamic by adding server code to it.  One of the core design goals behind Razor is to make this coding process fluid, and to enable you to quickly integrate server code into your HTML markup with a minimum of keystrokes.
To see a quick example of this let’s create a simple “hello world” sample that outputs a message like so:
image
Building it with .ASPX Code Nuggets
If we were to build the above “hello world” sample using ASP.NET’s existing .ASPX markup syntax, we might write it using <%= %> blocks to indicate “code nuggets” within our HTML markup like so:
image
One observation to make about this “hello world” sample is that each code nugget block requires 5 characters (<%= %>) to denote the start and stop of the code sequence.  Some of these characters (in particular the % key – which is center top on most keyboards) aren’t the easiest to touch-type.
Building it with Razor Syntax
You denote the start of a code block with Razor using a @ character.  Unlike <% %> code nuggets, Razor does not require you to explicitly close the code-block:
image
The Razor parser has semantic knowledge of C#/VB code used within code-blocks – which is why we didn’t need to explicitly close the code blocks above.  Razor was able to identify the above statements as self-contained code blocks, and implicitly closed them for us.
Even in this trivial “hello world” example we’ve managed to save ourselves 12 keystrokes over what we had to type before.  The @ character is also easier to reach on the keyboard than the % character which makes it faster and more fluid to type. 

Loops and Nested HTML Sample

Let’s look at another simple scenario where we want to list some products (and the price of each product beside it):
image
Building it with .ASPX Code Nuggets
If we were to implement this using ASP.NET’s existing .ASPX markup syntax, we might write the below code to dynamically generate a <ul> list with <li> items for each product inside it:
image 
Building it with Razor Syntax
Below is how to generate the equivalent output using Razor:
image
Notice above how we started a “foreach” loop using the @ symbol, and then contained a line of HTML content with code blocks within it.  Because the Razor parser understands the C# semantics in our code block, it was able to determine that the <li> content should be contained within the foreach and treated like content that should be looped.  It also recognized that the trailing } terminated the foreach statement.
Razor was also smart enough to identify the @p.Name and @p.Price statements within the <li> element as server code – and execute them each time through the loop. Notice how Razor was smart enough to automatically close the @p.Name and @p.Price code blocks by inferring how the HTML and code is being used together.
The ability to code like this without having to add lots of open/close markers throughout your templates ends up making the whole coding process really fluid and fast.

If-Blocks and Multi-line Statements

Below are a few examples of other common scenarios:
If Statements
Like our foreach example above, you can embed content within if statements (or any other C# or VB language construct), without having to be explicit about the code block’s begin/end.  For example:
image
Multi-line Statements
You can denote multiple lines of code by wrapping it within a @{ code } block like so:
image 
Notice above how variables can span multiple server code blocks – the “message” variable defined within the multi-line @{ } block, for example, is also being used within the @message code block.  This is conceptually the same as the <% %> and <%= %> syntax within .aspx markup files.
Multi-Token Statements
The @( ) syntax enables a code block to have multiple tokens.  For example, we could re-write the above code to concatenate a string and the number together within a @( code ) block:
image 

Integrating Content and Code

The Razor parser has a lot of language smarts built-into it – enabling you to rely on it to do the heavily lifting, as opposed to you having to explicitly do it yourself. 
Does it break with email addresses and other usages of @ in HTML?
Razor’s language parser is clever enough in most cases to infer whether a @ character within a template is being used for code or static content.  For example, below I’m using a @ character as part of an email address:
image
When parsing a file, Razor examines the content on the right-hand side of any @ character and attempts to determine whether it is C# code (if it is a CSHTML file) or VB code (if it is a VBHTML file) or whether it is just static content.  The above code will output the following HTML (where the email address is output as static content and the @DateTime.Now is evaluated as code:
image
In cases where the content is valid as code as well (and you want to treat it as content), you can explicitly escape out @ characters by typing @@.
Identifying Nested Content
When nesting HTML content within an if/else, foreach or other block statement, you should look to wrap the inner content within an HTML or XML element to better identify that it is the beginning of a content block.
For example, below I’ve wrapped a multi-line content block (which includes a code-nugget) with a <span> element:
image
This will render the below content to the client – note that it includes the <span> tag:
image
You can optionally wrap nested content with a <text> block for cases where you have content that you want to render to the client without a wrapping tag:
image
The above code will render the below content to the client – note that it does not include any wrapping tag:
image 
HTML Encoding
By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.

Layout/MasterPage Scenarios – The Basics

It is important to have a consistent look and feel across all of the pages within your web-site/application.  ASP.NET 2.0 introduced the concept of “master pages” which helps enable this when using .aspx based pages or templates.  Razor also supports this concept using “layout pages” – which allow you to define a common site template, and then inherit its look and feel across all the views/pages on your site.
Simple Layout Example
Below is a simple example of a layout page – which we’ll save in a file called “SiteLayout.cshtml”.  It can contain any static HTML content we want to include in it, as well as dynamic server code.  We’ll then add a call to the “RenderBody()” helper method at the location in the template where we want to “fill in” specific body content for a requested URL:
image
We can then create a view template called “Home.cshtml” that contains only the content/code necessary to construct the specific body of a requested page, and which relies on the layout template for its outer content:
image
Notice above how we are explicitly setting the “LayoutPage” property in code within our Home.cshtml file.  This indicates that we want to use the SiteLayout.cshtml template as the layout for this view.  We could alternatively indicate the layout file we want to use within a ASP.NET MVC Controller invoking Home.cshtml as a view template, or by configuring it as the default layout to use for our site (in which case we can specify it in one file in our project and have all view templates pick it up automatically).
When we render Home.cshtml as a view-template, it will combine the content from the layout and sub-page and send the following content to the client:
image

Compact, Clean, Expressive Code

One of the things to notice in the code above is that the syntax for defining layouts and using them from views/pages is clean and minimal.  The code screen-shots above of the SiteLayout.cshtml and Home.cshtml files contain literally all of the content in the two .cshtml files – there is no extra configuration or additional tags, no <%@ Page%> prefix, nor any other markup or properties that need to be set.
We are trying to keep the code you write compact, easy and fluid.  We also want to enable anyone with a text editor to be able to open, edit and easily tweak/customize them.  No code generation or intellisense required.

Layout/MasterPage Scenarios – Adding Section Overrides

Layout pages optionally support the ability to define different “sections” within them that view templates based on the layout can then override and “fill-in” with custom content.  This enables you to easily override/fill-in discontinuous content regions within a layout page, and provides you with a lot of layout flexibility for your site.
For example, we could return to our SiteLayout.cshtml file and define two sections within our layout that the view templates within our site can optionally choose to fill-in.  We’ll name these sections “menu” and “footer” – and indicate that they are optional (and not required) within our site by passing an optional=true parameter to the RenderSection() helper call .
image
Because these two sections are marked as “optional”, I’m not required to define them within my Home.cshtml file.  My site will continue to work fine if they aren’t there. 
Let’s go back into Home.cshtml, though, and define a custom Menu and Footer section for them.  The below screenshot contains all of the content in Home.cshtml – there is nothing else required in the file.  Note: I moved setting the LayoutPage to be a site wide setting – which is why it is no longer there.
image
Our custom “menu” and “footer” section overrides are being defined within named @section { } blocks within the file.  We chose not to require you to wrap the “main/body” content within a section and instead to just keep it inline (which both saves keystrokes and enables you to easily add sections to your layout pages without having to go back through all your existing pages changing their syntax). 
When we render Home.cshtml as a view-template again, it will now combine the content from the layout and sub-page, integrating the two new custom section overrides in it, and send down the following content to the client:
image

Encapsulation and Re-Use with HTML Helpers

We’ve covered how to maintain a consistent site-wide look and feel using layout pages.  Let’s now look at how we can also create re-usable “HTML helpers” that enable us to cleanly encapsulate HTML generation functionality into libraries that we can re-use across our site – or even across multiple different sites.
Code Based HTML Helpers
ASP.NET MVC today has the concept of “HTML Helpers” – which are methods that can be invoked within code-blocks, and which encapsulate generating HTML.  These are implemented using pure code today (typically as extension methods).  All of the existing HTML extension methods built with ASP.NET MVC (both ones we’ve built and ones built by others) will work using the “Razor” view engine (no code changes required):
image
Declarative HTML Helpers
Generating HTML output using a code-only class approach works – but is not ideal.
One of the features we are looking to enable with Razor is an easy way to create re-usable HTML helpers using a more declarative approach.  Our plan is to enable you to define reusable helpers using a @helper { } declarative syntax like below. 
image
You’ll be able to place .cshtml files that contain these helpers into a Views\Helpers directory and then re-use them from any view or page in your site (no extra steps required):
image
Note above how our ProductListing() helper is able to define arguments and parameters.  This enables you to pass any parameters you want to them (and take full advantage of existing languages features like optional parameters, nullable types, generics, etc).  You’ll also get debugging support for them within Visual Studio.
Note: The @helper syntax won’t be in the first beta of Razor – but is something we hope will be enabled with the next drop.  Code-based helpers will work with the first beta.
Passing Inline Templates as Parameters
One other useful (and extremely powerful) feature we are enabling with Razor is the ability to pass “inline template” parameters to helper methods.  These “inline templates” can contain both HTML and code, and can be invoked on-demand by helper methods.
Below is an example of this feature in action using a “Grid” HTML Helper that renders a DataGrid to the client:
image
The Grid.Render() method call above is C#.  We are using the new C# named parameter syntax to pass strongly-typed arguments to the Grid.Render method - which means we get full statement completion/intellisense and compile-time checking for the above syntax.
The “format” parameter we are passing when defining columns is an “inline template” – which contains both custom html and code, and which we can use to customize the format of the data.  What is powerful about this is that the Grid helper can invoke our inline template as a delegate method, and invoke it as needed and as many times as it wants. In the scenario above it will call it each time it renders a row in the grid – and pass in the “item” that our template can use to display the appropriate response.
This capability will enable much richer HTML helper methods to be developed.  You’ll be able to implement them using both a code approach (like the way you build extension methods today) as well as using the declarative @helper {} approach.

Visual Studio Support

As I mentioned earlier, one of our goals with Razor is to minimize typing, and enable it to be easily edited with nothing more than a basic text editor (notepad works great).  We’ve kept the syntax clean, compact and simple to help enable that.
We have also designed Razor so that you get a rich code editing experience within Visual Studio.  We will provide full HTML, JavaScript and C#/VB code intellisense within Razor based files:
image
Notice above how we are providing intellisense for a Product object on the “@p.” code embedded within the <li> element inside a foreach loop.  Also notice how our \Views folder within the Solution Explorer contains both .aspx and .cshtml view templates.  You can use multiple view engines within a single application – making it easy to choose whichever syntax feels best to you.

Summary

We think “Razor” provides a great new view-engine option that is streamlined for code-focused templating.  It a coding workflow that is fast, expressive and fun.  It’s syntax is compact and reduces typing – while at the same time improving the overall readability of your markup and code.  It will be shipping as a built-in view engine with the next release of ASP.NET MVC.  You can also drop standalone .cshtml/.vbhtml files into your application and run them as single-pages – which also enables you to take advantage of it within ASP.NET Web Forms applications as well.
Read More

© 2011-2016 Techimpulsion All Rights Reserved.


The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.