Sunday, June 14, 2015

Attach multiple file through the File upload control and attach to SharePoint list item on save



Uploading multiple files on save button to SharePoint  List Item 

Attachment Related tasks

File Upload Event
**************************************************************************
public void UploadButton_onClick(object sender, EventArgs e))
{
                     DataTable fileDt =new DataTable ();
                     DataRow row=null;
                     fileDt = GetFileTable();  
                     row = fileDt.NewRow();
                     row["Id"] = attachmentId;
                     row["FileName"] = fileAttachmentUpload.FileName;
                     row["FilePath"] = "";
                     row["FileContent"] = GetFileStream();  // This is File Byte stream
                     fileDt.Rows.Add(row);
                     ViewState["FilesList"] = fileDt;
}

Breaking the file in File Stream. and return the Byte array
************************ **************************************************
        /// <summary>
        /// Returning Files in byte [] array after reading by stream
        /// </summary>
        /// <returns></returns>
        public byte[] GetFileStream()
        {
            byte[] contents = null;
            try
            {
                Stream fStream = fileAttachmentUpload.PostedFile.InputStream;
                contents = new byte[fStream.Length];
                fStream.Read(contents, 0, (int)fStream.Length);
                fStream.Close();
            }
            catch (Exception ex)
            {
                errorLog.LogEntery(ex);
            }
            return contents;
        }

Attaching the files to SharePoint ListItem *************************************************************************
/// <summary>
        /// Adding Attachment Files To SharePoint ListItem
        /// </summary>
        /// <param name="Item"></param>
        public void AddAttachmentToList(SPListItem Item)
        {
            DataTable dt = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb web = SPContext.Current.Web;
                    if (ViewState["FilesList"] != null)
                    {
                        dt = (DataTable)ViewState["FilesList"];
                        foreach (DataRow row in dt.Rows)
                        {
                            byte[] fs = (byte[])row["FileContent"];
                            string fileName = (string)row["FileName"];
                             SPAttachmentCollection attachments = Item.Attachments;
                            attachments.Add(fileName, fs);
                           }
                    }
                    web.AllowUnsafeUpdates = true;
                    taskItem.Update();
                    web.AllowUnsafeUpdates = false;
                });
            }
            catch (Exception ex)
            {
                errorLog.LogEntery(ex);
            }

        }

Getting All Attachment from ListItem
************************************************************************

/// Getting all attachment from a listitem with fileName and its file url and return in Hashtable

public Hashtable GetListAttachemnts(SPListItem taskItem)
        {
            Hashtable _listItems = new Hashtable();
            try
            {

                SPAttachmentCollection attachments = taskItem.Attachments;

                foreach (var attachment in attachments)
                {
                    string attachmentAbsoluteURL = taskItem.Attachments.UrlPrefix + attachment;
                    _listItems.Add(attachment, attachmentAbsoluteURL);

                }
            }
            catch (Exception ex)
            {
                errorLog.LogEntery(ex);
            }
            return _listItems;
        }


Wednesday, June 10, 2015

Recover Lost Lookup Content after restoring the site backup or export/import of list from List Template operation in SharePoint



-------------------------------------------------------------------------------------------------
Try these steps:

Step1:  Download the STP of List template e.g.: test.stp

Step2:  Rename the STP as test.cab

Step3:  Extract the cab file.

Step4:  Change the values in manifest file after extracting the Cab

Find the Lookup values in manifest

<Field Type="Lookup" List="{Guid Value} "/>

Replace Guid value with Lists/ListName

<Field Type="Lookup"  List="Lists/ListName"/>

Step5: After saving the manifest.xml file, change it into cab file with the following command

C:\> makecab "C:\Temp\manifest.xml"  "temp.cab" /L   "C:\Temp"

Step6: After changing into Cab, rename it to STP again.

Step7: Upload the STP and create the list.

You will get your lost content.

Happy Coding




PowerShell command to configure state service in SharePoint 2010


$ErrorActionPreference = "Stop"

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

# The State Service is required in order to use the out-of-the-box workflows in
# SharePoint Server 2010 (e.g. Approval - SharePoint 2010) or any other features
# that leverage InfoPath Forms Services.
#
# When using the Farm Configuration Wizard to configure the State Service, the
# resulting database is named StateService_{GUID}. In order to avoid lengthy
# database names containing GUIDs, the State Service is configured using PowerShell.

function ConfigureStateService(
    [string] $stateServiceName = $(Throw "Value cannot be null: stateServiceName"),
    [string] $stateServiceDatabaseName =
        $(Throw "Value cannot be null: stateServiceDatabaseName"))
{
   Write-Host "Configuring the State Service..."

    Write-Debug "stateServiceName: $stateServiceName"
    Write-Debug "stateServiceDatabaseName: $stateServiceDatabaseName"

    $serviceApp = Get-SPStateServiceApplication -Identity "$stateServiceName" `
       -Debug:$false -EA 0

    If ($serviceApp -ne $null)
    {       
        Write-Host "The State Service has already been configured."
        return
    }
   
    $database = New-SPStateServiceDatabase -Name $stateServiceDatabaseName `
        -Debug:$false
               
    $serviceApp = New-SPStateServiceApplication -Name $stateServiceName `
        -Database $database -Debug:$false
               
    New-SPStateServiceApplicationProxy -ServiceApplication $serviceApp `
        -Name $stateServiceName -DefaultProxyGroup -Debug:$false > $null

                Write-Host -Fore Green "Successfully configured the State Service."
}

function Main()
{
    $stateServiceName = "State Service"
    $stateServiceDatabaseName = "StateService"

    ConfigureStateService $stateServiceName $stateServiceDatabaseName
}

Main


Thursday, June 4, 2015

Error occurred in deployment step ‘Add Solution': A feature with ID has already been installed in this farm.

Error occurred in deployment step ‘Add Solution': A feature with ID has already been installed in this farm



Error : 
Error occurred in deployment step ‘Add Solution': A feature with ID 0f92d042-22b6-4518-8c9f-3eb2ab720eed has already been installed in this farm.  Use the force attribute to explicitly re-install the feature
Reason :
The same solution/feature has been already Installed in the Farm or the site collection.
Resolution :
Find the Feature with the given Id (Here 0f92d042-22b6-4518-8c9f-3eb2ab720eed) in the solution. Open the feature in Visual Studio.
From the Property tab, Change the property “Always force Install” to “True”. Deploy the solution again…

Source: https://msbuzzz.wordpress.com/2011/09/07/error-occurred-in-deployment-step-add-solution-a-feature-with-id-has-already-been-installed-in-this-farm/

Disable Right Click on Page

<script type ="text/javascript" >


    var message = "Sorry, right-click has been disabled";

    function clickIE() { if (document.all) { (message); return false; } }
    function clickNS(e) {
        if
(document.layers || (document.getElementById && !document.all)) {
            if (e.which == 2 || e.which == 3) { (message); return false; }
        }
    }
    if (document.layers)
    { document.captureEvents(Event.MOUSEDOWN); document.onmousedown = clickNS; }
    else { document.onmouseup = clickNS; document.oncontextmenu = clickIE; }
    document.oncontextmenu = new Function("return false")

    document.onkeydown = function (ev) {
        var a;
        ev = window.event;
        if (typeof ev == "undefined") {
            alert("PLEASE DON'T USE KEYBORD");
        }
        a = ev.keyCode;

        alert("PLEASE DON'T USE KEYBORD");
        return false;
    }
    document.onkeyup = function (ev) {
        var charCode;

        if (typeof ev == "undefined") {
            ev = window.event;
            alert("PLEASE DON'T USE KEYBORD");
        } else {
            alert("PLEASE DON'T USE KEYBORD");
        }
        return false;
    }

    document.onLoad = setInterval("window.clipboardData.setData('text','')", 10);
    document.onselectstart = "return false";
    document.oncontextmenu = "return false";
   
    </script>
 <style type="text/css">
        
     @media print {
   BODY { display: none !important;}
   </style>

Exporting and Importing the Lists to other site or sub site or site in SharePoint through PowerShell


Add-PSSnapin "Microsoft.SharePoint.PowerShell"

   $sourceWebUrl = "http://adapt-proj-03:1515/pcf"
 
   #This is the destination web, where the lists will be copied to
    
   $destWebUrl  = "http://adapt-proj-03:1515/"
     
  #Location to store the export file
   $path = "C:\Navneet\Site-Backup(1515)-1-6-15\ListBackup\"
     
   #comma delimited list of List Names to copy
   $lists = @("List1","List2","List3")
    
   
   #Loop through the lists, export the list from the source, and import the list into the destination
 
  foreach($list in $lists)
  {
       "Exporting " + $sourceWebUrl + "/lists/" + $list
  
        Export-SPWeb $sourceWebUrl -ItemUrl ("lists/" + $list) -IncludeUserSecurity -IncludeVersions All -path ($path + $list + ".cmp")
  
       "Exporting complete."
    

       "Importing " + $destWebUrl + "/lists/" + $list 
    
        Import-SPWeb $destWebUrl -IncludeUserSecurity -path ($path + $list + ".cmp") -nologfile
 
       "Importing Complete"
    
 }

Changing Authentication from Windows to Claim base in SharePoint 2010


# Changing Authentication from Windows to Claim base in SharePoint 2010

$setcba = Get-SPWebApplication "http://s11:91/"
$setcba.UseClaimsAuthentication = 1;
$setcba.Update()



# For Migrating users from Windows authentication to Claim bases 

$WebAppName = “http://adapt-proj-03:1515“

#THIS SHOULD BE THE ACCOUNT THAT IS RUNNING THIS SCRIPT, WHO SHOULD ALSO BE A LOCAL ADMIN
$account = “Adaptindiaone\spadmin”

$wa = get-SPWebApplication $WebAppName

Set-SPwebApplication $wa -AuthenticationProvider (New-SPAuthenticationProvider) -Zone Default
# this will prompt about migration, CLICK YES and continue

#This step will set the admin for the site 
$wa = get-SPWebApplication $WebAppName
$account = (New-SPClaimsPrincipal -identity $account -identitytype 1).ToEncodedString()

#Once the user is added as admin, we need to set the policy so it can have the right access
$zp = $wa.ZonePolicies(“Default”)
$p = $zp.Add($account,”PSPolicy”)
$fc=$wa.PolicyRoles.GetSpecialRole(“FullControl”)
$p.PolicyRoleBindings.Add($fc)
$wa.Update()

#Final step is to trigger the user migration process
$wa = get-SPWebApplication $WebAppName
$wa.MigrateUsers($true)