Thursday 30 January 2014

Adding Document in Document Library Web part Using Sequential Workflow in Sharepoint with C# to simultaneously add Document in to another Document Library Web part in different Site Collection

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
using System.Diagnostics;
using System.Collections.Specialized;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using System.Net.Mail;
using System.Net;
using System.IO;
namespace REGTPDocuments.AddREGTPDocumentsWorkflow
{
    public sealed partial class AddREGTPDocumentsWorkflow : SequentialWorkflowActivity
    {
        public AddREGTPDocumentsWorkflow()
        {
            InitializeComponent();
        }
        private EventLog _eventLog;
        public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
        public string WMICountry, WMISharedGroups, Title, WMITags;
        private void onWorkflowItemChanged1_Invoked(object sender, ExternalDataEventArgs e)
        {
            try
            {
                WMICountry = workflowProperties.Item["WMICountry"] != null ? workflowProperties.Item["WMICountry"].ToString() : "";
                Title = workflowProperties.Item["Title"] != null ? workflowProperties.Item["Title"].ToString() : "";
                //WMITags = workflowProperties.Item["Tags"] != null ? workflowProperties.Item["Tags"].ToString() : "";

                SPListItem item = workflowProperties.Item;
                SPFile spFile = workflowProperties.Item.File;

                if (WMICountry != "")
                {
                    SPFieldLookupValueCollection countries = new SPFieldLookupValueCollection(WMICountry);

                    //loop all new collection (if new country is added)
                    foreach (SPFieldLookupValue country in countries)
                    {
                        //get country details
                        SPListItem countryItem = workflowProperties.Web.Lists["Country Sites"].GetItemById(country.LookupId);

                        string email = Convert.ToString(countryItem["Contact Email"]);
                        string contactName = Convert.ToString(countryItem["Contact Name"]);
                        string siteURL = Convert.ToString(countryItem["Site URL"]);
                        string active = Convert.ToString(countryItem["Active?"]);

                        //insert into record here
                        if (!string.IsNullOrEmpty(siteURL) && active.Trim().ToLower() == "true")
                        {
                            // Open the site
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                using (SPSite site = new SPSite(siteURL))
                                {
                                    using (SPWeb web = site.OpenWeb())
                                    {
                                        string libName = "Document";

                                        //get Document Library
                                        SPDocumentLibrary library = (SPDocumentLibrary)web.Lists[libName];
                                        SPFolder parentFolder = spFile.ParentFolder;

                                        //file inside a Folder
                                        if (false)
                                        {
                                            string foldername = string.Format(@"{0}/{1}", libName, parentFolder.Name);

                                            //ensure folder
                                            if (!web.GetFolder(foldername).Exists)
                                            {
                                                //add folder
                                                string url = library.RootFolder.ServerRelativeUrl.ToString();
                                                SPFolderCollection folders = web.GetFolder(url).SubFolders;
                                                folders.Add(foldername);
                                            }

                                            //currentFolder
                                            SPFolder currentFolder = library.RootFolder.SubFolders[foldername];

                                            //add file to folder
                                            SPFile uploadFile = currentFolder.Files.Add(item.Name, item.File.OpenBinary(), item.Properties, true);

                                            string application = Convert.ToString(item["Application"]);
                                            string docType = Convert.ToString(item["Document Type"]);

                                            if (!string.IsNullOrEmpty(application))
                                            {
                                                SPFieldLookupValue applicationLook = new SPFieldLookupValue(application);
                                                uploadFile.Item["Application"] = new SPFieldLookupValue(applicationLook.LookupId, applicationLook.LookupValue);
                                            }

                                            if (!string.IsNullOrEmpty(docType))
                                            {
                                                uploadFile.Item["Document Type"] = docType;
                                            }

                                            uploadFile.Item["PublisherItemID"] = item.ID;

                                            uploadFile.Update();
                                            uploadFile.Item.Update();
                                            currentFolder.Update();
                                        }
                                        else
                                        {
                                            SPFolder docLib = web.Folders["Document"];
                                            SPFile spFileItem = docLib.Files.Add(item.Name, item.File.OpenBinary(), item.Properties, true);

                                            //therefore, we manually CheckIN CheckOut file
                                            if (spFileItem.CheckOutType == SPFile.SPCheckOutType.None)
                                            {
                                                spFileItem.CheckOut();
                                                spFileItem.CheckIn("checkin");
                                            }
                                            else
                                            {
                                                spFileItem.CheckOut();
                                                spFileItem.CheckIn("checkin");
                                            }

                                            docLib.Update();
                                            spFileItem.Update();
                                            spFileItem.Item.Update();

                                            string application = Convert.ToString(item["Application"]);
                                            string docType = Convert.ToString(item["Document Type"]);

                                            if (!string.IsNullOrEmpty(application))
                                            {
                                                SPFieldLookupValue applicationLook = new SPFieldLookupValue(application);
                                                spFileItem.Item["ApplicationType"] = applicationLook.LookupValue;
                                            }

                                            if (!string.IsNullOrEmpty(docType))
                                            {
                                                spFileItem.Item["Document Type"] = docType;
                                            }

                                            spFileItem.Item["PublisherItemID"] = item.ID;

                                            docLib.Update();
                                            spFileItem.Update();
                                            spFileItem.Item.Update();

                                            //therefore, we manually CheckIN CheckOut file
                                            if (spFileItem.CheckOutType == SPFile.SPCheckOutType.None)
                                            {
                                                spFileItem.CheckOut();
                                                spFileItem.CheckIn("", SPCheckinType.MajorCheckIn);
                                            }
                                            else
                                            {
                                                spFileItem.CheckOut();
                                                spFileItem.CheckIn("", SPCheckinType.MajorCheckIn);
                                            }
                                        }

                                    }
                                }
                            });
                        }

                        else if (!string.IsNullOrEmpty(email))
                        {
                            //drop a mail
                            SendMail("", email, workflowProperties.Web, spFile.Name, spFile, contactName);
                        }
                    }
                }
            }
            catch (System.Exception Ex)
            {
                //Log exceptions in the Event Log
                InsertError(string.Format(@"https://wmiregtpportal.mcfcloud.com/country/CentroAmerica"), "Regtp Documents Error Message " + workflowProperties.ItemId, Ex.Message + "~" + Ex.StackTrace, "");
                _eventLog.WriteEntry("Workflow Error :" + Ex.Message.ToString(), EventLogEntryType.Information);
            }
        }

        public void SendMail(string siteURL, string mailAddress, SPWeb web, string fileName, SPFile spFile, string contactName)
        {
            //Get the Sharepoint SMTP information from the SPAdministrationWebApplication
            string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;

            string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

            //Create the mail message and supply it with from and to info
            MailMessage mailMessage = new MailMessage(smtpFrom, mailAddress);

            //Set the subject and body of the message
            mailMessage.Subject = string.Format(@"{0} - WMI BVHO Document", fileName);
            mailMessage.Body = string.Format(@"Hi {0},
                                                    {1} Attached you would find the document {2} that is shared through Walmart international BVHO", contactName, Environment.NewLine, fileName);

            //Download the content of the file with a WebClient
            WebClient webClient = new WebClient();

            //Supply the WebClient with the network credentials of our user
            webClient.Credentials = CredentialCache.DefaultNetworkCredentials;

            //Download the byte array of the file
            //byte[] data = webClient.DownloadData(insert_attachment_url);

            //Dump the byte array in a memory stream because
            //we can write it to our attachment
            MemoryStream memoryStreamOfFile = new MemoryStream(spFile.OpenBinary());

            //Add the attachment
            mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, fileName));

            //Create the SMTP client object and send the message
            SmtpClient smtpClient = new SmtpClient(smtpServer);
            smtpClient.Send(mailMessage);


            //            Microsoft.SharePoint.Utilities.SPUtility.SendEmail(web, true, false, mailAddress,
            //                                                                         string.Format(@"{0} - WMI BVHO Document", fileName),
            //                                                                         string.Format(@"Hi, <br/> <br/> Attached you would find the document {0} that is
            //                                                                        shared through Walmart international BVHO", fileName));
        }


        public void InsertError(string spSiteURL, string title, string body, string Expires)
        {
            DateTime? dateExpires = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(spSiteURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Errors"];

                        SPListItem item = list.Items.Add();

                        item["Title"] = title;
                        item["Body"] = body;

                        if (Expires != "")
                        {
                            item["Expires"] = Expires;
                        }
                        else
                        {
                            item["Expires"] = dateExpires;
                        }

                        item.Update();
                    }
                }
            });
        }


    }
}

No comments:

Post a Comment