Tuesday, March 29, 2011

Asp.Net Page LifeCycle

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal.Each request for an .aspx page that hits IIS is handed over to HTTP Pipeline. HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content. The start point of HTTP Pipeline is the HttpRuntime class. The ASP.NET infrastructure creates each instance of this class per AppDomain hosted within the worker process. HttpRuntime class picks up an HttpApplication object from an internal pool and sets it to work on the request. It finds out what class has to handle the request. The association between the resources and handlers are stored in the configurable file of the application
Once the HTTP page handler class is fully identified, the ASP.NET runtime calls the handler's ProcessRequest to start the process. This implementation begins by calling the method FrameworkInitialize(), which builds the control trees for the page. This is a protected and virtual member of TemplateControl class, class from which page itself derives.

Next the processRequest() makes page transits various phases: initialization, loading of viewstate and postback data, loading of page's user code and execution postback server-side events. Then page enters in render mode, the viewstate is updated and HTML generated is sent to the output console. Finally page is unloaded and request is considered completely served. 

Page_PreInit: Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.

Page_Init : This is fired after the page's control tree has been successfully created. All the controls that are statically declared in the .aspx file will be initialized with the default values. Controls can use this event to initialize some of the settings that can be used throughout the lifetime of the incoming web request. Viewstate information will not be available at this stage. This Event Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.Use this event to read or initialize control properties. 
Page_PreLoad: Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance. 
Page_Load: After initialization, page framework loads the view state for the page. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests. It contains the state of the controls the last time the page was processed on the server. By overriding LoadViewState() method, component developer can understand how viewstate is restored.Once viewstate is restored, control will be updated with the client side changes. It loads the posted data values. The PostBackData event gives control a chance to update their state that reflects the state of the HTML element on the client.

At the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, load event is fired.

 
btnSubmit_Clicked: Key event in the life cycle is when the server-side code associated with an event triggered on the client. When the user clicks on the button, the page posts back. 
RaisePostBackEvent: Page framework calls the RaisePostBackEvent. This event looks up for the event handler and run the associated delegate.
 
Page_PreRender: After PostBack event, page prepares for rendering. PreRender event is called. This is the place where user can do the update operations before the viewstate is stored and output is rendered. This Event Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.
Use the event to make final changes to the contents of the page or its controls before the rendering stage begins. 
SaveViewState: Next stage is saving view state, all the values of the controls will be saved to their own viewstate collection. The resultant viewstate is serialized, hashed, base24 encoded and associated with the _viewstate hidden field.
 
Render: Next the render method is called. This method takes the HtmlWriter object and uses it to accumulate all HTML text to be generated for the control. For each control the page calls the render method and caches the HTML output. The rendering mechanism for the control can be altered by overriding this render method. This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Page_Unload: This is called just before the page object is dismissed. In this event, you can release critical resources you have such as database connections, files, graphical objects etc. After this event browser receives the HTTP response packet and displays the page. At this time Response object not available. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception. If you observe the given sample, if we use Response in this event, the system raises an error that says 'Response Object not available at this stage'

To understand the page life cycle clearly, create a website and add a PageLifeCycle.aspx page to the website. Add the below lines of code to the page and view it in the browser. 
PageLifeCycle.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageLifeCycle.aspx.cs" Inherits="PageLifeCycle" %>

<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Name</td><td><asp:TextBox ID="tbName" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td>Designation</td><td><asp:DropDownList ID="ddlDesignation" runat="server" ></asp:DropDownList> </td>
</tr>
<tr>
<td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Clicked" /> </td>
</tr>
</table>
</div>
</form>
</body>
</html>


PageLifeCycle.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PageLifeCycle : System.Web.UI.Page
{
int counter = 1;


protected void Page_PreLoad(object sender, EventArgs e)
{
WriteOutput("Page_PreLoad");
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
BindDesignation();
}
WriteOutput("Page_Load");
}


private void BindDesignation()
{
List<Info> infoList = new List<Info>();
for (int i = 1; i <= 5; i++)
{
infoList.Add(new Info("Venkat"+i,"Software Engineer"+i));
}
ddlDesignation.DataSource = infoList;
ddlDesignation.DataValueField = "Designation";
ddlDesignation.DataTextField = "Designation";
ddlDesignation.DataBind();
}

protected override void LoadControlState(object savedState)
{
base.LoadControlState(savedState);
WriteOutput("LoadControlState");

}

protected void Page_LoadViewState(object sender, EventArgs e)
{
WriteOutput("LoadViewState");
}

protected override void LoadViewState(object viewState)
{
base.LoadViewState(viewState);
WriteOutput("LoadViewState");
}

protected override object SaveViewState()
{
WriteOutput("SaveViewState");
return base.SaveViewState();
}


protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArg)
{
base.RaisePostBackEvent(sourceControl,eventArg);
WriteOutput("RaisePostBackEvent");
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
WriteOutput("Render");
}


protected void btnSubmit_Clicked(object sender, EventArgs e)
{
WriteOutput("btnSubmit_Clicked");
}

protected void Page_PreInit(object sender, EventArgs e)
{
WriteOutput("Page_PreInit");
}
protected void Page_Init(object sender, EventArgs e)
{
WriteOutput("Page_Init");
}

protected void Page_PreRender(object sender, EventArgs e)
{
WriteOutput("Page_PreRender");
}
protected void Page_Unload(object sender, EventArgs e)
{
//WriteOutput("Page_Unload");
}


private void WriteOutput(string eventName)
{
Response.Write("Step no: " + counter++ + "--> "+eventName+"<br/>");
Response.Write("Name: " + (tbName.Text == null ? "Null" : tbName.Text + "<br/>"));
Response.Write("Designation: " + (ddlDesignation.SelectedValue == null ? "Null" : ddlDesignation.SelectedValue + "<br/><br/>"));
}

}

public class Info
{
public string Name { get; set; }
public string Designation { get; set; }
public Info(string name,string designation)
{
Name = name;
Designation = designation;
}
}

If you view the page in the browser , the below screen will be shown,

Click on the Submit Button to Postback the page, then the below screen will be shown. 


 

Monday, March 28, 2011

Why IsPostBack Check?

Binding Data
We often bind data to Dropdown lists and Repeater etc, in ‘PageLoad’ event. Sometimes we bind data without checking page ‘IsPostBack’ value.Due to this small mistake, the changes that we made to dropdown selection will be lost. When trying to catch the selected value of the dropdown list in the ‘Post back’ event, it will be set to default value. Any novice learner of .Net will get surprised to see, if their changes were not effecting.
Here what happens is the ’Page Load’ events occurs first, and then the ‘Post back’ event. Here the drop down list (in our case) binds two times. Whenever we submit a page by clicking on the button, the first event that takes place is ‘Page Load’ event then the ‘Button click’ event. So the BindDropDown() will executes again and the changes that we made will get lost.
So here the conclusion is Data Binding operation should be done before page post back.
Here is the Sample Code:Binding the data by checking the page ‘Post Back’ event.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 runat="server">
<title>Page Post back and Databinding</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
<br />
<asp:DropDownList ID="ddlBooks" runat="server" EnableViewState="true" ></asp:DropDownList>
<asp:Button ID="btnSubmit" OnClick="BtnSubmitClicked" Text="Submit" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.ObjectModel;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(objectsender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
List<string> books = new List<string>();
books.Add("C# fundamentals");
books.Add("Masteringin Styles");
books.Add("C#Advanced");
books.Sort();
ddlBooks.DataSource = books;
ddlBooks.DataBind();
ddlBooks.Items.Insert(0,new ListItem("Select ne","select"));
}
protected void BtnSubmitClicked(object sender, entArgs e)
{
lblStatus.Text =ddlBooks.SelectedValue;
}
}
Try to remove the IsPostBak condition and run the code.see the difference.

Another mistake we often do is forget to ‘Enable View State’ of the page. By default view state is enabled for all controls, there is no need to explicitly enable it. However, if we disable it in ‘web.config’ file, we have to explicitly enable it where ever we want. Here are some guide lines to enable view state of drop down list.

‘View State’ can be disabled/enabled in
I. Web.config file (to disable ‘view sate’ of all pages)
II. Master page
III. Aspx Page.
IV. User control
V. With in the Control itself.
Take an example of ‘drop down list’, when the view state set to false for all pages in ‘web.config’ file,
view state won’t work for all pages. After submitting the page the drop down will have no items bound to it.
To enable view state for a particular page , we have to enable it on both Master page, and the Aspx Page. If the drop down list is placed in a user control, then we have to enable the view state in the user control also, other wise the view state of the drop down will get disabled.
Even if it is set to true in all, but disabled in the control, then it get disabled but the converse is false.
Conclusion:If you want to enable view state on dropdown list when the view state get disabled in web.config file; We should explicitly enable it on the Master page, Aspx Page where it’s being declared and the user control(if it is declared in User control). Then only the viewstate of the control get enabled.
If Viewstate enabled in web.config and disabled in either of master page or Aspx Page, then viewstate of dropdown list get disabled. If the view state enabled on both Master page and Aspx Page, then no need to explicitly enable it in user control and the control itself.

Friday, March 25, 2011

How to debug silverlight webpart in sharepoint 2010.?

SharePoint Silverlight debugging in Visual Studio is not supported by default, due to Script debugging settings turned on. It means that you can’t set breakpoints and step into your code in VS if you are not deploying Silverlight controls via feature. Such functionality is supported when you host your SL project in external Web Project (another reason not to host in SharePoint during development)



To provide the SharePoint SL debugging capabilities you need to package your .XAP file in SharePoint Project (in VS) and deploy as a Feature. Such approach allows to enable “Siverlight Debugging” instead of client one, and step into your .cs code from Visual Studio 2010. This options is set from the VS IDE. Navigate to the SharePoint project properties –> SharePoint Tab –> click “Enable Silverlight Debugging”. That checkbox will activate the Remote Debugger and you will be able to debug SL hosted in SharePoint using Visual Studio 2010 (but you need to configure the Remote Debugger first, opening the firewall ports. On the 64bit windows you need to configure the x86 version of msvsmon.exe because the Visual Studio is x86)


Note: Debugging doesn’t work if you don’t have another instance of the the SL page opened in browser. Seems there is a bug resolving assemblies, because when you start debugging your solution might be re-builded , IIS restarts, thus remote debugger can’t attach to the right assemblies. To fix it just open another tab in browser, navigate to page with SL control you are debugging and only after that start debugging which will open the second instance of that page.

 Debug both silverlight and javascript together

Sometimes you need to debug both silverlight and javascript together, especially when you’re doing HTML bridge development where requests seamlessly pass between SL and JS

  1. Use Chrome instead of IE,
  2. Rig your SharePoint project to use Silverlight debugging,
  3. Inside Chrome press CTRL_ALT_J to open the javascript debugger, and use chrome’s SL debugger.


Thursday, March 24, 2011

SP 2010 PowerShell Commands

Windows PowerShell is a command-line scripting tool that provides an administrator full access to applicable application programming interfaces (APIs), along with the ability to unlock the capability to interact directly with SharePoint 2010 Products to manipulate Web applications, site collections, sites, lists and much more. In addition, the administrator has the ability to script cmdlets (pronounced "command-lets"), which makes for an improved experience from past product versions.



Windows PowerShell 2.0 is a pre-requisite for installing SharePoint 2010 Products. It will be installed, if necessary, when you run the Microsoft SharePoint Products Preparation Tool. By default, Windows PowerShell is located at the following path: <%SystemRoot%>\System32\WindowsPowerShell\v1.0\PowerShell.exe.


Windows PowerShell 2.0 includes the following new features.


  Remoting
   
      Windows PowerShell 2.0 lets you run commands on one or many remote
      computers with a single Windows PowerShell command. You can run
      individual commands, or you can create a persistent connection
      (a session) to run a series of related commands. You can also start a
      session with a remote computer so that the commands you type run
      directly on the remote computer.


      The remoting features of Windows PowerShell are built on Windows
      Remote Management (WinRM). WinRM is the Microsoft implementation of
      the WS-Management protocol, a standard SOAP-based, firewall-compatible
      communications protocol.


      The remote computers must have Windows PowerShell 2.0, the Microsoft .NET
      Framework 2.0, and the WinRM service. Remote commands are supported
      on all operating systems that can run Windows PowerShell. The
      current user must have permission to run commands on the remote
      computers.


      To support remoting, the Invoke-Command, Enter-PSSession, and
      Exit-PSSession cmdlets have been added, along with other cmdlets
      that contain the PSSession noun. These cmdlets let you create and manage
      persistent connections.


      The ComputerName parameter has also been added to several cmdlets,
      including the Get-Process, Get-Service, and Get-Eventlog cmdlets. This
      parameter allows you to get information about remote computers.
      These cmdlets use .NET Framework methods to get their data,
      so they do not rely on Windows PowerShell remoting. They do not require
      any new programs or configuration.

  

Background Jobs
   
      Background jobs are commands that run asynchronously. When you run a
      background job, the command prompt returns immediately, even if the
      command is still running. You can use the background job feature to run a
      complex command in the background so that you can use your session for
      other work while the command runs.


      You can run a background job on a local or remote computer and then save
      the results on the local or remote computer. To run a job remotely, use
      the Invoke-Command cmdlet.
   

      Windows PowerShell includes a set of cmdlets that contain the Job noun
      (the Job cmdlets). Use these cmdlets for creating, starting, managing,
      and deleting background jobs and for getting the results of a background
      job. To get a list of the job cmdlets, type the following command:

          get-command *-job

  Script Debugger
   
      Windows PowerShell 2.0 includes a cmdlet-based debugger for scripts and
      functions. The debugger is supported by a fully documented public API
      that you can use to build your own debugger or to customize or extend
      the debugger.


      The debugger cmdlets let you set breakpoints on lines, columns,
      variables, and commands. These cmdlets let you manage the breakpoints
      and display the call stack. You can create conditional breakpoints and
      specify custom actions at a breakpoint, such as running diagnostic and
      logging scripts.


      When you reach a breakpoint, Windows PowerShell suspends execution
      and starts the debugger. The debugger includes a set of custom commands
      that let you step through the code. You can also run standard Windows
      PowerShell commands to display the values of variables, and you can use
      cmdlets to investigate the results.



  Data Section
   
      Scripts designed for Windows PowerShell 2.0 can have one or more
      DATA sections that isolate the data from the script logic. The data in
      the new DATA section is restricted to a specified subset of the Windows
      PowerShell scripting language.


      In Windows PowerShell 2.0, the DATA section is used to support
      script internationalization. You can use the DATA section to isolate
      and identify user message strings that will be translated into
      multiple user interface languages.


  Script Internationalization
   
      Windows PowerShell 2.0 script internationalization features allow you
      to better serve users throughout the world. Script internationalization
      enables scripts and functions to display messages and Help text to users
      in multiple languages.


      The script internationalization features query the operating system user
      interface culture ($PsUICulture) during execution and then import the
      appropriate translated text strings so you can display them to the user.
      The Data section lets you store text strings separate from code so that
      they are easily identified. A new cmdlet, ConvertFrom-StringData,
      converts text strings into dictionary-like hash tables to facilitate
      translation.


  WMI Cmdlets
   
      The Windows Management Instrumentation (WMI) functionality of
      Windows PowerShell 2.0 is improved with the addition of the following
      cmdlets:

          - Remove-WmiObject
          - Set-WmiInstance
          - Invoke-WmiMethod


      New parameters have been added to the Get-WmiObject cmdlet. All the WMI
      cmdlets now support the following parameters:

          - EnableAllPrivileges
          - Impersonation
          - Authentication
          - Authority


      These new parameters give you more refined control over the security
      configuration of your WMI operations without requiring you to work
      directly with the types in the .NET Framework Class Library.


      For a list of WMI cmdlets, type the following command:

          get-help *wmi*

      To get help for each cmdlet, type get-help followed by the cmdlet name.

   
  The Get-WinEvent Cmdlet
   
      The Get-WinEvent cmdlet gets events from Event Viewer logs and from
      Event Tracing for Windows (ETW) event log files on local and remote
      computers. It can get events from classic event logs and from the
      Windows Event Logs that were introduced in Windows Vista.


      You can use Get-WinEvent to get the objects that represent event logs, event
      log providers, and the events in the logs. Get-WinEvent lets you combine
      events from different sources in a single command. It supports
      advanced queries in XML Path Language (XPath), XML, and hash table
      format.


      Get-WinEvent requires Windows Vista or Windows Server 2008 and the
      Microsoft .NET Framework 3.5.


  The Out-Gridview Cmdlet
   
      The Out-GridView cmdlet displays the results of other commands in an
      interactive table in which you can search, sort, group, and filter the
      results. For example, you can send the results of a Get-Process,
      Get-WmiObject, Get-WinEvent, or Get-Eventlog command to Out-GridView and
      then use the table features to examine the data.

        help out-gridview -full


  The Add-Type Cmdlet
   
      The Add-Type cmdlet lets you add .NET Framework types to
      Windows PowerShell from the source code of another .NET Framework
      language.


      Add-Type compiles the source code that creates the types and generates
      assemblies that contain the new .NET Framework types. Then, you can use
      the .NET Framework types in Windows PowerShell commands along with the
      standard object types provided by the .NET Framework.


      You can also use Add-Type to load assemblies into your session so that
      you can use the types in the assemblies in Windows PowerShell.


      Add-Type allows you develop new .NET Framework types, to
      use .NET Framework types in C# libraries, and to access Win32 APIs.

   

  Event Notification
   
      Windows PowerShell 2.0 introduces event notification. Users can register
      and subscribe to events, such as Windows PowerShell events, WMI events,
      or .NET Framework events. And, users can listen, forward, and act on
      management and system events both synchronously and asynchronously.


      Developers can write applications that use the event architecture
      to receive notification about state changes. Users can write
      scripts that subscribe to various events and that react to the content.
  

      Windows PowerShell provides cmdlets that create new events, get
      events and event subscriptions, register and unregister events,
      wait for events, and delete events. For more information about these
      cmdlets, type the following command:

          get-command *-event

  
  Modules
   
      Windows PowerShell modules let you divide and organize your
      Windows PowerShell scripts into independent, self-contained,
      reusable units. Code from a module executes in its own context,
      so it does not add to, conflict with, or overwrite the variables,
      functions, aliases, and other resources in the session.

   
      You can write, distribute, combine, share, and reuse modules to build
      simple scripts and complex applications.


      Windows PowerShell 2.0 includes cmdlets to add, get, and remove modules
      and to export module members. For more information about the cmdlets
      that are related to modules, type the following command:

          get-command *-module*


  Transactions
   
      Windows PowerShell 2.0 includes support for transactions. Transactions
      let you undo an entire series of operations. Transactions are available
      only for operations that support transactions. They are designed for
      applications that require atomicity, consistency, isolation, and
      recoverability, like databases and message queuing.


      Cmdlets and providers that support transactions have a new
      UseTransaction parameter. To start an operation within a transaction,
      use the Start-Transaction cmdlet. Then, when you use the cmdlets that
      perform the operation, use the UseTransaction parameter of each cmdlet
      when you want the command to be part of a transaction.


      If any command in the transaction fails at any point, use the
      Rollback-Transaction cmdlet to undo all the commands in the transaction.
      If all the commands succeed, use the Commit-Transaction cmdlet to make
      the command actions permanent.


      Windows PowerShell 2.0 includes cmdlets to start, use, commit, and roll
      back transactions. For information about these cmdlets, type the
      following command:

          get-command *transaction*


Accessing Windows PowerShell for SharePoint 2010 Products

After installing SharePoint 2010 Products, the applicable Windows PowerShell cmdlets are available by using the SharePoint 2010 Management Shell, or by using the Windows PowerShell console. With the management shell, you can manage every aspect of SharePoint 2010 Products. You can create new site collections, Web applications, user accounts, service applications, proxies, and more. The commands from the management shell output SharePoint objects based on the Microsoft .NET Platform. These objects can be applied as input to subsequent commands or stored in local variables for later use.

With the management shell, you do not have to register the snap-in that contains the cmdlets. Registration of the Microsoft.SharePoint.PowerShell.dll module for SharePoint 2010 cmdlets is automatic, as a result of the line Add-PSSnapin Microsoft.SharePoint.PowerShell in the SharePoint.ps1 file located in %CommonProgramFiles%\Microsoft Shared\Web Server Extensions\14\Config\PowerShell\Registration. If you choose to use the Windows PowerShell console, you must register this snap-in manually.

Whether you are using the management shell or the Windows PowerShell console, you can also load additional snap-ins. For more information, see Customizing Profiles (http://go.microsoft.com/fwlink/?LinkId=183166).

To access the SharePoint 2010 Management Shell

   1.On the Start menu, click All Programs.
   2.Click Microsoft SharePoint 2010 Products.
   3.Click SharePoint 2010 Management Shell.


The SharePoint 2010 Management Shell and the Windows PowerShell console also differ in the use of the ReuseThread option, which defines how the threading model is used. The management shell's use is defined by this line, {Host.Runspace.ThreadOptions = "ReuseThread"}, which is in the SharePoint.ps1 file. For more information, see PS Thread Options (http://go.microsoft.com/fwlink/?LinkId=183145).

Permissions

Before you can use the management shell and the Windows PowerShell cmdlets, verify that you meet the following minimum requirements:

If you do not have membership in the SharePoint_Shell_Access role or WSS_Admin_WPG local group, use the Add-SPShellAdmin cmdlet. When the Add-SPShellAdmin cmdlet is used, the user is added to the WSS_Admin_WPG group in all front-end Web servers and is added to the SharePoint_Shell_Access role. If the target database does not have a SharePoint_Shell_Access role, the role is automatically created. Once the Add-SPShellAdmin cmdlet has been run, the user can run SharePoint 2010 Windows PowerShell cmdlets in a multiple-server farm environment.

When you run the Add-SPShellAdmin cmdlet to add a user to the SharePoint_Shell_Access role, you must have the following security permissions:

    * Securityadmin server role access on the SQL instance and the db_owner role in a database.

    * Administrative permission on the local computer.


Typically, the person that will use the Add-SPShellAdmin cmdlet must be associated with the user account that was used for Setup.

You must run the Add-SPShellAdmin cmdlet for all databases to which you want to grant access. If no database is specified, the farm configuration database is used. If you do specify a database, the farm content database will be included in addition to the farm configuration database you specify.

To see a list of all of the *SPShellAdmin cmdlets, from a Windows PowerShell command prompt, type Get-Command -Noun SPShellAdmin.

Scripts and execution policies

Although you can use Windows PowerShell to perform a single administrative task, the real benefit of using Windows PowerShell cmdlets is the ability to use a script to automate a series of tasks. A script is a plain text file that contains one or more Windows PowerShell commands. Windows PowerShell scripts have a .ps1 file name extension.

When using a script, be aware that the minimum required execution policy for SharePoint 2010 Products is RemoteSigned, while the default policy for Windows PowerShell is Restricted. If the policy is left as Restricted, the SharePoint 2010 Management Shell will change the policy for Windows PowerShell to RemoteSigned. This means the SharePoint 2010 Management Shell must be launched with elevated administrative permission by selecting Run as administrator. This change will apply to all Windows PowerShell sessions.


Web Site vs Web Application project in .Net

Website project type was introduced in the VS 2005 and Web Application model introduced in VS 2003. Website project type is based on folder structure and does not require a project file. Later in VS 2005 sp1 project file was introduced for the VS 2005 website project type. Now in VS 2008 we can create both project types.A common question by asp.net developers is what project model should I use for asp.net application?Every project model has it's own advantages and disadvantages.

Major difference between Web Application and Website is when you deploy the WebApps, you can just copy the Compiled Assembly and Visual elements to the IIS folder where as in Website you need to copy everything to the IIS to work.

Website:
It is a collection of web pages and other information such as images, sound, and video files, etc. that are made available to end users using different browsers like IE, FireFox, Chrome etc. through a single web server.


Web Application:
A web application serves a specific function such a shopping cart or a blogging application.

A web site can be a collection of several web applications. 

Web Application project model
  1. Provides the same Web project semantics as Visual Studio .NET 2003 Web projects.
  2. Has a project file (structure based on project files).
  3. Build model - all code in the project is compiled into a single assembly.
  4. Supports both IIS and the built-in ASP.NET Development Server.
  5. Supports all the features of Visual Studio 2005 (refactoring, generics, etc.) and of ASP.NET 2.0 (master pages, membership and login, site navigation, themes, etc).
  6. Using FrontPage Server Extensions (FPSE) are no longer a requirement.
Web Site project model
  1. No project file (Based on file system).
  2. New compilation model.  (Read here or here for more details) and ...
  3. Dynamic compilation and working on pages without building entire site on each page view.
  4. Supports both IIS and the built-in ASP.NET Development Server.
  5. Each page has it's own assembly.
  6. Different code model.  (Read here for more details)
Which model should I use?
  1. You need to migrate large Visual Studio .NET 2003 applications to VS 2005? use the Web Application project.
  2. You want to open and edit any directory as a Web project without creating a project file? use Web Site project.
  3. You need to add pre-build and post-build steps during compilation? use Web Application project.
  4. You need to build a Web application using multiple Web projects? use Web Application project.
  5. You want to generate one assembly for each page? use Web Site project. 
  6. You prefer dynamic compilation and working on pages without building entire site on each page view? use Web Site project. 
  7. You prefer single-page code model to code-behind model? use Web Site project.

Sharepoint server 2010 vs Sharepoint Foundation 2010

Here is an image showing differences between sharepoint  2010 versions.You can find all these in the below link
http://sharepoint.microsoft.com/en-us/buy/Pages/Editions-Comparison.aspx


How to Deploy a SharePoint site from one server to another?

Some times we need to deploy our share point Site on Staging server for client access to test the website.


Follow the below steps to  migrate Sharepoint site from Dev Server to Staging.

Method I


1. Use SQL Management Studio to backup the Content Database
How to: Back Up a Database (SQL Server Management Studio):
http://msdn.microsoft.com/en-us/library/ms187510.aspx

2. Restore the Content Database to your new SQL server
How to: Restore a Database Backup (SQL Server Management Studio):
http://msdn.microsoft.com/en-us/library/ms177429.aspx

3. Create a new web application in Central Admin on the new farm:
Create a Web application (SharePoint Foundation 2010):
http://technet.microsoft.com/en-us/library/cc288705.aspx
 
4. Delete the content Database that get's created by the new web application(from step 4)
Central Admin > Application Management > Content Databases > delete the empty db from your web application (created in step 3)

5. Use SharePoint Management Shell(Mount-SPContentDatabase), Stsadm(-o addcontentdb) or Central Admin to add the contentdatabase:
Add a content database (SharePoint Server 2010):
http://technet.microsoft.com/en-us/library/cc825314.aspx
 
6. Make sure that your account has administrative permissions on the site collection(update site collection administrator)
 
Add or remove site collection administrators (SharePoint Server 2010):
 
 Method II

We can use Central Adminstration to take back up of a farm or site collection to a shared location and we can restore the backup file into a new server farm using the new server farm's Central Administration as shown in the below images.

Sitefinity 3.7 - Custom Url Rewrite Module

In our application we need to redirect the user from a old website page to the new website page. Sitefinity has built in Module to rewrite the url. The below link clearly explains it.

http://www.sitefinitywatch.com/blog/09-01-08/URL_Rewriting_with_Sitefinity_s_AdvancedUrlRewriter.aspx

In our application we have plenty of  URLS to rewrite and we dont want to put all these stuff in web.config. So We have created a Custom Module to rewrite the URLs. This module reads the xml file (which contains a set of url rewrites and the format is same as url rewrites defined in the web.config.) and rewrites the URL.

In our application we have two xml files, one is for pdf documents and the other is for page re-directions.

Code :

App_Code/RedirectModule.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;


namespace Ramp.UrlRedirect
{

/// <summary>
/// Summary description for RedirectModule
/// </summary>
public class RedirectModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(OnBeginRequest);
}

private void OnBeginRequest(object src, EventArgs e)
{
HttpApplication app = src as HttpApplication;
string requestedUrl = app.Request.Url.AbsolutePath.ToLower();
if (requestedUrl == "/index.html")
{
try
{
app.Response.StatusCode = 301; // make a permanent redirect
app.Response.AddHeader("Location", "/");
app.Response.End();
return;
}
catch { }
}

if (!requestedUrl.Contains(ConfigurationManager.AppSettings["SearchResultsPage"].ToLower()))
{

DataSet dataset = new DataSet();

Regex pdfRegx = new Regex("(.pdf)$", RegexOptions.IgnoreCase);

if (pdfRegx.IsMatch(requestedUrl))
{
dataset.ReadXml(app.Server.MapPath("~/Res/Redirections/doc_redirections.xml"));
}
else
{
dataset.ReadXml(app.Server.MapPath("~/Res/Redirections/page_redirections.xml"));
}


for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
{
try
{
string sourceUrl = dataset.Tables[0].Rows[i].ItemArray[0].ToString();
string targetUrl = dataset.Tables[0].Rows[i].ItemArray[1].ToString();

Regex targetRegex = new Regex(targetUrl, RegexOptions.IgnoreCase);

if (targetRegex.IsMatch(requestedUrl))
{
return;
}

Regex sourceRegex = new Regex(sourceUrl, RegexOptions.IgnoreCase);
if (sourceRegex.IsMatch(requestedUrl))
{
string destinationUrl = sourceRegex.Replace(requestedUrl, targetUrl, 1);
app.Response.StatusCode = 301; // make a permanent redirect
app.Response.AddHeader("Location", destinationUrl + app.Request.Url.Query);
app.Response.End();
break;
}
}
catch { }
}
}

}

public void Dispose()
{
}
}
}

web.config changes
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ScriptModule" />
<remove name="Cms" />
<!--<remove name="LibraryModule"/>-->
<remove name="RadUploadModule" />
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="Cms" type="Telerik.Cms.Web.CmsHttpModuleUrlRewrite, Telerik.Cms" />
<add name="RedirectModule" type="Ramp.UrlRedirect.RedirectModule, App_Code" />

<!-- Http Module for extension mappings in Library module.-->
<!--<add name="LibraryModule" type="Telerik.Libraries.LibraryHttpModule, Telerik.Libraries"/>-->
<add name="RadUploadModule" preCondition="managedHandler" type="Telerik.Web.UI.RadUploadHttpModule, Telerik.Web.UI" />
</modules>
...............................
.................................

Xml file URL rewrite element format

<?xml version="1.0" standalone="yes"?>
<urlrewrites>
<rule>
<url>subscribe.html</url>
<rewrite>subscribe.aspx</rewrite>
</rule>
<rule>

    . . . . . . .

</rule>
.. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
</urlrewrites>