Exemple #1
0
 private void Bw_sharepoint_safety_site_lib_DoWork(object sender, DoWorkEventArgs e)
 {
     //throw new NotImplementedException();
     toolStripStatusLabel1.Text = "Connecting to Safety Libraries";
     using (Microsoft.SharePoint.Client.ClientContext context = new Microsoft.SharePoint.Client.ClientContext(spCandidateSite))
     {
         try
         {
             context.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(O365UserName, O365Password);
             context.Load(context.Web, w => w.Title);
             context.ExecuteQuery();
             //toolStripStatusLabel1.Text = "Connecting to Libraries..";
             Microsoft.SharePoint.Client.List doclist = context.Web.Lists.GetByTitle(docLibraryName);
             context.Load(doclist);
             context.ExecuteQuery();
             //toolStripStatusLabel1.Text = "Connecting to Lists..";
             //Microsoft.SharePoint.Client.List list = context.Web.Lists.GetByTitle(quizListName);
             //context.Load(list);
             e.Result = doclist;
         }
         catch (Microsoft.SharePoint.Client.ServerException ex)
         {
             e.Result = ex;
         }
         catch (Exception ex)
         {
             e.Result = ex;
         }
     }
 }
Exemple #2
0
        public override bool Write(string fileName, byte[] data)
        {
            try
            {
                SharepointClientContext.Load(SharepointList.RootFolder);
                SharepointClientContext.ExecuteQuery();

                string fileUrl = String.Format("{0}/{1}", SharepointList.RootFolder.ServerRelativeUrl, fileName);
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(_clientContext, fileUrl, new MemoryStream(data, false), true);
                _clientContext.ExecuteQuery(); //Uploaded .. but still checked out...


                //Load the FieldCollection from the list...
                SP.FieldCollection fileFields = SharepointList.Fields;
                _clientContext.Load(fileFields);
                _clientContext.ExecuteQuery();

                SP.File     uploadedFile    = _web.GetFileByServerRelativeUrl(fileUrl);
                SP.ListItem newFileListItem = uploadedFile.ListItemAllFields;
                newFileListItem.Update();
                _clientContext.ExecuteQuery();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #3
0
        private void AddViews(frm_Data_View viewForm, string listId, string siteAddress, string siteName)
        {
            Guid g = new Guid(listId);

            SP.ClientContext clientContext = SharePoint.GetClient(siteAddress, frm_Main_Menu.username, frm_Main_Menu.password);
            SP.List          oList         = clientContext.Web.Lists.GetById(g);

            // Load in the Views
            clientContext.Load(oList.Views);
            clientContext.ExecuteQuery();

            int i = 0;

            foreach (SP.View oView in oList.Views)
            {
                i++;

                clientContext.Load(oView.ViewFields);
                clientContext.ExecuteQuery();

                string viewName   = oView.Title;
                string viewId     = oView.Id.ToString();
                string fieldCount = oView.ViewFields.Count.ToString();
                string rowLimit   = oView.RowLimit.ToString();
                string viewQuery  = oView.ViewQuery;
                string url        = frm_Main_Menu.siteUrl + oView.ServerRelativeUrl;

                viewForm.AddRow(i, viewName, siteName, siteAddress, fieldCount, rowLimit, viewId, viewQuery, url);

                lbl_Row_Count.Text = i.ToString() + " record(s) found";
                lbl_Row_Count.Refresh();
            }
        }
Exemple #4
0
    private void GetDocIDURL(ref StringBuilder permaurl)
    {
        string ctxurl = permaurl.ToString(0, 24);
        string relurl = permaurl.Replace("https://sp.contoso.com", "").ToString();

        // Starting with ClientContext, the constructor requires a URL to the
        // server running SharePoint.
        SP.ClientContext context = new SP.ClientContext(ctxurl);
        // The SharePoint web at the URL.
        SP.Web web = context.Web;
        // Load
        context.Load(web);
        // Execute query.
        context.ExecuteQuery();
        //
        SP.File     ObjFile = web.GetFileByServerRelativeUrl(relurl);
        SP.ListItem item    = ObjFile.ListItemAllFields;
        //
        context.Load(ObjFile);
        context.Load(item);
        context.ExecuteQuery();
        //
        //string fileName = item.FieldValues["FileLeafRef"].ToString();
        //string fileType = System.IO.Path.GetExtension(fileName);
        //Guid uniqueId = new Guid(item.FieldValues["UniqueId"].ToString());
        var furl = item.FieldValues["_dlc_DocIdUrl"] as SP.FieldUrlValue;

        permaurl.Clear();
        permaurl.Append(furl.Url);
    }
Exemple #5
0
        public Web CreateSubSite(Microsoft.SharePoint.Client.ClientContext ctx, Web hostWeb, string txtUrl,
                                 string template, string title, string description)
        {
            // Create web creation configuration
            WebCreationInformation information = new WebCreationInformation();

            information.WebTemplate = template;
            information.Description = description;
            information.Title       = title;
            information.Url         = txtUrl;
            // Currently all english, could be extended to be configurable based on language pack usage
            information.Language = 1033;

            Microsoft.SharePoint.Client.Web newWeb = null;
            newWeb = hostWeb.Webs.Add(information);
            ctx.ExecuteQuery();

            ctx.Load(newWeb);
            ctx.ExecuteQuery();

            // Add sub site link override
            new LabHelper().AddJsLink(ctx, newWeb, this.Request);

            // Set oob theme to the just created site
            new LabHelper().SetThemeBasedOnName(ctx, newWeb, hostWeb, "Orange");

            // All done, let's return the newly created site
            return(newWeb);
        }
        protected void btnAddTask_Click(object sender, EventArgs e)
        {
            string SiteCollectionURL = txtSiteCollection.Text;

            CLOM.ClientContext      context    = new CLOM.ClientContext(SiteCollectionURL);
            CLOM.List               taskList   = context.Web.Lists.GetByTitle("Tasks");
            CLOM.CamlQuery          query      = new CamlQuery();
            CLOM.ListItemCollection myTaskList = taskList.GetItems(query);

            context.Load(myTaskList,
                         itms => itms.ListItemCollectionPosition,
                         itms => itms.Include(
                             itm => itm["Title"],
                             itm => itm["Body"],
                             itm => itm["DueDate"]));

            context.ExecuteQuery();

            ListItemCreationInformation newTask = new ListItemCreationInformation();

            CLOM.ListItem newTaskItem = taskList.AddItem(newTask);

            newTaskItem["Title"]   = txtTitle.Text;
            newTaskItem["Body"]    = txtDesc.Text;
            newTaskItem["DueDate"] = Calendar1.SelectedDate;
            newTaskItem.Update();

            context.ExecuteQuery();

            lblResult.Text = "Added Task " + txtTitle.Text;
        }
Exemple #7
0
        internal ClientContext GetContext(Website site)
        {
            var spCtx = new Microsoft.SharePoint.Client.ClientContext(site.Url);

            spCtx.AuthenticationMode = ClientAuthenticationMode.Default;
            spCtx.Credentials        = System.Net.CredentialCache.DefaultNetworkCredentials;
            spCtx.ExecuteQuery();
            spCtx.Load(spCtx.Web, w => w.ServerRelativeUrl);
            spCtx.ExecuteQuery();
            return(spCtx);
        }
        public override void Process(Microsoft.SharePoint.Client.ClientContext context, bool add, string path)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(System.IO.File.ReadAllText(path));
            XmlNodeList themes = doc.SelectNodes("Themes/Theme");
            //upload the spcolor file
            string themeName = string.Empty;
            string fontName  = string.Empty;

            if (add)
            {
                //load the server relative url
                var web = context.Web;
                context.Load(web, w => w.ServerRelativeUrl);
                context.ExecuteQuery();
                foreach (XmlNode theme in themes)
                {
                    //upload the spcolor file
                    uploadThemeFile(context, "Theme Gallery", "15", theme.Attributes[Constants.ThemeAttributeNames.SPColorFile].Value, add, out themeName);
                    //upload the font file
                    uploadThemeFile(context, "Theme Gallery", "15", theme.Attributes[Constants.ThemeAttributeNames.FontFile].Value, add, out fontName);
                    //add the composed look item
                    List     list         = context.Web.Lists.GetByTitle("Composed Looks");
                    ListItem composedlook = list.AddItem(new ListItemCreationInformation());
                    composedlook["Title"]         = theme.Attributes[Constants.ThemeAttributeNames.Title].Value;
                    composedlook["Name"]          = theme.Attributes[Constants.ThemeAttributeNames.Name].Value;
                    composedlook["DisplayOrder"]  = theme.Attributes[Constants.ThemeAttributeNames.DisplayOrder].Value;
                    composedlook["MasterPageUrl"] = web.ServerRelativeUrl + theme.Attributes[Constants.ThemeAttributeNames.MasterPageUrl].Value;
                    composedlook["ThemeUrl"]      = web.ServerRelativeUrl + "/_catalogs/theme/15/" + themeName;
                    composedlook["ImageUrl"]      = theme.Attributes[Constants.ThemeAttributeNames.ImageUrl].Value;
                    composedlook["FontSchemeUrl"] = fontName == string.Empty ? string.Empty : web.ServerRelativeUrl + "/_catalogs/theme/15/" + fontName;
                    composedlook.Update();
                    context.ExecuteQuery();
                }
            }
            else
            {
                foreach (XmlNode theme in themes)
                {
                    uploadThemeFile(context, "Theme Gallery", "15", theme.Attributes[Constants.ThemeAttributeNames.SPColorFile].Value, add, out themeName);
                    uploadThemeFile(context, "Theme Gallery", "15", theme.Attributes[Constants.ThemeAttributeNames.FontFile].Value, add, out fontName);
                    //delete the composed look item
                    List list = context.Web.Lists.GetByTitle("Composed Looks");
                    ListItemCollection items = list.GetItems(new CamlQuery {
                        ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Name'/><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", theme.Attributes[Constants.ThemeAttributeNames.Name].Value)
                    });
                    context.ExecuteQuery();
                    items[0].DeleteObject();
                    context.ExecuteQuery();
                }
            }
        }
Exemple #9
0
        private async void btn_Upload_Click(object sender, EventArgs e)
        {
            try
            {
                ctx = connect_Sharepoint();
                if (ctx != null)
                {
                    try {
                        List doclist = ctx.Web.Lists.GetByTitle(docLibraryName);
                        ctx.Load(doclist);
                        ctx.ExecuteQuery();
                        Microsoft.SharePoint.Client.List list = ctx.Web.Lists.GetByTitle(quizListName);
                        ctx.Load(list);
                        ctx.ExecuteQuery();
                        label5.Visible            = true;
                        progressBarUpload.Visible = true;
                        foreach (DataRow row in candidateList.Rows)
                        {
                            label5.Text = "Processing : " + row["First_Name"] + row["Last_Name"];
                            if (Convert.ToString(row["Upload_Status"]) == "Failed")
                            {
                                if (Convert.ToString(row["IsReturningCandidate"]) == "No")
                                {
                                    await upload_new_Candidates(row, ctx, doclist, list);

                                    row["Current_Upload_Status"] = "Uploaded";
                                    progressBarUpload.PerformStep();
                                }
                                else
                                {
                                    await upload_RC_Candidates(row, ctx, doclist, list);

                                    row["Current_Upload_Status"] = "Uploaded";
                                    progressBarUpload.PerformStep();
                                }
                            }
                        }
                        label5.Text = "Upload Complete";
                    }
                    catch (Exception ex)
                    {
                    }
                }
                else
                {
                    MessageBox.Show("Error connecting to Sharepoint. Kindly check internet connectivity");
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemple #10
0
        /// <summary>
        /// This is simple demo on sub site creation based on selected "template" with configurable options
        /// </summary>
        /// <param name="txtUrl"></param>
        /// <param name="template"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="cc"></param>
        /// <param name="page"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public Web CreateSubSite(string txtUrl, string template, string title, string description,
                                 Microsoft.SharePoint.Client.ClientContext cc, Page page, XDocument baseConfiguration,
                                 bool isChildSite = false, Web subWeb = null)
        {
            // Resolve the template configuration to be used for chosen template
            XElement templateConfig = GetTemplateConfig(template, baseConfiguration);
            string   siteTemplate   = SolveUsedTemplate(template, templateConfig);

            // Create web creation configuration
            WebCreationInformation information = new WebCreationInformation();

            information.WebTemplate = siteTemplate;
            information.Description = description;
            information.Title       = title;
            information.Url         = txtUrl;
            // Currently all english, could be extended to be configurable based on language pack usage
            information.Language = 1033;

            Microsoft.SharePoint.Client.Web newWeb = null;
            //if it's child site from xml, let's do somethign else
            if (!isChildSite)
            {
                // Load host web and add new web to it.
                Microsoft.SharePoint.Client.Web web = cc.Web;
                cc.Load(web);
                cc.ExecuteQuery();
                newWeb = web.Webs.Add(information);
            }
            else
            {
                newWeb = subWeb.Webs.Add(information);
            }
            cc.ExecuteQuery();
            cc.Load(newWeb);
            cc.ExecuteQuery();

            DeployFiles(cc, newWeb, templateConfig);
            DeployCustomActions(cc, newWeb, templateConfig);
            DeployLists(cc, newWeb, templateConfig);
            DeployNavigation(cc, newWeb, templateConfig);
            DeployTheme(cc, newWeb, templateConfig, baseConfiguration);
            SetSiteLogo(cc, newWeb, templateConfig);

            if (!isChildSite)
            {
                DeploySubSites(cc, newWeb, templateConfig, page, baseConfiguration);
            }

            // All done, let's return the newly created site
            return(newWeb);
        }
Exemple #11
0
        private void AddJsLink(Microsoft.SharePoint.Client.ClientContext ctx)
        {
            Web web = ctx.Web;

            ctx.Load(web, w => w.UserCustomActions);
            ctx.ExecuteQuery();

            ctx.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId);
            ctx.ExecuteQuery();

            UserCustomAction userCustomAction = web.UserCustomActions.Add();

            userCustomAction.Location = "Microsoft.SharePoint.StandardMenu";
            userCustomAction.Group    = "SiteActions";
            BasePermissions perms = new BasePermissions();

            perms.Set(PermissionKind.ManageWeb);
            userCustomAction.Rights   = perms;
            userCustomAction.Sequence = 100;
            userCustomAction.Title    = "Modify Site";

            string realm    = TokenHelper.GetRealmFromTargetUrl(new Uri(ctx.Url));
            string issuerId = WebConfigurationManager.AppSettings.Get("ClientId");

            var    modifyPageUrl = string.Format("https://{0}/Pages/Modify.aspx?{{StandardTokens}}", Request.Url.Authority);
            string url           = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}',{{width:300,height:200,title:'Modify Site'}});";

            url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, modifyPageUrl);

            userCustomAction.Url = url;
            userCustomAction.Update();
            ctx.ExecuteQuery();

            // Remove the entry from the 'Recents' node
            NavigationNodeCollection nodes = web.Navigation.QuickLaunch;

            ctx.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children));
            ctx.ExecuteQuery();
            var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault();

            if (recent != null)
            {
                var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault();
                if (appLink != null)
                {
                    appLink.DeleteObject();
                }
                ctx.ExecuteQuery();
            }
        }
        static void GetChanges(ClientContext SPClientContext, string ListId, ILogger log)
        {
            Web  spWeb  = SPClientContext.Web;
            List myList = spWeb.Lists.GetByTitle(ConfigurationManager.AppSettings["whListName"]);

            SPClientContext.Load(myList);
            SPClientContext.ExecuteQuery();

            ChangeQuery myChangeQuery = GetChangeQueryNew(ListId);

            var allChanges = myList.GetChanges(myChangeQuery);

            SPClientContext.Load(allChanges);
            SPClientContext.ExecuteQuery();

            foreach (Change oneChange in allChanges)
            {
                if (oneChange is ChangeItem)
                {
                    int myItemId = (oneChange as ChangeItem).ItemId;

                    log.LogInformation($"---- Changed ItemId : " + myItemId);
                    ListItem myItem = myList.GetItemById(myItemId);
                    Microsoft.SharePoint.Client.File myFile       = myItem.File;
                    ClientResult <System.IO.Stream>  myFileStream = myFile.OpenBinaryStream();
                    SPClientContext.Load(myFile);
                    SPClientContext.ExecuteQuery();

                    byte[] myFileBytes = ConvertStreamToByteArray(myFileStream);

                    TextAnalyzeOCRResult myResult = GetAzureTextAnalyzeOCR(myFileBytes).Result;
                    log.LogInformation($"---- Text Analyze OCR Result : " + JsonConvert.SerializeObject(myResult));

                    myItem["Language"] = myResult.language;
                    string myText = string.Empty;
                    for (int oneLine = 0; oneLine < myResult.regions[0].lines.Count(); oneLine++)
                    {
                        for (int oneWord = 0; oneWord < myResult.regions[0].lines[oneLine].words.Count(); oneWord++)
                        {
                            myText += myResult.regions[0].lines[oneLine].words[oneWord].text + " ";
                        }
                    }
                    myItem["OCRText"] = myText;
                    myItem.Update();
                    SPClientContext.ExecuteQuery();
                    log.LogInformation($"---- Text Analyze OCR added to SharePoint Item");
                }
            }
        }
Exemple #13
0
        public string VerifyFileToDownload(string filePath, string fileName)
        {
            ToEcm.ClientContext context = null;
            string flag       = "";
            string retMessage = "";

            try
            {
                string siteUrl      = SLMConstant.Ecm.SiteUrl;  //http://ecm/dept/public
                string domain       = SLMConstant.Ecm.Domain;
                string username     = SLMConstant.Ecm.Username;
                string password     = SLMConstant.Ecm.Password;
                string fileFullname = filePath + fileName;

                //Ex.fileFullname = /dept/public/OBTDocument/160083566900/ActPaymentType_25590517_045936.png

                flag = "connection";
                using (context = new ToEcm.ClientContext(siteUrl)
                {
                    Credentials = new NetworkCredential(username, password, domain)
                })
                {
                    context.ExecuteQuery();
                    log.Info("Verify connection: Sucess");
                }

                flag = "file";
                using (FileInformation sharePointFile = ToEcm.File.OpenBinaryDirect(context, fileFullname))
                {
                    log.Info("Verify file: Sucess");
                }
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                if (flag == "connection")
                {
                    log.Error("Verify connection: Failed because " + message);
                    retMessage = "ไม่สามารถเชื่อมต่อระบบ ECM ได้";
                }
                else if (flag == "file")
                {
                    log.Error("Verify file: Failed because " + message);
                    retMessage = "ไม่พบไฟล์บนระบบ ECM";
                }
                else
                {
                    log.Error(message);
                }
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }

            return(retMessage);
        }
Exemple #14
0
        public bool VerifyConnection()
        {
            ToEcm.ClientContext context = null;
            try
            {
                string siteUrl  = SLMConstant.Ecm.SiteUrl;      //http://ecm/dept/public
                string domain   = SLMConstant.Ecm.Domain;
                string username = SLMConstant.Ecm.Username;
                string password = SLMConstant.Ecm.Password;

                using (context = new ToEcm.ClientContext(siteUrl)
                {
                    Credentials = new NetworkCredential(username, password, domain)
                })
                {
                    log.Info("==============================================================================");
                    context.ExecuteQuery();
                    log.Info("Verify Connection: Sucess");
                }
                return(true);
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                log.Error("Verify connection: Failed because " + message);
                throw new Exception("ไม่สามารถเชื่อมต่อระบบ ECM ได้");
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }
        }
Exemple #15
0
        public static void LoadFolder(TreeNode parentNode, SPClient.Folder folder, MainBrowser form, bool isRootFolder = false)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(folder);
                ctx.ExecuteQuery();

                // Add folder node
                TreeNode node = parentNode.Nodes.Add(isRootFolder ? "Root Folder" : folder.Name);
                node.ImageKey         = Constants.IMAGE_FOLDER;
                node.SelectedImageKey = Constants.IMAGE_FOLDER;
                node.Tag = folder;
                node.ContextMenuStrip = form.mnContextItem;

                AddLoadingNode(node, LoadType.Folder);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (isRootFolder)
                {
                    TreeNode node = parentNode.Nodes.Add("Root Folder (Error)");
                    node.ImageKey         = Constants.IMAGE_FOLDER;
                    node.SelectedImageKey = Constants.IMAGE_FOLDER;
                }
                else
                {
                    AddLoadingNode(parentNode, LoadType.Folder);
                }
            }
        }
Exemple #16
0
        public spClient.ListItemCollection getSharePointData(string subProjectRiskUrl, string query)
        {
            spClient.ListItemCollection collectionList = null;
            try
            {
                string[] validUrlApi = subProjectRiskUrl.Split(new string[] { "/Lists/" }, StringSplitOptions.None);
                string   newriskUrl  = subProjectRiskUrl;
                if (validUrlApi.Length != 0)
                {
                    newriskUrl = validUrlApi[0] + "/";
                }
                using (spClient.ClientContext ctx = new spClient.ClientContext(newriskUrl))
                {
                    var passWord = new SecureString();
                    foreach (var c in "intel@123")
                    {
                        passWord.AppendChar(c);
                    }
                    ctx.Credentials = new spClient.SharePointOnlineCredentials("*****@*****.**", passWord);

                    spClient.Web       myWeb   = ctx.Web;
                    spClient.List      proList = myWeb.Lists.GetByTitle("Risk List");
                    spClient.CamlQuery myQuery = new spClient.CamlQuery();
                    myQuery.ViewXml = query;
                    collectionList  = proList.GetItems(myQuery);
                    ctx.Load(collectionList);
                    ctx.ExecuteQuery();
                }
            }
            catch (Exception e)
            {
                collectionList = null;
            }
            return(collectionList);
        }
        public int UpdateEntry(EmployeeModel emp, string siteUrl, string ID)
        {
            try
            {
                using (MSC.ClientContext context = GetContext(siteUrl))
                {
                    MSC.List list = context.Web.Lists.GetByTitle("TIM_DailyAttendance");

                    MSC.ListItem listItem = null;

                    MSC.ListItemCreationInformation itemCreateInfo = new MSC.ListItemCreationInformation();
                    listItem = list.GetItemById(Convert.ToInt32(ID));

                    listItem["AttendanceDate"] = Convert.ToDateTime(emp.attendance_date).ToString("dd-MM-yyyy");
                    listItem["CheckinTime"]    = emp.checkin_time;
                    listItem["CheckoutTime"]   = emp.checkout_time;
                    listItem["Comment"]        = emp.comment;
                    listItem["EmpNo"]          = emp.empno;
                    listItem["Hours"]          = emp.hours;
                    listItem["EmpName"]        = emp.name;
                    listItem["EmpMail"]        = emp.office_email;
                    listItem.Update();
                    context.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
            }

            return(0);
        }
Exemple #18
0
 public static SP.List GetListFromWeb(SP.ClientContext context, string listTitle)
 {
     SP.List list = context.Web.Lists.GetByTitle(listTitle);
     context.Load(list);
     context.ExecuteQuery();
     return(list);
 }
        public EmployeeModel CheckNewEntry(string EMPCode, string siteUrl)
        {
            int           returnVal      = 0;
            EmployeeModel employeeModels = new EmployeeModel();

            using (MSC.ClientContext context = GetContext(siteUrl))
            {
                var      dataDateValue = DateTime.Today;
                MSC.List list          = context.Web.Lists.GetByTitle("TIM_DailyAttendance");
                MSC.ListItemCollectionPosition itemPosition = null;
                var q = new CamlQuery()
                {
                    ViewXml = "<View><Query><Where><And><Eq><FieldRef Name='EmpNo' /><Value Type='Text'>" + EMPCode + "</Value></Eq><Eq><FieldRef Name='AttendanceDate' /><Value Type='Text'>" + dataDateValue.ToString("dd-MM-yyyy") + "</Value></Eq></And></Where></Query></View>"
                };
                MSC.ListItemCollection Items = list.GetItems(q);

                context.Load(Items);
                context.ExecuteQuery();
                itemPosition = Items.ListItemCollectionPosition;

                returnVal = Items.Count;
                if (returnVal > 0)
                {
                    employeeModels.ID    = Items[0]["ID"].ToString();
                    employeeModels.count = Items.Count;
                }
                else
                {
                    employeeModels.count = Items.Count;
                }
            }


            return(employeeModels);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // The following code gets the client context by using TokenHelper.
            if (!Page.IsPostBack)
            {
                SPSocial.SocialFeedManager feedMngr;
                string contextToken;
                string hostWeb;

                // The following code handles authentication/authorization against our SPO tenant
                // because this page is not running in SharePoint. The important thing for us is to
                // be able to get the ClientContext object.
                // NOTE: The TokenHelper class is the one provided by the Visual Studio template for
                // autohosted Apps, so we haven't modified it's implementation in any way.
                HttpRequest req;
                req           = Page.Request;
                contextToken  = TokenHelper.GetContextTokenFromRequest(req);
                hostWeb       = Page.Request["SPHostUrl"];
                clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority);

                // Now we are into the useful bits that enable us to work with feeds, posts, replies, and so on.
                feedMngr = new SPSocial.SocialFeedManager(clientContext);
                clientContext.Load(feedMngr);
                clientContext.ExecuteQuery();

                // Call our own function (see below) to render the three most recent posts as tiles.
                LoadPosts();
            }
        }
Exemple #21
0
        public static void LoadRoleDefinitions(TreeNode parentNode, SPClient.RoleDefinitionCollection roleDefinitions, MainBrowser form, LoadType loadType)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(roleDefinitions);
                ctx.ExecuteQuery();

                int total   = roleDefinitions.Count;
                int current = 0;

                foreach (var roleDefinition in roleDefinitions)
                {
                    LoadRoleDefinition(parentNode, form, roleDefinition);

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, loadType);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // The following code gets the client context by using TokenHelper.
            if (!Page.IsPostBack)
            {
                SPSocial.SocialFeedManager feedMngr;
                string contextToken;
                string hostWeb;

                // The following code handles authentication/authorization against our SPO tenant
                // because this page is not running in SharePoint. The important thing for us is to
                // be able to get the ClientContext object.
                // NOTE: The TokenHelper class is the one provided by the Visual Studio template for
                // autohosted Apps, so we haven't modified it's implementation in any way.
                HttpRequest req;
                req = Page.Request;
                contextToken = TokenHelper.GetContextTokenFromRequest(req);
                hostWeb = Page.Request["SPHostUrl"];
                clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority);

                // Now we are into the useful bits that enable us to work with feeds, posts, replies, and so on.
                feedMngr = new SPSocial.SocialFeedManager(clientContext);
                clientContext.Load(feedMngr);
                clientContext.ExecuteQuery();

                // Call our own function (see below) to render the three most recent posts as tiles.
                LoadPosts();
            }
        }
Exemple #23
0
        public static void LoadProperties(TreeNode parentNode, SPClient.PropertyValues properties, MainBrowser form, LoadType loadType)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(properties);
                ctx.ExecuteQuery();

                int total   = properties.FieldValues.Count;
                int current = 0;

                foreach (var property in properties.FieldValues)
                {
                    TreeNode node = parentNode.Nodes.Add(string.Format("{0}", property.Key));
                    node.ImageKey         = Constants.IMAGE_PROPERTY;
                    node.SelectedImageKey = Constants.IMAGE_PROPERTY;
                    node.Tag = property;
                    node.ContextMenuStrip = form.mnContextItem;

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, loadType);
            }
        }
Exemple #24
0
        public static void LoadWorkflowTemplates(TreeNode parentNode, SPClient.Workflow.WorkflowTemplateCollection workflows, MainBrowser form, LoadType loadType)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(workflows);
                ctx.ExecuteQuery();

                int total   = workflows.Count;
                int current = 0;

                foreach (var workflow in workflows)
                {
                    TreeNode node = parentNode.Nodes.Add(workflow.Name);
                    node.ImageKey         = Constants.IMAGE_WORKFLOW_ASSOCIATION;
                    node.SelectedImageKey = Constants.IMAGE_WORKFLOW_ASSOCIATION;
                    node.Tag = workflow;
                    node.ContextMenuStrip = form.mnContextItem;

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, loadType);
            }
        }
Exemple #25
0
        public static void LoadViews(TreeNode parentNode, SPClient.ViewCollection views, MainBrowser form)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(views);
                ctx.ExecuteQuery();

                int total   = views.Count;
                int current = 0;

                foreach (SPClient.View view in views)
                {
                    TreeNode node = parentNode.Nodes.Add(view.Title);
                    node.ImageKey         = Constants.IMAGE_VIEW;
                    node.SelectedImageKey = Constants.IMAGE_VIEW;
                    node.Tag = view;
                    node.ContextMenuStrip = form.mnContextItem;

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, LoadType.ListViews);
            }
        }
Exemple #26
0
        public static void LoadSubWebs(TreeNode parentNode, SPClient.WebCollection webs, MainBrowser form)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(webs);
                ctx.ExecuteQuery();

                int total   = webs.Count;
                int current = 0;

                foreach (SPClient.Web subweb in webs)
                {
                    LoadWeb(parentNode, subweb, form);

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, LoadType.WebSubWebs);
            }
        }
Exemple #27
0
 public static SP.View GetViewFromList(SP.ClientContext context, SP.List list, string viewName)
 {
     SP.View view = list.Views.GetByTitle(viewName);
     context.Load(view);
     context.ExecuteQuery();
     return(view);
 }
Exemple #28
0
        /// <summary>
        /// Retrieves the server-relative URL of a folder from its absolute URL.
        /// </summary>
        /// <param name="webUrl">Web URL to establish context.</param>
        /// <param name="folderUrl">folder URL</param>
        /// <param name="username">Username for SharePoint authentication.</param>
        /// <param name="password">Password for SharePoint authentication.</param>
        /// <returns>The server-relative folder URL if found. Null otherwise.</returns>
        private string GetFolderUrlDirect(string webUrl, string folderUrl, string username, string password)
        {
            string methodName = "SharePointManager2003.GetFolderUrlDirect";

            try
            {
                SP.ClientContext context = new SP.ClientContext(webUrl);
                context.Credentials = new NetworkCredential(username, password);

                // load the web data
                SP.Web web = context.Web;
                context.Load(web);

                // load the folder data
                Uri       uri    = new Uri(folderUrl);
                SP.Folder folder = web.GetFolderByServerRelativeUrl(uri.AbsolutePath);
                context.Load(folder);

                context.ExecuteQuery();

                // check if the URL belongs to a folder
                if (folder != null)
                {
                    return(folder.ServerRelativeUrl);
                }

                return(null);
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("{0}: Could not find folder with URL {1}.", methodName, folderUrl), e);
                return(null);
            }
        }
Exemple #29
0
        public static void LoadRecycleBin(TreeNode parentNode, SPClient.RecycleBinItemCollection recycleBinItems, MainBrowser form, LoadType loadType)
        {
            try
            {
                SPClient.ClientContext ctx = GetClientContext(parentNode);
                ctx.Load(recycleBinItems);
                ctx.ExecuteQuery();

                int total   = recycleBinItems.Count;
                int current = 0;

                foreach (var recycleBinItem in recycleBinItems)
                {
                    TreeNode node = parentNode.Nodes.Add(string.Format("{0}", recycleBinItem.Title));
                    node.ImageKey         = Constants.IMAGE_RECYCLE_BIN;
                    node.SelectedImageKey = Constants.IMAGE_RECYCLE_BIN;
                    node.Tag = recycleBinItem;
                    node.ContextMenuStrip = form.mnContextItem;

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, loadType);
            }
        }
Exemple #30
0
        private async Task Update_List(string candidateID)
        {
            try
            {
                Microsoft.SharePoint.Client.List list = ctx.Web.Lists.GetByTitle(quizListName);
                ctx.Load(list);
                //CamlQuery camlQuery = new CamlQuery();

                //camlQuery.ViewXml= "<View><Query><Where><Geq><FieldRef Name='CandidateID'/>" +
                //"<Value Type='Text'>"+candidateID+"</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
                Microsoft.SharePoint.Client.ListItemCollection listitems = list.GetItems(CreateCandidateQuery(CandID, CandName.Split('_')[0]));
                ctx.Load(listitems);
                ctx.ExecuteQuery();
                FieldLookupValue lval = await GetLookupValue(ctx, jobName, "Job", "JobFullName", "Text", false);

                foreach (ListItem oListItem in listitems)
                {
                    //oListItem["JobSite"] = lval.LookupValue;
                    oListItem["JobSite"] = lval;
                    oListItem["Job"]     = jobName;
                    //double percent = Convert.ToDouble(no_of_passes) / Convert.ToDouble(dt.Rows.Count);
                    //if (percent >= 0.7 && percent < 1.0)
                    //    oListItem["Hire_Status"] = "Conditional Hire";
                    //else
                    //    oListItem["Hire_Status"] = "Hired";
                    oListItem["Hire_Status"] = hireStatus;
                    string        tempFolderurl = docFolder.ServerRelativeUrl;
                    FieldUrlValue _url          = new FieldUrlValue();
                    _url.Url                    = tempFolderurl.Substring(0, tempFolderurl.LastIndexOf('/'));;
                    _url.Description            = "View Tests";
                    oListItem["FolderUrl"]      = _url;
                    oListItem["Remaining_Test"] = remaining_test;
                    oListItem["Category"]       = pos_category;
                    //newItem["FolderUrl"] = folder.ServerRelativeUrl;

                    oListItem.Update();
                    ctx.Load(oListItem);
                    ctx.ExecuteQuery();
                }
                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void AddSiteInformationJsLink(Microsoft.SharePoint.Client.ClientContext clientContext)
        {
            Web web = clientContext.Web;

            clientContext.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId);
            clientContext.ExecuteQuery();

            string issuerId = ConfigurationManager.AppSettings.Get("ClientId");

            DeleteExistingActions(clientContext, web);

            UserCustomAction userCustomAction = web.UserCustomActions.Add();

            userCustomAction.Location = "Microsoft.SharePoint.StandardMenu";
            userCustomAction.Group    = "SiteActions";
            BasePermissions perms = new BasePermissions();

            perms.Set(PermissionKind.ManageWeb);
            userCustomAction.Rights   = perms;
            userCustomAction.Sequence = 100;
            userCustomAction.Title    = "Site Information";
            userCustomAction.Name     = "SiteInformationApp";

            string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(clientContext.Url));

            string host = "";

            foreach (Uri u in OperationContext.Current.Host.BaseAddresses)
            {
                if (u.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase))
                {
                    host = u.Authority;
                }
            }

            var    appPageUrl = string.Format("https://{0}/Pages/Default.aspx?{{StandardTokens}}", host);
            string url        = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}', {{width:600,height:400,title:'Site Information'}});";

            url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, appPageUrl);

            userCustomAction.Url = url;
            userCustomAction.Update();
            clientContext.ExecuteQuery();
        }
        /// <summary>
        /// Retrieves the server-relative URL of a folder from its absolute URL.
        /// </summary>
        /// <param name="webUrl">Web URL to establish context.</param>
        /// <param name="folderUrl">folder URL</param>
        /// <param name="username">Username for SharePoint authentication.</param>
        /// <param name="password">Password for SharePoint authentication.</param>
        /// <returns>The server-relative folder URL if found. Null otherwise.</returns>
        private string GetFolderUrlDirect(string webUrl, string folderUrl, string username, string password)
        {
            string methodName = "SharePointManager2003.GetFolderUrlDirect";

            try
            {
                SP.ClientContext context = new SP.ClientContext(webUrl);
                context.Credentials = new NetworkCredential(username, password);

                // load the web data
                SP.Web web = context.Web;
                context.Load(web);

                // load the folder data
                Uri uri = new Uri(folderUrl);
                SP.Folder folder = web.GetFolderByServerRelativeUrl(uri.AbsolutePath);
                context.Load(folder);

                context.ExecuteQuery();

                // check if the URL belongs to a folder
                if (folder != null)
                {
                    return folder.ServerRelativeUrl;
                }

                return null;
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("{0}: Could not find folder with URL {1}.", methodName, folderUrl), e);
                return null;
            }
        }
Exemple #33
0
        private void CheckCalendarAsync(object sender, DoWorkEventArgs e)
        {
            calendarDaysForWeek.Clear();

            using (Microsoft.SharePoint.Client.ClientContext client = new Microsoft.SharePoint.Client.ClientContext(ConfigManager.SharePointWebUrl))
            {
                var optionsVM = ViewModelLocater.OptionsViewModel;
                var mainWindowVM = ViewModelLocater.MainWindowViewModel;

                if (optionsVM.SpecifyUserCredentials && optionsVM.CredentialsAreValid)
                {
                    NetworkCredential cred = new NetworkCredential(optionsVM.Username, optionsVM.Password, optionsVM.Domain);
                    client.Credentials = cred;
                }

                List list = client.Web.Lists.GetByTitle(ConfigManager.SharepointCalendarName);
                CamlQuery camlQuery = new CamlQuery();

                camlQuery.ViewXml =
                    @"<View>
                <Query>
                    <Where>
                    <And>
                        <Eq>
                            <FieldRef Name='Author' LookupId='TRUE' />
                            <Value Type='Integer'><UserID/></Value>
                        </Eq>
                        <Or>
                            <And>
                                <Geq>
                                    <FieldRef Name='EventDate' />
                                    <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.StartOfWeek.Date.ToString("o") + @"</Value>
                                </Geq>
                                <Leq>
                                    <FieldRef Name='EventDate' />
                                    <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.EndOfWeek.Date.ToString("o") + @"</Value>
                                </Leq>
                            </And>
                            <And>
                                <Geq>
                                    <FieldRef Name='EndDate' />
                                    <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.StartOfWeek.Date.ToString("o") + @"</Value>
                                </Geq>
                                <Leq>
                                    <FieldRef Name='EndDate' />
                                    <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.EndOfWeek.Date.ToString("o") + @"</Value>
                                </Leq>
                            </And>
                        </Or>
                    </And>
                    </Where>
                </Query>
                <RowLimit>100</RowLimit>
                </View>";

                ListItemCollection listItems = list.GetItems(camlQuery);
                client.Load(
                    listItems,
                    items => items
                                    .Include(
                                        item => item["Title"],
                                        item => item["EventDate"],
                                        item => item["EndDate"]));
                client.ExecuteQuery();

                foreach (ListItem listItem in listItems)
                    calendarDaysForWeek.Add(new CalendarDayModel(listItem));
            }
        }
        /// <summary>
        /// Checks if a URL belongs to a SharePoint website.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="username">Username for SharePoint authentication.</param>
        /// <param name="password">Password for SharePoint authentication.</param>
        /// <returns>True if the URL is a SharePoint website. False, otherwise.</returns>
        private bool IsWeb(string url, string username, string password)
        {
            string methodName = "SharePointManager2013.IsWeb";

            try
            {
                Logger.DebugFormat("{0}: Checking if {1} is a website.", methodName, url);

                SP.ClientContext context = new SP.ClientContext(url);
                context.Credentials = new NetworkCredential(username, password);

                SP.Web web = context.Web; // The SharePoint web at the URL.
                context.Load(web, w => w.Title); // We want to retrieve the web's properties.
                context.ExecuteQuery(); // Execute the query to the server.

                Logger.DebugFormat("{0}: URL {1} is a website with title {2}.", methodName, url, web.Title);
                return true;
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("{0}: Error checking URL {1}.", methodName, url), e);
                return false;
            }
        }