Tuesday, November 27, 2012

How to Deploy Multiple Solutions using PowerShell Scropt in SharePoint 2010



$InstallDIR = "D:\CAWSP\Backup\4"
Write-Host "Working, Please wait...."
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$Dir = get-childitem $InstallDIR -Recurse
$WSPList = $Dir | where {$_.Name -like "*.wsp*"}
Foreach ($wsp in $WSPList )
{
                $WSPFullFileName = $wsp.FullName
                $WSPFileName = $wsp.Name
                clear
                Write-Host -ForegroundColor White -BackgroundColor Blue "Working on $WSPFileName"

                try
                {
                                Write-Host -ForegroundColor Green "Checking Status of Solution"
                                $output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
                }
                Catch
                {
                                $DoesSolutionExists = $_
                }
                If (($DoesSolutionExists -like "*Cannot find an SPSolution*") -and ($output.Name -notlike  "*$WSPFileName*"))
                {
                                Try
                                {
                                                Write-Host -ForegroundColor Green "Adding solution to farm"
                                                Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null

                                                Write-Host -ForegroundColor Green "Checking Status of Solution"
                                                $output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
                                                $gobal = $null
                                                if ($output.Deployed -eq $false)
                                                {
                                                                try
                                                                {
                                                                                Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
                                                                                Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
                                                                }
                                                                Catch
                                                                {
                                                                                $gobal = $_
                                                                }
                                                                If ($gobal -like "*This solution contains*")
                                                                {
                                                                                Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
                                                                                Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
                                                                }
                                                }

                                                Sleep 1
                                                $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
                                                If ($dpjobs -eq $null)
                                {
                                Write-Host -ForegroundColor Green "No solution deployment jobs found"
                                }
                                                Else
                                                {
                                                                If ($dpjobs -is [Array])
                                                                {
                                                                                Foreach ($job in $dpjobs)
                                                                                {
                                                                                                $jobName = $job.Name
                                                                                                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                                                                                                {
                                                                                                                Write-Host -ForegroundColor Yellow -NoNewLine "."  Start-Sleep -Seconds 5
                                                                                                }
                                                                                                Write-Host
                                                                                }

                                                                }
                                                Else
                                                {
                                                                                $jobName = $dpjobs.Name
                                                                                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                                                                                {
                                                                                                Write-Host -ForegroundColor Yellow -NoNewLine "." Start-Sleep -Seconds 5
                                                                                }
                                                                                Write-Host
                                                }
                                                }
                                }
                                Catch
                                {
                                                Write-Error $_
                                                Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
                                                Read-Host
                                }
                }
                Else
                {
                                $skip = $null
                                $tryagain = $null
                                Try
                                {
                                                if ($output.Deployed -eq $true)
                                                {
                                                Write-Host -ForegroundColor Green "Retracting Solution"
                                                Uninstall-SPSolution -AllWebApplications -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
                                                }
                                }
                                Catch
                                {
                                                $tryagain = $_
                                }
                                Try
                                {
                                                if ($tryagain -ne $null)
                                                {
                                                                Uninstall-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
                                                }
                                }
                                Catch
                                {
                                                Write-Host -ForegroundColor Red "Could not Retract Solution"
                                }

                                Sleep 1
                                $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
                                If ($dpjobs -eq $null)
                {
                Write-Host -ForegroundColor Green "No solution deployment jobs found"
                }
                                Else
                                {
                                                If ($dpjobs -is [Array])
                                                {
                                                                Foreach ($job in $dpjobs)
                                                                {
                                                                                $jobName = $job.Name
                                                                                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                                                                                {
                                                                                                Write-Host -ForegroundColor Yellow -NoNewLine "." Start-Sleep -Seconds 5
                                                                                }
                                                                                Write-Host
                                                                }
                                                }
                                Else
                                {
                                                                $jobName = $dpjobs.Name
                                                                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                                                                {
                                                                                Write-Host -ForegroundColor Yellow -NoNewLine "." Start-Sleep -Seconds 5
                                                                }
                                                                Write-Host
                                }
                                }                             

                                Try
                                {
                                                Write-Host -ForegroundColor Green "Removing Solution from farm"
                                                Remove-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
                                }
                                Catch
                                {
                                                $skip = $_
                                                Write-Host -ForegroundColor Red "Could not Remove Solution"
                                                Read-Host
                                }
                                if ($skip -eq $null)
                                {
                                                Try
                                                {
                                                                Write-Host -ForegroundColor Green "Adding solution to farm"
                                                                Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null
                                                                $gobal = $null
                                                                try
                                                                {
                                                                                Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
                                                                                Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
                                                                }
                                                                Catch
                                                                {
                                                                                $gobal = $_
                                                                }
                                                                If ($gobal -like "*This solution contains*")
                                                                {
                                                                                Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
                                                                                Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
                                                                }
                                                }
                                                Catch
                                                {
                                                                Write-Error $_
                                                                Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
                                                                Read-Host
                                                }

                                                Sleep 1
                                                $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
                                                If ($dpjobs -eq $null)
                                {
                                Write-Host -ForegroundColor Green "No solution deployment jobs found"
                                }
                                                Else
                                                {
                                                                If ($dpjobs -is [Array])
                                                                {
                                                                                Foreach ($job in $dpjobs)
                                                                                {
                                                                                                $jobName = $job.Name
                                                                                                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                                                                                                {
                                                                                                                Write-Host -ForegroundColor Yellow -NoNewLine "." Start-Sleep -Seconds 5
                                                                                                }
                                                                                                Write-Host
                                                                                }
                                                                }
                                                Else
                                                {
                                                                                $jobName = $dpjobs.Name
                                                                                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                                                                                {

                                                                                                Write-Host -ForegroundColor Yellow -NoNewLine "."  Start-Sleep -Seconds 5
                                                                                }
                                                                                Write-Host
                                                }
                                                }
                }
                Else
                {
                                Write-Host -ForegroundColor Red "Cannot Install $WSPFileName, Please try manually"
                                Read-Host
                }
}
}

How to Create a Site using PowerShell Script


Write-Host
# define variables for script
$SiteTitle = "Lab 1 - Getting Started"
$SiteUrl = "http://ServerName:1234/sites/HR"
$SiteTemplate = "STS#1"
# check to ensure Microsoft.SharePoint.PowerShell is loaded
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

# delete any existing site found at target URL
$targetUrl = Get-SPSite | Where-Object {$_.Url -eq $SiteUrl}
if ($targetUrl -ne $null) {
  Write-Host "Deleting existing site at" $SiteUrl
  Remove-SPSite -Identity $SiteUrl -Confirm:$false
}

# create new site at target URL
Write-Host "Creating new site at" $SiteUrl
$NewSite = New-SPSite -URL $SiteUrl -OwnerAlias Administrator -Template $SiteTemplate -Name $SiteTitle
$RootWeb = $NewSite.RootWeb

# display site info
Write-Host
Write-Host "Site created successfully" -foregroundcolor Green
Write-Host "-------------------------------------" -foregroundcolor Green
Write-Host "URL:" $RootWeb.Url -foregroundcolor Yellow
Write-Host "ID:" $RootWeb.Id.ToString() -foregroundcolor Yellow
Write-Host "Title:" $RootWeb.Title -foregroundcolor Yellow
Write-Host "-------------------------------------" -foregroundcolor Green





Hot to get SPUser from sharepoint list item fileld



using (SPSite site = new SPSite(workflowProperties.SiteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList spList = web.Lists["MySpList"];
SPQuery spQuery = new SPQuery();
                    spQuery.Query = "<Where>--</And></Where>";
                    SPListItemCollection collListItems = spList.GetItems(spQuery);
                    foreach (SPListItem listItem in collListItems)
                    {
string EmpName = GetSPUser(listItem, "UserName");
}
    }
}


public SPUser GetSPUser(SPListItem spListItem, String fieldName)
        {
            SPUser spUser = null;
            try
            {
                if (fieldName != string.Empty)
                {
                    SPFieldUser field = spListItem.Fields[fieldName] as SPFieldUser;
                    if (field != null && spListItem[fieldName] != null)
                    {
                        SPFieldUserValue fieldValue = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValue;
                        if (fieldValue != null)
                        {
                            spUser = fieldValue.User;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return spUser;
        }

How to cancel running workflows in a sharepoint list using server code.

SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    web = site.OpenWeb();
                    SPWorkflowManager manager = site.WorkflowManager;
                    SPList list = web.Lists["mySPList"];
                    SPQuery q = new SPQuery();
                    q.Query = "<Where><Eq><FieldRef Name='EmpId'/><Value Type='Number'>" +Convert.ToInt32(lblEmpId.Text) + "</Value></Eq></Where>";
                   SPListItemCollection collection = list.GetItems(q);
                    foreach (SPListItem item in collection)
                    {
      foreach (SPWorkflow workflow in manager.GetItemActiveWorkflows(item))
                        {
                            foreach (SPWorkflowTask t in workflow.Tasks)
                            {
                                t["Status"] = "Canceled";
                                t.Update();
                            }
                            SPWorkflowManager.CancelWorkflow(workflow);
                        }
                        break;
                    }
                });

Saturday, November 17, 2012

How to restrict the '/_layouts/viewlsts.aspx' page from anonymous users in SharePoint 2010

Reference Links:
Locking down Office SharePoint Server sites
C:\inetpub\wwwroot\wss\VirtualDirectories\1234\web.config
<location path="_layouts/viewlsts.aspx">
            <system.web>
                  <authorization>
                       <allow users="domainname\user1,domainname\user2"/>
                        <deny users="?" />
                        <deny users="*" />
                  </authorization>
            </system.web>
      </location>
Inline image 1

Saturday, October 20, 2012

Update Shared Document Custom Fields Using Server Object Model in SharePoint 2010 Timer Job

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Workflow;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Collections;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.Publishing;

namespace SP2010_TimerJob
{
    class SP2010_TimerJob
    {
    }

    public class SP2010_Timer_Job : SPJobDefinition
    {
        DateTime today = DateTime.Now;
        public string[] strArray;
        StringBuilder sbwfIds = new StringBuilder();
        StringBuilder sbResignationID = new StringBuilder();
        public bool isWFRunning;
        public string conString;

        public string name, passport, dept, nationality;

        #region Sql Variables
        public SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter sqlDa;
        DataTable dt;
        #endregion

        public const string JOB_DEFINITION_NAME = "SP2010_TimerJob";
        public const string JOB_DEFINITION_TITLE = "SP2010 TimerJob";

        public SP2010_Timer_Job()
        {
            Title = JOB_DEFINITION_TITLE;
        }

        public SP2010_Timer_Job(SPWebApplication webApplication)
            : base(JOB_DEFINITION_NAME, webApplication, null, SPJobLockType.Job)
        {
            Title = JOB_DEFINITION_TITLE;
        }

        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);
            SPWebApplication webApp = WebApplication;
            try
            {
                using (var site = new SPSite(webApp.Sites[0].ID))
                {
                    using (var oWebsite = site.OpenWeb())
                    {
                        //SPListCollection collLists = oWebsite.Lists;
                        SPList oList = oWebsite.Lists["Shared Documents"];
                        if (oList.Title == "Shared Documents")
                        {
                            if (oList.BaseType == SPBaseType.DocumentLibrary)
                            {
                                SPDocumentLibrary oDocumentLibrary = (SPDocumentLibrary)oList;

                                if (!oDocumentLibrary.IsCatalog && oList.BaseTemplate != SPListTemplateType.XMLForm)
                                {
                                    SPFolder folder = oWebsite.GetFolder(System.Web.Configuration.WebConfigurationManager.AppSettings["PassportCopyUrl"].ToString());
                                    if (folder.Exists)
                                    {
                                        SPFileCollection collFile = folder.Files;
                                        oWebsite.AllowUnsafeUpdates = true;
                                        foreach (SPFile oFile in collFile)
                                        {

                                            if (!Convert.ToBoolean(oFile.Item["Refiled"]))
                                            {
                                                if (oFile.Item["Employee_x0020_ID"] != null)
                                                {
                                                    PassportCopy(Convert.ToInt32(oFile.Item["Employee_x0020_ID"].ToString()));

                                                    if (!string.IsNullOrEmpty(name))
                                                    {
                                                        oFile.Item["Employee_x0020_Name"] = name.ToString().Trim();
                                                    }
                                                    oFile.Item["Refiled"] = System.Web.Configuration.WebConfigurationManager.AppSettings["Refiled"].ToString();
                                                    oFile.Item.Update();
                                                    oDocumentLibrary.Update();
                                                    oWebsite.Update();
                                                }
                                            }
                                        }
                                    }
                                    oWebsite.AllowUnsafeUpdates = false;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }


        #region Sql Connection
        public void SqlConnection()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"].ToString());

                if (con != null)
                {
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                }
            });
        }
        #endregion


        #region Stored Procedure PassportCopy

        public void PassportCopy(int EmpID)
        {
            try
            {
                SqlConnection();
                cmd = new SqlCommand("sp_PassportCopy", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@userid", EmpID); //.DbType = DbType.Int32;
                sqlDa = new SqlDataAdapter(cmd);
                dt = new DataTable();
                sqlDa.Fill(dt);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["AAA"] != null)
                        {
                            name = dt.Rows[0]["AAA"].ToString();
                        }
                        if (dt.Rows[0]["BBB"] != null)
                        {
                            passport = dt.Rows[0]["BBB"].ToString();
                        }
                        if (dt.Rows[0]["CCC"] != null)
                        {
                            dept = dt.Rows[0]["CCC"].ToString();
                        }
                        if (dt.Rows[0]["DDD"] != null)
                        {
                            nationality = dt.Rows[0]["DDD"].ToString();
                        }
                    }
                }
            }
            catch (Exception obj)
            {

            }

            finally
            {
                con.Close();
            }
        }
        #endregion
    }
}


after that go to --> C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\OWSTIMER.EXE.CONFIG  and edit and change as follows.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
  </runtime>
<appSettings>
<add key="ConnectionString" value="Data Source=Trainingsql2k8;Initial Catalog=SP2010_PRODUCTION;Trusted_Connection=True" />
<add key="PassportCopyUrl" value="/shared documents/Passport Copy" />
<add key="Refiled" value="1" />
</appSettings>
</configuration> 

note: after add above configuration file mate sure restart the SharePoint timer job service in services (start -> run -> services.msc)

following code is SharePoint 2010 timer job code

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Linq;

namespace SP2010_TimerJob.Features.SP2010_TimerJob_Feature
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("327dbb7a-1dcb-4c80-8c61-96d276660370")]
    public class SP2010_TimerJob_FeatureEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp == null) throw new Exception("webApp");

            var FCJOB = from SPJobDefinition job in webApp.JobDefinitions
                        where job.Name == SP2010_Timer_Job.JOB_DEFINITION_NAME 
                        select job;
            if (FCJOB.Count() > 0)
                FCJOB.First().Delete();


            var DailySchedule = new SPDailySchedule
            {
                BeginHour = 0,
                BeginMinute = 0,
                BeginSecond = 0,
                EndHour = 2,
            };

            var myJOb = new SP2010_Timer_Job(webApp)
            {
                Schedule =  DailySchedule,
                IsDisabled = false
            };

            myJOb.Update();
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp == null) throw new Exception("webApp");

            var FCJOB = from SPJobDefinition job in webApp.JobDefinitions
                        where job.Name == SP2010_Timer_Job.JOB_DEFINITION_NAME
                        select job;
            if (FCJOB.Count() > 0)
                FCJOB.First().Delete();
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}



Featured Post

Sent Email in C#

Sent Email in C# : //Option 1: using S ystem; using System.Net.Mail; using System.Security; using System.Text; using System.Threading.T...

Popular posts