Faqs on asp.net,c#,vb.net and sqlserver2005

this blog covers all the Faqs related to .net technologies like asp.net,vb.net,c#.net,ajax,javascript and sqlserver2005.

Mar 17, 2008

Validating Images before Upload by Checking the File Stream

Validating Images before Upload by Checking the File Stream

Rather than just checking for valid file extensions, there are more advanced ways of checking that your users are not uploading rubbish to your image file store (we currently use MOSS for storage at Lend Lease).
///summary
/// Added to validate that an image is being uploaded - not just any document
/// summary
private bool IsImage(byte[] data)
{
//read 64 bytes of the stream only to determine the type
string myStr = System.Text.Encoding.ASCII.GetString(data).Substring(0, 16);
//check if its definately an image.
if (myStr.Substring(8, 2).ToString().ToLower() != "if")
{
//its not a jpeg
if (myStr.Substring(0, 3).ToString().ToLower() != "gif")
{
//its not a gif
if (myStr.Substring(0, 2).ToString().ToLower() != "bm")
{
//its not a .bmp
if (myStr.Substring(0, 2).ToString().ToLower() != "ii")
{
//its not a tiff
//ProcessErrors("notImage");
myStr = null;
return false;
}
}
}
}
myStr = null;
return true;
}
public Response> AddAssetImageToSession( string fileName, Stream contentStream, IWebPageView currentView, string parentWindow)
{
Response response = GetAssetImageSingle();
if (string.IsNullOrEmpty(fileName))
{
response.Errors.Add(new Error(ErrorName.FileError, Errors.MissingFileName)); response.IsSuccessful = false;
}
else
{
SharepointDocumentDto item = new SharepointDocumentDto();
item.Name = fileName;
//Set FileName item.
IsNewItem = true;
//Flag as true so we know to save it when the asset is saved item.
GeneratedListItemId = Guid.NewGuid().ToString();
MemoryStream ms = new MemoryStream();
byte[] data = new byte[256];
int c = contentStream.Read(data, 0, data.Length);
//Check if it is a valid image
if (!IsImage(data))
{
response.Errors.Add(new Error(ErrorName.FileError, Errors.InvalidImageUploaded)); response.IsSuccessful = false;
return response;
//invalid
}
//Read into buffer until end of file
while (c > 0)

Reference:http://ddkonline.blogspot.com/2008/03/checking-for-valid-images-by-checking.html

Happy Programming

Latest Developments in the .Net World


Do you want to know about the latest development in the .Net technology? Here is a comprehensive look at the latest developments in the world of Microsoft’s.NET.
If you are committed software developer, you must be aware that ‘web services’ is the latest buzzword to have hit the IT industry. And that this technology trend holds tremendous potential for addressing business problems.
Extensible markup language (XML) is the universal format for data on the web. With XML web services gaining momentum among developers as the next generation of internet-based computing. A platform that made it similar to build these solutions and provide a reliable framework for integration and interoperability was needed. Microsoft’s answer to this much-felt need was .NET—a platform for building, deploying, operating and integrating XML web services.
.NET is the only platform that has been built to support XML services ground up, and Microsoft has been extensively working with the industry to develop standard s like SOAP and UDDI, the XML web services search directory that exits today.
Let’s now take a detailed look at all that Microsoft’s .NET has to offer software developers by the analyzing the latest developments that have taken place in this platform.
ASP.NET
ASP.NET is more than the next version of active server pages (APS) ----- it is the unified web development platform that provides the services necessary for developers to build enterprise-class web applications.ASP.NET is a compiled, .NET –based environment; you can author applications in any.NET compatible language, including ASP.NET Visual Basic .NET,C#, and the jscript.NET.Additionally, the entire .NET framework is available to any ASP.NET application.
Developers can choose from one of two features when creating an ASP.NET application, web services, or combine these in any way they see fit.
Web forms to allow you to build powerful forms-based web pages. When building these pages, you can use ASP.NET server controls to create common UI elements, and programs then from common tasks.
These controls to allow you to rapidly build a web form out of reusable built-in or custom components, simplifying the code of a page.
An XML web service provides the means to access server functionality remotely. Using web services, interfaces to their data or business logic, which is turn can be obtained and manipulated by client and server applications. XML web services enable the exchange of data in client-server or server- server scenarios, using standards like HTTP and XML messaging to move data across firewalls.
Each of these models can take full advantage of all ASP.NET framework and.NET framework common language runtime. These features and how you can use them are outlined as follow:
If you have ASP development skills, the new ASP.NET programming model will seem very familiar to you. However, the ASP.NET object model has changed significantly from ASP, making it move structured and object oriented.
Accessing database from ASP.NET application is an often-used technique for displaying data to website visitors. ASP.NET makes it easier then ever to access database for this purpose.
ASP.NET provides a simple model that enables developers to write logic that runs at the application level. Developers can write this code in the global. Asax text files or in a compiled class deployed as an assembly.
ASP.NET provides easy-to-use application and session-state-facilities that are familiar to ASP developers and readily compatible with all other .NET framework APIs.
For advanced developers who wants to use APIs as powerful as the ISPI programming interfaces that were included with previous version of ASP, ASP.NET offer the IHttpHandler interfaces.
ASP.NET takes advantage of performance enhancements found in the .NET framework and common language runtime.
The. NET framework and ASP.NET provide default authorization and authentication schemes for web application.
ASP.NET configuration setting are stored in XML-based files , which are human readable and writable.
VB.NET
Visual basic .NET enable you to create rich application for Microsoft Windows in less time, incorporate data access from a wider range of database scenarios, create components with minimal code, and build web-based application using your exiting skills. Builds powerful windows-based applications in less time and more robust windows-based applications with less code.
1. Web-based applications
Helps to create web solutions in visual basic.NET using the shared web forms designer and HTML designer
2. Flexible, simplified data access
Offers support to tackle any data access scenario easily with Microsoft ADO.NET and Microsoft Active X Data objects (ADO) data access.
3. Improved coding
It brings a multitude of enhancements to the code editor, including enhanced intellisence , smart listing of code for greater readability , squiggles , and a background compiler for realtime notification of syntax .
4. Direct access to the platform
Features quick leverage of registry , eventlog , performance counters , and file system in user’ application and eliminates the need to use declared statements .
5. Full object-oriented constructs
Helps create reusable, enterprise-class code using full object-oriented constructs .Language features include full implementation inheritance, encapsulation ,and polymorphism .
6. XML Web services
The new XML .Web services project templates builds all underlying Web services enable you to call components running on any platform.
7. Mobile applications
These new features give developers a single, mobile Web interface to support a broad range of Web devices, including WWL 1.1 for WAP-enabled cellular phones , compact HTML (cHTML) for i-mode phones ,and HTML for pocket PC handheld devices , and pagers . Reach out to more than 80 different Internet-enabled mobile devices using the Microsoft mobile Internet Toolkit .
8. Com interoperability
This feature enables seamless bi-directional communication between Visual Basic 6.0 and Visual Basic Net applications.
VS .NET
Visual Studio .NET is the comprehensive tool for rapidly building and inter grating XML. Web services and application dramatically increasing developer productivity, and enabling new business opportunities.
1. Enterprise Architect
Visually specify and communicate application architecture: It uses Microsoft Visio-based Modeling Language (UML) modeling to specify and communicate application architecture and functionality.
Gain unparalleled support for database modeling: Full roundtrip engineering, with logical and physical data models, enables communication from the business analyst to the database designer.
Easily shared best practices: Senior developers and architects can customize enterprise template projects to provide application starting points and guidance for less experienced developers.
Use the industry-leading development environment: Leverage the powerful capabilities in Visual Studio.Net for rapidly building XML web services and applications that span devices and platforms.
Define and communicate development policies: developers can immediately view any policy violations and discrepancies in their code in the task list window.
Enterprise Developers:
Fast and easy test of XML web services and applications: VS.Net can quickly create and run tests within the visual studio.Net environment to fine-tune the performance of XML web services and applications and verify functionality.
Maximize developer productivity: It leverages the powerful capabilities in Visual Studio .Net for rapidly building XML web services and applications that span devices and platforms.
Simplify server-side development: This feature helps to visually build server-side components with the server explorer and Visual component Designer.
Build, leverage, and extend scalable XML web services: it creates components that can be accessed on any platform by using XML web services easily publish and component as XML web services, and reuse existing XML web services running on any platform.
Get support for the complete lifecycle: The Visual Studio integration technologies bring a broad array of partners of visual studio .Net developers and enables third party languages, components and tools to integrate tightly with visual studio .Net through various stages of the development in lifecycle.VS .NET Professional :
XML web services : It helps to create components that can be accessed on any platform by using XML web services . Converts existing functions to XML web services and reuses existing XML web services.
High-performance database application with XML : It uses the built-in Microsoft ADO.NET tools to build database applications with Microsoft SQL Server , Oracle ,or any other XML-based data source .
Supports Rapid Application Devlopment (RAD) for the server developed for thin-client devices : Offers developers a single mobile web interface to support a broad range of web devices –including WML .1.1 for WAP cell phones , compact HTML(cHTML) for i-mode , and HTML, for pocket PC, palm-size PCs pagers .
Shared IDE : It uses a single unified integrated development environment (IDE) for all languages with a single toolbox debugger and task window across Visual Basic ,C++ and C# project .
Windows CE .NET
Window CE .NET is the successor to Windows CE 3.0 Designed from the ground up for the embedded marketplace , Window CE .NET aims to deliver a robust realtime operating system for rapidly building the next generation of smart mobile and small footprint devices. With a complete operating system feature set and end-to-end development environment Windows CE-based devices that requires rich networking hard real time, and a small footprint , as well as rich multimedia and Web browsing capabilities. Windows CE .NET offers.
Scalable wireless technologies : Windows CE.NET include scalable wireless technologies that enable mobile devices to flexibly connect into existing infrastructures . Supported wireless technologies include.
Bluetooth : Windows CE .NET allows a devices to use a Bluetooth-enabled cellular phone as a data modem , and to use a Bluetooth-enabled local area network (LAN) access point to provide network connectivity.
802.1x/Zero Configuration – New features in window CE .NET i.e., 802.11 zero configuration, aim to simplify setup of 802.11 network and to enable seamless roaming from one 802.11 network to another. 801.1x and EAP enhance the security of 802.11 by enabling user/password, certificate, or original equipment manufacturer (OEM) specific authentication to log on to the network.
Object Exchange (OBEX) protocol – Windows CE .Net’s support for OBEX works over Bluetooth and infra red data association (IrDA) protocols . Object Exchange (OBEX) is an efficient, compact binary protocol that enables a wide range of devices to exchange data spontaneously in a simple, efficient manner.
Media Sense – This feature improves the roaming experience for mobile devices users by notifying application of network status.
Real time collaboration and communication (RTC/SIP) – Real time communication (RTC) enables messaging, presence, and audio (voice over IP between any two IP-enabled devices.
Realiable core operating system services for demanding embedded designs : Windows CE .ET offers reliable core operating system services that enable the most demanding real time embedded designs across a breadth of devices . New and enhanced operating system features include.
Small footprint: Continuing the effort to minimize the operating system footprint for embedded devices, Windows CE .NET provides granular Kernel componentization. Windows CE .NET supports a minimum configuration platform as small as 200 KB with minimum Kernel functions only.
Enterprise-scale – Network security enhancements include support for the Kerberos Security Protocol.
Wide selection of CPUs- Windows CE .NET provides a high level of processor flexibility with support for the following four families of microprocessors and emulation technologies like ARM, MIPS, SHx, x 86 etc.
Real time – Real time processing support for the most demanding support for the most demanding deterministic applications with 256 priority levels and nested interrupt support.
Net- enabled for creating rich personalized experiences - Windows CE .NET enables you to build smart Microsoft .NET-enabled devices and create rich, personalized experiences.
XML – XML allows developers to easily describe and deliver rich, structured data from any application in a standard consistent way.
Net compact Framework : The .NET Compact Framework supports all processors supported by windows CE .NET . For more information on how to develop application using the .NET Framework, please see .NET on the MSDN site. Look in the .NET Compact Framework Read me’ for specific information about implementation issues in your embedded design.
Microsoft Direct3D API – Provides support for interactive three-dimensional (3-D) graphics applications by allowing device dependent access to 30d video-display hardware in devices-independent manner.
Windows Media 8 compressor/decompressor (codecs) and controls – Supports the latest Microsoft Windows Media 8 codes and controls ,which allows for the latest high-bandwidth encoded multimedia streams.
Easy-to-use end-to-end tool set: Windows CE .NET provides an integrated end-to-end tool set to help developers reduce both operating system and application development time, allowing them to get devices to market faster. These tools include.
Emulation technology - Windows CE .NET include emulation technology to enable developers to build and test their designs on their Windows 2000 or Windows xp professional workstations without additional hardware investments.
The new platform wizard – The new platform wizard provides a foundation for startingDevice designs for:
Cellophanes / Smart phones
Custom devices
Digital imaging devices
Industrial automation devices
Internet/media appliances
Personal digital assistants (PDA)/Mobile handhelds
Residential gateways
Retail point-of-sale
Set-top boxes
Tiny kernels
Web pads Windows thin clients.
CE .Net also provides support for managed and native code – To write applications for Windows CE .NET, Microsoft offers a rich set of languages for creating managed .NET-enabled or unmanaged (native) applications.
NET Compact Framework
Microsoft Corp. Has recently released the beta of the Microsoft .NET Compact Framework, extending the .NET strategy to smart handheld devices. The .NET Compact Framework is Microsoft’s mobile application platform technology that harnesses the power of XML Web services on mobile devices. As a subset of the .NET Framework, the .NET Compact Framework shares same programming model and application development tools, enabling .NET developers to transfer their existing skills to build mobile applications, which is expected to accelerate adoption of mobile solutions. It provides key features for smart devices such as a programming model unified with the .Net framework on desktop and server, integral XML web services support, enterprise-class data access using ADO.Net and XML, and rich class libraries that enable developers to build powerful applications in minimal time. Runtime features such as managed code and just-in-time compilation help ensure reliable, high performance applications for a better user experience.The .Net compact framework is complemented by other technologies such as Microsoft SQL server 2000, windows CE edition version 2.0 and the Microsoft mobile internet toolkit (MMIT), SQL server CE is the compact, relational database for rapidly developing applications that extend enterprise data management capabilities to new smart devices. The SQL server CE is the only mobile database that integrates with the .Net compact framework, allowing data to be locally and securely stored and extracted to interact with back-end applications or web services. The Microsoft mobile internet toolkit offers a wide reach to project applications to any kind of mobile device with a browser. The development experience for these technologies is unified through Microsoft Visual Studio >net, which provides a consistent set of tools and interfaces for building applications using Microsoft’s mobile technologies.

Happy Programming

Mar 14, 2008

Web Farming with the Network Load Balancing Service in Windows Server 2003

When a single Web Server machine isn’t enough to handle the traffic on your Web site it’s time to look into building a Web Farm that uses multiple machines on the network acting as a single server. In this article Rick looks at the Windows Load Balancing Service and the new interface it sports in Windows Server 2003, which makes creating a Web Farm quick and easy and – gasp –even an affordable solution.
With the release of Windows Server 2003 Network Load Balancing has become a much more visible tool as a part of the operating system, providing a very usable and relatively easy to configure interface that makes it easy to build a Web Farm. The Network Load Balancing Service has been around in one incarnation or another since Windows NT SP4, but Windows Server 2003 is the first operating system that brings this service into the forefront as a main component of the OS. A new Network Load Balancing Manager application is now directly available from the Adminstrative Tasks menu and it’s powerful enough to allow to configure the entire cluster from a single console. The service is now available for all products in the Windows Server family including the lower end Web Edition which means that you now have a much more affordable solution to create Web Farms at your disposal. Just add servers please.

In this article I’ll review the basics of a Load Balancing service and then show you how to set up configure a basic installation using two machines.
Web Farms for city folk – do you need it?
A Web Farm is a not so fancy term for a collection of servers that act as a single Web server. The process behind the scenes maps a ‘virtual’ IP address to multiple machines. Software such as the Network Load Balancing Service or hardware like a specialized router or Load Balancer then deals with dishing up requests to the appropriate machine in the server pool.
Web Farms are an obvious choice if you’ve hit the limits of your single machine hardware. But before jumping on the Web Farm band wagon (or is that a tractor?) you should look closely at your hardware and application and be sure that you can’t make it all run on a single machine first. Although the process of creating a Web Farm isn’t difficult, administration of two or more servers and keeping them properly synched is actually a lot more work than administering a single server.

Upgrading your hardware is certainly one option available to you. Today’s hardware is incredibly capable and should be sufficient to handle all but the most demanding Web applications on a single box. Multiprocessor machines with up to 16 processors on Windows make a pretty powerful platform to run Web applications with, even if those high end machines are rather pricey. While the Yahoo’s and Amazon’s won’t run on a single box (or on Windows for that matter), a vast majority of applications are likely to be able to comfortably serve millions of transactional hits a day from a single machine even with a single processor.

But Load Balancing can also provide benefits in the overload scenario. For one, it’s generally cheaper to throw mid-level machines at a load problem rather than buying one top of the line high end machine. Even with server licenses involved multiple low end machines might provide a more cost efficient solution.

Load Balancing also provides something else that has nothing to do with scalability: The ability to have failover support if something goes wrong on one of the servers in the pool. Because a Web Farm are made up of essentially identically configured servers, a failure on a single server will not bring down the entire Web site. Other servers in the pool can continue to process requests and pick up the slack. For many companies this feature of load balancing is often important for peace of mind both in the knowledge that a single point of failure on the Web Server is avoided as well as providing an in place mechanism to grow the application should the need arise at a later point.


Reference:
http://www.west-wind.com/presentations/loadbalancing/NetworkLoadBalancingWindows2003.asp

Happy Programming

ListView and DataPager in ASP.NET 3.5

New controls in asp.net 3.5
I spent a couple of hours today looking over the ListView and DataPager controls in ASP.NET 3.5. Both controls sound interesting and both provide welcome new features to the ASP.NET control arsenal. Although I'm a little wary of having yet another list control (as if we haven't enough of those already between DataGrid, DataList, Repeater, GridView and now the ListView) the ListView control kind of combines functionality of all of these controls into one. Maybe the most important feature of this control is that like the Repeater control it provides much more control over the rendering process at the cost of more markup code in the page.
The ListView is a sort of hybrid between a DataGrid and Repeater that combines the free form templating of the Repeater with the editing features of the data grid. It looks interesting because it basically allows you much more control over the layout than a DataGrid does while still giving you many of the more advanced features of the data grid. The ListView doesn't support paging natively, so the DataPager serves as an external control to provide paging features. The advantage of a separate control is that it gives you much more control about what the pager looks like and where it can be placed on the page - anywhere basically. The Pager is essentially an extender control that extends the ListView with paging capabilities.
The ListView Control
Using the ListView for basic data display is very similar to using a Repeater. You have the ListView control and a set of templates that you can apply which include:
LayoutTemplate
ItemTemplate
AlternatingItemTemplate
SelectedItemTemplate
EmptyItemTemplate
EmptyDataTemplate (?)
ItemSeparatorTemplate
GroupTemplate
GroupSeparatorTemplate
EditItemTemplate
InsertItemTemplate
That's a lot of templates . There are a few new ones here like GroupTemplate and InsertItemTemplate. I haven't figured out how GroupTemplate works, but InsertItemTemplate certainly is a nice addition so you can handle both editing and adding in the same space (previously with a DataGrid you had to insertion externally or insert data manually into a DataTable to display the empty row).


Reference:
http://www.west-wind.com/WebLog/posts/127340.aspx

Happy Programming

Mar 13, 2008

Lambda expressions in C# 3.0

1. Introduction
It is no secret for anybody that C#, which was initially conceived as a language targeted to subsume such different programming paradigms as procedural (imperative), object-oriented (in line with the standards set by C++ and later Java) and component-based (with two clear referents, Delphi and Visual Basic), has evolved since then in a way that attempts to take into account and integrate into the language the best ideas arisen under another points of view of programming, like dynamic languages (Perl, Python, Ruby), data manipulation languages (SQL, XML) or functional programming (LISP, ML).
Lambda expressions, one of the most important new features to be included in the next 3.0 version of C# [3] and one that offers support needed by the LINQ Project [4], are precisely a feature coming from the world of functional programming. In LISP and its dialects, like Scheme, the lambda construction is a mechanism that allows the programmer to define new functions. For instance, the expression:
(define square (lambda (x) (* x x)))

defines a variable named square, whose value is a function that produces the square of its argument. One of the most prominent characteristics of functional languages, to which the architects of .NET Framework give great importance [2], is that lambda functions can be treated not only as pieces of code that can be invoked, but also as “common and earthly” values that can be manipulated by other code blocks. Using a term I heard the first time more than 20 years ago from my tutor of then, Dr. Luciano Garcia, lambda functions facilitate metaprogramming – the writing of programs capable of manipulating other programs.
This article describes the implementation of lambda expressions in C# 3.0, concentrating mainly on its exploitation as code blocks; issues related to the representation as data and further programmatic manipulation of lambda expressions will be only introduced for the sake of completeness, and a more in-depth discussion of them will be left for a next installment of this column.

2. Lambda expressions as code entities
The natural way of implementing a definition like that of the square lambda function in C# would be through a delegate type and a delegate instance [5]:
delegate T Mapping(T x);
Mapping square = delegate(int x) { return x * x; };

The first line above defines a generic delegate type named Mapping. From this type model, we will be able to create delegate instances for functions that produce a value of type T from another value of the same type T (that is, functions that map – remember the term, which we will be using more frequently in the near future – a value of type T into another value of the same type).
The second line of code defines an instance of the previous delegate type that “points” to a function that returns the square of an integer number. In this sentence we make use of another feature added to C# in version 2.0, anonymous methods, that allow the in-line specification of the block of code that defines the functionality we wish to associate to the delegate instance. In the original version of C# we would have had to define the function explicitly (besides, the delegate couldn’t have been generic):
static int Square(int x)
{
return x * x;
}
Mapping square2 = Square;

Although anonymous methods offer a more compact and direct notation, their syntax is still quite verbose and imperative by nature. In particular, when defining an anonymous method it is necessary:
· To explicitly use the keyword delegate.
· To explicitly specify the types of the parameters, without any possibility of compiler inference from the usage context.
· In the relatively frequent case when the body of the function is a simple return sentence followed by an expression that calculates the result (as in the case of our square), the excess in syntax is even more evident.
Lambda expressions can be seen as an extension of anonymous methods that offers a more concise and functional syntax. The syntax of a lambda expression consists of a list of variables-parameters, followed by the implication (function application) sign =>, then followed by the expression or block that implements the desired functionality. For instance, our definition of square could be rewritten using a lambda expression like this:
Mapping square3 = x => x * x;

Shorter - impossible, right? This sentence expresses in quite a succinct and natural way that square3 references a function that, given some x, produces x multiplied by itself. In this case, the compiler automatically infers from the context that the type of the parameter and the result should be int. We could have indicated that explicitly:
Mapping square4 = (int x) => x * x;

If the type of the parameter is specified, or if the expression has more than one parameter (be their type indicated explicitly or not) parenthesis are mandatory. On the other hand, in the right side of the implication we can place a simple expression, as previously, or a block of sentences of any complexity (as long as it produces a result of the correct type):
Mapping square5 = (int x) => { return x * x; };

Until now we have been using our own generic delegate type Mapping, but in practice most of the times we will use the different “overloads” of the predefined generic delegate type Func:
// in System.Query.dll
// namespace System.Query
public delegate T Func();
public delegate T Func(A0 a0);
public delegate T Func(A0 a0, A1 a1);
public delegate T Func(A0 a0, A1 a1, A2 a2);
public delegate T Func(A0 a0, A1 a1, A2 a2, A3 a3);

The Func family of types represents delegate instances that reference functions (with 0, 1, 2 or 3 arguments, respectively) that return T. Using Func, we could define a new version of square like this:
Func square6 = x => x * x;

Below we show some more examples of definition and usage of lambda expressions:
// more examples
static Func hypotenuse =
(x, y) => Math.Sqrt(x * x + y * y);

static Func divisibleBy =
(int a, int b) => a % b == 0;

static Func isPrime =
x => {
for (int i = 2; i <= x / 2; i++) if (divisibleBy(x, i)) return false; return true; }; static void Main(string[] args) { int n = 19; if (isPrime(n)) Console.WriteLine(n + " is prime"); Console.ReadLine(); } 3. Lambda expressions as data entities
Considering what we’ve seen until now, anybody could think that lambda expressions are mere “syntactic sugar” added to the language in order to “sweeten” the consumption of delegates and anonymous methods. But C# 3.0 lambda expressions offer an additional possibility not available to anonymous methods, and one that plays a key role in the implementation of the LINQ (Language Integrated Query) technology, that will also be included in the next version of C# and VB and that constitutes, in the humble opinion of this author, one of the most significant advances in programming languages and systems in recent times.
This additional possibility is that of being compiled as expression trees, data objects that efficiently represent in memory the algorithm of evaluation of lambda expressions. These in-memory trees can later be easily manipulated by software (metaprogramming!), stored, transmitted, etc. Although we’ll defer a more detailed analysis of expression trees until our next installment, let’s see a small example:
static Expression func double, hypotenuseExpr =
(x, y) => Math.Sqrt(x * x + y * y);

static void Main(string[] args)
{
Console.WriteLine(hypotenuseExpr);
// prints '(x, y) => Sqrt(Add(Multiply(x, x), Multiply(y, y)))'

hypotenuse = hypotenuseExpr.Compile(); // here ILAsm is generated!
Console.WriteLine("Hypotenuse(3, 4) = " + hypotenuse(3, 4));
// prints 'Hypotenuse(3, 4) = 5'

Console.ReadLine();
}

In the code fragment above, the lambda expression that calculates the hypotenuse of a right triangle is assigned not to a delegate, but to a variable of the predefined generic type Expression:
// in System.Query.dll
// namespace System.Expressions
public class Expression : LambdaExpression { … }

In this case, the compiler does not generate the ILAsm code corresponding to the expression; an object tree that represents the sequence of actions needed for expression’s evaluation is produced instead. You can get an idea of the internal structure of this tree by watching the output produced by the call to its ToString() method.
Note also that the Expression class offers a Compile() method that makes it possible to dynamically generate the executable code corresponding to the expression when needed. That is, this method serves as a “bridge” between both worlds, translating data into code when it becomes necessary to evaluate the expression.


Reference:
http://www.elguille.info/NET/futuro/firmas_octavio_ExpresionesLambda_EN.htm

Happy Programming

Lambda Expressions Feature in C# 3.0

C# 2.0 (released in November 2005) introduced a new feature, anonymous methods, that allows you to declare your method code inline instead of with a delegate function. Lambda expressions, a new feature in C# 3.0, have a more concise syntax to achieve the same goal. Take a closer look at anonymous methods before discussing lambda expressions.
Suppose you want to create a button that updates a ListBox on your form when you click it. In C# 1.0 and 1.1, you would do it as follows:public MyForm()
{
listBox = new ListBox(...);
textBox = new TextBox(...);
addButton = new Button(...);
addButton.Click += new EventHandler(AddClick);
}
void AddClick(object sender, EventArgs e)
{
listBox.Items.Add(textBox.Text);
}
With C# 2.0, you could have it as under:public MyForm()
{
listBox = new ListBox(...);
textBox = new TextBox(...);
addButton = new Button(...);
addButton.Click += delegate
{
listBox.Items.Add(textBox.Text);
};
As you can see, you don't have to explicitly declare a new method to link it with an event. You can use anonymous methods to achieve the same thing in C# 2.0. C# 3.0 introduces an even simpler syntax, lambda expressions, which you write as a parameter list followed by the "=>" token, followed by an expression or a statement block.

Parameters to Lambda Expressions
The parameters of a lambda expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:(int x) => x + 1 // explicitly typed parameter
(y,z) => return y * z; // implicitly typed parameter
Lambda Expressions Demonstration
The following code snippet from
the downloadable source code uses two techniques to print out strings in a list whose length is even. The first technique, implemented in the function AnonMethod, is through anonymous methods. The second technique, implemented in the function LambdaExample, is through a lambda expression:// Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;
namespace LambdaExample
{
public delegate bool KeyValueFilter(K key, V value);
static class Program
{
static void Main(string[] args)
{
List list = new List();
list.Add("AA");
list.Add("ABC");
list.Add("DEFG");
list.Add("XYZ");
Console.WriteLine("Through Anonymous method");
AnonMethod(list);
Console.WriteLine("Through Lambda expression");
LambdaExample(list);
Dictionary varClothes= new Dictionary();
varClothes.Add("Jeans", 20);
varClothes.Add("Shirts", 15);
varClothes.Add("Pajamas", 9);
varClothes.Add("Shoes", 9);
var ClothesListShortage = varClothes.FilterBy((string name,
int count) => name == "Shoes" && count <> 0)
Console.WriteLine("We are short of shoes");
Console.ReadLine();
}
static void AnonMethod(List list)
{
List evenNumbers =
list.FindAll(delegate(string i)
{ return (i.Length % 2) == 0; });
foreach (string evenNumber in evenNumbers)
{
Console.WriteLine(evenNumber);
}
}
static void LambdaExample(List list)
{
var evenNumbers = list.FindAll(i =>
(i.Length % 2) == 0); // example of single parameter
foreach(string i in evenNumbers)
{
Console.WriteLine(i);
}
}
}
public static class Extensions
{
public static Dictionary FilterBy
(this Dictionary items, KeyValueFilter filter)
{
var result = new Dictionary();
foreach(KeyValuePair element in items)
{
if (filter(element.Key, element.Value))
result.Add(element.Key, element.Value);
}
return result;
}
}
}

full article on Lambda Expressions Feature in C# 3.0 read: http://www.developer.com/net/csharp/article.php/3598381

Happy Programming

Using Enterprise Library 1.1 with .NET 2.0

Enterprise Library problem while using ASP.NET 1.1 webservice in ASP.NET 2.0 webservice.

Introduction
Microsoft's Enterprise Library stands out as one of those rare collections of code with a truly representative name - an enterprise's library of useful features. Many architects deem them so useful they mandate the library for all of their applications. Unfortunately, there are situations when such decisions can prove painful.

Troubles encountered when running components using the Enterprise Library 1.1 with the ASP.NET 2.0 Beta releases became one such situation. Suddenly that enterprise library was far from a productivity boon. It did not even work with another version of ASP.NET!

The culprit turned out to be changes in ASP.NET 2.0 configuration mechanics. This adversely effected how Enterprise Library 1.1 components load. The immense gaggle of information residing within the many XML nodes of the Library's numerous configuration files, such as, dataConfiguration.config and loggingConfiguration.config , could not be either properly read or deserialized without some hack or fix.

Organizations leveraging Enterprise Library 1.1 bits within their .NET 1.1 components suddenly faced some tough choices. Avoid ASP 2.0? Wait for Enterprise Library 2.0 and port code? Hack Enterprise Library 1.1? Drop the Enterprise Library altogether from their components? None of these options appeal to an enterprise architect.

This article explores a different solution, based on some code that I've referred to as the Enterprise Library Adapter , which is available as the sample download for this article. One based on adapting how Enterprise Library 1.1 obtains its configuration information and instantiates its different application blocks. As seen in
Figure-1 the use of the Enterprise Library Adapter provides a little assistance via the Library's very own public methods to solve the problem.
For more details on implementation please read:http://microsoft.apress.com/feature/80/using-enterprise-library-11-with-net-20

Happy Programming

ASP.NET 3.5 controls

ASP.NET 3.5 controls
In addition to infrastructure improvements to better support IIS7, and in addition to toolset enhancements, web developers get 3 new controls in ASP.NET 3.5 (specifically in System.Web.Extensions.dll and specifically in the System.Web.UI.WebControls namespace): ListView, DataPager, and now in Beta 2 we see for the first time LinqDataSource.

Windows Communication Foundation (WCF) in .NET 3.0

As .NET 2.0 and 3.0 share the same CLR, everything written in .NET 2.0 works in .NET 3.0 which is an important and significant departure from previous versions. In terms of change, for those who love algebra equations the relationship can be summed anecdotally as:


.NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Window CardSpace + Workflow Foundation


The .NET Framework 3.0 achieves this objective through four key standards-based pillars corresponding to areas identified and requested by our customers. It also introduced a key new language called XAML. XAML is a declarative XML-based language that defines objects and their properties in XML allowing customers to develop workflows (WF) and immersive user experiences (WPF) declaratively. Let us explore the key pillars of the .NET 3.0 framework in greater detail.

Windows Communication Foundation (WCF)
WCF allows you to architect services by offering a standards- based framework and a composable architecture. The three key design philosophies for WCF are interoperability, productivity and service-oriented development.

Microsoft provides a number of messaging layer channels and service model layer behaviours that can be added and removed easily. It also allows you to define your own custom instances, for example you can write or buy a custom encoder for ASCII and insert it as a reusable channel in the messaging layer that can be used across various systems. WCF interoperates with existing investments and combines and extends existing Microsoft distributed systems technologies like Enterprise Services, System.Messaging, Microsoft .NET Remoting, ASMX and Web Services Extensions (WSE). This change implies that you can use a single model for different types of application behaviours which significantly reduces the complexity in application development. WCF also offers interoperability with non-Microsoft applications through support of the WS-I basic profile and a number of additional WS-* standards.
Finally in terms of productivity you can get a significant order of magnitude difference in developing secure transactional web services using WCF. Think of WCF as tens of thousands of lines of code that you would need to develop, generate and maintain, but instead are provided now as part of the base framework. WCF offers one of the first core programming frameworks that have been designed from the ground-up for services oriented development.
Happy Programming

Mar 12, 2008

First Look at Silverlight 2


Last September
we shipped Silverlight 1.0 for Mac and Windows, and announced our plans to deliver Silverlight on Linux. Silverlight 1.0 focused on enabling rich media scenarios in a browser, and supports a JavaScript/AJAX programming model.
We are shortly going to release the first public beta of Silverlight 2, which will be a major update of Silverlight that focuses on enabling Rich Internet Application (RIA) development. This is the first of several blog posts I'll be doing over the weeks and months ahead that talk in more depth about it.
Cross Platform / Cross Browser .NET Development
Silverlight 2 includes a cross-platform, cross-browser version of the .NET Framework, and enables a rich .NET development platform that runs in the browser. Developers can write Silverlight applications using any .NET language (including VB, C#, JavaScript, IronPython and IronRuby). We will ship Visual Studio 2008 and Expression Studio tool support that enables great developer / designer workflow and integration when building Silverlight applications.
This upcoming Beta1 release of Silverlight 2 provides a rich set of features for RIA application development. These include:
WPF UI Framework: Silverlight 2 includes a rich WPF-based UI framework that makes building rich Web applications much easier. In includes a powerful graphics and animation engine, as well as rich support for higher-level UI capabilities like controls, layout management, data-binding, styles, and template skinning. The WPF UI Framework in Silverlight is a compatible subset of the WPF UI Framework features in the full .NET Framework, and enables developers to re-use skills, controls, code and content to build both rich cross browser web applications, as well as rich desktop Windows applications.
Rich Controls: Silverlight 2 includes a rich set of built-in controls that developers and designers can use to quickly build applications. This upcoming Beta1 release includes core form controls (TextBox, CheckBox, RadioButton, etc), built-in layout management panels (StackPanel, Grid, Panel, etc), common functionality controls (Slider, ScrollViewer, Calendar, DatePicker, etc), and data manipulation controls (DataGrid, ListBox, etc). The built-in controls support a rich control templating model, which enables developers and designers to collaborate together to build highly polished solutions.
Rich Networking Support: Silverlight 2 includes rich networking support. It includes out of the box support for calling REST, WS*/SOAP, POX, RSS, and standard HTTP services. It supports cross domain network access (enabling Silverlight clients to directly access resources and data from resources on the web). Beta1 also includes built-in sockets networking support.
Rich Base Class Library: Silverlight 2 includes a rich .NET base class library of functionality (collections, IO, generics, threading, globalization, XML, local storage, etc). It includes rich APIs that enable HTML DOM/JavaScript integration with .NET code. It also includes LINQ and LINQ to XML library support (enabling easy transformation and querying of data), as well as local data caching and storage support. The .NET APIs in Silverlight are a compatible subset of the full .NET Framework.

Reference:
http://weblogs.asp.net/scottgu/archive/2008/02/22/first-look-at-silverlight-2.aspx

Happy Programming

Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)


LINQ (language integrated query) is one of the new features provided with VS 2008 and .NET 3.5. LINQ makes the concept of querying data a first class programming concept in .NET, and enables you to efficiently express queries in your programming language of choice.
One of the benefits of LINQ is that it enables you to write type-safe queries in VB and C#. This means you get compile-time checking of your LINQ queries, and full intellisense and refactoring support over your code.


Reference:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Happy Programming

Free Patterns and Practices Guidance Explorer for ASP.NET and .NET

JD Meier from the Prescriptive Architecture Guidance Group (aka PAG) at Microsoft stopped by my office this morning to show me the new Guidance Explorer tool he has been working on. This is a cool WinForms client application that aggregates PAG guidance and suggestions, and allows you to search and sort across it. This makes it ideal for quickly reviewing checklists of suggestions for ASP.NET projects. Each guidance rule covers why it should be followed, and includes instructions on how to implement it.

Reference:
http://weblogs.asp.net/scottgu/archive/2006/06/29/Free-Patterns-and-Practices-Guidance-Explorer-for-ASP.NET-and-.NET.aspx

Happy Programming

What is new in .NET 3.0 ?

c# 3.0 features
what is new in .NET 3.5?
First, as you no doubt know by now, .NET 3.0 is what we were calling WinFx until last week and is composed of (among other things):

Technology Name (Acronym) [Former Code Name]

Windows Presentation Foundation Classes (WPF) [Avalon] - Arguably the heart of .NET 3, this is the technology for building rich Windows applications with special features for managing layout, text, 2-d and 3-d graphics and much more.

Nothing new in .NET3.5 except some small features.
Windows Communication Foundation Classes (WCF) [Indigo] - A new framework for inter-process communication that will change the way we interact with web services and the way we implement remoting.




Windows Workflow Foundation Classes (WF) - You’d think this would be WWF but the World Wide Wrestling Foundation thinks differently. This is a framework for creating workflow engines that can be incorporated into your application
Info Spaces [InfoCards] - A very nice way to deal with controlling how you identify yourself and how much information you provide on the web.




At the same time that .NET 3 is coming out, ASP.NET is changing, though not quite simultaneously and not as part of the .NET 3.0 release. The key change to ASP.NET will be the release of ATLAS, the .NET Ajax technology and controls.
While all this is happening, Microsoft will also be getting ready to release ORCAS - the next release of Visual Studio, and, oh by the way, C# 3 (with some very impressive new features and the next release of Visual Basic.






Happy Programming

Top 10 new features in SQL Server 2005

What is new in SQL Server 2005?
New features in Sql Server 2005

1. T-SQL (Transaction SQL) enhancements
T-SQL is the native set-based RDBMS programming language offering high-performance data access. It now incorporates many new features including error handling via the TRY and CATCH paradigm, Common Table Expressions (CTEs), which return a record set in a statement, and the ability to shift columns to rows and vice versa with the PIVOT and UNPIVOT commands.

2. CLR (Common Language Runtime)
The next major enhancement in SQL Server 2005 is the integration of a .NET compliant language such as C#, ASP.NET or VB.NET to build objects (stored procedures, triggers, functions, etc.). This enables you to execute .NET code in the DBMS to take advantage of the .NET functionality. It is expected to replace extended stored procedures in the SQL Server 2000 environment as well as expand the traditional relational engine capabilities.
3. Service Broker
The Service Broker handles messaging between a sender and receiver in a loosely coupled manner. A message is sent, processed and responded to, completing the transaction. This greatly expands the capabilities of data-driven applications to meet workflow or custom business needs.
4. Data encryption
SQL Server 2000 had no documented or publicly supported functions to encrypt data in a table natively. Organizations had to rely on third-party products to address this need. SQL Server 2005 has native capabilities to support encryption of data stored in user-defined databases.
5. SMTP mail
Sending mail directly from SQL Server 2000 is possible, but challenging. With SQL Server 2005, Microsoft incorporates SMTP mail to improve the native mail capabilities. Say "see-ya" to Outlook on SQL Server!
6. HTTP endpoints
You can easily create HTTP endpoints via a simple T-SQL statement exposing an object that can be accessed over the Internet. This allows a simple object to be called across the Internet for the needed data.
7. Multiple Active Result Sets (MARS)
MARS allow a persistent database connection from a single client to have more than one active request per connection. This should be a major performance improvement, allowing developers to give users new capabilities when working with SQL Server. For example, it allows multiple searches, or a search and data entry. The bottom line is that one client connection can have multiple active processes simultaneously.
8. Dedicated administrator connection
If all else fails, stop the SQL Server service or push the power button. That mentality is finished with the dedicated administrator connection. This functionality will allow a DBA to make a single diagnostic connection to SQL Server even if the server is having an issue.
9. SQL Server Integration Services (SSIS)
SSIS has replaced DTS (Data Transformation Services) as the primary ETL (Extraction, Transformation and Loading) tool and ships with SQL Server free of charge. This tool, completely rewritten since SQL Server 2000, now has a great deal of flexibility to address complex data movement.
10. Database mirroring:
It's not expected to be released with SQL Server 2005 at the RTM in November, but I think this feature has great potential. Database mirroring is an extension of the native high-availability capabilities.

Happy Programming

Restore Database Backup using SQL Script (T-SQL)

How to restore database in Sqlserver2005?

Database YourDB has full backup YourBaackUpFile.bak. It can be restored using following two steps.

Step 1: Retrive the Logical file name of the database from backup.RESTORE FILELISTONLY FROM DISK = 'D:BackUpYourBaackUpFile.bak'
GO

Step 2: Use the values in the LogicalName Column in following Step.--Make Database to single user Mode

ALTER DATABASE YourDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--Restore Database
RESTORE DATABASE YourDB
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.mdf'
--If there is no error in statement before database will be in multiuser mode.
--If error occurs please execute following command it will convert database in multi user.
ALTER DATABASE YourDB SET MULTI_USER
GO


Happy Programming

When I open C drive by double click it'll pop up Open With windows and ask me to choose the program to open C drive?

When I open C drive by double click it'll pop up Open With windows and ask me to choose the program to open C drive?

Ans:

This is due to pest in your system. To get rid of this you remove the autorun.inf file from the root directory of C: drive.

use the following steps to find the autorun.inf

1) Open command prompt using windows+R and type cmd in the text box and press enter.

2) In command prompt type dir/a. example: c:\>dir/a

By this you can find the autorun.inf

3) Just find the autorun.inf and remove it.

To remove this file you should have admin privileges.
This you can do from command prompt by using attrib.
Remove the Hidden, read-only and system attributes.
To know the usage of attrib command just type attrib/? In your command prompt.
Ex: c:\>attrib/?
Then remove the file directly.

This will remove pest in your system.
Don’t keep .inf files in your root directory.

Happy Programming

Unity IoC Dependency Injection and ASP.NET Model-View-Presenter

Unity IoC Dependency Injection and ASP.NET Model-View-Presenter

The Unity IoC Container can be used in your ASP.NET Web Applications to provide dependency injection, especially when using Model-View-Presenter. There are several ways that one can use Unity to wire-up the presenter class and its dependencies to the ASP.NET view. In this example, I will use a Page Base Class that accesses the UnityContainer on the HttpApplication Class and uses Unity to create an instance of the Presenter Class associated with the view.

Happy Programming

Mar 11, 2008

export GridView to Word using ASP.NET 2.0 and C#.

First,you need to import the namespace from System.Data.SqlClient.
using System.Data.SqlClient;
The System.Data.SqlClient namespace contains The System.Data.SqlClient namespace is the .NET Framework Data Provider for SQL Server.The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space. In tutorial, we need "AddHeader" and "ContentType" to do the work.The AddHeader method adds a new HTML header and value to the response sent to the client. It does not replace an existing header of the same name. After a header has been added, it cannot be removed. The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML. We use the Button1_Click event to do the work. We then call "Response.AddHeader" to export a file which is named FileName.doc. We then use "Response.ContentType" to denotes the type of the file being exported.

protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/vnd.word";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{ }


The front end GridViewExportWordCsharp.aspx page looks something like this:
asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export to Word"Width="99px" asp:GridView ID="GridView1" runat="server"/asp:GridView

The flow for the code behind page is as follows.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string ConnectionString = "Data Source=(local);
Initial Catalog=pubs;
User Id=sa;
Password=sa123";
SqlConnection cn1;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection cn = new SqlConnection(ConnectionString);
cn.Open();
cn1 = new SqlConnection(ConnectionString);
cn1.Open();
SqlCommand cmd = new SqlCommand("select * from [authors]", cn);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
cmd.Dispose();
cn.Dispose();
cn1.Dispose();
cn = cn1 = null;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/vnd.word";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}

How to do time taking operations in asp.net?

How to avoid request timeout?
have a web page with a single button that causes postback.
The button_OnClick method takes some time to finish, something like 30 minutes.
After 5-10 minutes the page goes to "The Page Cannot Be Displayed" screen.
I changed the timeout values in IIS, but it didn't make any change.


Try setting the httpRuntime node in your web.config. You can set things like maximum upload size, or execution timeout. "executionTimeout" is in seconds.
configuration
system.web
!-- MAX UPLOAD FILE SIZE: 100MB HTTP TIMEOUT: 30MIN--
httpRuntime maxRequestLength="102400" executionTimeout="1800"/
/system.web
/configuration
I used this for an app that needed to stay running for half an hour (it created like 2300+ zip files).
use open and close angular brackets in the code

Happy Programming

Disable some ads in AdRotator XML

Is there a property that can be used to disable an AD in the ads xml file? which would result in ad not being displayed..
Something like this -->
openangular barcket Advertisements close angular bracket
openangular barcket
Ad Enabled="false"
close angular bracket
... ....
Ans:
if you want to disable a AD, you can give the Impression property to "0", it will not displayed.


Happy Programming

adding user controls dynamically in asp.net

How to add user control dynamically to a asp.net webpage?

protected void addUserControl()
{
Control c = LoadControl("UserControl1.ascx");
c.ID = "uc";
this.Panel1.Controls.Add(c);
}
protected void Button1_Click(object sender, EventArgs e)
{
addUserControl();
}

References:

http://aspalliance.com/565_Dynamic_Loading_of_ASPNET_User_Controls
http://www.singingeels.com/Articles/Dynamically_Created_Controls_in_ASPNET.aspx

Happy Programming

How to expire a web page immediately?

If user clicked Sign Out, the session is abandon and the browser diaplays the login screen. If the user clicks the browser Back button, the previous page should not come back. How does it work?

You need to set the page to not cache and check if the session exists on page load and redirect to the login page if it doesn't. Something like:

protected void Page_Load(object sender, EventArgs e)
{
SessionCheck();
Cache.SetCacheability(HttpCacheability.NoCache);
}
private void SessionCheck()
{
if (Session.Count == 0)
{
Response.Redirect("~/login.aspx");
}
}

Happy Programming

ASP.NET Wiki (Beta) has just launched

Scott Hanselman just announced the launching of the ASP.NET Wiki (Beta). If you are wondering why a Wiki this is what Scott has to say: "To provide a targeted, categorized, human-hand-edited, and living Wiki for finding answers to ASP.NET questions."
If you have some great content on your blog that is not in there, get it in there.

Happy Programming

Beginning SQL Server 2005 Reporting Services Part 1

Sqlserver Reporting services by steve joubert
Building and deploying basic reports

SSRS 2005 is the latest version of SQL Reporting Services, and ships with all versions of SQL Server 2005. SSRS allows you to quickly and easily create reports from multiple database sources. The finished reports can be presented directly from the reporting services website, or they can be displayed in your web- or Windows-based applications. Reports can be exported to multiple formats, including comma delimited text, XML, portable document format (pdf) and Microsoft Excel.

This article is the first of four parts, which will provide in-depth coverage of SQL Server 2005 Reporting Services:

Part 1 covers the basics of the SSRS. It demonstrates how to build quick, simple reports and will familiarize you with the basic Report Designer environment
Part 2 will cover use of custom functions, aggregate functions, sub-reporting, the matrix control, drill-downs, and sorting.
Part 3 will take an in-depth look at the charting control
Part 4 digs into the actual Report Definition Language (RDL) and the new Report Builder tool.

Installing and configuring Reporting Services

After much debate, we decided that full installation and configuration details were outside the scope of an article focused on how to build basic reports using SSRS, especially as there are already several online resources that treat this area in detail. See, for example:
http://msdn2.microsoft.com/en-us/library/ms143736.aspx
and
http://www.awprofessional.com/articles/article.asp?p=357694&seqNum=1&rl=1
Well worth reviewing are the details in the latter on the need to install SSL on any machine hosting SSRS.

---Editor's installation notes---
In order to test the reports in this article, I went through a single-machine installation on Windows XP (meaning that SQL Server 2005, Reporting Services, and much more, are all installed on my poor laptop). Since I didn't install SSRS when I installed SQL Server 2005 (I didn't have IIS installed at the time), I had to first install IIS 5.1, and then Reporting Services (from the SS2005 disks). I then jumped immediately into Reporting Services Configuration Manager tool (All Programs ¬ SQL Server 2005 ¬ Configuration tools). The left panel acts as a sort of checklist of items to configure:

All went well until the Database Setup. Because I had not installed SSRS at the same time that I installed SQL Server, the ReportServer and ReportServerTempDB were not created by default. These databases hold all the report definitions and reporting server configuration information. Connecting to SQL Server using Service Credentials, the databases appeared to be created, but I received an error suggesting that I didn't have permissions to perform the requested task, and a red cross remained next to the Database Setup icon. This had me stumped for a while – eventually I appeared to solve it by hopping to the Server Status section, stopping the Report Server, opening SSMS and deleting both the ReportServer and ReportServerTempDB databases, and then restarting the Report Server and trying again! Even though I swear this didn't work the first time I tried it, it seemed to do the trick the second time (while I was on the phone moaning to Steve that I couldn't get it to work!). However, I'm still not clear why I had the problem in the first place – or why it suddenly went away.
This wasn't quite the end of my problems. Installing SSRS creates two new virtual directories under the default website on IIS. By default, they are named Reports and ReportServer. The ReportServer site hosts a web service for running and managing reports. The Reports site allows you upload reports from a browser and run reports over the web. When I tried to navigate to http://localhost/ReportServer I received the following error: "Failed to access IIS metabase". Fortunately, the information on the error page is quite useful (for a change) and this, coupled with a quick Google search, led me to grant access to the metabase to the ASPNET user account by executing the following from the directory housing the aspnet_regiis executable (WINDOWS\Microsoft.NET\Framework\v2.0.50727, in my case):

aspnet_regiis -ga ASPNET

This did the trick, and I was up and running. I received some raised eyebrows here when I proposed to install SSRS. It made my long-suffering sys admin team particularly nervous. The 2000 version of SSRS seems to have a very bad reputation among the Red Gate team, both as a performance nightmare, and in one case for "completely annihilating" a developer's machine. However, the above slight quirks aside, the SSRS 2005 experience seems pretty smooth and I've had no real performance, or other, issues. So far.-----End of Editor's note----
Once you've completed the installation and configuration process, the first thing to do is download the code file for this article (see the Code Download link in the speech bubble to the right of the article title). The code file contains a sample Visual Studio project and a SQL Script for creating the ReportDemo database. You will need this database if you want to follow the examples in this series of articles so go ahead and create the database using the ReportingDemoDatabaseScript.sql script or, alternatively, by restoring the provided ReportingDemo.bak file.
If you are using SQL Server Authentication on your SQL Server you will also need to set up a login with permissions to the ReportDemo database (for the examples, I set up a login called DemoUser as a DBO on my ReportDemo database).

Using the Report Wizard

There are two ways to create SSRS Reports. You can build the report manually, or you can use the Report Wizard to give yourself a head start. For this first report, we are going to take advantage of the wizard. Start a new Business Intelligence project in Visual Studio 2005. Then, from the menu, select Project > Add New Item. Select the Report Wizard option and call the file "FirstReportWZ.rdl". Click Add. Click Next on the Welcome screen and this will bring you to the Select the Data Source screen:


Select the New data source radio button and give the data source a name. Select Microsoft SQL Server as the type.
Note:Use of the Shared data source option is actually a better option in most cases but, for the sake of this example, we will just create a new data source. We're going to set up a shared data source later in this article.
Click the Edit button to bring up the Connection Properties dialog:


Enter or select a server name. The default is to log on using Windows Authentication. If you are using SQL Server Authentication, choose that setting, and enter the username and password. Finally, select a database, in this case ReportingDemo. Make sure you test the connection before you click OK.
Next up is the Design the Query screen. You can use the Query Builder by clicking the button at the top left, but in this case simply enter "Select * From Customer" into the Query string text box and click Next. On the Select the Report Type simply select the type you prefer (tabular or matrix) and hit Next.
This brings up the Design the Table screen:


Select State in the Available fields box and click the Group button. This will group the data in the result set by State. Select Next. On the Choose the Table Layout page, select the Stepped option and check the Enable Drilldown checkbox. On the next screen, choose a style for your report (I chose Ocean) and click Next.
This brings up the final screen, Completing the Wizard:


It shows a summary of your report options, and gives you an opportunity to rename the report and to preview it. Click Finish to end the wizard.
You should be shown the report in the standard Report Designer:


There are three tabs: Data, Layout and Preview. You should be on the Layout tab. Click on the Preview tab to view the report. Since this report doesn't take any arguments, it will run as soon as you click on the tab.


Use the +/- symbols next to the State abbreviations to expand and collapse the grouping of the report.

Manual report creation

The previous section, while perhaps overly simplistic, does show you how to get a report up and running with zero code and zero property setting. Obviously, such reports will not meet most development requirements, but do not discount this option as a starting point for more complicated reports. Once you've created a report with the Report Wizard, you are free to make any modifications to it.
In this section, we are going to create a more realistic report from scratch, including how to create and use a shared data source object, stored procedures, and how to format your report, set report properties and use report parameters.
Creating a shared data source
Before we start the report, we are going to build a shared data source i.e. a data source that is common to, and can be used by, all of the reports on a reporting server. While each report can contain its own connection information, it is good practice to use shared data sources, as it will save you a lot time and headaches. This way, you only have to set the connection information once. For example, let's say your company has Development, Test and Production environments. If you put the connection information into each report, you will have to change it each time when you publish to Development, Test and Production. If you use a shared data source, you still have to set up a data source object for each of three environments, but you can simply publish the report to each environment, and they will automatically use the connection information associated with that environment.
From the menu select Project > Add New Item > Select Data Source. On the General tab, call the data source "ReportsDB". Leave the Type as Microsoft SQL Server. Click the Edit button on the right, and enter the connection information for Reporting Demo, as before. Click OK on the Shared Data Source screen and the data source is done.
Add a new report
From the menu select Project > Add New Item. Select Report and name it "FirstReportMan.rdl". A new report will be added to the project, and the Report Designer will open at the Data tab. At this point, let's take a closer look at the Report Designer tool. At the top of the Report Designer window are three tabs: Data, Layout and Preview. The Data tab is used to build data sources for your report. The Layout tab is the physical report designer where you set up the header, the footer and the data presentation of the report. The Preview tab allows you to actually run the report from Visual Studio 2005, without having to publish it to a report server first. If your report takes parameters, the Preview tab will ask you to fill them out before it runs the report.
The first thing we need to do is get data into our report. At the top of the Data tab choose from the dropdown list:



The Dataset dialog opens:



Name the dataset "ReportData", and select the ReportsDB data source from the dropdown. Select StoredProcedure as the command type, and enter "spr_CustomerSelectAll" in the query string box. Click OK to close the dialog.
Note:
spr_CustomerSelectAll is a very simple, parameter-less stored procedure that selects all of the columns from the Customer table. The source code is included in the ReportingDemoDatabaseScript.sql script with the code download.
Test the dataset by clicking on the big red exclamation point at the top of the report designer. This executes the query and displays the results. You can repeat these steps if you wish to add multiple datasets to your report.
Setting up the report display
Next, switch to the Layout tab. This is where you actually build the report display. Start by dragging a table from the Toolbox, onto the Body section of the report. By default, the table shows a header row at the top, a detail row in the middle and a footer row at the bottom. You can add additional columns to the table by right-clicking on one of the columns and selecting one of the two Insert Column options.
Click on the Datasets tab under Toolbox on the left-hand side of the Visual Studio environment. You should see the ReportData dataset. Expand it, select FirstName and drag it to the first cell of the body row of the table. This will display the First Name field in the first column. Now put the LastName in the second column, and the CustomerStatus in the third:

Note that, when you drag the column FirstName into the body row of the table, SSRS make a guess as to what to call the row. It calls it "First Name". You can click on the Preview tab to view the report.
Adding formatting
OK, so we have a basic, very plain, report. Let's add some formatting to make it look good. Let's add the DateOfBirth column to the table. You can expand and shrink the size of the columns by highlighting and dragging:

If you wish to get rid of the footer row of the table and then click on any field in the table. You will see a grey box surround the table. Right-click on the icon at the beginning of the body row and then click the Table Footer option to deselect it.
The table header is next. To format all the cells in the header in the same way, click and drag over all the cells to select them. Open the Properties window and set background color, font, and so on.

Note, however, that if you wish to change the justification of the text or the size, then you do so using the main menu at the top, not via the properties window. Again, you can click on the Preview tab to view the report.
Add a report header
The table already has a header, but the report can also have a header and footer. Report headers and footers appear on every page of the report. Put the Report Designer in Layout mode and select Report > Page Header from the menu. A new band labeled Page Header appears on the report above the body. Drag a text box onto the header and click directly on it. Type "My First Report", not in the Properties window, but right on the control.



To adjust the text style and size of your heading, highlight the text box and use the option from the top menu.
Formatting
Each field can have formatting. Let's deal with that ugly Date of Birth field. The time information is superfluous, so let's format the date properly. Right-click on the cell that contains the date of birth, and choose Properties. Next, select the Format tab.



Click on the second button (labeled "…") to the right of the Format code field. When the dialog opens, use the standard options. Select Date in the list on the left, then choose the sample date format you want on the right. Click OK to close the dialog.



Click OK to close the Properties window and then click on the Preview tab to view the report.
Setting report properties
To access the report properties, you need to be on the Layout tab of the Report Designer. When you click on this tab, a new menu item, Report, activates. This menu gives you options for turning on and off the report header and footer sections (as we have seen), adding embedded images, setting report properties, and setting report parameters.
Setting up the report print settings is not intuitive, compared to other products. In the report Layout tab you see your report with a ruler across the top. That ruler is set up in inches. A standard sheet of paper is 8.5 x 11 inches. The default setting in SSRS is to have a 1-inch margin all the way around the content area. So, at 8.5 inches wide with a 1-inch margin on the left and another on the right, you have 6.5 inches for content. Any more, and the content beyond the 6.5 inches will spill over onto a second sheet of paper when printed. It will not automatically shift to Landscape.
To get Landscape reports, you have to make the proper report settings. Navigate to the Layout tab of the Report Designer. From the Report menu select Report Properties. Switch to the Layout tab of the dialog box. To switch to Landscape printing, you need to change Page width to 11in and the Page height to 8.5in.




On the same Layout tab, you can also get up your report to display the data in multiple columns, and you can control the margins. By default, all the margins are set at 1 inch. Remember, if your report width, plus the right and left margins, is greater than the width of the printer, you will get spill-over when you print out your report.
Using parameters
There are two ways to add parameters to your reports. The first is to use parameters in the queries in your data sources. The second is to set up parameters through the Report Parameters dialog box. We will do both.
Query parameters
First, we will set up parameters using a data source query. Navigate to the Data tab, and click the "…" button right next the Dataset dropdown box. The Dataset dialog box opens and allows you to edit the query for the dataset. Change the Query string from "spr_CustomerSelectAll" to "spr_CustomerSelectByState".
Note:spr_CustomerSelectByState accepts a parameter called StateCD that allows us to filter the data from the Customer table by State. Again, the source code is included in the ReportingDemoDatabaseScript.sql script with the code download.
Click OK and then run the query by clicking the red exclamation point (!) on the Data tab toolbar. You will be prompted to enter a parameter value for StateCD (the State code). Enter "CA" and click OK. The query should return all the customers that live in California.
Switch to the Preview tab. Instead of the report just running, there should be a place for you to enter a value for the "StateCD" and run the report. Enter "CA" and click the View Report button. You should see your report filtered by state.
To edit the parameters, or to add new ones, switch to the Layout tab of the Report Designer and open the Report Parameters dialog from the Report menu. First, we are going to make the "State code" prompt a little more friendly. Select StateCD in the Parameters list box then, in the Parameters Properties box, change the prompt to read "State". In the Available values section enter "California" and "CA" on the first line. Enter "Louisiana" and "LA" on the second line.




This will make the prompt for "State value" into a dropdown. You can also build additional datasets into your report, and use the values in those datasets as criteria for dropdowns.
Report parameters
Now let's add a parameter that is not used in a query. Click the Add button in the Report Parameters dialog from the Report menu. Give the new parameter the name "ReportTitle". Its Data type should be String. Set the Prompt to "Report Title". Click OK and close the dialog box.
Drag a new text box onto the report header area. Right-click on it and choose the Expression option. In the Edit Expression dialog select Parameters. Double-click on the ReportTitle parameter. This text box will now display the value you pass to the Report Title parameter.





Switch to the Preview tab and try it out.
Publishing your reports
Up to now, you have been running your reports in the Visual Studio 2005 environment but, to make them useful, you must publish them to a report server. The easiest way to do this is to have Visual Studio publish your reports.
Start by right-clicking on Project in the Project Explorer and choose Properties.
Set TargetServerURL to the URL of your report server. Use the TargetReportFolder property to set up a folder for your reports. If the folder does not exist, the Publisher will create it for you. The other key thing to pay attention to here is the OverwriteDataSources property. When this property is set to "True", it will automatically copy over all your data source objects when you publish. When set to "False", it will copy any new data source objects, but it will not overwrite existing ones. This is important when dealing with development, test and production servers. You can publish a set of data source objects to each server, pointed at the correct database, and never have to worry about what database your reports are hitting in each environment.
From the Build menu select Deploy Solution. This will publish the project to the selected folder on your report server. You can also deploy individual reports by right-clicking on the file in the Solution explorer and selecting Deploy.
Once your report has been published, you can access and run it on your server through the browser at
http://servername/reportservername. From the Home page, you should be able to find the folder you published to, with the reports in it. Select a report to run. At the top of the page you can enter any values for report parameters, and then run the report. From here, you can also print or export the report.

Reference: http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/



Happy Programming