T4 to rescue and save you time

by Vahid 11. June 2010 05:56

till yesterday i had never used T4 for a real problem solving. i knew what it is but i did not know how great and easy it is.

in my current scenario i have a database table which contains options available for each property of 30 available properties of items to be added to the system. the table has almost 500 records.  in the item registration page i had to create a structure like this for each property:

<div id="div1" runat="server" class="row">
<asp:Label ID="SmartLabel13" runat="server" AssociatedControlID="" Text="Title of the property"></asp:Label>
<asp:DropDown ID="SmartDropDown1" runat="server">
<asp:ListItem Selected="True" Text="-----------" Value="">
<asp:ListItem Selected="True" Text="option 1" Value="option 1 value">
<asp:ListItem Selected="True" Text="option 2" Value="option 2 value">
.
.
.
.
<asp:ListItem Selected="True" Text="option n" Value="option n value">
</asp:ListItem>
</asp:DropDown>
</div>

creating 50 of these snippet and adding almost 12 list item for each of them along with setting the control names and property title and also AssociatedControlID of each would have taken me at least a day. i thought i could benefit from T4(Text Template Transformation Toolkit which is used for code generation) to save myself some time. so i started creating a T4 file to do this and vala… 15 minutes later i had it done. i have to say that, it was the first time that i actually was using T4. i cannot believe how easy it is to use it. the following few lines of code saved me at least a day by generating around 1000 lines of code:

<#@ template language="C#" debug="True" #>
<#@ output extension="txt" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #> 
<#@ import namespace="System.Data.SqlClient" #>
<#
string catName=string.Empty;
int i=50;
System.Data.SqlClient.SqlConnection cn=new  System.Data.SqlClient.SqlConnection("data source=.\\sqlexpress;integrated security=true;database=Irizzle");
SqlCommand cmd=new SqlCommand("select * from IRZ.Lookupvalues order by Category",cn);
cn.Open();
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{    
if(catName==dr["Category"].ToString())
{#>
<asp:ListItem Text="<#= dr["Name"].ToString()#>" Value="<#= dr["Code"].ToString()#>" />
<#}
else
{
if(catName!=string.Empty){#>
</Irizzle:SmartDropDown>
</div>
<#}#>
<div id="div<#= dr["Category"].ToString()#>" runat="server" class="row">
<label for="drp<#= dr["Category"].ToString()#>"><#= dr["Title"].ToString()#></label>
<Irizzle:SmartDropDown ID="drp<#= dr["Category"].ToString()#>" runat="server">
<asp:ListItem Selected="True" Text="-----------" Value=""/>
<asp:ListItem Text="<#= dr["Name"].ToString()#>" Value="<#= dr["Code"].ToString()#>" />
<#}
catName=dr["Category"].ToString();
#>        
<#    i++;}
dr.Close();
cn.Close();
#>
</Irizzle:SmartDropDown>
</div>

i am sure T4 can save you and your companies hell lot of time. what i am wondering about is why not so many people talk about this great feature.

Tags: , ,

.Net | Technical

Differences between asp.net web Site and asp.net Web Application

by Vahid 10. December 2009 06:05
Have ever wondered what the differences between 2 types of asp.net web projects in visual studio 2005 (asp.net web site project and asp.net web application project) are?Well personally I had some idea here and there about the differences but when I found the following tables from MSDN which describe the differences in an organized way, I thought of sharing them with you.Just one important thing is missing and this is:In asp.net web application project we can assign a static port number for your internal web server whereas in asp.net web site project we are restricted to use the dynamically assigned port number. Static port number assignment functionality comes handy in many situation starting from an automated testing.The following table lists Web project options or tasks and indicates which project model best implements those options.

Option or Task

Web Application Projects Web Site Projects
Need to migrate large Visual Studio .NET 2003 applications X  
Prefer single-page code model to code-behind model   X
Prefer dynamic compilation and working on pages without building entire site on each page view (that is, save file and then simply refresh the page in the browser).   X
Need to control names of output assemblies X  
Need to generate one assembly for each page   X
Need stand-alone classes to reference page and user control classes X  
Need to build a Web application using multiple Web projects X  
Need to add pre-build and post-build steps during compilation X  
Want to open and edit any directory as a Web project without creating a project file   X
The following table helps you select a project type by describing some of the key differences between Web application projects and Web site projects.

Scenario

Web Application Project Web Site Project
Project definition Similar to Visual Studio .NET 2003. Only files that are referenced in the project file are part of the project, are displayed in Solution Explorer, and are compiled during a build. Because there is a project file, some scenarios are more easily enabled: You can subdivide one ASP.NET application into multiple Visual Studio projects.You can easily exclude files from the project and from source code-control. Web site projects use the folder structure to define the contents of the project. There is no project file and all files in the folder are part of the project. This project type is desirable if you have an existing folder structure representing an ASP.NET application that you want to edit in Visual Studio without having to explicitly create a project file.
Compilation and build outputs The compilation model for Web application projects is very similar to that in Visual Studio .NET 2003. All code-behind class files and stand-alone class files in the project are compiled into a single assembly, which is placed in the Bin folder. Because this is a single assembly, you can specify attributes such as assembly name and version, as well as the location of the output assembly.Certain other applications scenarios are better enabled, such as the Model-View-Controller (MVC) pattern, because they allow stand-alone classes in the project to reference page and user control classes. The Build command compiles Web site projects only to test them. To run Web site projects, you deploy source files and rely on ASP.NET dynamic compilation to compile pages and classes in the application. Alternatively, you can precompile the site for performance, which uses the same compilation semantics as ASP.NET dynamic compilation. The ASP.NET dynamic compilation system has two modes—batch mode (the default) and fixed-names mode. In batch mode, many assemblies (typically one per folder) are produced when precompiling the site. In fixed mode, one assembly is produced for each page or user control in the Web site.
Iterative development To run and debug pages, you must build the entire Web project. Building the entire Web application project is usually fast, because Visual Studio employs an incremental build model that builds only the files that have changed. You can configure build options Visual Studio 2005 for when you run the site: build the site, an individual page, or nothing at all. In the last case, when you run a Web site, Visual Studio simply launches the browser and passes to it the current or start page. The request then invokes ASP.NET dynamic compilation. Because pages are compiled dynamically and compiled into different assemblies as needed, it is not required that the entire project compile successfully in order to run and debug a page.By default, Visual Studio completely compiles Web site projects whenever you run or debug any page. This is done to identify compile-time errors anywhere in the site. However, a complete site build can significantly slow down the iterative development process, so it is generally recommended that you change the build project option to compile only the current page on run or debug.
Deployment Because all class files are compiled into a single assembly, only that assembly needs to be deployed, along with the .aspx and .ascx files and other static content files. In this model, .aspx files are not compiled until they are run in the browser. However, when used with Web Deployment Projects (a downloadable add-in to Visual Studio 2005), the .aspx files can also be compiled and included in a single assembly for deployment.Each time you deploy the single assembly produced in this model, you replace the code for all pages in the project. Both .aspx files and code-behind files can be compiled into assemblies using the Publish Website command in Visual Studio. (Note that the Build command does not create a deployable set of assemblies.) The updateable publish option supports compiling only code-behind files while leaving .aspx files unchanged for deployment. The default mode for precompiling produces several assemblies in the Bin folder, typically one per folder. The fixed-names option produces one assembly per page or user control and can be used to create deployable versions of individual pages. However, the fixed-names option increases the number of assemblies and can result in increased memory usage.
Upgrade from Visual Studio .NET 2003 Because the Web application project model is the same as in the Visual Studio .NET 2003, upgrade is generally simple and will usually not require any restructuring of the application. The compilation option for Web site projects is significantly different than Visual Studio .NET 2003. A conversion wizard is available to upgrade existing Visual Studio .NET 2003 Web projects to Web site projects. For any reasonably complex Visual Studio .NET 2003 projects, manual fix-up is usually required after the conversion. For most scenarios, it is preferable to upgrade existing Visual Studio .NET 2003 projects to Web application projects in Visual Studio 2005.
 

Tags: ,

.Net | Learning resource | Technical

Export to PDF, Excel and Image in asp.net

by Vahid 18. July 2009 19:48

recently in our project we had a requirement to export html to PDF in asp.net. there are so many components around which we can use to do this but the restriction for us was that we had to do it without spending money means we had to go for an open source component. doing so much I&D on this, we came to know about itextSharp which is a powerful open source component to create PDF files in .net. first it seemed good to us but spending sometimes on it we came to know it was not what we were looking for. two reason for that:

  1. it requires a big learning curve
  2. it’s not at all easy to work with

then the idea of using crystal report came to our mind. we could build the report in crystal report, load it through code without showing anything to user and through it’s API calling the export to pdf function. but it did not work since we had to run some setup components on the live server which we are not allowed to do.

meantime i just remembered we have rdlc reports in .net framework and also Microsoft report viewer. since these are .net component we don't have to install anything on the production server and Xcopy of the required assemblies will work for us. normally you can deploy the .net report files (.rdlc) using xcopy but in order to be able to use the reports you need to install Microsoft report viewer redistributable package which is freely available to download and distribute. this is fine when you have the rights to install components on the server. anyways spending sometime on this technology i found the files required to make the functionality up and running. if you don't want to install report viewer component you need to put these four dll in your bin folder:

Microsoft.ReportViewer.Common.dll
Microsoft.ReportViewer.ProcessingObjectModel.dll
Microsoft.ReportViewer.WebForms.dll
Microsoft.ReportViewer.WinForms.dll


you can download the files from here:
http://cid-c1dc0bf06aa2e3a6.skydrive.live.com/self.aspx/BlogFiles/ReportViewerFiles.zip

you need to create a report file by click on add new item in your project and selecting Report. then you need to design your report in visual studio as desired. you can use report parameters as placeholder for the values to be passed to to report.

then you need the following lines of code to export:

string[] streamids;
string mimeType;
string encoding;
string extension;
string fileFormat = "PDF";//can also be "Excel" or "Image";
Microsoft.Reporting.WebForms.LocalReport localReport = 
new Microsoft.Reporting.WebForms.LocalReport();
localReport.ReportPath = Server.MapPath("Report1.rdlc");
Microsoft.Reporting.WebForms.Warning[] warnings;
byte[] bytes = localReport.Render(
fileFormat, null, out mimeType, out encoding,
out extension,
out streamids, out warnings);
System.IO.FileStream fs = 
new System.IO.FileStream(Server.MapPath("output.pdf"),
System.IO.FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
Response.Redirect("output.pdf");

remember you can export to PDF, Excel and Image

you can use this method both for asp.net applications and windows application.

hope this comes handy for you.

Tags: , ,

.Net | Technical

Some cool .Net open source applicaitons

by Vahid 10. March 2009 17:31

i have worked with some cool open source applications which are based on microsoft .net framework and i thought of sharing them with you.

DotNetNuke

URL: http://www.dotnetnuke.com

dotnetnuke

DotNetNuke® is the most widely adopted framework for building websites and web applications on Microsoft ASP.NET.  Using DotNetNuke, businesses can quickly develop and deploy interactive, dynamic websites, intranets, extranets and applications. 

With hundreds of thousands of deployments around the world, a thriving user community and a huge array of available third-party extensions DotNetNuke is the smartest way to develop and deploy Internet applications.

YetAnotherForum

URL: http://www.yetanotherforum.net/

yetanotherjpg

 YetAnotherForum.NET (YAF) is a Open Source discussion forum or bulletin board system for web sites running ASP.NET. The latest version is ASP.NET v2.0 with a Microsoft SQL Server backend. The full C# source code is available licensed as GPL.

Oxite

URL: http://visitmix.com/Lab/Oxite

oxite

Oxite is an open source, web standards compliant, blog engine built on ASP.NET MVC. It is fully featured and includes support for all the blogging features you would expect.

Born out of a necessity to showcase Microsoft’s muscle in the blogging scene, Oxite provides example of ‘core blog functionality’ in a reusable way. The entire VisitMIX site runs on Oxite, which just shows the potential quality of the finished product. I love the effort that they have put into the design of MIX, and for once, we are able to show others a production Microsoft site running a Microsoft product that really shines visually.

nopCommerce

URL: http://www.nopcommerce.com/

nopcommerce

Running on C# nopCommerce is a fully customizable shopping cart. It’s stable and highly usable. nopCommerce is a open source e-commerce solution that is ASP.NET 3.5 based with a MS SQL 2005 backend database.

It is pretty feature packed when you take a look around the system, and should serve as a good platform to build on for some developers. Whilst they aren’t over on the MVC system they have taken care of some of the problems with querystrings, and include a URL rewrite module.

Most developers should be able to get up and running quickly, simply change your web.config in a few places and the autoinstaller should get you going. well worth investigating if you are a .NET developer with a background in e-commerce.

BlogEngine.NET

URL: http://dotnetblogengine.net

blogengine

BlogEngine.NET is an stable open source .NET blogging project. Touted as the next alternative to Wordpress for .NET developers it integrates the best features of the .NET platform into its offering. It also has received backing from Redmond, and is featured on the Microsoft.NET website as a Starter Kit.

actually my blog is also runnin using this applicaiton. i am quite happy with it.

 

Tags: ,

.Net | Applications | Technical

patterns & practices Application Architecture Guide 2.0

by Vahid 14. January 2009 07:29

I have been waiting for this for long time. the first version has been really usefull for me.

this is an official guied for application architecture provided by patterns and practicess team at microsoft. i hope this will be usefull for you also and let's thank the team for the greate job.

Get it here

Tags: , ,

.Net | Technical

IsNumeric() function in C#?

by Vahid 3. January 2009 05:36

hi,

as you may know c# is missing the nice and usfull IsNumeric function which is available in VB.net. but it is a trivial task to implement a generic equvelant function for it. look at the following code. it will return true if the value is numeric and false if the value is false.

static bool IsNumeric(object value)

{

double retNum;return Double.TryParse(Convert.ToString(value), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);

}

 

Tags: ,

Technical | .Net