Home > Computers and Internet > How to upload document with custom column in sharepoint site

How to upload document with custom column in sharepoint site

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Configuration;
using System.Xml;
using System.Net;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Security.Principal;
using System.Diagnostics;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

[WebService(Namespace = "http://microsoft.com/webservices/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService
{
    public Service()
    {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    /// <summary>
    /// this function are used for upload doucuments in sharepoint sites.
    /// </summary>
    /// <param name="Client">Name of Client</param>
    /// <param name="ProposalId"> Any id for documents</param>
    /// <param name="PM"> PM name</param>
    /// <param name="BDM">BDM name</param>
    /// <param name="GH">GH name</param>
    /// <returns></returns>
    [System.Web.Services.WebMethod(Description = "Upload the Document in Sharepoint web site")]
    public string UploadDocument(string Client, string ProposalId, string PM, string BDM, string GH, string ProjectOffice)
    {

        SPSite site = null;
        SPWeb web = null;
        StringBuilder strBatch = new StringBuilder();
        string sFileIDinList;
        string msg = string.Empty;
        bool uploadFileFlag = false;
        string spServer = string.Empty;
        string sDocLib = string.Empty;
        string sRemoteFileURL = string.Empty;
        string flagPermission = string.Empty;

        try
        {

            // File name with format******
            string localFileName = ConfigurationManager.AppSettings["TemplateFilePath"].ToString();
            localFileName = localFileName + "TemplateFile.txt";
            string remoteFileName = "Proposal_" + ProposalId + ".doc";

            //Url and folder *********************
            spServer = ConfigurationManager.AppSettings["SharePointServer"];
            sDocLib = ConfigurationManager.AppSettings["DocLibrary"];

            //**********************************
            ntpc00457.Lists listService = new ntpc00457.Lists();
            listService.Url = (spServer + "/_vti_bin/lists.asmx");
            listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

            //User information********************
            ntpc00457.UserGroup userGroup = new ntpc00457.UserGroup();
            userGroup.Url = (spServer + "/_vti_bin/usergroup.asmx");
            userGroup.Credentials = System.Net.CredentialCache.DefaultCredentials;

            #region "Check blank Fields"

            if (PM.Length == 0) return "PM name should not be blank";
            if (BDM.Length == 0) return "BDM name should not be blank";
            if (GH.Length == 0) return "GH name should not be blank";
            if (Client.Length == 0) return "Client name should not be blank";
            if (ProposalId.Length == 0) return "Proposal Id should not be blank";

            #endregion

            string PMName = PM.Substring(PM.IndexOf("\\") + 1);
            string BDMName = BDM.Substring(BDM.IndexOf("\\") + 1);
            string GHName = GH.Substring(GH.IndexOf("\\") + 1);

            XmlNode PM_ID = null;
            XmlNode BDM_ID = null;
            XmlNode GH_ID = null;
            XmlNode PO_ID = null;

            #region "add user if does not exist"

            try
            {
                PM_ID = userGroup.GetUserInfo(PM);
            }
            catch (Exception)
            {
                userGroup.AddUserToGroup("Home Visitors", PMName, PM, PMName + "@nihilent.com", "Updation");
                PM_ID = userGroup.GetUserInfo(PM);
            }

            try
            {
                BDM_ID = userGroup.GetUserInfo(BDM);
            }
            catch (Exception)
            {
                userGroup.AddUserToGroup("Home Visitors", BDMName, BDM, BDMName + "@nihilent.com", "Updation");
                BDM_ID = userGroup.GetUserInfo(BDM);
            }

            try
            {
                GH_ID = userGroup.GetUserInfo(GH);
            }
            catch (Exception)
            {
                userGroup.AddUserToGroup("Home Visitors", GHName, GH, GHName + "@nihilent.com", "Updation");
                GH_ID = userGroup.GetUserInfo(GH);
            }

            try
            {
                PO_ID = userGroup.GetUserInfo(ProjectOffice);
            }
            catch (Exception)
            {
                return ProjectOffice + ": User doesnot exist in SharePoint site. Follow proper format like Domain\\User";
            }
            #endregion

            string PMID = PM_ID.FirstChild.Attributes["ID"].Value.ToString();
            string BDMID = BDM_ID.FirstChild.Attributes["ID"].Value.ToString();
            string GHID = GH_ID.FirstChild.Attributes["ID"].Value.ToString();
            string POID = PO_ID.FirstChild.Attributes["ID"].Value.ToString();

            PM = PMID + ";#" + PM;
            BDM = BDMID + ";#" + BDM;
            GH = GHID + ";#" + GH;
            ProjectOffice = POID + ";#" + ProjectOffice;

            #region "File Upload"

            string updateListFlag = string.Empty;
            System.IO.FileStream Strm = new System.IO.FileStream(localFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm);
            byte[] filecontents = reader.ReadBytes((int)Strm.Length);
            reader.Close();
            Strm.Close();
            sRemoteFileURL = (spServer + ("/"
                        + (sDocLib + ("/" + remoteFileName.TrimEnd().TrimStart().Trim()))));
            sRemoteFileURL = sRemoteFileURL.Replace(" ", "%20");
            sRemoteFileURL = sRemoteFileURL.Replace("\\", "/");
            WebClient WC = new WebClient();
            WC.Credentials = System.Net.CredentialCache.DefaultCredentials;

            //upload documents in sharepoint
            #region "Check open site and web"
            if (site != null)
            {
                site.AllowUnsafeUpdates = false;
                site.Close();
            }
            if (web != null)
            {
                web.AllowUnsafeUpdates = false;
                web.Close();
            }
            site = new SPSite(spServer);
            web = site.OpenWeb();
            site.AllowUnsafeUpdates = true;
            web.AllowUnsafeUpdates = true;

            #endregion
            //file is already exists or not
            SPDocumentLibrary docLibAll = (SPDocumentLibrary)web.Lists[sDocLib];
            foreach (SPListItem doceach in docLibAll.Items)
            {
                if (doceach.File.Name.Equals(remoteFileName))
                {
                    return "File try to upload is already exist at SharePoint";
                }
            }

            SPList list = web.Lists[sDocLib];
            SPField fldPM = list.Fields["PM"];
            SPField fldBDM = list.Fields["BDM"];
            SPField fldGH = list.Fields["GH"];
            SPField fldPO = list.Fields["ProjectOffice"];
            SPField fldPI = list.Fields["ProposalId"];
            SPField fldCN = list.Fields["ClientName"];

            fldPM.ReadOnlyField = false;
            fldBDM.ReadOnlyField = false;
            fldGH.ReadOnlyField = false;
            fldPO.ReadOnlyField = false;
            fldPI.ReadOnlyField = false;
            fldCN.ReadOnlyField = false;

            fldPM.Update();
            fldBDM.Update();
            fldGH.Update();
            fldPO.Update();
            fldPI.Update();
            fldCN.Update();

            web.Folders[sDocLib].Files.Add(remoteFileName, filecontents, true);
            SPFile doc = web.Folders[sDocLib].Files[remoteFileName];

            if (doc.CheckOutStatus != SPFile.SPCheckOutStatus.None)
            {
                doc.CheckIn("");
            }
            uploadFileFlag = true;
            #endregion

            #region "Update Custom Columns"
            sFileIDinList = sGetID(listService.Url, sDocLib, sRemoteFileURL);
            if (sFileIDinList != "")
            {
                if (strBatch.Length > 0) strBatch.Remove(0, strBatch.Length);
                strBatch.Append("<Method ID=’1′ Cmd=’Update’>");
                strBatch.Append("<Field Name = ‘ID’>" + sFileIDinList + "</Field>");
                strBatch.Append("<Field Name = ‘PM’ ReadOnly=’True’ ShowInEditForm = ‘FALSE’ >" + PM + "</Field>");
                strBatch.Append("<Field Name = ‘BDM’>" + BDM + "</Field>");
                strBatch.Append("<Field Name = ‘GH’>" + GH + "</Field>");
                strBatch.Append("<Field Name = ‘ProjectOffice’>" + ProjectOffice + "</Field>");
                strBatch.Append("<Field Name = ‘ProposalId’>" + ProposalId + "</Field>");
                strBatch.Append("<Field Name = ‘ClientName’ >" + Client + "</Field>");
                strBatch.Append("</Method>");

                XmlDocument xmlDoc = new System.Xml.XmlDocument();
                System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");
                elBatch.InnerXml = strBatch.ToString();

                System.Xml.XmlNode result = listService.UpdateListItems(sDocLib, elBatch);
                if (!result.InnerText.Equals("0x00000000"))
                {
                    msg = DeleteFile(spServer, sDocLib, sRemoteFileURL, site, web);
                    return msg;
                }
            }

            fldPM.ReadOnlyField = true;
            fldBDM.ReadOnlyField = true;
            fldGH.ReadOnlyField = true;
            fldPO.ReadOnlyField = true;
            fldPI.ReadOnlyField = true;
            fldCN.ReadOnlyField = true;

            fldPM.Update();
            fldBDM.Update();
            fldGH.Update();
            fldPO.Update();
            fldPI.Update();
            fldCN.Update();

            site.AllowUnsafeUpdates = false;
            web.AllowUnsafeUpdates = false;

            #endregion

            flagPermission = BreakRole(spServer, sDocLib, sRemoteFileURL, site, web);

            if (flagPermission.Equals("TRUE"))
            {
                flagPermission = SetPermissionsUpdate(spServer, PM, BDM, GH, ProjectOffice, sDocLib, sRemoteFileURL, site, web);

                if (flagPermission.Equals("TRUE"))
                {
                    return "File Uploaded and Permissions Setting has been Done";
                }
                else
                {
                    msg = DeleteFile(spServer, sDocLib, sRemoteFileURL, site, web);
                    return msg;
                }
            }
            else
            {
                msg = DeleteFile(spServer, sDocLib, sRemoteFileURL, site, web);
                return msg;
            }
        }
        catch (Exception ex)
        {
            if (uploadFileFlag)
            {
                msg = DeleteFile(spServer, sDocLib, sRemoteFileURL, site, web);
                return msg + ex.Message;
            }
            else
            {
                return "Error during Uploading document – " + ex.Message;
            }
        }
        finally
        {
            if (site != null)
            {
                site.AllowUnsafeUpdates = false;
                site.Close();
            }
            if (web != null)
            {
                web.AllowUnsafeUpdates = false;
                web.Close();
            }
        }

    }

    private string DeleteFile(string SiteUrl, string docLib, string fileName, SPSite site, SPWeb web)
    {

        try
        {
            site.AllowUnsafeUpdates = true;
            web.AllowUnsafeUpdates = true;
            web.Folders[docLib].Files.Delete(fileName);
            site.AllowUnsafeUpdates = false;
            web.AllowUnsafeUpdates = false;
            return "Error Occur";

        }
        catch (Exception ex)
        {
            return "Error during deleting uploaded file – " + ex.Message;
        }

    }

    private string sGetID(string sURL, string sListGUID, string sFileName)
    {
        ntpc00457.Lists L = new ntpc00457.Lists();
        L.Credentials = System.Net.CredentialCache.DefaultCredentials;
        L.Url = sURL;
        XmlDocument xmldoc = new XmlDocument();
        XmlNode query = xmldoc.CreateNode(XmlNodeType.Element, "Query", "");
        query.InnerXml = "<OrderBy><FieldRef Name=\’Modified\’  Ascending=\’False\’></FieldRef></OrderBy>\"";
        try
        {
            XmlNode caml = L.GetListItems(sListGUID, null, query, null, "1", null, null);
            string id = caml.ChildNodes[1].ChildNodes[1].Attributes["ows_ID"].Value;
            return id;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    /// <summary>
    /// This function are used for setting permission on uploaded files.
    /// </summary>
    /// <param name="absSite"></param>
    /// <param name="PM"></param>
    /// <param name="BDM"></param>
    /// <param name="GH"></param>
    /// <param name="docLibrary"></param>
    /// <param name="fileName"></param>
    public string BreakRole(string absSite, string docLibrary, string fileName, SPSite site, SPWeb web)
    {

        try
        {
            site.AllowUnsafeUpdates = true;
            web.AllowUnsafeUpdates = true;

            bool bflagPermission = false;
            string sflagPermission = string.Empty;

            fileName = fileName.Substring(fileName.LastIndexOf("/") + 1);

            SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists[docLibrary];
            bool isCompleted = false;

            foreach (SPListItem doc in docLib.Items)
            {
                if (doc.File.Name.Equals(fileName))
                {
                    try
                    {
                        if (!doc.HasUniqueRoleAssignments)
                        {
                            doc.BreakRoleInheritance(true);

                        }

                        isCompleted = true;
                        bflagPermission = true;

                    }
                    catch (Exception ex)
                    {
                        sflagPermission = ex.Message;
                    }
                }
                if (isCompleted) break;
            }

            site.AllowUnsafeUpdates = false;
            web.AllowUnsafeUpdates = false;

            if (bflagPermission)
            {
                return "TRUE";
            }
            else
            {
                return "FALSE";
            }
        }
        catch (Exception ex)
        {
            return "Error During breaking credential – " + ex.Message;
        }

    }
    public string SetPermissionsUpdate(string absSite, string PM, string BDM, string GH, string ProjectOffice, string docLibrary, string fileName, SPSite site, SPWeb web)
    {

        try
        {
            site.AllowUnsafeUpdates = true;
            web.AllowUnsafeUpdates = true;

            bool bflagPermission = false;
            string sflagPermission = string.Empty;

            PM = PM.Substring(PM.IndexOf("\\") + 1);
            BDM = BDM.Substring(BDM.IndexOf("\\") + 1);
            GH = GH.Substring(GH.IndexOf("\\") + 1);
            ProjectOffice = ProjectOffice.Substring(ProjectOffice.IndexOf("\\") + 1);

            fileName = fileName.Substring(fileName.LastIndexOf("/") + 1);

            SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists[docLibrary];
            bool isCompleted = false;

            foreach (SPListItem doc in docLib.Items)
            {
                if (doc.File.Name.Equals(fileName))
                {
                    try
                    {

                        SPRoleDefinition roleDefPM = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        SPRoleAssignment roleAsgnPM = new SPRoleAssignment("FPS" + "\\" + PM.ToString(), PM.ToString() + "@nihilent.com", PM, "");
                        roleAsgnPM.RoleDefinitionBindings.Add(roleDefPM);

                        SPRoleDefinition roleDefBDM = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        SPRoleAssignment roleAsgnBDM = new SPRoleAssignment("FPS" + "\\" + BDM.ToString(), BDM.ToString() + "@nihilent.com", BDM, "");
                        roleAsgnBDM.RoleDefinitionBindings.Add(roleDefBDM);

                        SPRoleDefinition roleDefGH = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        SPRoleAssignment roleAsgnGH = new SPRoleAssignment("FPS" + "\\" + GH.ToString(), GH.ToString() + "@nihilent.com", GH, "");
                        roleAsgnGH.RoleDefinitionBindings.Add(roleDefGH);

                        SPRoleDefinition roleDefPO = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                        SPRoleAssignment roleAsgnPO = new SPRoleAssignment("FPS" + "\\" + ProjectOffice.ToString(), ProjectOffice.ToString() + "@nihilent.com", ProjectOffice, "");
                        roleAsgnPO.RoleDefinitionBindings.Add(roleDefPO);

                        doc.RoleAssignments.Add(roleAsgnPM);
                        doc.RoleAssignments.Add(roleAsgnBDM);
                        doc.RoleAssignments.Add(roleAsgnGH);
                        doc.RoleAssignments.Add(roleAsgnPO);
                        if (doc.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                        {
                            doc.File.CheckOut();

                        }

                        doc.Update();

                        if (doc.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                        {
                            doc.File.CheckIn("");
                        }

                        isCompleted = true;
                        bflagPermission = true;
                        site.AllowUnsafeUpdates = true;
                        web.AllowUnsafeUpdates = true;

                    }
                    catch (Exception ex)
                    {
                        sflagPermission = ex.Message;
                    }
                }
                if (isCompleted) break;
            }

            if (bflagPermission)
            {
                return "TRUE";
            }
            else
            {
                return "FALSE";
            }
        }
        catch (Exception ex)
        {
            return "Error During setting Permissions – " + ex.Message;
        }

    }

}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: