http://siteurl/_vti_bin/owssvr.dll?Cmd=Display&List={LIST GUID}&XMLDATA=TRUE
Never dishearten by failure, as it will give you the experience and confidence not to commit the same mistake and to improve yourself to reach towards your goal with perfection..........
Thursday, April 26, 2012
Thursday, April 12, 2012
An Introduction to New Features in C# 5.0
An Introduction to New Features in C# 5.0
Introduction of New Features in C# 5.0
1. C# Evolution Matrix
In order to get a big picture of the whole evolution of C# language, I summarized all the key features
into a C# Evolution Matrix for your reference as below diagram shows:
In C# version 5.0, there are two key features: Async Programming and Caller Information.
2. Async Feature
Two new key words are used for Async feature: async modifier and await operator. Method markedwith async modifier is called async method. This new feature will help us a lot in async programming.
For example, in the programming of Winform, the UI thread will be blocked while we use
HttpWebRequest synchronously request any resource in the Internet. From the perspective of user
experience, we cannot interact with the form before the request is done.
private void
btnTest_Click(object sender, EventArgs e)
{
var request = WebRequest.Create(txtUrl.Text.Trim());
var content=new MemoryStream();
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
responseStream.CopyTo(content);
}
}
txtResult.Text = content.Length.ToString();
}
In the above example, after we clicked the Test button, we cannot not make any change to the form
before the txtResult textbox shows the result.
In the past, we can also use BeginGetResponse method to send async request as this sample in MSDN
shows:
http://msdn.microsoft.com/zh-cn/library/system.net.httpwebrequest.begingetresponse(v=vs.80).aspx. But it
will takes us a lot effort to realize it.
Now, we can simply use below code to do request asynchronously :
private async void
btnTest_Click(object sender, EventArgs e)
{
var request = WebRequest.Create(txtUrl.Text.Trim());
var content = new MemoryStream();
Task<WebResponse> responseTask = request.GetResponseAsync();
using (var response = await responseTask)
{
using (var
responseStream = response.GetResponseStream())
{
Task copyTask = responseStream.CopyToAsync(content);
//await operator to supends the excution of the method until the task is completed. In the meantime,
the control is returned the UI thread.
await copyTask;
}
}
txtResult.Text = content.Length.ToString();
}
The await operator is applied to the returned task. The await operator suspends execution of the
method until the task is completed. Meanwhile, control is returned to the caller of the suspended
method.
3. Caller Information
Caller Information can help us in tracing, debugging and creating diagnose tools. It will help usto avoid duplicate codes which are generally invoked in many methods for same purpose, such
as logging and tracing.
We could get the below information of caller method :
- CallerFilePathAttribute Full path of the source
file that contains the caller. This is the file path at compile time. - CallerLineNumberAttribute Line number in the
source file at which the method is called. - CallerMemberNameAttribute Method or property
name of the caller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace
ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
InsertLog("Main");
MethodB();
Console.ReadLine();
}
static void MethodA()
{
InsertLog("MethodA");
MethodB();
}
static void MethodB()
{ }
static void
InsertLog(string methodName)
{
Console.WriteLine("{0} called method B at {1}", methodName,
DateTime.Now);
}
}
}
In both Main and MethodA methods, method InsertLog is invoked for logging. Now we can change the
codes to be as per below lines:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace
ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
//InsertLog("Main");
MethodB();
Console.ReadLine();
}
static void MethodA()
{
//InsertLog("MethodA");
MethodB();
}
static void MethodB(
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
InsertLog(memberName);
}
static void
InsertLog(string methodName)
{
Console.WriteLine("{0} called method B at {1}", methodName,
DateTime.Now);
}
}
}
4. Summary
The new features in C# 5.0 will help us to code more easily and improve the productivity. Have a niceexperience with the new release of Visual Studio 11!
Creating and deploying site template(wsp) using powershell
Follwoing code to install and deploye site
# Parameter Section Start
$languagePack="{1033}" # this line is used to notify the language pack used by the sharepoint server
$path= "C:\Test\Test1\Deployment\Sites\TestSite.wsp" # path of the wsp to be read
$feature = " Test Site_Feature4" #Feature Name of the wsp to be activated which should be site as scope
$solution = " Test Site.wsp" # Solution name for the wsp which is going to be installed and deployed
$targetUrl = "http:// Test 1:22222/ Test /" # Target location of the site with its url going to be created
$targetWebAppUrl = "http:// Test 1:22222" # web application URl where the site will be deployed
$targetSiteColUrl = "http:// Test 1:22222" # site collection URl where the site will be deployed
$SiteTitle = " Test " # Title of the site which will be fetched from web template
$SiteName =" Test " # Name of the site which will be created
$SiteDesc = " Test Site" # Description of the site which will be created
# Parameter Section End
# Function Section Start # Below code is used as a timer job for the installation and retracting process
function WaitForJobToFinish([string]$SolutionFileName)
{
$JobName = "*solution-deployment*$SolutionFileName*"
$job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
if ($job -eq $null)
{
Write-Host 'Timer job not found'
}
else
{
$JobFullName = $job.Name
Write-Host -NoNewLine "Waiting to finish job $JobFullName"
while ((Get-SPTimerJob $JobFullName) -ne $null)
{
Write-Host -NoNewLine .
Start-Sleep -Seconds 2
}
Write-Host "Finished waiting for job.."
}
}
# Function Section End
# Main Section Start
Add-PsSnapin Microsoft.SharePoint.PowerShell
$user=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host "Deploying Solution Started.."
$WSP = Get-SPSolution | Where {
($solution -eq $_.Name)
}
if($WSP -eq $null) {
}
else
{
Write-Host "De-Activating feature -"$feature
Disable-SPFeature -identity $feature -Url $targetSiteColURL -Confirm:$false
Write-Host "Feature de-activated - "$feature
Write-Host "Found " $WSP " - Uninstalling."
Uninstall-SPSolution -Identity $solution -Confirm:$false
WaitForJobToFinish($solution)
Write-Host $WSP "Uninstalled."
Write-Host "removing Solution -" $solution
Remove-SPSolution -Identity $solution -Confirm:$false
WaitForJobToFinish($solution)
Write-Host "removed Solution -" $solution
Write-Host "Deleting target site -" $targetUrl
Remove-SPWEB -identity $targetUrl -Confirm:$false
Write-Host "Deleted target site - " $targetUrl
}
Write-Host "Adding Solution"
Add-SPSolution -LiteralPath $path -Confirm:$false
Write-Host "Added Solution"
Write-Host "Installing Solution"
Install-SPSolution -Identity $solution -GACDeployment -Confirm:$false
WaitForJobToFinish($solution)
Write-Host "Installed Solution"
Write-Host "Activating feature - "$feature
Enable-SPFeature -identity $feature -Url $targetWebAppURL -Confirm:$false
Write-Host "Feature activated - " $feature
#Below code finds the TemplateID for the site
$site= new-Object Microsoft.SharePoint.SPSite($targetWebAppUrl)
$loc= [System.Int32]::Parse(1033)
$templates= $site.GetWebTemplates($loc)
$templateId=""
foreach ($child in $templates)
{
if($child.Title -eq $SiteTitle)
{
$templateId= $child.Name
}
}
$site.Dispose()
Write-Host "Creating New site with templateID -" $templateId
$web = New-SPWeb -Url $targetUrl -Name $SiteName -Description $SiteDesc -AddToTopNav -Confirm:$false
Write-Host "New Site Created"
Write-Host "Applying template please wait....."
$web.ApplyWebTemplate($templateId)
$web.Dispose()
Write-Host "Site template applied successfully"
Write-Host -Fore Green "Solution deployment completed"
Write-Host "To visit the created site Browse - "-Fore Blue $targetUrl
get-pssession | remove-pssession
# Main Section End
//Using batch file to run the above script which we will name as InstallSite.ps1
Call it using batch file (.bat) which would contain follwoing code to run:
@echo off
@echo Creates and deploys Test.wsp
@echo args are folder path for solution file
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe " & ' C:\ Test \ Test \Deployment\Sites\InstallSite.ps1'
@Pause
Similarly the webparts can be deployed just we need to check the scope of the webpart. and deploying site section wont be included.
# Parameter Section Start
$languagePack="{1033}" # this line is used to notify the language pack used by the sharepoint server
$path= "C:\Test\Test1\Deployment\Sites\TestSite.wsp" # path of the wsp to be read
$feature = " Test Site_Feature4" #Feature Name of the wsp to be activated which should be site as scope
$solution = " Test Site.wsp" # Solution name for the wsp which is going to be installed and deployed
$targetUrl = "http:// Test 1:22222/ Test /" # Target location of the site with its url going to be created
$targetWebAppUrl = "http:// Test 1:22222" # web application URl where the site will be deployed
$targetSiteColUrl = "http:// Test 1:22222" # site collection URl where the site will be deployed
$SiteTitle = " Test " # Title of the site which will be fetched from web template
$SiteName =" Test " # Name of the site which will be created
$SiteDesc = " Test Site" # Description of the site which will be created
# Parameter Section End
# Function Section Start # Below code is used as a timer job for the installation and retracting process
function WaitForJobToFinish([string]$SolutionFileName)
{
$JobName = "*solution-deployment*$SolutionFileName*"
$job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
if ($job -eq $null)
{
Write-Host 'Timer job not found'
}
else
{
$JobFullName = $job.Name
Write-Host -NoNewLine "Waiting to finish job $JobFullName"
while ((Get-SPTimerJob $JobFullName) -ne $null)
{
Write-Host -NoNewLine .
Start-Sleep -Seconds 2
}
Write-Host "Finished waiting for job.."
}
}
# Function Section End
# Main Section Start
Add-PsSnapin Microsoft.SharePoint.PowerShell
$user=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host "Deploying Solution Started.."
$WSP = Get-SPSolution | Where {
($solution -eq $_.Name)
}
if($WSP -eq $null) {
}
else
{
Write-Host "De-Activating feature -"$feature
Disable-SPFeature -identity $feature -Url $targetSiteColURL -Confirm:$false
Write-Host "Feature de-activated - "$feature
Write-Host "Found " $WSP " - Uninstalling."
Uninstall-SPSolution -Identity $solution -Confirm:$false
WaitForJobToFinish($solution)
Write-Host $WSP "Uninstalled."
Write-Host "removing Solution -" $solution
Remove-SPSolution -Identity $solution -Confirm:$false
WaitForJobToFinish($solution)
Write-Host "removed Solution -" $solution
Write-Host "Deleting target site -" $targetUrl
Remove-SPWEB -identity $targetUrl -Confirm:$false
Write-Host "Deleted target site - " $targetUrl
}
Write-Host "Adding Solution"
Add-SPSolution -LiteralPath $path -Confirm:$false
Write-Host "Added Solution"
Write-Host "Installing Solution"
Install-SPSolution -Identity $solution -GACDeployment -Confirm:$false
WaitForJobToFinish($solution)
Write-Host "Installed Solution"
Write-Host "Activating feature - "$feature
Enable-SPFeature -identity $feature -Url $targetWebAppURL -Confirm:$false
Write-Host "Feature activated - " $feature
#Below code finds the TemplateID for the site
$site= new-Object Microsoft.SharePoint.SPSite($targetWebAppUrl)
$loc= [System.Int32]::Parse(1033)
$templates= $site.GetWebTemplates($loc)
$templateId=""
foreach ($child in $templates)
{
if($child.Title -eq $SiteTitle)
{
$templateId= $child.Name
}
}
$site.Dispose()
Write-Host "Creating New site with templateID -" $templateId
$web = New-SPWeb -Url $targetUrl -Name $SiteName -Description $SiteDesc -AddToTopNav -Confirm:$false
Write-Host "New Site Created"
Write-Host "Applying template please wait....."
$web.ApplyWebTemplate($templateId)
$web.Dispose()
Write-Host "Site template applied successfully"
Write-Host -Fore Green "Solution deployment completed"
Write-Host "To visit the created site Browse - "-Fore Blue $targetUrl
get-pssession | remove-pssession
# Main Section End
//Using batch file to run the above script which we will name as InstallSite.ps1
Call it using batch file (.bat) which would contain follwoing code to run:
@echo off
@echo Creates and deploys Test.wsp
@echo args are folder path for solution file
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe " & ' C:\ Test \ Test \Deployment\Sites\InstallSite.ps1'
@Pause
Similarly the webparts can be deployed just we need to check the scope of the webpart. and deploying site section wont be included.
Subscribe to:
Posts (Atom)