public static SPListItem CreateLinkToDocumentFile(SPDocumentLibrary list, SPContentTypeId contentTypeId, string name, SPFieldUrlValue urlVal, string overrideIcon = null)
    {
        SPContentType contentType = list.ContentTypes[contentTypeId];
        string        extension   = "";

        if (urlVal != null && urlVal.Url != null)
        {
            extension = Path.GetExtension((urlVal.Url).Trim()).TrimStart(".".ToCharArray());
        }
        SPFolder         currentFolder = list.RootFolder;
        SPFileCollection files         = currentFolder.Files;
        string           fileUrl       = string.Concat(currentFolder.Url, "/", name, ".aspx");
        string           fileTemplate  = "<%@ Assembly Name='{0}' %>\r\n <%@ Register TagPrefix='SharePoint' Namespace='Microsoft.SharePoint.WebControls' Assembly='Microsoft.SharePoint' %>\r\n <%@ Import Namespace='System.IO' %>\r\n <%@ Import Namespace='Microsoft.SharePoint' %>\r\n <%@ Import Namespace='Microsoft.SharePoint.Utilities' %>\r\n <%@ Import Namespace='Microsoft.SharePoint.WebControls' %>\r\n <html>\r\n <head> <meta name='progid' content='SharePoint.Link' /> </head>\r\n <body>\r\n <form id='Form1' runat='server'>\r\n <SharePoint:UrlRedirector id='Redirector1' runat='server' />\r\n </form>\r\n </body>\r\n </html>";
        StringBuilder    fileContent   = new StringBuilder(fileTemplate.Length + 400);

        fileContent.AppendFormat(fileTemplate, typeof(SPDocumentLibrary).Assembly.FullName);
        Hashtable       properties = new Hashtable();
        SPContentTypeId ctId       = contentType.Id;

        properties["ContentTypeId"] = ctId.ToString();
        SPFile     file = files.Add(fileUrl, new MemoryStream((new UTF8Encoding()).GetBytes(fileContent.ToString())), properties, false, false);
        SPListItem item = file.Item;

        item[FLD_URL] = urlVal;
        if (list.Fields.Contains(g_guidIconOverride))
        {
            item[g_guidIconOverride] = string.Concat("|", overrideIcon ?? extension, "|");
        }
        item.IconOverlay = "linkoverlay.gif";
        item.UpdateOverwriteVersion();
        return(item);
    }
        /// <summary>
        ///
        /// </summary>
        /// <param name="web"></param>
        /// <param name="fileNameWithOutExtension"></param>
        /// <param name="fileName"></param>
        /// <param name="DocLib"></param>
        public void CreateWebPartPage(string fileNameWithOutExtension, string fileName, string DocLib)
        {
            SPWeb            web           = SPContext.Current.Web;
            SPFolder         libraryFolder = web.GetFolder(DocLib);
            SPFileCollection files         = libraryFolder.Files;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //string templateFilename = "spstd2.aspx";
                //string cityName = txtCityPageName.Text.Trim();
                string cityName         = fileNameWithOutExtension;
                string templateFilename = "NewCityPageLayout.aspx";
                //string hive = SPUtility.GetGenericSetupPath("15\\TEMPLATE\\" + SPContext.Current.Web.Language + "\\STS\\DOCTEMP\\SMARTPGS\\");
                string hive = "C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\15\\TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\";

                using (FileStream stream = new FileStream(hive + templateFilename, FileMode.Open))
                {
                    // SPFolder libraryFolder = web.GetFolder(DocLib);
                    //SPFileCollection files = libraryFolder.Files;
                    if (!isFileExists(files, fileName))
                    {
                        SPFile newFile = files.Add(fileName, stream);

                        SPLimitedWebPartManager wpmngr = newFile.Web.GetLimitedWebPartManager(newFile.ServerRelativeUrl, PersonalizationScope.Shared);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityDivisionHeader.dwp"), "Header", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "CitiesLeftNavigation.webpart"), "LeftColumn", 0);
                        //  wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "CityPageSummaryLinks.webpart"), "RightColumn", 0);
                        //wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityLOBs.dwp"), "MiddleColumn", 0);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Residential CEWP.dwp"), "Middle1Column", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Residential"), "Middle1Column", 1);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Commercial CEWP.dwp"), "Middle1Column", 2);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Commercial"), "Middle1Column", 3);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Industrial CEWP.dwp"), "Middle2Column", 0);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Industrial"), "Middle2Column", 1);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "Operational CEWP.dwp"), "Middle2Column", 2);
                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "TopDocumentsFromDocumentLibrary.webpart", cityName, "Operational"), "Middle2Column", 3);

                        wpmngr.AddWebPart(GetWebPartToAdd(wpmngr, "NewCityDummyDescription.dwp"), "MiddleColumn", 2);

                        AddToCitiesList(fileNameWithOutExtension);

                        lblMsg.Text += string.Format("{0} Webpage successfully created...!<br>", fileName);
                    }
                    else
                    {
                        lblMsg.Text = "page already exists...!";
                    }
                }
            });

            // updatedatainCEWP(fileName, DocLib, txtbxDivision.Text.Trim(), txtbxStateCode.Text.Trim(), fileNameWithOutExtension);
        }
Ejemplo n.º 3
0
        private static SPFile CopyExternal(SPWeb web, SPFile copyFile, string destinationFolderUrl, string destination)
        {
            //copy the source file to the external location
            web.AllowUnsafeUpdates = true;
            SPFileCollection spFiles = web.GetFolder(destinationFolderUrl).Files;

            byte[] bFile = copyFile.OpenBinary();
            spFiles.Add(SPUrlUtility.CombineUrl(destination, copyFile.Name), bFile, false);
            web.AllowUnsafeUpdates = false;

            return(web.GetFile(web.Url + "/" + destinationFolderUrl + copyFile.Name));
        }
Ejemplo n.º 4
0
        public static void UploadFile(string spsURL, string srcFile, string dstFolder, string dstFile, string comments, string pubFlag)
        {
            using (SPSite site = new SPSite(spsURL)) {
                using (SPWeb web = site.OpenWeb()) {
                    if (File.Exists(srcFile))
                    {
                        // Check dst file exist and checkOut status
                        SPFile oDstFile = web.GetFile(dstFolder + "/" + dstFile);
                        Console.WriteLine("Get file: " + srcFile);
                        if (oDstFile.Exists)
                        {
                            if (oDstFile.CheckOutStatus.ToString() == "None")
                            {
                                oDstFile.CheckOut();
                            }
                        }
                        // Read data from file to variable
                        Stream fs       = File.Open(srcFile, FileMode.Open, FileAccess.Read);
                        byte[] var_data = new byte[fs.Length];
                        fs.Read(var_data, 0, var_data.Length);
//				oDstFile.CheckOut();
                        // Write data to MOSS 2007
                        SPFolder         folder = web.GetFolder(dstFolder);
                        SPFileCollection files  = folder.Files;
                        files.Add(dstFile, var_data, true);
                        if (pubFlag == "2")
                        {
                            oDstFile.CheckIn("");
                            oDstFile.Publish(comments);
                        }
                        else if (pubFlag == "1")
                        {
                            oDstFile.CheckIn(comments);
                        }
                        else if (pubFlag == "0")
                        {
                        }
                    }
                    else
                    {
                        Console.WriteLine("File not copy: " + srcFile);
                        // ERRRRRRRRRRRRROOOOOOOOOOOOOOOOOORRRRRRRRRRR
                    } // End if srcFile Exist
                }     // SPWeb close
            }         // SPSite close
        }             // Method UploadFile close
Ejemplo n.º 5
0
        // Creates document in given list (root folder).
        // Returns true if the file was created, false if it already exists
        // or throws exception for other failure
        protected bool CreateDocument(string sFilename, string sContentType, string sList)
        {
            try
            {
                SPSite site = SPContext.Current.Site;

                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[sList];
                    // this always uses root folder
                    SPFolder         folder = web.Folders[sList];
                    SPFileCollection fcol   = folder.Files;

                    // find the template url and open
                    string sTemplate = list.ContentTypes[sContentType].DocumentTemplateUrl;
                    SPFile spf       = web.GetFile(sTemplate);
                    byte[] binFile   = spf.OpenBinary();
                    // Url for file to be created
                    string destFile = fcol.Folder.Url + "/" + sFilename;

                    // create the document and get SPFile/SPItem for
                    // new document
                    SPFile addedFile = fcol.Add(destFile, binFile, false);
                    SPItem newItem   = addedFile.Item;
                    newItem["ContentType"] = sContentType;
                    newItem.Update();
                    addedFile.Update();
                    return(true);
                }
            }
            catch (SPException spEx)
            {
                // file already exists?
                if (spEx.ErrorCode == -2130575257)
                {
                    return(false);
                }
                else
                {
                    throw spEx;
                }
            }
        }
Ejemplo n.º 6
0
        internal static SPFile AddDocument2Collection(SPFile _template, SPFileCollection _dstCollection, string _fileName)
        {
            SPFile _docFile = default(SPFile);

            using (Stream _tmpStrm = _template.OpenBinaryStream())
                using (MemoryStream _docStrm = new MemoryStream())
                {
                    byte[] _buff = new byte[_tmpStrm.Length + 200];
                    int    _leng = _tmpStrm.Read(_buff, 0, (int)_tmpStrm.Length);
                    _docStrm.Write(_buff, 0, _leng);
                    _docStrm.Position = 0;
                    WordprocessingDocument _doc = WordprocessingDocument.Open(_docStrm, true);
                    _doc.ChangeDocumentType(WordprocessingDocumentType.Document);
                    _doc.Close();
                    _docFile = _dstCollection.Add(_fileName, _docStrm, true);
                    _docStrm.Flush();
                    _docStrm.Close();
                }
            return(_docFile);
        }
Ejemplo n.º 7
0
        public static void EnsureWebpartPage(this SPWeb web, string url, string title, bool overwrite, bool useForm)
        {
            url = url.TrimStart("/".ToCharArray());

            SPFile file = null;

            if (IsAbsoluteUrl(url))
            {
                file = web.Site.RootWeb.GetFile(url);
            }
            else
            {
                file = web.GetFile(url);
            }

            if (file.Exists && !overwrite)
            {
                return;
            }

            //if (!file.Exists)
            {
                string   folderPath = Path.GetDirectoryName(url);
                SPFolder folder     = null;
                if (IsAbsoluteUrl(folderPath))
                {
                    folder = web.Site.RootWeb.GetFolder(folderPath);
                }
                else
                {
                    folder = web.GetFolder(folderPath);
                }
                if (folder == null)
                {
                    return;
                }

                var forms = folder.SubFolders.Cast <SPFolder>().FirstOrDefault(p => p.Name == "Forms");

                string templateFilename = "spstd11.aspx";
                if (useForm && forms != null && folder.Name != "Pages")
                {
                    folder = forms;
                }
                else
                {
                    templateFilename = "spstd4.aspx";
                }


                string newFilename = Path.GetFileName(url);
                string hive        = SPUtility.GetGenericSetupPath("TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\");
                using (FileStream stream = new FileStream(hive + templateFilename, FileMode.Open))
                {
                    SPFileCollection files   = folder.Files;
                    SPFile           newFile = files.Add(newFilename, stream, true);
                }
                //SPList list = web.Lists[folder.ParentListId];

                //if (list == null) return;


                //string postInformation =

                //  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +

                //  "<Method>" +

                //    "<SetList Scope=\"Request\">" + list.ID + "</SetList>" +

                //    "<SetVar Name=\"ID\">New</SetVar>" +

                //    "<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +

                //    "<SetVar Name=\"Type\">WebPartPage</SetVar>" +

                //    "<SetVar Name=\"WebPartPageTemplate\">8</SetVar>" +

                //    string.Format("<SetVar Name=\"Title\">{0}</SetVar>" , title)+

                //    "<SetVar Name=\"Overwrite\">true</SetVar>" +

                //  "</Method>";

                //web.ProcessBatchData(postInformation);
            }
        }
        public SPFileInstance Add(params object[] args)
        {
            var urlOfFile                 = TypeConverter.ToString(args.GetValue <object>(0));
            var file                      = args.GetValue <Base64EncodedByteArrayInstance>(1);
            var properties                = args.GetValue <object>(2);
            var createdBy                 = args.GetValue <object>(3);
            var modifiedBy                = args.GetValue <object>(4);
            var timeCreated               = args.GetValue <object>(5);
            var timeLastModified          = args.GetValue <object>(6);
            var checkInComment            = args.GetValue <object>(7);
            var overwrite                 = args.GetValue <object>(8);
            var requireWebFilePermissions = args.GetValue <object>(9);

            if (urlOfFile.IsNullOrWhiteSpace())
            {
                throw new JavaScriptException(this.Engine, "Error", "File Url must be specified as the first parameter.");
            }

            if (file == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "File Url must be specified as the first parameter.");
            }

            Hashtable htProperties = null;

            if (properties is HashtableInstance)
            {
                htProperties = (properties as HashtableInstance).Hashtable;
            }
            else if (properties != null && properties != Null.Value && properties != Undefined.Value)
            {
                htProperties = SPHelper.GetFieldValuesHashtableFromPropertyObject(properties);
            }

            var uCreatedBy = SPBaristaContext.Current.Web.CurrentUser;

            if (createdBy is SPUserInstance)
            {
                uCreatedBy = (createdBy as SPUserInstance).User;
            }


            var uModifiedBy = SPBaristaContext.Current.Web.CurrentUser;

            if (modifiedBy is SPUserInstance)
            {
                uModifiedBy = (modifiedBy as SPUserInstance).User;
            }

            var dtTimeCreated = DateTime.UtcNow;

            if (timeCreated is DateInstance)
            {
                dtTimeCreated = (timeCreated as DateInstance).Value;
            }
            else if (timeCreated != null && timeCreated != Null.Value && timeCreated != Undefined.Value)
            {
                dtTimeCreated = new DateInstance(this.Engine.Object.InstancePrototype, DateInstance.Parse(TypeConverter.ToString(timeCreated))).Value;
            }

            var dtTimeLastModified = DateTime.UtcNow;

            if (timeLastModified is DateInstance)
            {
                dtTimeLastModified = (timeLastModified as DateInstance).Value;
            }
            else if (timeLastModified != null && timeLastModified != Null.Value && timeLastModified != Undefined.Value)
            {
                dtTimeLastModified = new DateInstance(this.Engine.Object.InstancePrototype, DateInstance.Parse(TypeConverter.ToString(timeLastModified))).Value;
            }

            string strCheckInComment = null;

            if (checkInComment != null && checkInComment != Null.Value && checkInComment != Undefined.Value)
            {
                strCheckInComment = TypeConverter.ToString(checkInComment);
            }

            var bOverwrite = false;

            if (overwrite != null && overwrite != Null.Value && overwrite != Undefined.Value)
            {
                bOverwrite = TypeConverter.ToBoolean(overwrite);
            }

            var bRequireWebFilePermissions = false;

            if (requireWebFilePermissions != null && requireWebFilePermissions != Null.Value && requireWebFilePermissions != Undefined.Value)
            {
                bRequireWebFilePermissions = TypeConverter.ToBoolean(requireWebFilePermissions);
            }

            using (var ms = new MemoryStream(file.Data))
            {
                var result = m_fileCollection.Add(urlOfFile, ms, htProperties, uCreatedBy, uModifiedBy, dtTimeCreated, dtTimeLastModified, strCheckInComment, bOverwrite, bRequireWebFilePermissions);
                return(result == null
                    ? null
                    : new SPFileInstance(this.Engine.Object.InstancePrototype, result));
            }
        }
        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (tbxUserName.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxUserName, "User Name is required");
                tbxUserName.Focus();
            }
            else if (tbxPassword.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxPassword, "Password is required");
                tbxPassword.Focus();
            }
            else if (tbxDomain.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxDomain, "Domain is required");
                tbxDomain.Focus();
            }
            else if (tbxSharePointURL.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(tbxSharePointURL, "SharePoint Site is required");
                tbxSharePointURL.Focus();
            }
            else if (drpdnlFormLibrary.Text.Trim() == "")
            {
                errorList.Clear();
                errorList.SetError(drpdnlFormLibrary, "Formlibrary is required");
                drpdnlFormLibrary.Focus();
            }
            else
            {
                int highestFolderFileCount = 0;
                //int fileCount = 1;
                string        siteUrl         = String.Empty;
                byte[]        byteArr         = null;
                StreamReader  streamReader    = null;
                FileInfo[]    fileCollections = null;
                DirectoryInfo dirInfo         = null;
                StringBuilder fileName        = new StringBuilder();
                FileStream    fileStream      = null;

                try
                {
                    WindowsImpersonationContext wic = Utility.CreateIdentity(tbxUserName.Text.Trim(), tbxDomain.Text.Trim(), tbxPassword.Text.Trim()).Impersonate();

                    SPSite site = null;

                    //Check whether user enters full url of the site including "http"
                    if (tbxSharePointURL.Text.StartsWith("http"))
                    {
                        site = new SPSite(tbxSharePointURL.Text.Trim());
                    }
                    else
                    {
                        site = new SPSite("http://" + tbxSharePointURL.Text.Trim());
                    }
                    //MessageBox.Show(site.Url + "/" + drpdnlFormLibrary.Text.Trim());
                    SPWeb            web       = site.OpenWeb();
                    string           weburl    = web.Url;
                    SPFileCollection filesInSP = web.Files;

                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates  = true;

                    SPFile sharePointFile = null;
                    dirInfo         = new DirectoryInfo(tbxTargetFolder.Text.Trim());
                    fileCollections = dirInfo.GetFiles();

                    XmlDocument     xmlInputData = new XmlDocument();
                    XmlDataDocument xmlUserMap   = new XmlDataDocument();

                    LoadUserMapping(ref xmlUserMap);

                    //DataTable dtInputData = LoadInput2table(xmlInputData);
                    int      maxNumber     = 0;
                    SPFolder highestFolder = null;
                    string   tempSiteUrl   = String.Empty;
                    if (cbxFolderStructure.Checked)
                    {
                        highestFolder          = FileSplitUtility.GetHighestFolder(web, drpdnlFormLibrary.Text.Trim(), tbxArchiveFolderPrefix.Text, ref maxNumber);
                        highestFolderFileCount = highestFolder.Files.Count;
                        tempSiteUrl            = weburl + "/" + drpdnlFormLibrary.SelectedItem.ToString() + "/" + highestFolder.Name;
                    }
                    else
                    {
                        tempSiteUrl = weburl + "/" + drpdnlFormLibrary.SelectedItem.ToString();
                    }

                    FileUploadParam fileUploadParam = null;
                    string          currentUser     = tbxDomain.Text + "/" + tbxUserName.Text;

                    foreach (FileInfo file in fileCollections)
                    {
                        fileName.Append(file.FullName.Substring(file.DirectoryName.Length));

                        if (fileName.Length > 128)
                        {
                            fileName.Replace(fileName.ToString(), fileName.ToString().Substring(0, 124));
                            fileName.Append(file.Extension);
                        }
                        fileStream = file.Open(FileMode.Open, FileAccess.Read);
                        siteUrl    = tempSiteUrl + "/" + fileName.ToString().Substring(fileName.ToString().LastIndexOf(@"\") + 1);


                        streamReader = new StreamReader(fileStream);

                        byteArr = System.Text.Encoding.ASCII.GetBytes(streamReader.ReadToEnd());

                        string fileNameWithoutExtn = fileName.ToString().Substring(1, fileName.Length - 5);

                        try
                        {
                            //DateTime dtCreatedDate = Convert.ToDateTime("10-10-2006");//drCurrRecord["CreatedDate"]);
                            //DateTime dtModifiedDate = Convert.ToDateTime("10-10-2006");//drCurrRecord["LastModifiedDate"]);

                            //Check whether user needs folder structure to upload the files,
                            //If yes, assign values to file upload parameters
                            if (cbxFolderStructure.Checked)
                            {
                                //Assigning values to the parameters for uploading files.
                                fileUploadParam = new FileUploadParam();
                                //fileUploadParam.CreatedBy = strCreatedWinUser;
                                //fileUploadParam.ModifiedBy =strModifiedWinUser;
                                fileUploadParam.FileContent            = byteArr;
                                fileUploadParam.CurrentFileName        = fileName.ToString();
                                fileUploadParam.HighestFolderName      = highestFolder.Name;
                                fileUploadParam.HighestFolderFileCount = highestFolderFileCount;
                                fileUploadParam.FolderPrefix           = tbxArchiveFolderPrefix.Text.Trim();
                                fileUploadParam.SiteUrl    = siteUrl;
                                fileUploadParam.TargetList = web.Lists[drpdnlFormLibrary.Text.Trim()];
                                //fileUploadParam.CreatedDate =dtCreatedDate;
                                //fileUploadParam.ModifiedDate = dtModifiedDate;
                                fileUploadParam.AllowedFileLimit = int.Parse(tbxMaxFileLimit.Text);

                                sharePointFile = FileSplitUtility.UploadFilesInSharePoint(fileUploadParam);

                                if (highestFolderFileCount >= int.Parse(tbxMaxFileLimit.Text.Trim()))
                                {
                                    highestFolderFileCount = 0;
                                }
                                ++highestFolderFileCount;
                            }
                            else
                            {
                                try
                                {
                                    //SPUser creator = web.Users[strCreatedWinUser];
                                    //SPUser modifier = web.Users[strModifiedWinUser];

                                    //if (creator.LoginName != "" && modifier.LoginName != "")
                                    //{
                                    //    sharePointFile = filesInSP.Add(siteUrl, byteArr, creator, modifier, dtCreatedDate, dtModifiedDate);
                                    //}
                                    //else
                                    //{
                                    sharePointFile = filesInSP.Add(siteUrl, byteArr, true);
                                    //}
                                }
                                catch (Exception exception)
                                {
                                    LogInfo("ERROR while convertin winuser to SPUser for file:" + fileName.ToString() + "  Error:" + exception.Message);
                                    sharePointFile = filesInSP.Add(siteUrl, byteArr, true);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            if (highestFolderFileCount >= int.Parse(tbxMaxFileLimit.Text.Trim()))
                            {
                                highestFolderFileCount = 0;
                            }
                            ++highestFolderFileCount;
                        }
                        //ends here

                        fileStream.Flush();
                        fileName.Remove(0, fileName.Length);
                    }
                    wic.Undo();
                    MessageBox.Show("Uploaded Successfully", "Upload");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in  uploading the file " + fileName + Environment.NewLine +
                                    "Cannot proceed further." + Environment.NewLine +
                                    "See log file for more details in root folder", "Upload Error");
                    StreamWriter logWriter = new StreamWriter(dirInfo.Root + "/Log.txt", false);
                    logWriter.Write("Error Message: " + ex.Message + System.Environment.NewLine + "Source of Error: " + fileName);
                    logWriter.Flush();
                    return;
                }
                finally
                {
                    streamReader.Close();
                    fileStream.Close();
                }
            }
        }
Ejemplo n.º 10
0
        private string Converter(SPItemEventProperties properties)
        {
            // find the template url and open
            SPList list = properties.Web.Lists[CustomerRecordsDocumentLibrary];
            // this always uses root folder
            SPFolder         folder = properties.Web.Folders[CustomerRecordsDocumentFolder];
            SPFileCollection fcol   = folder.Files;

            // find the template url and open

            //string sTemplate = "/" + CustomerRecordsDocumentFolder + "/Forms/template.dotx"; //cannot use the one in forms folder???
            string sTemplate = "/_cts/" + ContentType + "/template.dotx";
            SPFile spfDotx   = properties.Web.GetFile(sTemplate);

            byte[] binFileDotx = spfDotx.OpenBinary();
            // Url for file to be created

            string destFile = fcol.Folder.Url + "/" + properties.ListItem["Title"] + " " + properties.ListItem["FirstName"] + ".docx";

            MemoryStream documentStream;

            using (Stream tplStream = spfDotx.OpenBinaryStream())
            {
                documentStream = new MemoryStream((int)tplStream.Length);
                CopyStream(tplStream, documentStream);
                documentStream.Position = 0L;
            }

            using (WordprocessingDocument template = WordprocessingDocument.Open(documentStream, true))
            {
                template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);

                MainDocumentPart mainPart = template.MainDocumentPart;

                mainPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(@"c:\nonssense\xxx.dotx", UriKind.Absolute));

                mainPart.Document.Save();
            }

            SPFile addedFile = fcol.Add(destFile, documentStream, true);

            SPItem newItem = addedFile.Item;

            newItem["ContentType"]        = ContentType;
            addedFile.Item["ContentType"] = ContentType;

            //0x010100728E6ABBF6164BBC9A96D73680ED991B006E7E7B2E66671049AA392BFF57A7E72C still won't work
            //newItem["ContentTypeId"] = "0x010100728E6ABBF6164BBC9A96D73680ED991B";
            //addedFile.Item["ContentTypeId"] = "0x010100728E6ABBF6164BBC9A96D73680ED991B";

            //update content type
            newItem.Update();
            addedFile.Item.SystemUpdate();

            addedFile.Item["Accountant"] = properties.ListItem["Accountant"];
            addedFile.Item["Business"]   = properties.ListItem["Business"];
            addedFile.Item["Correspondance Preference"] = properties.ListItem["CorrespondancePreference"];
            addedFile.Item["Date Captured"]             = properties.ListItem["DateCaptured"];

            newItem["Accountant"] = properties.ListItem["Accountant"];
            newItem["Business"]   = properties.ListItem["Business"];
            newItem["Correspondance Preference"] = properties.ListItem["CorrespondancePreference"];
            newItem["Date Captured"]             = properties.ListItem["DateCaptured"];

            newItem["DOB"]          = properties.ListItem["DoB"];
            newItem["Email"]        = properties.ListItem["Email"];
            newItem["Gender"]       = properties.ListItem["Gender"];
            newItem["Home"]         = properties.ListItem["Home"];
            newItem["Mobile"]       = properties.ListItem["Mobile"];
            newItem["Marital"]      = properties.ListItem["Marital"];
            newItem["Qantas"]       = properties.ListItem["Qantas"];
            newItem["RACV"]         = properties.ListItem["RACV"];
            newItem["Referrer"]     = properties.ListItem["Referrer"];
            newItem["Residential"]  = properties.ListItem["Residential"];
            newItem["Solicitor"]    = properties.ListItem["Solicitor"];
            newItem["Will"]         = properties.ListItem["Will"];
            newItem["First Name"]   = properties.ListItem["FirstName"];
            newItem["Accountant P"] = properties.ListItem["AccountantP"];
            newItem["Business P"]   = properties.ListItem["BusinessP"];
            newItem["Correspondance Preference P"] = properties.ListItem["CorrespondancePreferenceP"];
            newItem["Date of Birth P"]             = properties.ListItem["DoBP"];
            newItem["Email P"]       = properties.ListItem["EmailP"];
            newItem["First Name P"]  = properties.ListItem["FirstNameP"];
            newItem["Gender P"]      = properties.ListItem["GenderP"];
            newItem["Home P"]        = properties.ListItem["HomeP"];
            newItem["Marital P"]     = properties.ListItem["MaritalP"];
            newItem["Mobile P"]      = properties.ListItem["MobileP"];
            newItem["Qantas P"]      = properties.ListItem["QantasP"];
            newItem["RACVP"]         = properties.ListItem["RACVP"];
            newItem["Smoker P"]      = properties.ListItem["SmokerP"];
            newItem["Smoker"]        = properties.ListItem["Smoker"];
            newItem["Solicitor P"]   = properties.ListItem["SolicitorP"];
            newItem["Sur Name P"]    = properties.ListItem["SurNameP"];
            newItem["Will P"]        = properties.ListItem["WillP"];
            newItem["Residential P"] = properties.ListItem["ResidentialP"];
            //newItem["Father"] = properties.ListItem["Father"];
            //newItem["Father DOB"] = properties.ListItem["FatherDOB"];
            //newItem["Father Health"] = properties.ListItem["FatherHealth"];
            //newItem["Mother"] = properties.ListItem["Mother"];
            //newItem["Mother DOB"] = properties.ListItem["MotherDOB"];
            //newItem["Mother Health"] = properties.ListItem["MotherHealth"];
            //newItem["Brother"] = properties.ListItem["Brother"];
            //newItem["Brother DOB"] = properties.ListItem["BrotherDOB"];
            //newItem["Brother Health"] = properties.ListItem["BrotherHealth"];
            //newItem["Brother 2"] = properties.ListItem["Brother2"];
            //newItem["Brother 2 DOB"] = properties.ListItem["Brother2DOB"];
            //newItem["Brother Health 2"] = properties.ListItem["BrotherHealth2"];
            //newItem["Sister"] = properties.ListItem["Sister"];
            //newItem["Sister DOB"] = properties.ListItem["SisterDOB"];
            //newItem["Sister Health"] = properties.ListItem["SisterHealth"];
            //newItem["Sister 2"] = properties.ListItem["Sister2"];
            //newItem["Sister DOB 2"] = properties.ListItem["SisterDOB2"];
            //newItem["Sister Health 2"] = properties.ListItem["SisterHealth2"];
            //newItem["Father P"] = properties.ListItem["FatherP"];
            //newItem["Father PDOB"] = properties.ListItem["FatherPDOB"];
            //newItem["Father Health 1"] = properties.ListItem["FatherHealth1"];
            //newItem["Mother P"] = properties.ListItem["MotherP"];
            //newItem["Mother PDOB"] = properties.ListItem["MotherPDOB"];
            //newItem["Mother Health P"] = properties.ListItem["MotherHealthP"];
            //newItem["Brother P"] = properties.ListItem["BrotherP"];
            //newItem["Brother PDOB"] = properties.ListItem["BrotherPDOB"];
            //newItem["Brother Health P"] = properties.ListItem["BrotherHealthP"];
            //newItem["Brother 2 P"] = properties.ListItem["Brother2P"];
            //newItem["Brother 2 PDOB"] = properties.ListItem["Brother2PDOB"];
            //newItem["Brother Health 2 P"] = properties.ListItem["BrotherHealth2P"];
            //newItem["Sister P"] = properties.ListItem["SisterP"];
            //newItem["Sister PDOB"] = properties.ListItem["SisterPDOB"];
            //newItem["Sister P Health"] = properties.ListItem["SisterHealthP"];
            //newItem["Sister 2 P"] = properties.ListItem["Sister2P"];
            //newItem["Sister 2 PDOB"] = properties.ListItem["Sister2PDOB"];
            //newItem["Sister Health 2 P"] = properties.ListItem["SisterHealth2P"];
            //newItem["Dependants First 1"] = properties.ListItem["DependantsFirst1"];
            //newItem["Dependants Education Occupation Level 1"] = properties.ListItem["DependantsEducationOccupationLevel1"];
            //newItem["Dependants School University 1"] = properties.ListItem["DependantsSchoolUniversity1"];
            //newItem["Dependants Surname 1"] = properties.ListItem["DependantsSurName1"];
            //newItem["Dependants"] = properties.ListItem["Dependants1"];
            //newItem["Relation 1"] = properties.ListItem["Relation1"];
            //newItem["Dependants Health 1"] = properties.ListItem["DependantsHealth1"];
            //newItem["Dependants First 2"] = properties.ListItem["DependantsFirst2"];
            //newItem["Dependants Surname 2"] = properties.ListItem["DependantsSurName2"];
            //newItem["Dependants 2"] = properties.ListItem["Dependants2"];
            //newItem["Relation 2"] = properties.ListItem["DependantsSurName1ddRelation2"]; //??
            //newItem["Dependants Education Occupation Level 2"] = properties.ListItem["DependantsEducationOccupationLevel2"];
            //newItem["Dependants School University 2"] = properties.ListItem["DependantsSchoolUniversity2"];
            //newItem["Dependants Health 2"] = properties.ListItem["DependantsHealth2"];
            //newItem["Dependants First 3"] = properties.ListItem["DependantsFirst3"];
            //newItem["Dependants Surname 3"] = properties.ListItem["DependantsSurName3"];
            //newItem["Dependants 3"] = properties.ListItem["Dependants3"];
            //newItem["Relation 3"] = properties.ListItem["Relation3"];
            //newItem["Dependants Education Occupation Level 3"] = properties.ListItem["DependantsEducationOccupationLevel3"];
            //newItem["Dependants School University 3"] = properties.ListItem["DependantsSchoolUniversity3"];
            //newItem["Dependants Health 3"] = properties.ListItem["DependantsHealth3"];
            //newItem["Dependants First 4"] = properties.ListItem["DependantsFirst4"];
            //newItem["Dependants Surname 4"] = properties.ListItem["DependantsSurName4"];
            //newItem["Dependants 4"] = properties.ListItem["Dependants4"];
            //newItem["Relation 4"] = properties.ListItem["Relation4"];
            //newItem["Dependants Education Occupation Level 4"] = properties.ListItem["DependantsEducationOccupationLevel4"];
            //newItem["Dependants School University 4"] = properties.ListItem["DependantsSchoolUniversity4"];
            //newItem["Dependants Health 4"] = properties.ListItem["DependantsHealth4"];
            //newItem["Dependants First 5"] = properties.ListItem["DependantsFirst5"];
            //newItem["Dependants Surname 5"] = properties.ListItem["DependantsSurName5"];
            //newItem["Dependants 5"] = properties.ListItem["Dependants5"];
            //newItem["Relation 5"] = properties.ListItem["Relation5"];
            //newItem["Dependants Education Occupation Level 5"] = properties.ListItem["DependantsEducationOccupationLevel5"];
            //newItem["Dependants School University 5"] = properties.ListItem["DependantsSchoolUniversity5"];
            //newItem["Dependants Health 5"] = properties.ListItem["DependantsHealth5"];
            //newItem["Job Title 1"] = properties.ListItem["JobTitle1"];
            //newItem["Employment Status"] = properties.ListItem["EmploymentStatus"];
            //newItem["Employer"] = properties.ListItem["Employer"];
            //newItem["Hours Per Week"] = properties.ListItem["HoursPerWeek"];
            //newItem["Qualifications"] = properties.ListItem["Qualifications"];
            //newItem["Remuneration"] = properties.ListItem["Remuneration"];
            //newItem["Duties"] = properties.ListItem["Duties"];
            //newItem["Job Title P"] = properties.ListItem["JobTitleP"];
            //newItem["Employment Status P"] = properties.ListItem["EmploymentStatusP"];
            //newItem["Employer P"] = properties.ListItem["EmployerP"];
            //newItem["Hours Per Week P"] = properties.ListItem["HoursPerWeekP"];
            //newItem["Qualifications P"] = properties.ListItem["QualificationsP"];
            //newItem["Remuneration P"] = properties.ListItem["RemunerationP"];
            //newItem["Duties P"] = properties.ListItem["DutiesP"];
            //newItem["Health Condition"] = properties.ListItem["HealthCondition"];
            //newItem["Health Condition P"] = properties.ListItem["HealthConditionP"];
            //newItem["House"] = properties.ListItem["House"];
            //newItem["Contents"] = properties.ListItem["Contents"];
            //newItem["Super"] = properties.ListItem["Supe"];
            //newItem["Cash"] = properties.ListItem["Cash"];
            //newItem["Shares"] = properties.ListItem["Shares"];
            //newItem["Investment Properties"] = properties.ListItem["InvestmentProperties"];
            //newItem["Business Value"] = properties.ListItem["BusinessValue"];
            //newItem["Potential Inheritance"] = properties.ListItem["PotentialInheritance"];
            //newItem["Mortgage"] = properties.ListItem["Mortgage"];
            //newItem["Personal Loans"] = properties.ListItem["PersonalLoans"];
            //newItem["Credit Card Debt"] = properties.ListItem["CreditCardDebt"];
            //newItem["Investment Loans"] = properties.ListItem["InvestmentLoans"];
            //newItem["Leases"] = properties.ListItem["Leases"];
            //newItem["Business Debt"] = properties.ListItem["BusinessDebt"];
            //newItem["Liabilities"] = properties.ListItem["Liabilites"];
            //newItem["House P"] = properties.ListItem["HouseP"];
            //newItem["Contents P"] = properties.ListItem["ContentsP"];
            //newItem["Super P"] = properties.ListItem["SuperP"];
            //newItem["Cash P"] = properties.ListItem["CashP"];
            //newItem["Shares P"] = properties.ListItem["SharesP"];
            //newItem["Investment Properties P"] = properties.ListItem["InvestmentPropertiesP"];
            //newItem["Business Value P"] = properties.ListItem["BusinessValueP"];
            //newItem["Potential Inheritance P"] = properties.ListItem["PotentialInheritanceP"];
            //newItem["Mortgage P"] = properties.ListItem["MortgageP"];
            //newItem["Personal Loans P"] = properties.ListItem["PersonalLoansP"];
            //newItem["Credit Card Debt P"] = properties.ListItem["CreditCardDebtP"];
            //newItem["Investment Loans P"] = properties.ListItem["InvestmentLoansP"];
            //newItem["Leases P"] = properties.ListItem["LeasesP"];
            //newItem["Business Debt P"] = properties.ListItem["BusinessDebtP"];
            //newItem["Liabilities P"] = properties.ListItem["LiabilitesP"];
            //newItem["House J"] = properties.ListItem["HouseJ"];
            //newItem["Contents J"] = properties.ListItem["ContentsJ"];
            //newItem["Super J"] = properties.ListItem["SuperJ"];
            //newItem["Cash J"] = properties.ListItem["CashJ"];
            //newItem["Shares J"] = properties.ListItem["SharesJ"];
            //newItem["Investment Properties J"] = properties.ListItem["InvestmentPropertiesJ"];
            //newItem["Business Value J"] = properties.ListItem["BusinessValueJ"];
            //newItem["Potential Inheritance J"] = properties.ListItem["PotentialInheritanceJ"];
            //newItem["Mortgage J"] = properties.ListItem["MortgageJ"];
            //newItem["Personal Loans J"] = properties.ListItem["PersonalLoansJ"];
            //newItem["Credit Card Debt J"] = properties.ListItem["CreditCardDebtJ"];
            //newItem["Investment Loans J"] = properties.ListItem["InvestmentLoansJ"];
            //newItem["Leases J"] = properties.ListItem["LeasesJ"];
            //newItem["Business Debt J"] = properties.ListItem["BusinessDebtJ"];
            //newItem["Liabilities J"] = properties.ListItem["LiabilitesJ"];
            //newItem["Income"] = properties.ListItem["Income"];
            //newItem["Client Income"] = properties.ListItem["ClientIncome"];
            //newItem["Partner Income"] = properties.ListItem["PartnerIncome"];
            //newItem["Income Protection"] = properties.ListItem["IncomeProtection"];
            //newItem["Income Protection C"] = properties.ListItem["IncomeProtectionC"];
            //newItem["Income Protection P"] = properties.ListItem["IncomeProtectionP"];
            //newItem["Life Cover"] = properties.ListItem["LifeCover"];
            //newItem["Disable"] = properties.ListItem["Disable"];
            //newItem["Trauma"] = properties.ListItem["Trauma"];
            //newItem["Other Insured"] = properties.ListItem["OtherInsured"];
            //newItem["Life Cover P"] = properties.ListItem["LifeCoverP"];
            //newItem["Disable P"] = properties.ListItem["DisableP"];
            //newItem["Trauma P"] = properties.ListItem["TraumaP"];
            //newItem["Other Insured P"] = properties.ListItem["OtherInsuredP"];
            //newItem["Life Cover C"] = properties.ListItem["LifeCoverC"];
            //newItem["Disable C"] = properties.ListItem["DisableC"];
            //newItem["Trauma C"] = properties.ListItem["TraumaC"];
            //newItem["Other Insured C"] = properties.ListItem["OtherInsuredC"];

            newItem.Update();
            addedFile.Item.Update();
            addedFile.Update();

            return((string)addedFile.Item[SPBuiltInFieldId.EncodedAbsUrl]);
        }