private static void AddAppointmentEventToSpCalendar(Appointment a)
        {
            string siteUrl = "http://sp16.geek-ish.com", calendarName /*listName*/ = "Calendar1" /*"Customers"*/;

            string[] listFields = new string[] { "ID", "Title", "Start Time", "End Time" /*"FirstName", "LastName", "City", "State", "Body" */ };
            string   camlXml    = "<View><ViewFields><FieldRef Name='ID'/><FieldRef Name='Title'/><FieldRef Name='Start Time'/><FieldRef Name='Title'/>'FirstName'/><FieldRef Name='LastName'/><FieldRef Name='City'/><FieldRef Name='State'/><FieldRef Name='Body'/>*/</ViewFields></View>";

            camlXml = "<View><ViewFields><FieldRef Name='ID'/><FieldRef Name='Title'/><FieldRef Name='EventDate'/><FieldRef Name='EndDate'/></ViewFields></View>";
            System.Net.NetworkCredential creds            = new System.Net.NetworkCredential("*****@*****.**", "helloWorld55!");
            Microsoft.SharePoint.Client.ClientContext ctx = new Microsoft.SharePoint.Client.ClientContext(siteUrl)
            {
                Credentials = creds
            };
            Microsoft.SharePoint.Client.ListItemCollection lic = GetSpListItems(ctx, siteUrl, calendarName, camlXml);

            Microsoft.SharePoint.Client.ListItemCreationInformation lici = new Microsoft.SharePoint.Client.ListItemCreationInformation();
            Microsoft.SharePoint.Client.List     list = ctx.Web.Lists.GetByTitle(calendarName);
            Microsoft.SharePoint.Client.ListItem li   = list.AddItem(lici);

            //string[] trainerName = a.Trainer.Split(new char[] { ',' });
            //string trainer = string.Format("{0}. {1}", trainerName[1].Trim().Substring(0, 1), trainerName[0].Trim());
            //string apptTime = a.StartDateTime.ToString("hh:mm tt");

            li["Title"]    = a.Title; /*string.Format("{0} {1}", trainer, apptTime);*/ //"Added " + DateTime.Now.ToString();
            li["County"]   = a.County;                                                 /*"New Castle";*/
            li["CountyId"] = a.CountyId;                                               /*1;*/
            li["Trainer"]  = a.Trainer;                                                /*"Fish, Harry";*/
                                                                                       //li["TrainerId"] = 90;
            li["EventDate"] = a.StartDateTime;
            li["EndDate"]   = a.EndDateTime;                                           /*new DateTime(a.StartDateTime.Ticks + 3600000);*/
            li.Update();
            ctx.ExecuteQuery();
        }
Пример #2
0
        protected Microsoft.SharePoint.Client.ClientContext GetContext(string url)
        {
            var context = new Microsoft.SharePoint.Client.ClientContext(url);

            context.Credentials = ConfigurationManager.Instance.UserCredential;
            return(context);
        }
Пример #3
0
        public static bool DownloadFile(string psURL, string psFile, string psSavePath)
        {
            bool returnValue = false;

            try
            {
                Uri    filename       = new Uri(psURL + psFile);
                string server         = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
                string serverrelative = filename.AbsolutePath;

                Microsoft.SharePoint.Client.ClientContext   clientContext = new Microsoft.SharePoint.Client.ClientContext(server);
                Microsoft.SharePoint.Client.FileInformation f             = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, serverrelative);

                string fileName = psFile.Substring(psFile.LastIndexOf('/') + 1);

                using (var fileStream = new FileStream(psSavePath + fileName, FileMode.Create))
                {
                    f.Stream.CopyTo(fileStream);
                }

                returnValue = true;
            }
            catch
            {
                returnValue = false;
            }

            return(returnValue);
        }
Пример #4
0
 private Microsoft.SharePoint.Client.Folder OpenBaseFolder(Microsoft.SharePoint.Client.ClientContext Context)
 {
     // Open Base Folder
     Microsoft.SharePoint.Client.Folder SPBaseFolder = Context.Web.RootFolder;
     Context.Load(SPBaseFolder);
     Context.ExecuteQuery();
     return(SPBaseFolder);
 }
Пример #5
0
        public bool Validate(FileCollection sourceFiles, Microsoft.SharePoint.Client.ClientContext ctx)
        {
            int scount = 0;
            int tcount = 0;

            foreach (var sf in sourceFiles)
            {
                scount++;
                string fileName   = sf.Src;
                string folderName = sf.Folder;
                string fileUrl    = UrlUtility.Combine(ctx.Web.ServerRelativeUrl, folderName + "/" + fileName);
                var    file       = ctx.Web.GetFileByServerRelativeUrl(UrlUtility.Combine(ctx.Web.ServerRelativeUrl, folderName + "/" + fileName));
                ctx.Load(file, f => f.Exists, f => f.Length);
                ctx.ExecuteQuery();

                if (file.Exists)
                {
                    tcount++;

                    #region File - Security
                    if (sf.Security != null)
                    {
                        ctx.Load(file, f => f.ListItemAllFields);
                        ctx.ExecuteQuery();
                        bool isSecurityMatch = ValidateSecurityCSOM(ctx, sf.Security, file.ListItemAllFields);
                        if (!isSecurityMatch)
                        {
                            return(false);
                        }
                    }
                    #endregion

                    #region Overwrite validation
                    if (sf.Overwrite == false)
                    {
                        // lookup the original added file size...should be different from the one we retrieved from SharePoint since we opted to NOT overwrite
                        var files = System.IO.Directory.GetFiles(@".\framework\functional\templates");
                        foreach (var f in files)
                        {
                            if (f.Contains(sf.Src))
                            {
                                if (new System.IO.FileInfo(f).Length == file.Length)
                                {
                                    return(false);
                                }
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #6
0
        public static Task <Microsoft.SharePoint.Client.ClientContext> GetAuthenticatedContext(string sharepointSiteUrl)
        {
            // see: https://stackoverflow.com/questions/15316613/when-should-taskcompletionsourcet-be-used

            var promise = new TaskCompletionSource <Microsoft.SharePoint.Client.ClientContext>();

            UseWPFThread(() =>
            {
                var win = new System.Windows.Window();

                var webBrowser = new WebBrowser();

                win.Content = webBrowser;

                webBrowser.Navigated += (_s, _args) =>
                {
                    var cookies = CookieReader.GetCookieCollection(_args.Uri)
                                  .OfType <Cookie>();

                    var FedAuth = cookies.FirstOrDefault(c => string.Equals("FedAuth", c.Name, StringComparison.OrdinalIgnoreCase));
                    var rtfa    = cookies.FirstOrDefault(c => string.Equals("rtFa", c.Name, StringComparison.OrdinalIgnoreCase));

                    if (FedAuth != null && rtfa != null)
                    {
                        // from: http://jcardy.co.uk/creating-a-sharepoint-csom-clientcontext-with-an-authentication-cookie/
                        var context = new Microsoft.SharePoint.Client.ClientContext(_args.Uri);
                        context.ExecutingWebRequest += (sender, e) =>
                        {
                            e.WebRequestExecutor.WebRequest.Headers[HttpRequestHeader.Cookie] = "FedAuth=" + FedAuth.Value + ";rtFa=" + rtfa.Value;
                        };

                        if (!promise.Task.IsCompleted)
                        {
                            promise.SetResult(context);
                        }

                        win.Close(); // we are done so close the window
                    }
                };

                win.Closed += (_s, _args) =>
                {
                    if (!promise.Task.IsCompleted)
                    {
                        throw new Exception("Window closed before got authentication");
                    }
                };


                // make this one of the last things that happens
                webBrowser.Navigate(sharepointSiteUrl);

                win.ShowDialog();
            });// end of wpf thread

            return(promise.Task);
        }
Пример #7
0
        public async Task <DataTable> getAllJobs()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);

            spJobsite    = Convert.ToString(config.AppSettings.Settings["SharePointJobSite"].Value);
            O365UserName = Convert.ToString(config.AppSettings.Settings["O365UserName"].Value);
            joblistName  = Convert.ToString(config.AppSettings.Settings["jobListName"].Value);
            string tempString = config.AppSettings.Settings["O365Password"].Value;

            O365Password = new SecureString();
            foreach (char c in tempString)
            {
                O365Password.AppendChar(c);
            }
            using (Microsoft.SharePoint.Client.ClientContext context = new Microsoft.SharePoint.Client.ClientContext(spJobsite))
            {
                try
                {
                    context.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(O365UserName, O365Password);
                    context.Load(context.Web, w => w.Title);
                    context.ExecuteQuery();
                    Microsoft.SharePoint.Client.List list = context.Web.Lists.GetByTitle(joblistName);
                    context.Load(list);

                    Microsoft.SharePoint.Client.ListItemCollection listitems = list.GetItems(Microsoft.SharePoint.Client.CamlQuery.CreateAllItemsQuery());
                    context.Load(listitems);
                    context.ExecuteQuery();
                    DataTable dt = new DataTable();
                    dt.Columns.Add("Name", typeof(string));
                    dt.Columns.Add("JobNumber", typeof(string));
                    dt.Columns.Add("SiteUrl", typeof(string));
                    dt.Columns.Add("ProjectType", typeof(string));
                    foreach (Microsoft.SharePoint.Client.ListItem item in listitems)
                    {
                        DataRow row = dt.NewRow();
                        row["Name"]      = item["JobNumber"] + " - " + item["Title"];
                        row["JobNumber"] = item["JobNumber"];
                        Microsoft.SharePoint.Client.FieldUrlValue _url = (Microsoft.SharePoint.Client.FieldUrlValue)item["JobSiteUrl"];
                        row["SiteUrl"]     = _url.Url;
                        row["ProjectType"] = item["ProjectCategory"];
                        dt.Rows.Add(row);
                    }
                    dt.TableName = "JobSiteInfo";
                    await Task.Delay(1000);

                    return(dt);
                }

                catch (Exception ex)
                {
                    return(null);
                }
            }
        }
        static Microsoft.SharePoint.Client.ListItemCollection GetSpListItems(Microsoft.SharePoint.Client.ClientContext ctx, string siteUrl, string listName, string camlXml)//string[] listFields)
        {
            Microsoft.SharePoint.Client.List      list      = ctx.Web.Lists.GetByTitle(listName);
            Microsoft.SharePoint.Client.CamlQuery camlQuery = new Microsoft.SharePoint.Client.CamlQuery()
            {
                ViewXml = camlXml
            };
            Microsoft.SharePoint.Client.ListItemCollection lic = list.GetItems(camlQuery);

            ctx.Load(lic);
            ctx.ExecuteQuery();
            return(lic);
        }
Пример #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            URL      = textBox1.Text;
            USERNAME = textBox2.Text;
            PASSWORD = textBox3.Text;
            using (clientContextSource = new Microsoft.SharePoint.Client.ClientContext(URL))
            {
                /* For Converting Password to SecureString for Authenticating User To Sharepoint Online */

                SecureString encodedSourcepassWord = new SecureString();
                foreach (char c in PASSWORD)
                {
                    encodedSourcepassWord.AppendChar(c);
                }
                clientContextSource.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(USERNAME, encodedSourcepassWord);

                /* For Converting Password to SecureString for Authenticating User To Sharepoint Online */
                /* For Defining the Security Channel you can see in the browser in which site is open */
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                /* For Defining the Security Channel you can see in the browser in which site is open */

                // Execute the query to the server.
                try
                {
                    clientContextSource.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex);
                }

                Console.WriteLine("Connected");

                //using HtmlAgilityPack;
                string  Url = "https://spe307094.sharepoint.com";///sites/pwa/_layouts/15/AppMonitoringDetails.aspx?AppInstanceId=5d566d18-d5ce-4a4b-918c-d019c897d4c0";
                HtmlWeb web = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument doc = web.Load(Url);
                int x = 0;

                while (doc.DocumentNode.SelectNodes("//div")[x].InnerHtml != null)
                {
                    var pcode = doc.DocumentNode.SelectNodes("//div")[x].InnerHtml;
                    Console.WriteLine(pcode);
                    x++;
                }
            }
        }
Пример #10
0
        public override void Provision(Microsoft.SharePoint.Client.ClientContext context, Microsoft.SharePoint.Client.Web web)
        {
            //get the web's property bag
            var props = web.AllProperties;

            context.Load(props);
            context.ExecuteQuery();

            //set the ContosoBusinessImpact property and update
            props["ContosoBusinessImpact"] = cboSensitivity.SelectedValue;
            web.Update();
            context.ExecuteQuery();

            //call the base
            base.Provision(context, web);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // The following code gets the client context that represents the host web.
                string contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);

                // Because this is an Autohosted App, SharePoint will pass in the host Url in the querystring.
                // Therefore, we'll retrieve it so that we can use it in GetClientContextWithContextToken method call
                string hostWeb = Page.Request["SPHostUrl"];

                // Then we'll build our context, exactly as implemented in the Visual Studio template for Autohosted apps
                clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority);

                // Now we will use some pretty standard CSOM operations to enumerate the
                // document libraries in the host web...
                hostingWeb = clientContext.Web;
                Microsoft.SharePoint.Client.ListCollection libs = hostingWeb.Lists;
                clientContext.Load(hostingWeb);
                clientContext.Load(libs);
                clientContext.ExecuteQuery();
                bool foundLibrary = false;
                foreach (Microsoft.SharePoint.Client.List lib in libs)
                {
                    if (lib.BaseType == Microsoft.SharePoint.Client.BaseType.DocumentLibrary)
                    {
                        // We know that we have at least one library,
                        // so we'll set the foundLibrary variable to true...
                        foundLibrary = true;
                        // ... and add the library title to the dropdown list on the page
                        OutputLibrary.Items.Add(lib.Title);
                        CreateDocumentLink.CssClass = "tile tileOrange";
                        CreateDocumentLink.Text     = "Click here to create a document\nin the selected library";
                        CreateDocumentLink.Enabled  = true;
                    }
                }
                SiteTitle.Text = "Office Open XML (OOXML) Document Creator: " + hostingWeb.Title;
                // If no libraries have been found, inform the user
                if (!foundLibrary)
                {
                    CreateDocumentLink.CssClass = "tile tileRed";
                    CreateDocumentLink.Text     = "There are no libraries in the host Web.";
                    CreateDocumentLink.Enabled  = false;
                }
            }
        }
Пример #12
0
        private Microsoft.SharePoint.Client.Folder OpenFolder(Microsoft.SharePoint.Client.ClientContext Context, Microsoft.SharePoint.Client.Folder BaseFolder, String Name)
        {
            Microsoft.SharePoint.Client.Folder SPRootFolder = null;

            try
            {
                // Ensure SPRootFolder Exists
                SPRootFolder = BaseFolder.Folders.GetByUrl(Name);
                Context.Load(SPRootFolder);
                Context.ExecuteQuery();
            }
            catch (Microsoft.SharePoint.Client.ServerException)
            {
                // CreateSPRoot Folder
                SPRootFolder = BaseFolder.Folders.Add(Name);
                Context.Load(SPRootFolder);
                Context.ExecuteQuery();
            }

            return(SPRootFolder);
        }
Пример #13
0
 private Microsoft.SharePoint.Client.ClientContext GetClientContext(
     string accesstoken,
     string url)
 {
     try
     {
         if (string.IsNullOrEmpty(accesstoken) || string.IsNullOrEmpty(url))
         {
             throw new ArgumentNullException();
         }
         var context = new Microsoft.SharePoint.Client.ClientContext(url);
         context.ExecutingWebRequest += (sender, args) =>
         {
             args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accesstoken;
         };
         return(context);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public bool Validate(SiteSecurity source, SiteSecurity target, TokenParser parser, Microsoft.SharePoint.Client.ClientContext context)
        {
            tParser    = parser;
            cc         = context;
            XPathQuery = "/pnp:Templates/pnp:ProvisioningTemplate/pnp:Security";

            ProvisioningTemplate pt = new ProvisioningTemplate();

            pt.Security = source;
            string sSchemaXml = ExtractElementXml(pt);

            ProvisioningTemplate ptTarget = new ProvisioningTemplate();

            ptTarget.Security = target;
            string tSchemaXml = ExtractElementXml(ptTarget);

            // Use XML validation logic to compare source and target
            if (!ValidateObjectXML(sSchemaXml, tSchemaXml, null))
            {
                return(false);
            }

            return(true);
        }
Пример #15
0
 /// <summary>
 /// Iterates the row from the CSV file
 /// </summary>
 /// <param name="context">The ClientContext instance.</param>
 /// <param name="entries">The collection values per row.</param>
 /// <param name="logger">The logger.</param>
 public override void IterateCollection(Microsoft.SharePoint.Client.ClientContext context, System.Collections.ObjectModel.Collection <string> entries, LogHelper logger)
 {
     throw new NotImplementedException();
 }
Пример #16
0
        private void Download()
        {
            byte[] buffer   = new byte[buffersize];
            int    sizeread = 0;

            while (true)
            {
                try
                {
                    this.Log.Add(plmOS.Logging.Log.Levels.DEB, "Starting to download from SharePoint: " + this.URL);

                    using (Microsoft.SharePoint.Client.ClientContext SPContext = new Microsoft.SharePoint.Client.ClientContext(this.SiteURL.AbsoluteUri))
                    {
                        SPContext.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(this.Username, this.Password);

                        // Open Base Folder
                        Microsoft.SharePoint.Client.Folder SPBaseFolder = this.OpenBaseFolder(SPContext);

                        // Open Supplier Folder
                        Microsoft.SharePoint.Client.Folder SPSupplierFolder = this.OpenFolder(SPContext, SPBaseFolder, this.SupplierID);

                        // Open Project Folder
                        Microsoft.SharePoint.Client.Folder SPProjectFolder = this.OpenFolder(SPContext, SPSupplierFolder, this.ProjectID);

                        // Open Root Folder
                        Microsoft.SharePoint.Client.Folder SPRootFolder = this.OpenFolder(SPContext, SPProjectFolder, "Database");

                        // Get Listing of Transaction files on SharePoint
                        SPContext.Load(SPRootFolder.Files);
                        SPContext.ExecuteQuery();

                        // Create list of comitted Transactions
                        List <Int64> committedtransactions = new List <Int64>();

                        foreach (Microsoft.SharePoint.Client.File transactionfile in SPRootFolder.Files)
                        {
                            Int64 transactiondate = -1;

                            if (Path.GetExtension(transactionfile.Name).ToLower() == ".comitted")
                            {
                                if (Int64.TryParse(Path.GetFileNameWithoutExtension(transactionfile.Name), out transactiondate))
                                {
                                    if (!committedtransactions.Contains(transactiondate))
                                    {
                                        committedtransactions.Add(transactiondate);
                                    }
                                }
                            }
                        }

                        // Create List of Transactions that need to be Downloaded
                        List <Microsoft.SharePoint.Client.File> tobedownlaoded = new List <Microsoft.SharePoint.Client.File>();

                        foreach (Microsoft.SharePoint.Client.File transactionfile in SPRootFolder.Files)
                        {
                            Int64 transactiondate = -1;

                            if (Path.GetExtension(transactionfile.Name).ToLower() == ".zip")
                            {
                                if (Int64.TryParse(Path.GetFileNameWithoutExtension(transactionfile.Name), out transactiondate))
                                {
                                    if (committedtransactions.Contains(transactiondate))
                                    {
                                        if (!this.Downloaded.Contains(transactiondate))
                                        {
                                            tobedownlaoded.Add(transactionfile);
                                        }
                                    }
                                }
                            }
                        }

                        if (tobedownlaoded.Count > 0)
                        {
                            this.ReadingTotal  = tobedownlaoded.Count;
                            this.ReadingNumber = 0;
                            this.Reading       = true;

                            foreach (Microsoft.SharePoint.Client.File transactionfile in tobedownlaoded)
                            {
                                Int64 transactiondate = -1;

                                if (Int64.TryParse(Path.GetFileNameWithoutExtension(transactionfile.Name), out transactiondate))
                                {
                                    if (!this.Downloaded.Contains(transactiondate))
                                    {
                                        // Check if Transaction Folder Exists in Local Cache
                                        Boolean downloadneeded = true;

                                        DirectoryInfo localtransactionfolder    = new DirectoryInfo(this.LocalRootFolder.FullName + "\\" + transactiondate.ToString());
                                        DirectoryInfo localtransactiontmpfolder = new DirectoryInfo(this.LocalRootFolder.FullName + "\\" + transactiondate.ToString() + ".download");
                                        FileInfo      committed = new FileInfo(localtransactionfolder.FullName + "\\committed");

                                        if (localtransactionfolder.Exists)
                                        {
                                            if (committed.Exists)
                                            {
                                                downloadneeded = false;
                                            }
                                        }
                                        else
                                        {
                                            localtransactionfolder.Create();
                                        }

                                        if (downloadneeded)
                                        {
                                            // Download Transaction File from SharePoint
                                            FileInfo localtransactionfile = new FileInfo(this.LocalRootFolder.FullName + "\\" + transactionfile.Name);
                                            Microsoft.SharePoint.Client.FileInformation transactionfileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(SPContext, transactionfile.ServerRelativeUrl);

                                            using (FileStream sw = System.IO.File.OpenWrite(localtransactionfile.FullName))
                                            {
                                                using (transactionfileInfo.Stream)
                                                {
                                                    while ((sizeread = transactionfileInfo.Stream.Read(buffer, 0, buffersize)) > 0)
                                                    {
                                                        sw.Write(buffer, 0, sizeread);
                                                    }
                                                }
                                            }

                                            // Extract files from ZIP File
                                            if (!localtransactiontmpfolder.Exists)
                                            {
                                                localtransactiontmpfolder.Create();
                                            }
                                            else
                                            {
                                                foreach (FileInfo file in localtransactiontmpfolder.GetFiles())
                                                {
                                                    file.Delete();
                                                }
                                            }

                                            ZipFile.ExtractToDirectory(localtransactionfile.FullName, localtransactiontmpfolder.FullName);

                                            // Move XML Files to Transaction Directory
                                            foreach (FileInfo tmpxmlfile in localtransactiontmpfolder.GetFiles("*.xml"))
                                            {
                                                FileInfo xmlfile = new FileInfo(localtransactionfolder.FullName + "\\" + tmpxmlfile.Name);

                                                if (xmlfile.Exists)
                                                {
                                                    xmlfile.Delete();
                                                    xmlfile.Refresh();
                                                }

                                                tmpxmlfile.MoveTo(xmlfile.FullName);
                                            }

                                            // Move Vault Files to Vault
                                            foreach (FileInfo tmpvaultfile in localtransactiontmpfolder.GetFiles("*.dat"))
                                            {
                                                FileInfo vaultfile = new FileInfo(this.LocalVaultFolder.FullName + "\\" + tmpvaultfile.Name);

                                                if (vaultfile.Exists)
                                                {
                                                    vaultfile.Delete();
                                                    vaultfile.Refresh();
                                                }

                                                tmpvaultfile.MoveTo(vaultfile.FullName);
                                            }

                                            // Delete Temp Folder
                                            localtransactiontmpfolder.Delete(true);

                                            // Delete ZIP File
                                            localtransactionfile.Delete();

                                            // Create Committ File
                                            committed.Create();

                                            this.Downloaded.Add(transactiondate);
                                        }
                                        else
                                        {
                                            this.Downloaded.Add(transactiondate);
                                        }
                                    }
                                }

                                this.ReadingNumber++;
                            }

                            this.Reading       = false;
                            this.ReadingTotal  = 0;
                            this.ReadingNumber = 0;
                        }

                        // Set Initialised to true once done one Sync
                        if (!this.Initialised)
                        {
                            // Set to Initialised
                            this.Initialised = true;

                            // Start Upload
                            this.UploadThread = new Thread(this.Upload);
                            this.UploadThread.IsBackground = true;
                            this.UploadThread.Start();
                        }
                    }
                }
                catch (Exception e)
                {
                    this.Log.Add(plmOS.Logging.Log.Levels.ERR, "SharePoint download failed: " + e.Message);
                    this.Log.Add(plmOS.Logging.Log.Levels.DEB, "SharePoint download failed: " + e.Message + Environment.NewLine + e.StackTrace);
                }

                // Delay to next check
                Thread.Sleep(this.SyncDelay * 1000);
            }
        }
Пример #17
0
        private void Upload()
        {
            while (true)
            {
                try
                {
                    this.WritingTotal  = this.UploadQueue.Count;
                    this.WritingNumber = 0;

                    while (this.UploadQueue.Count > 0)
                    {
                        this.Writing = true;
                        this.WritingNumber++;

                        this.Log.Add(plmOS.Logging.Log.Levels.DEB, "Starting to upload to SharePoint: " + this.URL);

                        Int64 transactiondate = -1;

                        if (this.UploadQueue.TryPeek(out transactiondate))
                        {
                            DirectoryInfo transactiondir = new DirectoryInfo(this.LocalRootFolder.FullName + "\\" + transactiondate.ToString());

                            FileInfo committed = new FileInfo(transactiondir.FullName + "\\committed");

                            if (committed.Exists)
                            {
                                using (Microsoft.SharePoint.Client.ClientContext SPContext = new Microsoft.SharePoint.Client.ClientContext(this.SiteURL.AbsoluteUri))
                                {
                                    SPContext.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(this.Username, this.Password);

                                    // Open Base Folder
                                    Microsoft.SharePoint.Client.Folder SPBaseFolder = this.OpenBaseFolder(SPContext);

                                    // Open Supplier Folder
                                    Microsoft.SharePoint.Client.Folder SPSupplierFolder = this.OpenFolder(SPContext, SPBaseFolder, this.SupplierID);

                                    // Open Project Folder
                                    Microsoft.SharePoint.Client.Folder SPProjectFolder = this.OpenFolder(SPContext, SPSupplierFolder, this.ProjectID);

                                    // Open Root Folder
                                    Microsoft.SharePoint.Client.Folder SPRootFolder = this.OpenFolder(SPContext, SPProjectFolder, "Database");

                                    // Check for Transaction File on SharePoint
                                    SPContext.Load(SPRootFolder.Files);
                                    SPContext.ExecuteQuery();

                                    Boolean committedexists = false;

                                    foreach (Microsoft.SharePoint.Client.File spfile in SPRootFolder.Files)
                                    {
                                        if (spfile.Name == transactiondate.ToString() + ".committed")
                                        {
                                            committedexists = true;
                                            break;
                                        }
                                    }

                                    if (!committedexists)
                                    {
                                        // Create Temp Folder
                                        DirectoryInfo tmptransactiondir = new DirectoryInfo(transactiondir.FullName + ".upload");

                                        if (tmptransactiondir.Exists)
                                        {
                                            foreach (FileInfo file in tmptransactiondir.GetFiles())
                                            {
                                                file.Delete();
                                            }
                                        }
                                        else
                                        {
                                            tmptransactiondir.Create();
                                        }

                                        // Copy XML Files and Vault Files to temp folder
                                        foreach (FileInfo xmlfile in transactiondir.GetFiles("*.xml"))
                                        {
                                            if (xmlfile.Name.EndsWith(".file.xml"))
                                            {
                                                // Copy Vault File
                                                FileInfo vaultfile = new FileInfo(this.LocalVaultFolder.FullName + "\\" + xmlfile.Name.Replace(".file.xml", ".dat"));
                                                vaultfile.CopyTo(tmptransactiondir.FullName + "\\" + vaultfile.Name);
                                            }

                                            xmlfile.CopyTo(tmptransactiondir.FullName + "\\" + xmlfile.Name);
                                        }

                                        // Create ZIP File
                                        FileInfo transactionzipfile = new FileInfo(transactiondir.FullName + ".zip");

                                        if (transactionzipfile.Exists)
                                        {
                                            transactionzipfile.Delete();
                                        }

                                        ZipFile.CreateFromDirectory(tmptransactiondir.FullName, transactionzipfile.FullName);

                                        // Upload ZIP File
                                        using (FileStream sr = System.IO.File.OpenRead(transactionzipfile.FullName))
                                        {
                                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPContext, SPRootFolder.ServerRelativeUrl + "/" + transactionzipfile.Name, sr, true);
                                        }

                                        // Upload Comitted File
                                        using (FileStream sr = System.IO.File.OpenRead(committed.FullName))
                                        {
                                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPContext, SPRootFolder.ServerRelativeUrl + "/" + Path.GetFileNameWithoutExtension(transactionzipfile.Name) + ".comitted", sr, true);
                                        }

                                        // Delete ZIP File
                                        transactionzipfile.Delete();

                                        // Delete Temp Folder
                                        tmptransactiondir.Delete(true);
                                    }

                                    // Completed - remove Transaction from Queue
                                    this.UploadQueue.TryDequeue(out transactiondate);
                                }
                            }
                        }

                        this.Writing = false;
                    }
                }
                catch (Exception e)
                {
                    this.Log.Add(plmOS.Logging.Log.Levels.ERR, "SharePoint upload failed: " + e.Message);
                    this.Writing = false;
                }

                // Sleep
                Thread.Sleep(500);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // The following code gets the client context that represents the host web.
                string contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);

                // Because this is an Autohosted App, SharePoint will pass in the host Url in the querystring.
                // Therefore, we'll retrieve it so that we can use it in GetClientContextWithContextToken method call
                string hostWeb = Page.Request["SPHostUrl"];

                // Then we'll build our context, exactly as implemented in the Visual Studio template for Autohosted apps
                clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority);

                    // Now we will use some pretty standard CSOM operations to enumerate the
                    // document libraries in the host web...
                    hostingWeb = clientContext.Web;
                    Microsoft.SharePoint.Client.ListCollection libs = hostingWeb.Lists;
                    clientContext.Load(hostingWeb);
                    clientContext.Load(libs);
                    clientContext.ExecuteQuery();
                    bool foundLibrary = false;
                    foreach (Microsoft.SharePoint.Client.List lib in libs)
                    {
                        if (lib.BaseType == Microsoft.SharePoint.Client.BaseType.DocumentLibrary)
                        {
                            // We know that we have at least one library,
                            // so we'll set the foundLibrary variable to true...
                            foundLibrary = true;
                            // ... and add the library title to the dropdown list on the page
                            OutputLibrary.Items.Add(lib.Title);
                            CreateDocumentLink.CssClass = "tile tileOrange";
                            CreateDocumentLink.Text = "Click here to create a document\nin the selected library";
                            CreateDocumentLink.Enabled = true;
                        }
                    }
                    SiteTitle.Text = "Office Open XML (OOXML) Document Creator: " + hostingWeb.Title;
                    // If no libraries have been found, inform the user
                    if (!foundLibrary)
                    {
                        CreateDocumentLink.CssClass = "tile tileRed";
                        CreateDocumentLink.Text = "There are no libraries in the host Web.";
                        CreateDocumentLink.Enabled = false;
                    }

            }
        }
Пример #19
0
 /// <summary>
 /// Iterates the row from the CSV file
 /// </summary>
 /// <param name="tag">The tag.</param>
 /// <param name="context">The ClientContext instance.</param>
 /// <param name="entries">The collection values per row.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 public override Task IterateCollectionAsync(object tag, Microsoft.SharePoint.Client.ClientContext context, Collection <string> entries) => throw new NotImplementedException();
Пример #20
0
        public Login()
        {
            InitializeComponent();
            logger = new LogWriter("Login Form Opened");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("es");
            DSL       obj      = new DSL();
            DataTable category = obj.getCategories();
            DataRow   cat_row  = category.NewRow();

            cat_row["CategoryID"]   = -1;
            cat_row["CategoryName"] = "--Select--";
            category.Rows.InsertAt(cat_row, 0);
            cmxCategory.DataSource    = category;
            cmxCategory.DisplayMember = "CategoryName";
            cmxCategory.ValueMember   = "CategoryID";
            DataTable categoryRC     = obj.getCategories();
            DataRow   categoryRC_row = categoryRC.NewRow();

            categoryRC_row["CategoryID"]   = -1;
            categoryRC_row["CategoryName"] = "--Select--";
            categoryRC.Rows.InsertAt(categoryRC_row, 0);
            cmbxPositionRC.DataSource    = categoryRC;
            cmbxPositionRC.DisplayMember = "CategoryName";
            cmbxPositionRC.ValueMember   = "CategoryID";
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork          += Worker_DoWork;
            worker.ProgressChanged += Worker_ProgressChanged;
            // worker.RunWorkerAsync();
            qrcode = new QRCodeWinForm();
            QRCode_Panel.Controls.Add(qrcode);
            Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

            spJobsite       = Convert.ToString(config.AppSettings.Settings["SharePointJobSite"].Value);
            spCandidateSite = Convert.ToString(config.AppSettings.Settings["SharePointSafetySite"].Value);
            CandidateList   = Convert.ToString(config.AppSettings.Settings["quizListName"].Value);
            O365UserName    = Convert.ToString(config.AppSettings.Settings["O365UserName"].Value);
            string tempString = config.AppSettings.Settings["O365Password"].Value;

            O365Password = new SecureString();
            candidates   = new DataTable();
            candidates.Columns.Add("CandidateID", typeof(string));
            candidates.Columns.Add("First_name", typeof(string));
            candidates.Columns.Add("Last_name", typeof(string));
            candidates.Columns.Add("Job", typeof(string));
            candidates.Columns.Add("Hire_Status", typeof(string));
            candidates.Columns.Add("FolderURL", typeof(string));
            candidates.Columns.Add("Remaining_Test", typeof(string));
            candidates.Columns.Add("DisplayCombobox", typeof(string));
            candidates.Columns.Add("Category", typeof(string));
            candidates.Columns.Add("Date", typeof(string));
            candidates.Columns.Add("DOB", typeof(string));
            foreach (char c in tempString)
            {
                O365Password.AppendChar(c);
            }

            JobListName = Convert.ToString(config.AppSettings.Settings["jobListName"].Value);
            using (Microsoft.SharePoint.Client.ClientContext context = new Microsoft.SharePoint.Client.ClientContext(spJobsite))
            {
                try
                {
                    context.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(O365UserName, O365Password);
                    context.Load(context.Web, w => w.Title);
                    context.ExecuteQuery();
                    Microsoft.SharePoint.Client.List list = context.Web.Lists.GetByTitle(JobListName);
                    context.Load(list);

                    Microsoft.SharePoint.Client.ListItemCollection listitems = list.GetItems(Microsoft.SharePoint.Client.CamlQuery.CreateAllItemsQuery());
                    context.Load(listitems);
                    context.ExecuteQuery();
                    foreach (Microsoft.SharePoint.Client.ListItem item in listitems)
                    {
                        cmxJobList.Items.Add(item["JobNumber"] + " - " + item["Title"]);
                    }
                    cmxJobList.Items.Insert(0, "--Select--");
                    logger.LogWrite("JobComboBox Populated");
                }
                catch (Exception ex)
                {
                    logger.LogWrite("JobComboBox Population Failed");
                    logger.LogWrite(ex.StackTrace);
                }
            }
            using (Microsoft.SharePoint.Client.ClientContext context = new Microsoft.SharePoint.Client.ClientContext(spCandidateSite))
            {
                context.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(O365UserName, O365Password);
                context.Load(context.Web, w => w.Title);
                context.ExecuteQuery();
                Microsoft.SharePoint.Client.List list = context.Web.Lists.GetByTitle(CandidateList);
                context.Load(list);

                Microsoft.SharePoint.Client.ListItemCollection listitems = list.GetItems(Microsoft.SharePoint.Client.CamlQuery.CreateAllItemsQuery());
                context.Load(listitems);
                context.ExecuteQuery();
                DataRow row_select = candidates.NewRow();
                row_select["DisplayCombobox"] = "--Select--";
                row_select["CandidateID"]     = -1;
                candidates.Rows.Add(row_select);
                foreach (Microsoft.SharePoint.Client.ListItem item in listitems)
                {
                    // cmbxCandidateList.Items.Add(item["CandidateID"] + " - " + item["First_name"]+"_"+item["Last_name"]);
                    DataRow row = candidates.NewRow();
                    row["CandidateID"] = item["CandidateID"];
                    row["First_name"]  = item["First_name"];
                    row["Last_name"]   = item["Last_name"];
                    row["Job"]         = item["Job"];
                    row["Hire_Status"] = item["Hire_Status"];
                    Microsoft.SharePoint.Client.FieldUrlValue _url = (Microsoft.SharePoint.Client.FieldUrlValue)item["FolderUrl"];
                    row["FolderUrl"]       = _url.Url;
                    row["Remaining_Test"]  = item["Remaining_Test"];
                    row["DisplayCombobox"] = item["CandidateID"] + " - " + item["First_name"] + "_" + item["Last_name"];
                    row["Category"]        = item["Category"];
                    row["Date"]            = item["Modified"];
                    row["DOB"]             = item["DOB"];
                    candidates.Rows.Add(row);
                }
                cmbxCandidateList.DataSource = candidates;
                //cmbxCandidateList.Items.Add(new { Text = "---Select---", Value = -1 });
                cmbxCandidateList.DisplayMember = "DisplayCombobox";
                cmbxCandidateList.ValueMember   = "CandidateID";
                cmxJobList.SelectedIndex        = 0;
            }
        }
Пример #21
0
 public bool Validate(ClientSidePageCollection sourcePages, Microsoft.SharePoint.Client.ClientContext ctx)
 {
     return(true);
 }
Пример #22
0
 protected Microsoft.SharePoint.Client.ClientContext GetContext(string url)
 {
     var context = new Microsoft.SharePoint.Client.ClientContext(url);
     context.Credentials = ConfigurationManager.Instance.UserCredential;
     return context;
 }