Labels

Thursday, December 30, 2010

What's new in ASP.Net 3.5

One major improvement for Visual Studio 2008 over earlier versions is you can specifically choose the .NET Framework version for an application, allowing it to be used for older .NET 2.0 applications as easily as .NET 3.5 applications.

ASP.NET AJAX

LINQ

There are a number of new controls added to the ASP.NET environment that simplify the display of data on a Web page, as well as provide the user with more flexibility in viewing and selecting data. While ASP.NET 2.0 added several controls for working with data on the Web (notably GridView, DetailsView and FormView), they were restricted in their capabilities and flexibility. Two new controls, ListView and DataPager, are new in ASP.NET 3.5 and are extremely useful.

Support for several standard protocols has been added to ASP.NET 3.5, too. The most common protocols now supported are SOAP (a protocol for moving XML messages, SOAP is a foundation of the Web services protocol stack), RSS (Web feed format for frequently-updated content), JSON (JavaScript Object Notation, a data interchange format), and POX (Plain Old XML, which is actually XML with other specifications such as XML Namespaces, XInclude, XLink and Dublin Core.

ASP.NET 3.5 includes the ASP.NET MVC

New in .NET framework 2.0

It brings a lot of evolution in class of the framework and refactor control including the support of

Generics
Anonymous methods
Partial class
Nullable type
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework

New in .NET framework 3.0

Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website

New in .NET framework 3.5

It implement Linq evolution in language. So we have the following evolution in class:

Linq for SQL, XML, Dataset, Object
Addin system
p2p base class
Active directory
ASP.NET Ajax
Anonymous types with static type inference
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API
Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.

 

What's new in C#.NET 2005

The new features of C#.NET are classified into four categories:- Generics, Iterators, Anonymous methods and Partial Classes.

Generics were introduced to enable developers create type safe data structures. They can be defined as utility helper classes that do not commit the developer to the actual data types being used. This feature improves performance and results in higher quality code as the algorithms can be reused without duplicating type specific code. They are an extension to the CLR type system and allow developers to define types which are unspecified. They are then specified at runtime as the code references the generic type and fills in the details, tailoring the type to particular needs. Though generics serve a similar purpose as C++ templates in managed code they have some additional features which include absences of code bloat and developer confusion. Four distinct benefits accrue to the developer at compile time—Type safety, binary code reuse, performance and clarity.

Iterators are used to iterate over data structures such as arrays, collections using a foreach loop. The condition being that the GetEnumerator method is implemented to return an IEnumerator interface. C# 2.0 defines the generic type safe IEnumerable and IEnumerator interfaces in System.Collections.Generics namespace to overcome these problems. There is no need to work with a design pattern. A single typed method called GetEnumerator() is sufficient. The values will be returned directly. The new keyword yield replaces the return keyword. The compiler then converts the new implementation into a enumerator pattern and eases the process of development. It avoids unnecessary coding and keeps the source code short. A significant feature is that any method can be made enumerable. The method has to return a value defined by the IEnumerable and use the yield keyword to return a single value.

C#.NET 2.0 supports delegates as means of invoking one or more methods. The Delegates provide operators and methods for adding or removing target methods and are frequently used in .NET Framework for events, callbacks, asynchronous calls and multithreading. Anonymous methods are a new feature in C#.NET 2.0 that lets the developer define an anonymous method called by a delegate. This method is defined inline and is not a member method of any class and there is no way of applying method attributes to it. The anonymous method cannot define generic types or add generic constraints. The compiler has to infer the type of delegate used, instantiate a new delegate object of the inferred type, wrap the new delegate around the anonymous method and assign it to the delegate used in the definition of the anonymous method. Anonymous methods can be used anywhere and can be passed to any method that accepts the appropriate delegate type as a parameter. Anonymous methods can use generic types as parameters.

 Partial Classes are classes whose definition and implementation are split into two or more separate files. Every part of the class is marked with the new modifier partial. The compiler then looks for the marked and parts and merges the component parts and merges them into one complete implementation at runtime. A precondition is that the assembly of the code parts must be in the same project and a parallel compilation. The classes also should be matched logically and must have identical modifiers, supported interfaces etc. All attributes assigned at class level are handled automatically. This feature was directed towards rapid application development and probably for distinguishing between generated and custom code.

What's New in ASP.NET 2.0

1. Improving Development productivity by reducing the lines of code to be written by 70%. Most of the frequently required code is now available out of the box.

2. Making ASP.NET easier to use with existing devices like Web browsers, PDAs, Cell phones and so on with a potential to connect to new devices that may emerge in the future.

3. Increasing performance and scalability for developing fast web applications platforms by providing facilities such as caching.

4. Simplifying the administration and management of web applications

5. Providing enhanced hosting opportunities for Internet Service providers

6. Ensuring 100% backward compatibility.

The team split the process of enhancement into three parts:--Application services, Page effects and Rich controls. They focused on each of these parts to come up with an application development platform that is exciting and extremely developer friendly.

We shall briefly look at these enhancements in this section.

New Controls

It is expected that the final release of ASP.NET will include 40 new controls. The existing controls will be retained to ensure backward compatibility.

The data controls have received a face lift. The Grid View control has features for sorting, paging, selection and editing of contents out of the box. The communication with the database is transparently handled and is enabled for both reading and writing data to the database.

The DetailsView control displays single records in a vertical listing of data. This control can be configured to provide for custom outputs.

The TreeView control supports the Data Source Provider concept and a number of data sources can be bound to it, including XML data.

The Bulleted list control designed for data binding displays highly configurable HTML lists and provides support for hyperlinks and link buttons.

Apart from the above major new controls a number of other new controls have been introduced to for use of image maps, upload of files and rapid implementation of Wizards.

Master Pages

Master pages have been designed to help web developers design templates with place holders for content. Unlike in the earlier versions of ASP.NET developers can now rely on visual design support to design their pages.

Site Navigation

Implementation of navigation has been made simple with the integrated navigation structure based on XML data. The provider does the job of feeding the navigation structure with data instead of using the site map support. The provider acts as a bridge between the common framework functions and custom implementation.

User Management

An entire user management system is provided out of the box! Extensive API, special controls for registration, login and so on with data providers to handle the data storage without any code are the highlights of this feature. The configuration user management system and the creation of the database is also assisted by a Wizard. The administration feature helps the developer decide how passwords will be stored, reset and so on and also enables the management of user roles.

Personalization

Personalization makes it possible to assign information to an user account, save it to persistent storage and automatically load it back for the next session. This feature can be used in conjunction with the user management system. Complex data structures like shopping carts can also be persisted using XML serialization. The personalization feature also allows users define one or more zones and within the zone information (web parts) can be arranged using drag and drop. This implies that content can be moved, changed or deleted with ease. The Data Provider takes care of the data storage, freeing the developer from designing ways and means of storing data. All data can be stored in SQL Server or Microsoft Access database.

Themes and Skins

With the new ASP.NET allows developers define themes and skins for their applications. The only effort required is the definition of the theme. Some sample themes are included in the standard installation and they can be activated by making some configuration adjustments in the application. The Implementation of themes provides for design properties, CSS support and integration of individual graphics. A theme and a sub theme(called skin) can be local to the application, the page or the control.

Mobile devices

Mobile computing has been taken to new heights with ASP.NET 2.0. Controls for mobile devices included in ASP.NET 1.1 are still available but are not recommended for use. The new ASP.NET introduces the concept of “adaptive rendering” which makes controls redundant. Regular web controls will adapt to the requirements of the target device! A set of adapter classes have been defined and assigned to each control and they are included for common browsers and mobile devices. Customized adapters can also be defined by the developer. This leaves Microsoft with the option to add adapters for new devices that may enter the market in the future.

Site Counters

This feature helps in counting page requests and also clicks of controls (e.g. AdRotator, Button, link button etc). The .NET framework provides an extensive API to analyze, visualize and process the data.

Configuration

The new ASP.NET does away with the cumbersome configuration files of its earlier versions. The voluminous API to read and write configuration files like web.config in type safe manner makes the whole job easier. Each object gets one corresponding configuration segment and a whole collection where necessary. These objects can be edited and then saved back to the file. In the process every setting in the web application can be controlled by the developer. Web Site Administration tools and Configuration Settings Editor are two major additions under this head.

Deployment

ASP.NET 2.0 opens up several new possibilities for the deployment of the applications. Developers can now create or open projects using the file system or the local IIS, FrontPage Extensions or even FTP. The Web Copy Assistant supports the synchronization of local development version with the live server. The new functionality for compiling complete web applications includes copying of Dynamic link Libraries(DLLs) to the Web server. These libraries contain compiled source code and the content of the aspx and ascx files. This implies that no design time files will be required to be placed on the server and hence modification of the application becomes difficult.

The new features of Visual Studio.NET 2.0 and its repository of software including ASP.NET, C#.NET etc are dedicated solutions created to address specific problems of the developer. It attempts to simplify the overall programming model. The compiler is designed to generate most of the code and the developer is freed from repetitive programming tasks. Code has become more concise and readable.

Tuesday, November 30, 2010

URL Rewriting

URL Rewrite module for IIS7

using HttpModule andovercome the postback bug

using the new System.Web.Routing namespace? It's the same url routing library that comes with ASP.NET MVC and it works for ASP.NET "classic webforms" as well

Monday, November 15, 2010

JQuery Study

JQuery ThemeRoller tool

Latest jQuery and jQuery UI Theme links on Google CDN


JQuery API

.load( url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ] )

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function.

How to distinguish 2 dialog box since no ID associated?
I can address my dialog text field, because it has a unique ID:
'myDialog1', and from here I traverse upwards to the dialog  ("closest
()" searches the ancesters in the DOM tree) and from here downwards to
the title bar ("children()" traverses downwards), e.g.:
     $("#myDialog1").closest('.ui-dialog').children('.ui-dialog-
titlebar').hide()
or e.g.:
     $("#myDialog1").closest('.ui-dialog').children('.ui-dialog-
buttonpane').css({
         top: '80px',
         left: '70px',
         opacity: .8,
         background:"#ffcc99",
         border:"8px dashed #f00"
         });

D e m o :
     http://netzwerkstatt.de/jqui_zweiDialoge

Basic usage of the jQuery UI dialog

All jQuery UI plugins maintain state, such as the current option values, whether the plugin is enabled or disabled, which plugins have been initialized on the element, etc.  This state persists from the time the plugin is instantiated on the element until it is destroyed, either explicitly by the user calling .pluginName('destroy') or by removing the element (or one of its ancestors) via .remove().  Because of this state management, you cannot instantiate the same plugin on an element multiple times, unless you destroy the plugin instance first.

JQuery UI - Dialog BOX read ASP file

JQuery's methodology is simple: find things, do stuff. We select elements from the document (via the DOM) using the jQuery function, aliased as $(). This handy function acts just like document.getElementById(), except that instead of only supporting IDs, it supports CSS selectors and some XPath selectors; and, instead of returning one element, it can return an array of elements.

We then use functions to perform actions on our selections. For example, to append the text "Hello World!" to all divs with the class 'foo', then set the color to red, we'd use the following code:
$("div.foo").append("Hello World!").css("color","red");
Easy! Normally, this task would require two lines of code, like so:
$("div.foo").append("Hello World!");
$("div.foo").css("color","red")

Demo Effect

50+ Amazing Jquery Examples- Part1

How to create a stunning and smooth popup using jQuery


Simple Example:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
   <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>  
   <script type="text/javascript">
     function PopWindow_Click(ID)
     {
                var $dialog = $('<div></div>')
                .html('Sorry we can not display target page.')
                .dialog({height: 200, width:600, modal: true, autoOpen: false,title: 'Popup Dialog Box',hide:'blind'});
                $dialog.css({"opacity": "0.2"});
                var options = {};
//                $dialog.dialog({close:function(event, ui) { ... }});
//                $dialog.effect( 'blind', options, 500);
//                $dialog.fadeIn("slow");
//                $dialog.fadeOut("slow");
//                $('#close_message').click(function(){$dialog.effect({ top:"+ px",opacity:0 }, "slow");}});

                $dialog.load("sample.asp?ID=" + ID);
                $dialog.dialog('open');

//    //scroll the message box to the top offset of browser's scrool bar
//        $(window).scroll(function()
//        {
//          $('#message_box').animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});
//        });
     }
    
   </script>
    <title>JQuery test - Popup Window</title>
</head>
<body>
    This is JQuery Test<br />
    <u id="popupwindow" style="cursor: pointer" onclick="PopWindow_Click(2)">popup window</u>
</body>
</html>

Friday, October 29, 2010

ASP.net MVC Vs ASP.net Web Form

Software Architects have been involving lot of debates about different approaches and architectures. Some of the examples are ORM Vs Store Procedures, REST Vs SOAP, etc. There is a debate happening inside the Microsoft community about ASP.net web form Vs ASP.net MVC. Many people thinking that ASP.net MVC will be replace webforms at least eventually and others are thinking that ASP.net MVC will not be replace webforms. Will ASP.net MVC replace webforms?. ASP.net MVC is an alternative approach to webforms rather than a replacement. It will not replace webforms and webforms will not replace ASP.NET MVC. The fact is that ASP.NET MVC and webforms will co-exist and that ASP.NET MVC is not a replacement for webforms. If you prefer ASP.net MVC use it and you feel webform is more comfortable, you can use it. . Both approaches are just choices and different approaches and choices are good things. Different choices are available for other platforms especially in the Java platform.

Advantages of MVC Model
  1. Enable clean separation of concerns (SoC) .
  2. Enable full control over the rendered HTML.
  3. Enable Test Driven Development (TDD) (built with TDD in mind).
  4. SEO and REST friendly URL.
  5. Easy integration with JavaScript frameworks.
  6. Support third-party view engines such as NVelocity, Brail, NHaml.
  7. No ViewState and PostBack events.
  8. Follows the stateless nature of web.
  9. Extensible and Pluggable framework. 
  10. Ideal platform for Web 2.0 applications.
Advantages of Web Form Model
  1. Provides RAD development.
  2. Easy development model for heavy data-driven LOB applications.
  3. Provides rich controls.
  4. Familiar model for windows form developers.
 Problems with ASP.net Web Form
What are the problems with webforms? In webforms, Microsoft has tried to make windows form model development for web application development. That model was attracted lot of windows form developers especially VB 6.0 developers. Many of VB 6.0 developers had moved to ASP.net web development without knowing the basics of HTTP and web. For simulating windows form model development experience, webforms introduced event-driven approach and also introduced Viewstate and Postback. The end result is that web forms breaks the stateless nature of the Web. Both Viewstate and Postbacks have been made lot of problems and increased complexity of the web application development. Many web pages having hundreds of KB size of Viewstate that affected the performance of the applications sometime. Developers do not have the control of the rendering HTML of web forms and Server controls that render html with mixed inline style and deprecated tags that does not follows standards. Another problem with Web Forms is the integration of JavaScript frameworks due to the naming conventions of rendered HTML. The page life cycle of the Web Form is too complex and has the tightly coupling between all things in the ASP.net framework and a single class is used both to display output and handles user input. So unit testing is almost an impossible task. Today unit testing is very important in modern software development especially when we following agile methodologies and practices. Since web is a stateless thing, Events, Postbacks and Viewstate are not a good way. Today many ASP.net web form developers are facing different type pf browser compatibility issues when developing public face internet applications
The ASP.net MVC way
The ASP.NET MVC simplifies the complex parts of ASP.net Web Forms without any compromise of the power and flexibility of ASP.NET platform. ASP.net MVC implements Model-View-Controller UI pattern for web application development that lets you allows to develop applications in a loosely couples manner. MVC pattern is separating the application in three parts- Model, View and Controller. A view is responsible for rendering the user interface (UI) of the application and it is nothing more than html templates that filled with application’s data passed by the controller. The Model implements the logic for the application's data and it represents the business objects of the application that using the View for rendering user interface. Controllers are handles and responds to user input and interaction. The web request will be handled by the controller, and the controller will decide which model objects to use and which view objects to render. The MVC model replaces the Web Form events with the controller actions. The main advantages of the MVC models are clear separation of concerns, unit testing facility, and more control over the URLs and HTML. The MVC model does not use Viewstate, Postbacks, Server controls, and server-based forms that enable full control over the application and html rendered by the Views. MVC model is using Representational state transfer (REST) based URLs instead of file-name extensions used by the Web Form model so that we can make search engine optimization (SEO) URLs published by the application.


Which is the best approach?
The choice would be vary on different people. If you want more control over the HTML or you want Test Driven Development (TDD), or you care about web standards, accessibility, or you want to build SEO based URLs, you can choose MVC model. If you want rich controls and state oriented event-driven web development, you can choose Web Forms model. If you feel more comfortable with MVC, choose that model and you feel Web Form model is more comfortable, choose that model. Both are just choices. If you start your career with ASP.net Web Forms and do not have full knowledge of Web, it will be very difficult moving to MVC model.
I prefer MVC over Web Forms and I feel that Microsoft is going to a right direction through MVC. Its technical features as well as the open source nature are attracted me a lot.The MVC model allows me full control over the HTML and enables Test Driven Development (TDD). We can easily integrate with jQuery and other JavaScript frameworks with MVC. Using extension methods of C# 3.0, we can make powerful and rich HTML helper methods. I believe that tesatbility, refactoring capability and maintainability are the main factors for a successful project and prefer these factors than RAD capability. The MVC model allows to build highly testable, maintainable loosely coupled applications with good practices such as TDD, Seperation of Concerns (SoC) and Dependency Injection (DI). You MUST use ASP.NET MVC for public face internet applications.

http://weblogs.asp.net/shijuvarghese/archive/2008/07/09/asp-net-mvc-vs-asp-net-web-form.aspx

Thursday, October 21, 2010

Online Diagram Tools



Online Diagram Tools


Gliffy – Online Diagramming Creator
Online diagram creator tool that works entirely in your browser for diagramming purpose. Gliffy personally can consider as web based Visio killer diagram tools which able to draw a various types of diagram like Flow Chart, Development process, Web Layout, Floor plan, Class diagram, network diagram and etc.
Plus more, you can simple sign up Gliffy online diagram services freely and start drawing and assemble your diagram online.


DrawAnywhere:
Flowcharts, Process diagrams, Organizational charts, Export your diagram as an image file (jpg, png, etc) or a pdf file.

 Gomockingbird : Mockingbird is an easy and fast way to make clickable wireframes and prototypes. You can reate and share clickable mockups of your website or applications.

  Cacoo : Cacoo is a user friendly online drawing tool that allows you to create a variety of diagrams such as site maps, wire frames, UML and network charts. Cacoo can be used free of charge to collaboratively work on the diagramming. Multiple users can edit the same diagram in a simultaneous collaboration.

Lucidchart : Its again Online diagram and flowchart software. You can create diagrams and drawings such as flowcharts, network diagrams, UML diagrams like Class, Sequence and Activity; wireframes, user interface designs and other drawings online with this tool.

Mindomo: Online Mind Mapping Tool 
– Create, edit mind maps, and share them with your colleagues or your friends.


Flowchart:
Realtime online collaboration between multiple users with different browsers, Drawing Tools (Lines, Arrows, Bézier curves), Objects (Flowchart objects, clipart), Save your Flowchart as a PDF or PNG formats.


Mindmeister: all the standard features of a classic mind mapping tool with as many simultaneous users as you like.

Bubbl: Create colorful mind maps online, Share and work with friends, Embed your mind map in your blog or website. Email and print your mind map, Save your mind map as an image.

Creately for Enterprise




Free Diagram tools to replace Visio

Dia – Open source diagramming software
An open source diagram creation program released under the GPL license. Dia diagramming software can be used to draw many different kinds of diagrams such as entity relationship diagrams, UML diagrams, flowcharts, network diagrams, simple circuits and much more.
Dia free diagramming software even can print diagrams that span multiple pages, export to many formats (EPS, SVG, CGM and PNG), and the ability to use custom shapes created by the user as simple XML descriptions.

Kivio – KOffice Diagramming and flowchart tools
Kivio is a diagramming and flow charting application with tight integration to the other KOffice applications. It enables you to create network diagrams, organization charts, flowcharts and more.
Network Notepad – Free Network diagram software
a network diagram application that let you draw out interactive network diagrams, with user definable management features such as point and click telnet, FTP, HTTP and Ping. Drawing network infrastructure diagram using network notepad is simple. All you need is drag and drop network object on the interface. Meanwhile, you’re able to use the F1-F6 keys as hotkeys to ping, surf, or telnet to a device once IP addresses on network devices object.
Diagram Designer – free Simple Diagram software
a simple vector graphics editor for creating flowchart and diagrams. Its features are customizable template object palette, slide show viewer, import/export WMF, EMF, GIF, BMP, JPEG, PNG, MNG, and PCX images, simple graph plotter to plot mathematical expressions, spellchecker, advanced pocket calculator with equation solver, MeeSoft Image Analyzer integration for bitmap image editing and extended file format support, and uses compressed file format for minimizing drawing file size.

GoVisual Diagram editor (GDE) provides powerful diagramming functionality for editing and automatic layout of diagrams. Their diagrams are represented in form of graphs and cluster graphs. Plus more, all diagram can been printing or export to JPEG, PNG, BMP, and SVG are included.

yEd Diagram Editor – Free Diagram Editor
a free diagram software that able to create flow charts, UML diagrams, mind maps, and many other kinds of diagrams, graphs and networks. Choose from a wide range of highly sophisticated layout algorithms to automatically arrange your diagrams in no time. An intuitive and visually appealing user interface makes creating diagrams fun. Once you are done with creating a diagram you can save, print, or export it to popular formats like PDF, SWF, EMF, JPEG, GIF, XML, PNG, or SVG.

Monday, October 18, 2010

French à can't save correctly when post back save to database

 # <% Session.CodePage=encoding %> tells the server to write to the browser using a different code page than the server uses to read the page. For example, if your ASP page is encoded in Japanese (Shift-JIS), and your browser expects the HTML page to be encoded in UTF-8, then you must specify Session.CodePage=65001 to ensure that the HTML page is encoded in UTF-8. If you do not specify Session.CodePage, the server writes to the browser in the same language as it reads the page.

Note:    If session management has been turned off, you cannot set Session.CodePage.


http://devlibrary.businessobjects.com/businessobjectsxir2/en/en/RAS_SDK/rassdk_com_doc/doc/rassdk_com_doc/BestPractices11.html

Wednesday, September 29, 2010

Internet Explorer file downloads over SSL do not work with the cache control headers

When you try to open a Microsoft Office document or a PDF file by typing an HTTPS URL for the document in the Address bar of Internet Explorer 6 Service Pack 1 (SP1), you may receive the following error message:
Unable to download.

Internet Explorer was unable to open this site. The requested site is either unavailable or cannot be found. Please try again later. 
 
This issue occurs if the server sends a "Cache-control:no-store" header or sends a "Cache-control:no-cache" header.
 
http://support.microsoft.com/kb/323308

Thursday, September 23, 2010

Pivot table on SQL Server 2000

EXECUTE ftk_pivot 'select IPG_Name, IPG_SSN from IPGeneral
group by IPG_Name, IPG_SSN', 'sum(IPG_Earnings)', 'IPG_PlanID', 'IPGeneral'

ALTER PROCEDURE [dbo].[ftk_pivot]
@select varchar(8000),
@sumfunc varchar(100),
@pivot varchar(100),
@table varchar(100)

AS

DECLARE @sql varchar(8000), @delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

EXEC ('SELECT ' + @pivot + ' AS pivot INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE '
+ @pivot + ' Is Not Null')

SELECT @sql='',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )

SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '''' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'

SELECT @sql=@sql + '''' + convert(varchar(100), pivot) + ''' = ' +
stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN '
+ @delim + convert(varchar(100), pivot) + @delim + ' THEN ' ) + ', ' FROM ##pivot

DROP TABLE ##pivot

SELECT @sql=left(@sql, len(@sql)-1)
SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')

EXEC (@select)

Monday, September 13, 2010

ASP.NET Runtime Impersonation

Impersonation in ASP.NET

When we are doing I/O operations, the operation system makes security checks to understand if the user is authorized to do the operation. The same thing happens when you try to do operations on another machine in your network. Impersonation in ASP.NET occurs when ASP.NET executes code in the context of an authenticated and authorized user. By default, ASP.NET run in the ASPNET account. By using impersonation we can impersonate the ASPNET account to another account that has access to resources which aren’t granted in the internet security permission. One way to impersonate a user is by using the identity element in the web.config. When you use the following code in your web.config, ASP.NET impersonates to the authenticated user or to an anonymous internet user account:
<identity impersonate="true" />
If you want to impersonate to a specific user you can use the following configuration:
<identity impersonate="true" userName="domain\username" password="password" />

Runtime Impersonation

At my customer the previous configuration examples weren’t an option. The second way to impose impersonation is by runtime. This option can be achieved by using the System.Security.Principal and the WindowsIdentity class. The WindowsIdentity class has a method that makes impersonation and returns a WindowsImpersonationContext. The problem with this class is that you need to supply to it an IntPtr which is a security access token of the user that you wish to impersonate to. The solution is to use P/Invoke and call the LogonUser Win32 API. After you get the impersonation context you can run the network operations that you seek to perform. After you finish to do your operations you need to undo the impersonation. The following code shows an example of an impersonation service class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.InteropServices;
using System.Security.Principal;
 
namespace WebApplication1
{
public class ImpersonationService
{
#region Consts
 
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
 
#endregion
 
#region External API
 
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken
);
 
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool RevertToSelf();
 
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int CloseHandle(IntPtr hObject);
 
#endregion
 
#region Methods
 
public void PerformImpersonatedTask(string username, string domain, string password, 
int logonType, int logonProvider, Action methodToPerform)
{
IntPtr token = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUser(username, domain, password, logonType,
logonProvider, out token) != 0)
{
var identity = new WindowsIdentity(token);
var impersonationContext = identity.Impersonate();
if (impersonationContext != null)
{
methodToPerform.Invoke();
impersonationContext.Undo();
}
}
else
{
// do logging
}
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
}
 
#endregion
}
}
Here is an example of how to use the class in your ASP.NET application:
using System;
using System.IO;
 
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{       
#region Page Events
 
private void Page_Load(object sender, System.EventArgs e)
{
var service = new ImpersonationService();
service.PerformImpersonatedTask("username", "domain", "password",
ImpersonationService.LOGON32_LOGON_INTERACTIVE, ImpersonationService.LOGON32_PROVIDER_DEFAULT, new Action(MethodToPerform));
}
 
#endregion
 
#region Methods
 
public void MethodToPerform()
{
var serverPath = @"\\ServerName\test";
var dirInfo = new DirectoryInfo(serverPath);
Response.Write(dirInfo.Exists);
}
 
#endregion
}
}

Summary

In the post I showed a simple way to implement a class that impersonate to a relevant account in order to achieve some functionality that internet security permissions don’t allow.  You should consider to use the web.config instead since it does all the communication with Win32 API instead of the supplied code. The impersonation isn’t limited only to ASP.NET and can be used also in other frameworks.

Friday, September 10, 2010

#5 Practice Questions and Discussion for Exam 70-536

QUESTIONS Technology Focus: Improving the security of .NET Framework applications by using the NET Framework security features
1. You use the .NET Framework to develop a client-server application. The server part of the application runs on a computer running Microsoft Windows Server 2003. All client computers run Microsoft Windows XP Professional. You need to write code that performs authentication and establishes a secure connection between the server and the client. You must make sure that the Kerberos protocol is used for authentication.
You must also make sure that data is encrypted before it is transmitted over the network and decrypted when it reaches the destination. Which code segment should you use?

Option A:
C#
public void NetMethod(NetworkCredential credentials, Stream innerStream)
{
    NegotiateStream ns = new NegotiateStream(innerStream);
    ns.AuthenticateAsServer(credentials, ProtectionLevel.EncryptAndSign, 
        TokenImpersonationLevel.Impersonation);
    // Additional code
}
Visual Basic
Public Sub NetMethod( _
    ByVal credentials As NetworkCredential, _
    ByVal innerStream As Stream)
    Dim ns As NegotiateStream = New NegotiateStream(innerStream)
    ns.AuthenticateAsServer(credentials, ProtectionLevel.EncryptAndSign, _
    TokenImpersonationLevel.Impersonation)
    ' Additional code
End Sub
Option B:
C#
public void NetMethod(NetworkCredential credentials, Stream innerStream)
{
    NegotiateStream ns = new NegotiateStream(innerStream);
    ns.AuthenticateAsServer(credentials, ProtectionLevel.Sign,
        TokenImpersonationLevel.Impersonation);
    // Additional code
}
Visual Basic
Public Sub NetMethod( _
    ByVal credentials As NetworkCredential, _
    ByVal innerStream As Stream)
    Dim ns As NegotiateStream = New NegotiateStream(innerStream)
    ns.AuthenticateAsServer(credentials, ProtectionLevel.Sign, _
    TokenImpersonationLevel.Impersonation)
    ' Additional code
End Sub
Option C:
C#
public void NetMethod(X509Certificate serverCertificate, Stream innerStream)
{
    SslStream ss = new SslStream(innerStream);
    ss.AuthenticateAsServer(serverCertificate, true, 
        SslProtocols.Tls, true);
    // Additional code
}
Visual Basic
Public Sub NetMethod( _
    ByVal serverCertificate As X509Certificate, _
    ByVal innerStream As Stream)
    Dim ss As SslStream = New SslStream(innerStream)
    ss.AuthenticateAsServer(serverCertificate, True, _
        SslProtocols.Tls, True)
    ' Additional code
End Sub
Option D:
C#
public void NetMethod(X509Certificate serverCertificate, Stream innerStream)
{
    SslStream ss = new SslStream(innerStream);
    ss.AuthenticateAsServer(serverCertificate, true,
        SslProtocols.Ssl3, true);
    // Additional code
}
Visual Basic
Public Sub NetMethod( _
    ByVal serverCertificate As X509Certificate, _
    ByVal innerStream As Stream)
    Dim ss As SslStream = New SslStream(innerStream)
    ss.AuthenticateAsServer(serverCertificate, True, _
        SslProtocols.ssl3, True)
    ' Additional code
End Sub

2. You develop a .NET Framework application. This application is deployed throughout the company on all workstations. All workstations are networked and are part of a Microsoft Windows domain.
Your application requires certain permissions in order to run. As a domain administrator, you configure the enterprise policy to grant the required permissions to the application. This application may be part of more than one code group.
You must make sure that your application receives sufficient permissions to run at all times. You must override any policy changes made by end users that lower the permissions required by your application to run.What should you do?
A: Apply the Exclusive attribute to the application's code group on the enterprise policy level.
B: Apply the LevelFinal attribute to the application's code group on the user policy level.
C: Apply the LevelFinal attribute to the application's code group on the enterprise policy level.
D: Apply the Exclusive attribute to the application's code group on the user policy level.

3. You develop a .NET Framework application. The assembly is added to these four code groups at the Enterprise level policy:
* All Code code group with a permission set of Everything
* Known Code code group with a permission set of Local Intranet
* Unknown Code code group with a permission set of Internet
* Restricted Code code group with a permission set of Nothing

The assembly is not a member of any other code groups.When the assembly is executed, what permissions does the Common Language Runtime (CLR) assign to the assembly?
A: Internet
B: Everything
C: Local Intranet
D: Nothing

Thursday, September 9, 2010

Double data type never get accurate result

double x,y;
x =120.0;
y = 0.05;
double z= x % y;

tried this and expected the result to be 0, but it came out 0.04933333.
However,
x =120.0;
y = 0.5;
double z= x % y;
did indeed gave the correct result of 0.

Accuracy problems

Solution:  
Since Decimal types are perfectly accurate and float’s are not, why would we still want to use the intrinsic float/double types? Short answer – performance. In my speed tests Decimal types ran over 20 times slower than their float counterparts.

So if you’re writing a financial application for a bank that has to be 100% accurate and performance is not a consideration, use the Decimal type. On the other hand, if you need performance and extremely small floating point variations don’t affect your program, stick with the float and double types.

GoDaddy FAQ

How to move Domain to another hosting plan?

1. Use File Manage to Archive your content, download to your loca computer
2. Cancel current account, wait for about 1 -24 hour, setup the other hosting plan
3. Upload Archived ZIP file, then unArchive to destination

output Excel using classic ASP

Private Sub DownloadFile(file) 
     Dim strAbsFile 
     strAbsFile = server.MapPath("..\DownloadFiles") & "\" & file
     Set objFSO = Server.CreateObject("Scripting.FileSystemObject") 
     If objFSO.FileExists(strAbsFile) Then 
         Set objFile = objFSO.GetFile(strAbsFile) 
         Response.Clear 
        Response.AddHeader "Content-Disposition", "attachment; filename=" & objFile.Name 
         'The following line not working on IIS7 & Windows2008
         'Response.AddHeader "Content-Length", objFile.Size 
         'Response.ContentType = "application/octet-stream" 
         Response.ContentType="application/x-msexcel"
         Set objStream = Server.CreateObject("ADODB.Stream") 
         objStream.Open 
         '-- set as binary 
         objStream.Type = 1 
         Response.CharSet = "UTF-8" 
         '-- load into the stream the file 
         objStream.LoadFromFile(strAbsFile) 
         '-- send the stream in the response 
         Response.BinaryWrite(objStream.Read) 
         objStream.Close 
         Set objStream = Nothing 
         Set objFile = Nothing 
     Else 'objFSO.FileExists(strAbsFile) 
         Response.Clear 
         Response.Write("No such file exists.") 
     End If 
     Set objFSO = Nothing 
 End Sub 

Tuesday, September 7, 2010

#4 Practice Questions and Discussion for Exam 70-536

QUESTIONS Technology Focus: Implementing serialization and input/output functionality in a .NET Framework application
1. You are developing a logging module for a large application by using the .NET Framework.You need to append logging information to a file named application.log. This log file is opened when the application is started and is closed only when the application is closed. However, you append text several times to the file during a session.
You must minimize overhead to the logging process to ensure maximum performance.Which code segment should you use to create the log file?

Option A:
C#
StreamWriter sw = File.CreateText(@"c:\application.log");
Visual Basic
Dim sw As StreamWriter = File.CreateText("c:\application.log")
Option B:
C#
FileInfo fi = new FileInfo(@"c:\application.log");
FileStream fs = fi.Open(FileMode.Append);
Visual Basic
Dim fi As FileInfo = New FileInfo("c:\application.log")
Dim fs As FileStream = fi.Open(FileMode.Append)
Option C:
C#
FileInfo fi = new FileInfo(@"c:\application.log");
StreamWriter sw = fi.AppendText();
Visual Basic
Dim fi As FileInfo = New FileInfo("c:\application.log")
Dim sw As StreamWriter = fi.AppendText()
Option D
C# 
EventLog.LogNameFromSourceName("MyApp", "Application");
Visual Basic
EventLog.LogNameFromSourceName("MyApp", "Application")

2. You are developing a class library by using the .NET Framework. You create the following classes:
C#
public class Book
{
    public string Name;
}
public class Encyclopedia : Book
{
    public int Volume;
}
Visual Basic
Public Class Book
    Public Name As String
End Class
Public Class Encyclopedia
    Inherits Book
    Public Volume As Integer
End Class
You must be able to serialize the objects of the Encyclopedia class to a disk file. What should you do?
Option A:

C#
Add the [Serializable] attribute to the Book class only.

Visual Basic
Add the <Serializable> attribute to the Book class only.
Option B:

C#
Add the [Serializable] attribute to the Encyclopedia class only.

Visual Basic
Add the <Serializable> attribute to the Encyclopedia class only.
Option C:

C#
Add the [Serializable] attribute to the Book class. 
Add the [Serializable] attribute to the Encyclopedia class.

Visual Basic
Add the <Serializable> attribute to the Book class. 
Add the <Serializable> attribute to the Encyclopedia class.
Option D:

C#
Add the [Serializable] attribute to the Encyclopedia class. 
Add the [NonSerialized] attribute to the Name field.

Visual Basic
Add the <Serializable> attribute to the Encyclopedia class. 
Add the <NonSerialized> attribute to the Name field.


3. You are developing a Windows application by using the .NET Framework. The application uses a shared assembly for personalizing the user interface of the application.The same assembly is used by several other applications on the user's machine. Any changes in the user preferences in one application must be carried over to other applications.
You need to access the user's preferences for displaying the user interface.What should you do?
A: Use the IsolatedStorageFile.GetMachineStoreForAssembly method
B: Use the IsolatedStorageFile.GetMachineStoreForDomain method.
C. Use the IsolatedStorageFile.GetUserStoreForDomain method.
D: Use the IsolatedStorageFile.GetUserStoreForAssembly method.

Wednesday, September 1, 2010

70-564 Braindumps: Designing and Developing ASP.NET Applications Using the Microsoft .NET Framework 3.5

Q NO: 1
You work as an application developer at Abc.com. You instructions are to develop an application by using the .NET Framework 3.5. The Abc.com network users access applications using different operating systems and different browsers. You must also add a new control in the application. The control must meet the requirements below:
The application should be coded to be accessible through the Microsoft Visual Studio .NET 2008 toolbox.The application should be coded to operate without any other prerequisite controls. What should you do?
A. You should make use of an ActiveX control.
B. You should make use of a Web Parts control.
C. You should make use of a user control.
D. You should make use of a custom server control.
Ans: D

Q NO: 2
You work as an application developer at Abc.com. You use the .NET Framework 3.5 to develop an application that runs in the context of a specific user account. No other application should make use of this user account. Your application uses an asymmetric private key to encrypt and decrypt messages to other servers. You want to prevent other users or applications on the server from accessing the private key. What should you do?
A. You should make use of the Triple Data Encryption Standard algorithm to encrypt the private key before storing it in a file.
B. You should have the private key stored in the App_Data directory.
C. You should make use of the System.Security.SecureString class.
D. You should make use of the System.Security.ProtectedData class.
Ans: D

Q NO: 3
You work as an application developer at Abc.com. You use the .NET Framework 3.5 to develop an application for an online community. The application uses Forms authentication and contains a folder that is used to store confidential files in an Excel spreadsheet. You want to prevent unauthorized, automated scripts or bots from accessing the folders in the application. What should you do? (Choose two)
A. You should have the authorization node of the lockElementsattribute value set in the Web.config file.
B. You should have a <deny> element added to the <authorization> element in the Web.config file.
C. You should have a Completely Automated Public Turing Tests implemented to Tell Computers and Humans Apart (CAPTCHA) image control on each page of the application.
D. You should have a Robots.txt file implemented in the root directory of the application.
E. You should have the Excel files mapped to the ASP.NET ISAPI filter.
Ans: B,E

Q NO: 4
You work as an application developer at Abc.com. You use the .NET Framework 3.5 to develop an application which stores data in databases implemented using Microsoft SQL Server, Microsoft Access and various third-party databases. You have been asked to design a data access solution that allows all database platforms to make use of the same data access code, defines the SQL syntax used, and decreases the vulnerability to SQL injection attacks. What should you do to make this possible?
A. You should make use of dynamic SQL statements and string concatenation.
B. You should make use of parameterized stored procedures.
C. You should make use of the SqlCommandBuilder class.
D. You should make use of dynamic SQL statements and the StringBuilder class.
E. You should make use of parameterized SQL statements.
Ans: E

Q NO: 5
You work as an application developer at Abc.com. Your instructions are to develop an application by using the .NET Framework 3.5. Following is a list of the requirements that the application should meet:
The UI element should be coded to have custom logic for implementation in the application.The UI element should be coded to accommodate utilization in multiple pages in the application.The UI element should be coded to accommodate utilization on multiple places in the application.The UI element should be coded to accommodate redistribution on other applications without sharing source code or layout files. What should you do?
A. You should have a user control created.
B. You should have a custom Web control created.
C. You should have a master page created.
D. You should have a theme created.
Ans: B

Q NO: 6
You work as an application developer at Abc.com. You use the .NET Framework 3.5 to develop an application which utilizes the ViewState to store user preferences. You want to capture the ViewState information to be saved in a Microsoft SQL Server database making use of the proper event. What should you do?
A. You should make use of the SaveStateComplete event to capture the ViewState information to be saved in a Microsoft SQL Server database.
B. You should make use of the Init event to capture the ViewState information to be saved in a Microsoft SQL Server database.
C. You should make use of the Load event to capture the ViewState information to be saved in a Microsoft SQL Server database.
D. You should make use of the InitComplete event to capture the ViewState information to be saved in a Microsoft SQL Server database.
Ans: A

Q NO: 7
You work as an application developer at Abc.com. Your instructions are to develop an application by that makes use of ViewState to save user preferences. You are also instructed to capture and save all ViewState information to a SQL Server database. What should you do?
A. You should make use of the SaveStateComplete event.
B. You should make use of the Init event.
C. You should make use of the Load event.
D. You should make use of the InitComplete event.
Ans: A

Q NO: 8
You work as an application developer at Abc.com. Your instructions are to develop an application by using the .NET Framework 3.5. The application must include a custom control library which the developers will be able to use on Web pages in multiple applications. Various state management strategies are used on these applications. You need to implement consistent state management for all instances of the control in your custom control library. What should you do?
A. You should use the ViewState state repository.
B. You should use the ApplicationState state repository.
C. You should use the ControlState state repository.
D. You should use the SessionState state repository.
Ans: C

Q NO: 9
You work as an application developer at Abc.com. Your instructions are to develop an application by using the .NET Framework 3.5 containing a page with a DataPager control named AbcPager1. You need to make sure that the KingPager1 properties are exposed to the WebPartZoner controls on all other pages where Abc.com also wants AbcPager1 to be displayed. What should you do?
A. You should have the AbcPager1 control copied into a new user control whilst adding a reference to the new user control in each page by using the @Register directive. You should modify the WebPartZone control on each page by adding a zonelement element.
B. You should have the AbcPager1 control copied into a new web form whilst adding a reference to the new web form in each page by using the @Register directive. You should modify the WebPartZone control on each page by adding a zoneelement element.
C. You should have the AbcPager1 control copied into a new user control whilst adding a reference to the new user control in each page by using the @Register directive. You should modify the WebPartZone control on each page by adding a partstyle element.
D. You should modify the WebPartZone control on each page by adding a partstyle element.
Ans: A

Q NO: 10
You work as an application developer at Abc.com. You use the .NET Framework 3.5 to develop an application. During the course of the day Abc.com directed you to evaluate the application design which uses the specifications below:
The application should be coded to store data in a Microsoft SQL Server 2008 database.The application should be coded to retrieve data using the DataContext object.The application should be coded to display data using GridView controls. You want to use the required data source control which should be used in the design of the application. What should you do?
A. You should make use of the LingDataSource data source control.
B. You should make use of the XmlDataSource data source control.
C. You should make use of the ObjectDataSource data source control.
D. You should make use of the SqlDataSource data source control.
Ans: A

Q NO: 11
You work as an application developer at Abc.com. You use the .NET Framework 3.5 to develop an application containing a Data Access Layer (DAL) supporting databases from thirdparty vendors. You have configured the application to display the data using a GridView control. Additionally, Abc.com has instructed you to code the application so that it allows paging and provides optimistic concurrency. What should you do to adequately complete this task?
A. You should make use of the SqlDataReader data access objects in the Data Access Layer (DAL).
B. You should make use of the OleDbDataAdapter data access objects in the Data Access Layer (DAL).
C. You should make use of the OleDbDataReader data access objects in the Data Access Layer (DAL).
D. You should make use of the SqlDataAdapter data access objects in the Data Access Layer (DAL).
Ans: B