Thursday, August 30, 2012

.ps1 Script for Packaging of SharePoint 2010 Application.


How to Deploy application on Client Machine using Power-cell Scripting ?

Steps : 

1) Take a backup of application from Site Settings ->Save Site as Template. Download .wsp at local machine.
2) Now put .wsp ,.ps1 and installer in same folder.

in installer.Bat file we have to write
============================================

cd /d %~dp0

%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -file .\Install.ps1 %1 %2 %3 %4 "%~dp0

pause

============================================
3) Now here is .ps1 script for application.
 ( We can direct run the .Ps1 by right click on .Ps1 ->Run with PowerCell )


$sp_webapp_hostheader = "EDMS"
$sp_webapp_port = "2000"
$sp_webapp_apppoolaccount = "spserver3\administrator"
$sp_webapp_databaseserver = "spserver3\administrator"
$sp_wsp_path = "spserver3:2000"
$CurrentDir = "spserver3:2000"


$file = $CurrentDir + "Install.log"
start-transcript $file
trap {stop-transcript; break}

$ErrorActionPreference = "Stop"
#=======================================================================
#Include the SharePoint cmdlets

sleep 2
Add-PsSnapin Microsoft.SharePoint.PowerShell
sleep 2

# Set Execution Policy
Set-ExecutionPolicy unrestricted
sleep 3

Write-Host ‘———————————————————--------------------------------------------------------’
Write-Host ‘ EDMS SHAREPOINT Deployment.....’
Write-Host ‘———————————————————--------------------------------------------------------’
Write-Host ‘  ’

Write-Host $sp_webapp_hostheader
Write-Host ‘  ’
Write-Host $sp_webapp_port
Write-Host ‘  ’
Write-Host $sp_webapp_apppoolaccount
Write-Host ‘  ’
Write-Host $sp_webapp_databaseserver
Write-Host ‘  ’
Write-Host $sp_wsp_path
Write-Host ‘  ’
#====================================================================
#Create Web Application
#====================================================================

$sp_webapp_name = "EDMS1_" + $sp_webapp_port
$sp_wsp_name = "EDMS1.wsp"
$sp_wsp_path =  "spserver3:2000" + $sp_wsp_name
$sp_webapp_url = "http://" + $sp_webapp_hostheader
$sp_webapp_apppool = "EDMS1" + $sp_webapp_port
$sp_webapp_databasename = $sp_webapp_name

Write-Host $sp_webapp_name
Write-Host ‘  ’
Write-Host $sp_webapp_port
Write-Host ‘  ’
Write-Host $sp_webapp_hostheader
Write-Host ‘  ’
Write-Host $sp_webapp_url
Write-Host ‘  ’
Write-Host $sp_webapp_apppool
Write-Host ‘  ’
Write-Host $sp_webapp_apppoolaccount
Write-Host ‘  ’
Write-Host $sp_webapp_databasename
Write-Host ‘  ’
Write-Host $sp_webapp_databaseserver
Write-Host ‘  ’

$sp = Get-SPWebApplication | Where {$_.DisplayName -eq $sp_webapp_name}
Write-Host ‘  ’
Write-Host $sp
Write-Host ‘’

sleep 2
if($sp -eq $null)
{

#Create a new Web Application
New-SPWebApplication -name $sp_webapp_name -Port $sp_webapp_port -HostHeader $sp_webapp_hostheader -URL $sp_webapp_url -ApplicationPool $sp_webapp_apppool -ApplicationPoolAccount $sp_webapp_apppoolaccount -DatabaseName $sp_webapp_databasename -DatabaseServer $sp_webapp_databaseserver

# display site info
Write-Host
Write-Host "Web App created" -foregroundcolor Green
Write-Host "-------------------------------------" -foregroundcolor Green
}
else
{
      Write-Host
      Write-Host "Web Application already exists, skipping this step" -foregroundcolor yellow
}

sleep 2

#====================================================================
#Create Site Collection
#====================================================================

$sp_sc_webappurl = $sp_webapp_url + ":" + $sp_webapp_port
$sp_sc_name = "EDMS1"
Write-Host ‘  ’

$targetUrl = Get-SPSite | Where-Object {$_.Url -eq $sp_sc_webappurl }
if ($targetUrl -ne $null)
{
  Write-Host "Site already exist, Deleting existing site : " $sp_sc_webappurl -foregroundcolor yellow

  Remove-SPSite -Identity $sp_sc_webappurl -Confirm:$false

  Write-Host
  Write-Host "Existing site collection deleted..." -foregroundcolor yellow
}

$err = @()
#new-SPSite -url $sp_sc_webappurl -OwnerAlias Administrator -Name $sp_sc_name -ErrorVariable err  -ErrorAction SilentlyContinue
new-SPSite -url $sp_sc_webappurl -OwnerAlias Administrator -Name $sp_sc_name -ErrorVariable err  -ErrorAction SilentlyContinue

if ($err.count > 0 )
{
[System.Console]::Clear();
Write-Host $err
}

Write-Host
Write-Host "Site collection Created..." $sp_sc_webappurl  -foregroundcolor yellow

#****************  Edms  ************

sleep 3

$sp_sc_url = $sp_webapp_url + ":" + $sp_webapp_port
$sp_wsp_name = "EDMS1.wsp"
write-host " attached"

# If solution already exists, Retract, Remove old solution and Add, Deploy new solution

$solution = Get-SPSolution $sp_wsp_name -ErrorAction SilentlyContinue
if ($solution -ne $null)
{
  Write-Host
  Write-Host "Solution already exists. " $sp_wsp_name -foregroundcolor Yellow

  $sp_wsp_name | Uninstall-SPSolution -AllWebApplications  -confirm:$false  

  Write-Host "Retracting solution..." -foregroundcolor Yellow

  # Retracting job is assigned to timer job, so we need to wait for it to complete before removing solution.

   while ( $sp_wsp_name.JobExists )
  {
   sleep 3
   write-host "."
  }

  write-host "solution retracted" -foregroundcolor yellow
  Write-Host
  Write-Host "Removing solution " $sp_wsp_name -foregroundcolor Yellow
 
    #$sp_wsp_name | Remove-SPSolution -confirm:$false
  Remove-SPSolution–Identity $sp_wsp_name -confirm:$false
  Write-Host "Removed"

}

write-host "Adding solution " -foregroundcolor yellow

$sp_wsp_name_fullPath =  $CurrentDir + $sp_wsp_name

Add-SPUserSolution -LiteralPath $sp_wsp_name_fullPath -Site $sp_sc_webappurl

write-host "Installing solution " -foregroundcolor yellow

Install-SPUserSolution –Identity $sp_wsp_name -Site $sp_sc_webappurl

Write-Host "Site Created"

sleep 30

$x = Get-SPSite $sp_sc_webappurl
write-host "1" $x
$y = $x.GetWebTemplates(1033) | Where { $_.Title -eq "EDMS1" }
write-host "  2" $y
[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")
write-host "  3"
$site= new-Object Microsoft.SharePoint.SPSite($sp_sc_webappurl)
write-host "  4" $site
$site.OpenWeb().ApplyWebTemplate($y)
write-host "  5"
$site.Dispose()

Write-Host "Done "
#====================================================================
stop-transcript

4) Now run the .bat file. Installation will be finished.

Tuesday, August 28, 2012

Getting References to Sites, Web Applications, and Other Key Objects


There are two methods to do this: one method applies when your code will be used in a console or Windows-based application; the other applies when your code will be used in a browser-hosted application, such as when you choose "Web Site" as the type of Microsoft Visual Studio project.

To work with a deployment of SharePoint Foundation by means of a browser-hosted application, your code must first establish the site context or site collection context for requests that are made to the server.

You must obtain the HTTP context of the request in the code. Microsoft recommends that you do this by using the Microsoft.SharePoint.SPContext class and its members. Some examples are as follows.

To return the current site collection, you can use the Current.SPContext.Site property.

SPSite oSiteCollection = SPContext.Current.Site;
SPWeb oWebSite = SPContext.Current.Web;
SPWeb oWebSite = SPControl.GetContextWeb(Context);
SPWeb oWebSite = this.Web;

To return the current top-level server farm object, use SPContext.Current.Site.WebApplication.Farm.

SPFarm myFarm = SPContext.Current.Site.WebApplication.Farm;
SPWeb oTopSite = SPContext.Current.Site.RootWeb;


The SPContext class has no meaning in a console or Windows-based application. If you are writing code for either of those types of applications and you want to work with a specific site collection, use the SPSite constructor to instantiate an object that represents the site collection, as in the following example.
SPSite oSiteCollection = new SPSite("http://localhost");
oSitecollection.Dispose();
// Even better, take advantage of a "using" block to ensure
// that the object is disposed.
using (SPSite oSiteCollection = new SPSite("http://localhost"))
{
   ……..
                         }

SharePoint 2010 Update List Data & Other List Data Programmatically


Update Record in Same List using Event Receiver.
 
public override void ItemAdded(SPItemEventProperties properties)
        {
    using (SPSite site = new SPSite(properties.WebUrl))
            {
                using (SPWeb web = properties.OpenWeb())
                {
                    SPList CurrentList = web.Lists[properties.ListId];
                    SPListItem item = CurrentList.GetItemById(properties.ListItemId);

   SPListItem curritem = spProductKey.GetItemById(intID);
                    curritem["LicenseKey"] = strencvalidatekey;
                    curritem["From Date"] = fromDate;
                    curritem["Is Registered"] = 1;
                    curritem["MAC Address"] = strMacAdd;
                    curritem["Processor Id"] = strProcessorID;
                    curritem["To Date"] = toDate;
                    curritem.Update();
}
    }
}

Update Record in other List using Event Receiver.

  public override void ItemAdded(SPItemEventProperties properties)
        {
  using (SPSite site = new SPSite(properties.WebUrl))
            {
                using (SPWeb web = properties.OpenWeb())
                {
   SPList spProductKey = web.Lists["Product Key Generation"];
                    SPQuery qBudgetsubList = new SPQuery();
                    qBudgetsubList.Query = @"<Where><Eq><FieldRef Name='Product_x0020_Key' /><Value Type='Text'>" + strProductKey + "</Value></Eq></Where>";
                    SPListItemCollection splist = spProductKey.GetItems(qBudgetsubList);

                    DataTable dt = new DataTable();
                    dt = splist.GetDataTable();
                    int intID = Convert.ToInt32(dt.Rows[0]["ID"]);

   SPListItem oItem = properties.ListItem;
                    oItem["Validate_x0020_Key"] = strencvalidatekey;
                    oItem.Update();
}
   }
}














Friday, August 24, 2012

SharePoint 2010 Iterating through All the webs in the site

Sometimes we need to process all webs in a site collection, as you want to do some quick fixes in the web.


//Starting point
public void ProcessAllWeb(SPSite site)
{
    using (var web = site.RootWeb)
    {
        ProcessWebRecursive(web);
    }

}

//Recursive method
private static void ProcessWebRecursive(SPWeb web)
{
    //do some processing
    //web.Lists["listName"].ItemCount

    foreach (SPWeb subWeb in web.Webs)
    {
        using (subWeb)
        {
            ProcessWebRecursive(subWeb);            
        }
    }

}
The following code snippet shows the efficient way of processing all webs in the site collection:
public void ProcessAllWeb(SPSite site)
{
    string[] allWebUrls = site.AllWebs.Names;
    foreach (string webUrl in allWebUrls)
    {
        using (SPWeb web = site.OpenWeb(webUrl))
        {
            //process web
        }
    }
}

SharePoint 2010: Hide Recently Modified Items

In SharePoint 2010 we all are familiar with the following annoying quick-launch menu:


So if we have to hide this then we have to write .css for this in master page or in .css file.

<style type="text/css">
    .s4-recentchanges
    {
        display:none;
    }
</style>

Thursday, August 23, 2012

Use of Spservices in SharePoint 2010 (SPFilterDropdown, SPCascadeDropdowns, SPDisplayRelatedInfo)


Here i have example with code. In the code first portion i have written code for Spservice method for filter the drop value Base on login User.

Second portion is for the Cascading drop-down. Following 2 are the images for this.



Third portion is for Get Related Information from other list and fill related Information .
Following 2 are the images for this.


*********************                  Code Sample                ***********************
* Write a code in SharePoint Designer

<script type="text/javascript" src="../../Style%20Library/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../../Style%20Library/jquery.SPServices-0.7.1a.js"></script>
<script type="text/javascript" src="../../Style%20Library/jquery.SPServices-0.7.1a.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

// ************   Spservice method for filter the drop value Base on log in user    **********
$().SPServices.SPFilterDropdown({
  relationshipList: "Department",
  relationshipListColumn: "Title",
  columnName: "Department",
  CAMLQuery: "<Eq><FieldRef Name='UserName'/><Value Type='Integer'><UserID Type='Integer' /></Value></Eq>",
  completefunc: null,
  debug: false
});
//**************************** This method is used for the Cascading dropdown ****************************************//

$().SPServices.SPCascadeDropdowns({
relationshipList: "BudgetDetail",
relationshipListParentColumn: "Department",
relationshipListChildColumn: "Title",
parentColumn: "Department",
childColumn: "BudgetSubCode",
debug: true
});
//*************************** END  ******************************************//

//*************************** Get Related Information from other list ******************************************//
//This method is used for when u select dropdown value based on this value filled the value on textbox value
$().SPServices.SPDisplayRelatedInfo({      
                columnName: "BudgetSubCode",
relatedList: "BudgetDetail",
relatedListColumn: "Title",
relatedColumns: ["BudgetSubName","BudgetSubAmount","BudgetCode"],
displayFormat: "list",
headerCSSClass: "ms-hidden",
                rowCSSClass:"ms-hidden",
                completefunc: SetFields
});

function SetFields(){

            var srcDivId = "SPDisplayRelatedInfo_BudgetSubCode";
            var tds = document.getElementById(srcDivId).getElementsByTagName("td");
           
            if(tds.length>0)
            {
            var Column1Data1 = tds[0].innerHTML;
            var Column1Data2 = tds[1].innerHTML;
           
            $('#ctl00_m_g_8b1ecbc0_8438_4069_92d0_34cc9235ab90_ctl00_ctl05_ctl05_ctl00_ctl00_ctl04_ctl00_ctl00_TextField')[0].value = Column1Data1;
$('#ctl00_m_g_8b1ecbc0_8438_4069_92d0_34cc9235ab90_ctl00_ctl05_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_TextField')[0].value = Column1Data2;
     
}
else
{
            $('#ctl00_m_g_8b1ecbc0_8438_4069_92d0_34cc9235ab90_ctl00_ctl05_ctl05_ctl00_ctl00_ctl04_ctl00_ctl00_TextField')[0].value = '';
$('#ctl00_m_g_8b1ecbc0_8438_4069_92d0_34cc9235ab90_ctl00_ctl05_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_TextField')[0].value = '';


}
    };  

});
//*************************** END  ******************************************//
</script>



Make a Web Application using Power Cell command(I have taken application backup using "Save site as template" )


1) Create Web Application

New-SPWebApplication -name "ApplicationName" -HostHeader "spserver" -URL "http://spserver:9009" -ApplicationPool "Test" -ApplicationPoolAccount "spserver\Administrator" -DatabaseName "ApplicationName " -DatabaseServer "spserver\sharepoint"

2) Create Site Collection

new-SPSite -url "http://spserver:9009" -OwnerAlias Administrator -Name "ApplicationName" -ErrorVariable err  -ErrorAction SilentlyContinue

3) Add Solution

Add-SPUserSolution -LiteralPath "C:\Application.wsp" -Site "http://spserver:9009"

4) Activate Solution

Install-SPUserSolution –Identity  Application .wsp -Site "http://spserver:9009"

Monday, August 20, 2012

How to Deploy Wsp at Central Admin Level ...

1 - Register WSP

Add-SPSolution “WSP Path” -ErrorVariable err -ErrorAction SilentlyContinue  

Ex : Add-SPSolution “C:\CentralLink.wsp” -ErrorVariable err -ErrorAction SilentlyContinue  

2 - Add Solution
Install-SPSolution –Identity 'WSP Name' -GACDeployment

Ex : Install-SPSolution –Identity CentralLink.wsp -GACDeployment

3 - Activate features
Enable-SPFeature "feature ID" -Url "Central Admin URL"

Ex : Enable-SPFeature "8961a1ef-ce95-4e86-bde6-4765644a9b4f" -Url "http://spserver1:2222"

Hide Help, All Site Content and Recycle Bin using CSS


/* Hide All Site Content and Recycle Bin */
.s4-specialNavLinkList
{
display:none !important;
}

.s4-help
{
display:none !important;
}

Get lookup field values in list and put into Array


string lookupValue = "1;#Lookup A;#2;#Lookup B;#3;#Lookup C;#4;#Lookup D"

string lookupValue= listItem["Columnname"].ToString();
string[] lookupValueArray = lookupValue.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

ArrayList lookupValueArrayList = new ArrayList();
for (int i = 0; i < lookupValueArray.Length; i++)
{
  i++;
  lookupValueArrayList.Add(lookupValueArray[i].ToString());
}

Event Reciver Insert Data to Another List


   public override void ItemAdded(SPItemEventProperties properties)
       {
           string strParentNo = properties.ListItem["FileNo"].ToString();

           SPList list = properties.OpenWeb().Lists["FileSeries"];
           SPListItem myListItem = list.Items.Add();
           myListItem["Title"] = strParentNo;
           myListItem.Update();
         
       }