Sunday, December 18, 2011

Difference between TRUNCATE, DELETE and DROP commands


DELETE


The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.


 DELETE FROM emp;



TRUNCATE


TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.Truncate is also delete the records but it is not delete the table space which is created by the data base.


TRUNCATE TABLE emp;


DROP


The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.We can not recover the table before Oracle 10g. But Oracle 10g provide the command to recover it by using the command (FLASHBACK)
Drop command will delete the entire row also the structure.But truncate will delete the contenets only not the strucure, so no need to give specifications for another table creation.



 DROP TABLE emp;



Friday, December 16, 2011

Comparing ListView with GridView,DataList and Repeater




Supported Funcationalities
Control Paging Data Grouping Provide Flexible Layout Update,Delete Insert Sorting
ListView supported supported supported supported supported supported
GridView supported Not supported Not Supported supported Not Supported supported
DataList Not supported supported supported Not supported Not supported Not supported
Repeater Not supported Not supported supported Not supported Not supported Not supported






Control - Capabilities

GridView - Read/Edit
DataList - Read/Edit
Repeater - Read Only
DetailsView - Read/Edit/Create
FormView - Read/Edit/Create


Feature                Repeater  DataList       Grid View
Table layout         No           No                Yes
Style properties    No           Yes             Yes   




factorial logic


j=1;  

    for (i=1; i<=VALUE; i++)    

        j=j*i;  

    printf("The factorial of %d is %d\n",VALUE,j);

how to find 2nd highest salary



select Max(Salary) from tblSalaryDetails  where salary   Not IN(select Max(Salary) from tblSalaryDetails )


for 6 ,7 and other

select max(salary) from EmployeeDetails

where Salary NOT IN
(
SELECT TOP 5 (SALARY) from EmployeeDetails ORDER BY Salary Desc)

SQL - Difference between Truncate & Delete

1. TRUNCATE is a DDL (Data Definition Language) command and DELETE is a DML (Data Manipulation Language) command.

2. You can use WHERE clause with DELETE but not with TRUNCATE .

3. You cannot rollback data in TRUNCATE but in DELETE it is possible to rollback data.

4. A trigger doesn't get fired in case of TRUNCATE whereas Triggers get fired in case of a DELETE command.

5. TRUNCATE is faster than DELETE. TRUNCATE is faster than DELETE due to the way TRUNCATE "removes" rows. Actually, TRUNCATE does not remove data, but rather deallocates whole data pages and removes pointers to indexes. The data still exists until it is overwritten or the database is shrunk. This action does not require a lot of resources and is therefore very fast.

6. TRUNCATE resets the Identity counter if there is any identity column present in the table where DELETE does not reset the identity counter.

7. You cannot TRUNCATE a table that has any foreign key constraints. You will have to remove the contraints, TRUNCATE the table, and reapply the contraints.

8. DELETE and TRUNCATE operations are both logged. DELETE is a logged operation on a per row basis and TRUNCATE command logs the deallocation of the data

Wednesday, December 7, 2011

Calling web service using javascript.

Many a times there was this pressing need where I had to call a web service method and get the output and use it in javascript. There were many options available like making use of javascript to call web service method or using some third party javascript library or by making use of webservice behavior (HTML Component (HTC) file) or making use of AJAX and calling an ASPX page which in turn calls a webservice in the code behind and returns the output as XML or if you are using ASP.NET 2.0 then you can make use of “ScriptManager”. We will see all the above ways of invoking a webservice one by one except making use of third party javascript library. As there are many third party javascript libraries available in the internet so we will not concentrate on any as each have different ways of implementation.  Lets see each of the methods in action one by one.
Using javascript to invoke web service methods
One of the simplest and easiest way is to invoke web service methods is by making use of “XMLHttpRequest” objects in javascript. Before invoking the web service method using javascript lets see the web service methods which we are going to be invoked using javascript. Below are two sample methods which we are going to be invoked using javascript.
public class TestService : System.Web.Services.WebService
{
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public string CombineName(string firstName, string midleName, string lastName)
        {
            return string.Concat(string.Concat(firstName, " - ", midleName), " - ", lastName);
        }
}
The above two methods are pretty straight forward, one returns a string and the other takes three string arguments and combines them and returns as a string. We will see how to call a web service method without parameters and with parameters. Lets first see how to call the “HelloWorld” web method which doesn’t take any parameter. Below is the javascript code for invoking the “HelloWorld” web method.
function webServiceCallWithoutParameters()
{
        var xmlHttpReq = new XMLHttpRequest();
        xmlHttpReq.open("POST", "http://localhost/TestService.asmx/HelloWorld", false);       
        xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttpReq.send();       
        alert(xmlHttpReq.responseXML.childNodes[1].text);
}
In the above javascript function we are making use of “XMLHttpRequest” object to invoke web service method. We are making use of the “open” method which takes three arguments, first argument says whether the method used is “POST” or “GET”, second argument is the url for the web service and the third argument is to specify whether the “XMLHttpRequest” should be synchronous or asynchronous. The url for a .NET web method always ends with the name of the web method preceded by the url of the web service as shown in the above e.g. Once we have set the url and the method used to call the web service, in the next line we are setting the “Content-Type” for the request using the “setReqeustHeader” method of the “XMLHttpReqeust” object. Its very important to set the “Content-Type” of the request to “application/x-www-form-urlencoded” when you are trying to invoke a web service method, if the “Content-Type” is not set to “application/x-www-form-urlencoded” the following error will be thrown when you try to pass arguments to a web service method.
status: 500
statusText: Internal Server Error
responseText: System.InvalidOperationException: Request format is invalid: . at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
The status property of the “XMLHttpReqeust” object will have a value of 500, the “statusText” will be having “Internal Server Error” as the message and the “responseText” will have the type of error. To solve the problem set the “Content-Type” for the request as shown in the above e.g.
Now let’ see how to pass parameters to a web method.
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("POST", "http://localhost:3150/TestService.asmx/CombineName", false);
xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpReq.send("firstName=Sandeep&midleName=mid&lastName=p r");
alert(xmlHttpReq.responseXML);
In the above javascript function we are invoking the “CombineName” web method which takes three parameters. Everything else is the same as the previous javascript function except for the “send” method of the “XMLHttpReqeust” object. In the “send” method we are passing the parameters separated by the ampersand (&) symbol. To pass parameter to a web method you can use the “send” method of the “XMLHttpRequest” object. The parameters and their values should be separated by the “equal to” (=) symbol and each set of parameters should be separated by the ampersand symbol.
After this the next obvious question would be how to send complex objects to a web methods. There is no straight forward way of doing this, one can make use of Javascript Object Notations (JSON). You can find lots of e.g. on how to pass JSON over the net. Also you can use “WebService” behavior (HTC file) to send and receive complex objects or one can use “ScriptManager” to send and receive complex objects. We will see “HTC file” and “ScriptManager” usage in subsequent blogs. Receiving a complex object is pretty easy. When you invoke a web method and if that web method returns a complex object then the object will be serialized into a XML and the XML can be accessed through the “responseText” or “responseXML” property of the “XMLHttpRequest” object. Lets see with an e.g. Below is the web method code which returns a “Car” complex object.
[WebMethod]
public Car GetCarObject()
{
     return new Car { Model = "Ferrari", Color = "Ferrari Red", CC = 2555 };
}
//Car Class is pasted below.
public class Car
{
    public string Model
    {
        get;   set;
    }
    public int CC
    {
        get;   set;
    }
    public string Color
    {
        get;   set;
    }
}
The above web method is pretty straight forward. It creates an instance of a “Car” class and returns the same. The “Car” class is also pasted. The javascript method to invoke the above web method which returns “Car” complex object is pasted below.
function getComplexObject()
{
    var xmlHttpReq = new XMLHttpRequest();
    xmlHttpReq.open("POST", "http://localhost:3150/TestService.asmx/GetCarObject", false);
    xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttpReq.send();
    alert(xmlHttpReq.responseText);
}
The output returned in the form of the XML is pasted below.

http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
  Ferrari
  2555
  Ferrari Red
As you can see in the above XML the complex object returned by the web method is serialized as XML. That's about invoking web methods using javascript

Friday, December 2, 2011

how set startup controller in mvc3

 In global.asax
 
routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home" , action = "Index",
            id = UrlParameter.Optional } // Parameter defaults
        );

How to set startup page for debugging in asp.net mvc aplication?

Go to your project's properties and set the start page property.
  1. Go to the project's Properties
  2. Go to the Web tab
  3. Select the Specific Page radio button
  4. Type in the desired url in the Specific Page text box
  





Thursday, December 1, 2011

New HTML 5 input types in ASP.Net 4.5 Developer Preview

Microsoft has released developer previews for Visual Studio 2011 and .Net framework 4.5. There are lots of new features available in the developer preview. One of the most interested things for web developers is the support introduced for new HTML 5 form controls.
The following are the list of new controls available in HTML 5
  • email
  • url
  • number
  • range
  • Date pickers (date, month, week, time, datetime, datetime-local)
  • search
  • color
Describing the functionality for these controls is not in the scope of this article. If you want to know about these controls, refer the below URLs
http://msdn.microsoft.com/en-us/magazine/hh547102.aspx
http://www.w3schools.com/html5/html5_form_input_types.asp
ASP.Net 4.5 introduced more possible values to the Text Mode attribute to cater the above requirements. Let us evaluate these. I have created a project in Visual Studio 2011 developer preview, and created a page named “controls.aspx”. In the page I placed on Text box control from the toolbox
clip_image001[4]
Now select the control and go to the properties pane, look at the TextMode attribute.
clip_image002[4]
Now you can see more options are added here than prior versions of ASP.Net. I just selected Email as TextMode. I added one button to submit my page. The screen shot of the page in Visual Studio 2011 designer is as follows
clip_image003[4]
See the corresponding markup


   

        Enter your email:
           

   

Now let me run this page, IE 9 do not have the support for new form fields. I browsed the page using Firefox and the page appears as below.
clip_image004[4]
From the source of the rendered page, I saw the below markup for my email textbox
Try to enter an invalid email and you will see the browser will ask you to enter a valid one by default.
clip_image005[4]
When rendered in non-supported browsers, these fields are behaving just as normal text boxes. So make sure you are using validation controls with these fields.
See the browser support compatability matrix with these controls with various browser vendors.
clip_image006[4]
ASP.Net 4.5 introduced the support for these new form controls. You can build interactive forms using the newly added controls, keeping in mind that you need to validate the data for non-supported browsers.

Wednesday, November 23, 2011

What is difference between ViewData,ViewBag and TempData in MVC 3.0

ViewData: ViewData is a dictionary of objects that are accessible using strings as keys Eg.
1.ViewData[“JustLearn”]=”Just Learn on Beyond relational is rock!!”
ViewBag:ViewBag uses the dynamic feature that was added in to C# 4.0 It allows an object to dynamically have properties added to it. We can say viewBag=ViewData + dynamic wrapper around the ViewData dictionary. Eg.
1.ViewBag.JustLearn =”Just Learn on beyondrelational is rock!!”
TempData: Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. Eg.
view source
print?
1.TempData[“JustLearn”]=”Just Learn on beyondrelational is rock!!”
Hold Up

Search and Filters in Error List Window – Visual Studio 2011 Developer Preview

The Visual Studio “Error List Window” helps you display the errors, warnings, and messages produced during compiling code, build, code analysis or even some other scenarios as well. We can click on the particular error, warning or message to get the exact details and cursor moves to location where error or warning causes. When we are dealing with multiple project in a single solution, it is very much difficult to find out exact error within a specific file or with in a solution. We need to scroll through entire error list to get the file, errors, messages or warnings. Visual Studio 2011 introduced search and filtering with in error list window.

Visual Studio 2011 added a search box to the Error List to help you find the error, warning, or message. Just for example, if you are looking for an error with in a specific file, just enter the file name in search box, Error list will display the error, warnings and messages from the given file.

New Color Picker in Visual Studio 2011 Developer Preview for CSS

CSS editor in Visual Studio 2011 introduced many new features for web developers and it helps developers to work with CSS more efficiently and organize way. One of the nice features of the new CSS Editor is Color Picker. While designing styles for web applications, web developers refers different tool to choose the color and color code. But now, there is an integrated Color Picker that helps developer to pick up the color within editor itself.

In CSS Editor, locate the cursor next to any color attribute and press Space. A color pickup automatically popups up. You can select the color as per your requirements.

Hold Up

Creating Custom HTML Helpers in ASP.NET MVC

List of built-in HTML Helpers provided by ASP.NET MVC.

ActionLink() – Links to an action method.
BeginForm() – Marks the start of a form and links to the action method that renders the form.
CheckBox() – Renders a check box.
DropDownList() – Renders a drop-down list.
Hidden() – Embeds information in the form that is not rendered for the user to see.
ListBox() – Renders a list box.
Password() – Renders a text box for entering a password.
RadioButton() – Renders a radio button.TextArea() – Renders a text area (multi-line text box).
TextBox () – Renders a text box.

How to develop our own Custom HTML Helpers?

For developing custom HTML helpers the simplest way is to write an extension method for the HtmlHelper class. See the below code, it builds a custom Image HTML Helper for generating image tag.

using System;
using System.Web.Mvc;
namespace MvcHelpers
{
public static class CustomHtmlHelpers
{
public static TagBuilder Image(this HtmlHelper helper, string imageUrl, string alt)
{
if (!String.IsNullOrEmpty(imageUrl))
{
TagBuilder imageTag = new TagBuilder("img");
imageTag.MergeAttribute("src", imageUrl);
imageTag.MergeAttribute("alt", alt);
return imageTag;
}
return null;
}
}
}

TagBuilder represents a class that is used by HTML helpers to build HTML elements.
TagBuilder.MergeAttribute(String, String) method adds an attribute to the tag by using the specified key/value pair.

The next step is in order to make it available to Views, we should include the name space of out custom HTML helper class into Web.config

Build the solution to make sure the helper method is available to views. Goto any view in the solution access the newly created HTML image helper method.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>


Home




<%= Html.Encode(ViewData["Message"]) %>


<%=Html.Image("/Images/logo.png","logo") %>





<%=Html.Image(“/Images/logo.png”,”logo”) %>

The image HTML helper generates the following HTML.

”logo”/

Image Tag Helper is simple example of HTML helpers, we can put any sort of complex logic into HTML Helpers & access them with in the views with a simple method call. in turn which makes the view simpler.

How To Create Session-less Controller in MVC3

How to manage the controller’s session state?

Simply we can decorate the controller class with “SessionState” attribute. [SessionState()] attribute accepts SessionStateBehaviour enumeration.

SessionStateBehaviour enumeration has the following constants.

SessionStateBehavior.Default - ASP.NET default logic is used to determine the session state behavior for the request.
SessionStateBehavior.Required – Full read-write session state behavior is enabled for the request.
SessionStateBehavior.ReadOnly – Read only session state is enabled for the request.
SessionStateBehavior.Disabled – Session state is not enabled for processing the request.

How to return 404 Http status code from ASP.NET MVC Application?

ASP.NET MVC3 includes a new class HttpNotFoundResult in System.Web.Mvc namespace.

HttpNotFoundResult: Instance of HttpNotFoundResult class indicates to client(browser) that the requested resource was not found. It returns a 404 HTTP status code to the client. Generally we return 404 status code if a requested webpage is not available. In case of MVC applications we return 404 status code is in terms of resources, for example we are searching for particular user profile in the portal, if the user profile is not found, we can return 404.

How to return 404 status code from a MVC application?

First way is to instantiate HttpNotFoundResult class and return the object.

public ActionResult Index()
{
var result = new HttpNotFoundResult();
return result;
}

Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.

public ActionResult Index()
{
return HttpNotFound();
}

we can return 404 along with custom status code description,using the overloded version of HttpNotFound(string statusDescription).

public ActionResult Index()
{
return HttpNotFound("can not find requested resource");
}

How to select Block of Code in Visual Studio?

You can select line by line code very easily using mouse or keyboard. But if you want to copy some code block where you don’t to select all part of line or something like that, here is a Quick TIP For you. Press and Hold “Alt” Key, and select the code region..

Generate Method Stubs using Shortcut Key in Visual Studio

Ctrl + .” Or “ALT + SHIFT+F10” is one of the very useful shortcut key in Visual Studio. You can use that shortcut key to generate the methods stubs. Like, If you want to create method which will add to number, you can write like AddTwoNumber() and press “Ctrl+.” and Enter to generate the Stub for your methods automatically

Tuesday, November 22, 2011

Automatic Tag Update in Visual Studio 2011 Developer Preview

Visual Studio 2011 Developer Preview introduced a nice features that helps you to update HTML Start and End tag automatically. In previous version of Visual Studio If you wanted to update any html tags in markup you have had to update both start and end tags manually but, Visual Studio 2011 developer preview automatically update the tag with change of any one.

Monday, November 21, 2011

Clean up after Visual Studio

As programmer’s we know that if we create a temporary file during the running of our application we need to make sure it is removed when the application or process is complete. We do this, but why can’t Microsoft do it? Visual Studio leaves tons of temporary files all over your hard drive. This is why, over time, your computer loses hard disk space. This blog post will show you some of the most common places where these files are left and which ones you can safely delete.

.NET Left Overs

Visual Studio is a great development environment for creating applications quickly. However, it will leave a lot of miscellaneous files all over your hard drive. There are a few locations on your hard drive that you should be checking to see if there are left-over folders or files that you can delete. I have attempted to gather as much data as I can about the various versions of .NET and operating systems. Of course, your mileage may vary on the folders and files I list here. In fact, this problem is so prevalent that PDSA has created a Computer Cleaner specifically for the Visual Studio developer. Instructions for downloading our PDSA Developer Utilities (of which Computer Cleaner is one) are at the end of this blog entry.

Each version of Visual Studio will create “temporary” files in different folders. The problem is that the files created are not always “temporary”. Most of the time these files do not get cleaned up like they should. Let’s look at some of the folders that you should periodically review and delete files within these folders.

Temporary ASP.NET Files

As you create and run ASP.NET applications from Visual Studio temporary files are placed into the :\Windows\Microsoft.NET\Framework[64]\\Temporary ASP.NET Files folder. The folders and files under this folder can be removed with no harm to your development computer. Do not remove the "Temporary ASP.NET Files" folder itself, just the folders underneath this folder. If you use IIS for ASP.NET development, you may need to run the iisreset.exe utility from the command prompt prior to deleting any files/folder under this folder. IIS will sometimes keep files in use in this folder and iisreset will release the locks so the files/folders can be deleted.

Website Cache

This folder is similar to the ASP.NET Temporary Files folder in that it contains files from ASP.NET applications run from Visual Studio. This folder is located in each users local settings folder. The location will be a little different on each operating system. For example on Windows Vista/Windows 7, the folder is located at :\Users\\AppData\Local\Microsoft\WebsiteCache. If you are running Windows XP this folder is located at :\ Documents and Settings\\Local Settings\Application Data\Microsoft\WebsiteCache. Check these locations periodically and delete all files and folders under this directory.

Visual Studio Backup

This backup folder is used by Visual Studio to store temporary files while you develop in Visual Studio. This folder never gets cleaned out, so you should periodically delete all files and folders under this directory. On Windows XP, this folder is located at :\Documents and Settings\\My Documents\Visual Studio 200[5|8]\Backup Files. On Windows Vista/Windows 7 this folder is located at :\Users\\Documents\Visual Studio 200[5|8]\.

Assembly Cache

No, this is not the global assembly cache (GAC). It appears that this cache is only created when doing WPF or Silverlight development with Visual Studio 2008 or Visual Studio 2010. This folder is located in :\ Users\\AppData\Local\assembly\dl3 on Windows Vista/Windows 7. On Windows XP this folder is located at :\ Documents and Settings\\Local Settings\Application Data\assembly. If you have not done any WPF or Silverlight development, you may not find this particular folder on your machine.

Project Assemblies

This is yet another folder where Visual Studio stores temporary files. You will find a folder for each project you have opened and worked on. This folder is located at :\Documents and Settings\Local Settings\Application Data\Microsoft\Visual Studio\[8|9].0\ProjectAssemblies on Windows XP. On Microsoft Vista/Windows 7 you will find this folder at :\Users\\AppData\Local\Microsoft\Visual Studio\[8|9].0\ProjectAssemblies.

Remember not all of these folders will appear on your particular machine. Which ones do show up will depend on what version of Visual Studio you are using, whether or not you are doing desktop or web development, and the operating system you are using.

ASP.NET 4.5 Preview: Using model binding to update data

one of my current projects I have to show reports based on SQL Server views. My code should be not aware of data it shows. It just asks data from view and displays it user. As WebGrid didn’t seem to work with DataTable (at least with no hocus-pocus) I wrote my own very simple view that shows contents of DataTable.

I don’t focus right now on data querying questions as this part of my simple generic reporting stuff is still under construction. If the final result is something good enough to share with wider audience I will blog about it for sure.

My view uses DataTable as model. It iterates through columns collection to get column names and then iterates through rows and writes out values of all columns. Nothing special, just simple generic view for DataTable.
@model System.Data.DataTable
@using System.Data;

Report






@foreach (DataColumn col in Model.Columns)
{

}



@foreach (DataRow row in Model.Rows)
{

@foreach (DataColumn col in Model.Columns)
{

}

}

@col.ColumnName
@row[col.ColumnName]


In my controller action I have code like this. GetParams() is simple function that reads parameter values from form. This part of my simple reporting system is still under construction but as you can see it will be easy to use for UI developers.
public ActionResult TasksByProjectReport()
{
var data = _reportService.GetReportData("MEMOS",GetParams());
return View(data);
}

Before seeing next silver bullet in this example please calm down. It is just plain and simple stuff for simple needs. If you need advanced and powerful reporting system then better use existing components by some vendor.

Friday, November 18, 2011

Why should we use MVC vs normal ASP.NET

There are various positive points to moving towards MVC

1. SEO friendly URL by design (though now this is possible in ASP.NET 4 as well)
2. No ViewState (this may seem a bit of moving backward to some), but overall a good design decision.
3. Clean View Markup (no additional HTML emitted)
4. 100% extensible. You can add your own controller with IOC, switch view engines at will, control model binding at wish etc.
5. Rich UI support (possible through client side JS libraries like jQuery UI and others). Telerik has released some controls for MVC which includes Grid control as well (which are merely HTMLHelpers)
6. Session, JS, Ajax works. Validation is even more powerful with DataAnnotations and jquery.
7. Is MVC faster? Yes by default because of lack of viewstate and clean markup. But performance is subject and MVC by design is more performant that traditional ASP.NET webforms (though webforms can be made as fast as required.
8. Out of the box support for mitigating antiforgery attacks and XSS vulnerability (though asp.net does has this to some extent)
9. Out of the box minimal IOC support.
10. Full control over rendered HTML

MVC 3 dynamic authorization of multiple roles and users

[Authorize(Roles="Admin")]
public ActionResult UpdateArticle(ArticleModel model, int articleid)
{
return View();
}

Friday, November 4, 2011

.Net Shorcut

F6 / Shift+F6 / Ctrl+Shift+B : Build solution / Build project /
Build solution
Shift+Alt-C : Add a new class to your project
Ctrl+K+C : Comment a selected block of code
Ctrl+K+ U : Un-comment a selected block of code
Ctrl+M+O / Ctrl+M +P : Collapse all code to definitions /
Expand all code (stop collapsing)
Ctrl+Alt+L : Show the solution explorer
Ctrl+Shift+A / Alt+Shift+A : Add a new item to your project /
add an existing item to your project
Ctrl+K+F and CRTL+K+D : These two will format the code in the
window to be nicely indented. using "d" will format all the
document while using "f" will format only selected text. The
formatting is for all types of documents, HTML, Xaml, XML,
C#… This one is my favorite
Sift+Del : It’s just a regular cut (exactly the same as ctrl-x). This
one will cut the entire row from the document and past it to
the clipboard. No need to select the row, just put the marker
there and click SHIFT+Del and it is gone
Ctrl+K+S : This one opens up the code snippets dialogue within
the code
Ctrl+Space: Completes the symbol you're currently typing or
gives you a choice of various possibilities
F12 : This is the shortcut for the "Go to definition" command
which will take you to the definition of the object your marker
is currently on
F9 : This will add a breakpoint to the code line your marker is
currently at. Clicking F9 again will remove this breakpoint from
that line
Ctrl-M-M : This will expand or collapse based on where the
cursor is. Useful when everything is collapsed and you just
want to expand one of them.

Friday, October 28, 2011

latest version of the JavaScript language

The latest version of the JavaScript language is 1.8.5, released to the world at large on July 27, 2010.

The 1.8.5 update mainly served to provide full compliance to the ECMAScript 5 standard from December 2009, including "strict mode" and a number of other features.

If your only use of JavaScript is in a web browser (which accounts for most, though not all, of its usage worldwide) you should not have to worry about which version of the language is being used. Most browsers do not immediately support the latest versions of the language, and you are unlikely to find any web content that actually requires the use of any features from beyond JavaScript 1.5.

JQuery New Feature

Passing Attributes to jQuery(…)

Pre 1.4, jQuery supported adding attributes to an element collection via the useful "attr" method, which can be passed both an attribute name and value, or an object specifying several attributes. jQuery 1.4 adds support for passing an attributes object as the second argument to the jQuery function itself, upon element creation.

Let’s say you need to create an anchor element with several attributes. With 1.4 it’s as simple as:

You may have noticed the "text" attribute— you’ll probably be wondering what that’s doing there, after all there’s no "text" attribute for anchors! Well, jQuery 1.4 utilises its very own methods when you pass certain attributes. So the “text” attribute specified above would cause jQuery to call the ".text()" method, passing "Go to Google!" as its only argument.

A better example of this in action:

  1. jQuery('
    ', {
  2. id: 'foo',
  3. css: {
  4. fontWeight: 700,
  5. color: 'green'
  6. },
  7. click: function(){
  8. alert('Foo has been clicked!');
  9. }
  10. });

The "id" is added as a regular attribute, but the "css" and "click" properties trigger calling of each respective method. The above code, before the 1.4 release, would have been written like this:

  1. jQuery('
    ')
  2. .attr('id', 'foo')
  3. .css({
  4. fontWeight: 700,
  5. color: 'green'
  6. })
  7. .click(function(){
  8. alert('Foo has been clicked!');
  9. });

CLR

Common Language Runtime

Common Language Runtime (CLR) manages the execution of code and provides different services like Garbage collection and support for Base Class Libraries etc. The main constituents of CLR are described below

The common Language Runtime (CLR) a rich set of features for cross-language development and deployment. CLR supports both Object Oriented Languages as well as procedural languages. CLR provides security, garbage collection, cross language exception handling, cross language inheritance and so on.

The Common Type System, support both Object Oriented Programming languages as well as procedural languages. Basically CTS provides rich type system that is intended to support wide range of languages.

CLS (Common Language Specification) defines a subset of Common Type System, which all language compilers targeting CLR must adhere to. CLS is a subset of CTS.

All compilers under .NET will generate Intermediate Language no matter what language is used to develop an application. In fact, CLR will not be aware of the language used to develop an application. All language compilers will generate a uniform, common language called Intermediate Language. For this reason IL can be called as The language of CLR A platform for cross language development.

Friday, October 21, 2011

New Features in Microsoft .NET Framework 4

The new features and improvements are described in the following sections:

Programming Languages
Common Language Runtime (CLR)
Base Class Libraries
Networking
Web
Client
Data
Communications
Workflow

Common Language Runtime (CLR)

The following sections describe new features in security, parallel computing, performance and diagnostics, dynamic language runtime, and other CLR-related technologies.

Security

The .NET Framework 4.0 provides simplifications, improvements, and expanded capabilities in the security model. For more information, see Security Changes in the .NET Framework 4.

Parallel Computing

The .NET Framework 4.0 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new Parallel and Task classes, and other related types, support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.

Performance and Diagnostics

In addition to the following features, the .NET Framework 4.0 provides improvements in startup time, working set sizes, and faster performance for multithreaded applications.

ETW Events

You can now access the Event Tracing for Windows (ETW) events for diagnostic purposes to improve performance. For more information, see the following topics:

Performance Monitor (Perfmon.exe) now enables you to disambiguate multiple applications that use the same name and multiple versions of the common language runtime loaded by a single process. This requires a simple registry modification. For more information, see Performance Counters and In-Process Side-By-Side Applications.

Code Contracts

Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of pre-conditions, post-conditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and documentation generation.

The applicable scenarios include the following:

  • Perform static bug finding, which enables some bugs to be found without executing the code.

  • Create guidance for automated testing tools to enhance test coverage.

  • Create a standard notation for code behavior, which provides more information for documentation.

Lazy Initialiation

With lazy initialization, the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program. You can enable lazy initialization for any custom type by wrapping the type inside a System..::.Lazy<(Of <(T>)>) class.

Dynamic Language Runtime

The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework. In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.

In-Process Side-by-Side Execution

In-process side-by-side hosting enables an application to load and activate multiple versions of the common language runtime (CLR) in the same process. For example, you can run applications that are based on the .NET Framework 2.0 SP1 and applications that are based on .NET Framework 4.0 in the same process. Older components continue to use the same CLR version, and new components use the new CLR version. For more information, see Hosting Changes in the .NET Framework 4.

Interoperability

New interoperability features and improvements include the following:

  • You no longer have to use primary interop assemblies (PIAs). Compilers embed the parts of the interop assemblies that the add-ins actually use, and type safety is ensured by the common language runtime.

  • You can use the System.Runtime.InteropServices..::.ICustomQueryInterface interface to create a customized, managed code implementation of the IUnknown::QueryInterface method. Applications can use the customized implementation to return a specific interface (except IUnknown) for a particular interface ID.

Profiling

In the .NET Framework 4.0, you can attach profilers to a running process at any point, perform the requested profiling tasks, and then detach. For more information, see the [IClrProfiling::AttachProfiler]IClrProfiling Interface::AttachProfiler Method method.

Garbage Collection

The .NET Framework 4.0 provides background garbage collection; for more information, see the entry So, what’s new in the CLR 4.0 GC? in the CLR Garbage Collector blog.

Covariance and Contravariance

Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in the Common Language Runtime.

Base Class Libraries

The following sections describe new features in collections and data structures, exception handling, I/O, reflection, threading, and Windows registry.

Collections and Data Structures

Enhancements in this area include the new System.Numerics..::.BigInteger structure, the System.Collections.Generic..::.SortedSet<(Of <(T>)>) generic class, and tuples.

BigInteger

The new System.Numerics..::.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.

SortedSet Generic Class

The new System.Collections.Generic..::.SortedSet<(Of <(T>)>) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic..::.ISet<(Of <(T>)>) interface.

The System.Collections.Generic..::.HashSet<(Of <(T>)>) class also implements the ISet<(Of <(T>)>) interface.

Tuples

A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. Tuples are supported natively in languages such as F# and IronPython, but are also easy to use from any .NET Framework language such as C# and Visual Basic. The ..NET Framework 4.0 adds eight new generic tuple classes, and also a Tuple class that contains static factory methods for creating tuples.

Exceptions Handling

The .NET Framework 4.0 class library contains the new System.Runtime.ExceptionServices namespace, and adds the ability to handle corrupted state exceptions.

Corrupted State Exceptions

The CLR no longer delivers corrupted state exceptions that occur in the operating system to be handled by managed code, unless you apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.

Alternatively, you can add the following setting to an application's configuration file:

legacyCorruptedStateExceptionsPolicy=true

I/O

The key new features in I/O are efficient file enumerations, memory-mapped files, and improvements in isolated storage and compression.

File System Enumeration Improvements

New enumeration methods in the Directory and DirectoryInfo classes return IEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.

There are also new methods in the static File class that read and write lines from files by using IEnumerable<(Of <(T>)>) collections. These methods are useful in LINQ scenarios where you may want to quickly and efficiently query the contents of a text file and write out the results to a log file without allocating any arrays.

Memory-Mapped Files

The new System.IO.MemoryMappedFiles namespace provides memory mapping functionality, which is available in Windows. You can use memory-mapped files to edit very large files and to create shared memory for inter-process communication. The new System.IO..::.UnmanagedMemoryAccessor class enables random access to unmanaged memory, similar to how System.IO..::.UnmanagedMemoryStream enables sequential access to unmanaged memory.

Isolated Storage Improvements

Partial-trust applications, such as Windows Presentation Framework (WPF) browser applications (XBAPs) and ClickOnce partial-trust applications, now have the same capabilities in the .NET Framework as they do in Silverlight. The default quota size is doubled, and applications can prompt the user to approve or reject a request to increase the quota. The System.IO.IsolatedStorage..::.IsolatedStorageFile class contains new members to manage the quota and to make working with files and directories easier.

Compression Improvements

The compression algorithms for the System.IO.Compression..::.DeflateStream and System.IO.Compression..::.GZipStream classes have improved so that data that is already compressed is no longer inflated. This results in much better compression ratios. Also, the 4-gigabyte size restriction for compressing streams has been removed.

Reflection

The .NET Framework 4.0 provides the capability to monitor the performance of your application domains.

Application Domain Resource Monitoring

Until now, there has been no way to determine whether a particular application domain is affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4.0, you can get processor usage and memory usage estimates per application domain.

Application domain resource monitoring is available through the managed AppDomain class, native hosting APIs, and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process.

For more information, see the Element, and the following properties in the AppDomain class:

64-bit View and Other Registry Improvements

Windows registry improvements include the following:

Threading

General threading improvements include the following:

  • The new Monitor..::.Enter(Object, Boolean%) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.

  • You can use the Thread..::.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.

The following sections describe new threading features.

Unified Model for Cancellation

The .NET Framework 4.0 provides a new unified model for cancellation of asynchronous operations. The new System.Threading..::.CancellationTokenSource class is used to create a CancellationToken that may be passed to any number of operations on multiple threads. By calling Cancel()()() on the token source object, the IsCancellationRequested property on the token is set to true and the token’s wait handle is signaled, at which time any registered actions with the token are invoked. Any object that has a reference to that token can monitor the value of that property and respond as appropriate.

Thread-Safe Collection Classes

The new System.Collections.Concurrent namespace introduces several new thread-safe collection classes that provide lock-free access to items whenever useful, and fine-grained locking when locks are appropriate. The use of these classes in multi-threaded scenarios should improve performance over collection types such as ArrayList, and List<(Of <(T>)>).

Synchronization Primitives

New synchronization primitives in the System.Threading namespace enable fine-grained concurrency and faster performance by avoiding expensive locking mechanisms. The Barrier class enables multiple threads to work on an algorithm cooperatively by providing a point at which each task can signal its arrival and then block until the other participants in the barrier have arrived. The CountdownEvent class simplifies fork and join scenarios by providing an easy rendezvous mechanism. The ManualResetEventSlim class is a lock-free synchronization primitive similar to the ManualResetEvent class. ManualResetEventSlim is lighter weight but can only be used for intra-process communication. The SemaphoreSlim class is a lightweight synchronization primitive that limits the number of threads that can access a resource or a pool of resources at the same time; it can be used only for intra-process communication. The SpinLock class is a mutual exclusion lock primitive that causes the thread that is trying to acquire the lock to wait in a loop, or spin, until the lock becomes available. The SpinWait class is a small, lightweight type that will spin for a time and eventually put the thread into a wait state if the spin count is exceeded.

Networking

Enhancements have been made that affect how integrated Windows authentication is handled by the HttpWebRequest, HttpListener, SmtpClient, SslStream, NegotiateStream, and related classes in the System.Net and related namespaces. Support was added for extended protection to enhance security. The changes to support extended protection are available only for applications on Windows 7. The extended protection features are not available on earlier versions of Windows. For more information, seeIntegrated Windows Authentication with Extended Protection.

Web

The following sections describe new features in ASP.NET core services, Web Forms, Dynamic Data, and Visual Web Developer.

ASP.NET Core Services

ASP.NET introduces several features that improve core ASP.NET services, Web Forms, Dynamic Data, and Visual Web Developer. For more information, see What’s New in ASP.NET and Web Development.

ASP.NET Web Forms

Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been made in this area for ASP.NET 4, including the following:

  • The ability to set meta tags.

  • More control over view state.

  • Easier ways to work with browser capabilities.

  • Support for using ASP.NET routing with Web Forms.

  • More control over generated IDs.

  • The ability to persist selected rows in data controls.

  • More control over rendered HTML in the FormView and ListView controls.

  • Filtering support for data source controls.

Dynamic Data

For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. This includes the following:

  • Automatic validation that is based on constraints defined in the data model.

  • The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project.

ASP.NET MVC 4 Developer Preview with Mobile Support Released (My Experiences)

I am not at the Microsoft Build Conference and missing all the exciting developments . It’s going to take me a while to digest all the developments although it looks like I was mostly right about Windows 8 and the HTML5/CSS3/Javascript programming model even though .NET is not dead (yet).

I have been talking about work with the new project with ASP.NET MVC and then looking at things like Sencha Touch, PhoneGap, and jQuery/jQueryUI, as well as jQTouch. In fact, I was able to use straight HTML5/CSS3/Javascript with jQTouch to create a pretty comprehensive iPhone application.

But what got me really excited today was the release at Build of ASP.NET MVC 4 Developer Preview. I thought, “what if we could have one code base – ASP.NET MVC for the web app and also for the mobile clients?” That’s because a cool thing about MVC 4 is that there is a Mobile project template as well as lots of features for mobile development. So I downloaded it today at work and ran through the mobile tutorial. I’m impressed so far! I was able to use Safari for Windows and it’s developer mode to emulate a iOS/iPhone 4 application with the tutorial as well as playing around. MVC 4 is built on top or uses the wonderful jQuery Mobile. It’s a pretty good model using jQueryMobile’s markup like

    .

    The problem is that our “customer” will not be switching to iPhone 4’s and staying with the Blackberry Torch 9810 and 9900 devices. jQTouch definitely supports it. It doesn’t seem like ASP.NET MVC 4 does not (it doesn’t seem like there is any Blackberry support) but my good friend Brad Wilson on the ASP.NET team texted me in answer to that “It's built on BrowserCaps, and you can also extend it to include your own sub-types and rules fairly easily. For example, all mobile devices are .mobile right now, but you could add an iPhone rule and use .iphone” I don’t know what that means yet but I am hopeful to learn from my readers and the team. What do you think?