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;
        }
예제 #2
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);
    }
예제 #3
0
        public bool Validate1605(ProvisioningTemplate template, Microsoft.SharePoint.Client.ClientContext ctx)
        {
            var directoryFiles = new List <PnP.Framework.Provisioning.Model.File>();

            // Get all files from directories
            foreach (var directory in template.Directories)
            {
                var metadataProperties = directory.GetMetadataProperties();
                directoryFiles = directory.GetDirectoryFiles(metadataProperties);

                // Add directory files to template file collection
                foreach (var dFile in directoryFiles)
                {
                    var file = new PnP.Framework.Provisioning.Model.File
                    {
                        Src    = dFile.Src.Replace(directory.Src + "\\", ""),
                        Folder = directory.Folder
                    };
                    template.Files.Add(file);
                }
            }

            // validate all files
            return(Validate(template.Files, ctx));
        }
예제 #4
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;
         }
     }
 }
        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();
            }
        }
예제 #6
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);
            }
        }
예제 #7
0
        private void LoadFields(SP.List list)
        {
            cmbFilterField.Enabled = false;
            cmbFilterField.Items.Clear();

            if (cmbLists.SelectedIndex >= 0)
            {
                string webUrl = txtUrl.Text;

                List <string> fields = new List <string>();
                fields.Add("");

                using (SP.ClientContext ctx = GetClientContext(webUrl))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<Fields>");
                    progressBar1.Value++;

                    foreach (var item in list.Fields)
                    {
                        fields.Add(item.InternalName + " ( " + item.Title + " )");
                        sb.Append(item.SchemaXml);
                    }
                    sb.Append("</Fields>");
                    allFields      = sb.ToString();
                    txtFields.Text = FormatXml(allFields);

                    fields.Sort();
                    cmbFilterField.Items.AddRange(fields.ToArray());
                }
                cmbFilterField.Enabled = true;
            }
        }
예제 #8
0
파일: ConnectEcm.cs 프로젝트: KKPBank/SLM
        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);
        }
        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
            {
                Security = source
            };
            string sSchemaXml = ExtractElementXml(pt);

            ProvisioningTemplate ptTarget = new ProvisioningTemplate
            {
                Security = target
            };
            string tSchemaXml = ExtractElementXml(ptTarget);

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

            return(true);
        }
예제 #10
0
        /// <summary>
        /// Helper method to inject the custom webrequest provider that sets the UserAgent
        /// </summary>
        /// <returns>The new context.</returns>
        /// <param name="url">The url to create the context for.</param>
        private static SP.ClientContext CreateNewContext(string url)
        {
            var ctx = new SP.ClientContext(url);

            ctx.WebRequestExecutorFactory = new CustomWebRequestExecutorFactory(ctx.WebRequestExecutorFactory);
            return(ctx);
        }
예제 #11
0
        public List <IExportableComponent> GetExporters(string url, string user, string password)
        {
            var context = new Microsoft.SharePoint.Client.ClientContext(url)
            {
                Credentials    = new SharePointOnlineCredentials(user, password.GetSecureString()),
                RequestTimeout = Timeout.Infinite
            };

            return(new List <IExportableComponent>
            {
                new ComposedLook.ComposedLookExporter(context),
                new ContentTypes.ContentTypeExporter(context),
                new CustomActions.CustomActionsExporter(context),
                new Features.FeaturesExporter(context),
                new Files.FilesExporter(context),
                new Languages.LanguagesExporter(context),
                new Lists.ListExporter(context),
                new Navigation.NavigationExporter(context),
                new Pages.PagesExporter(context),
                new PropertyBag.PropertyBagExporter(context),
                new Region.RegionSettingsExporter(context),
                new SearchSettings.SearchSettingsExporter(context),
                new Security.SecurityExporter(context),
                new SiteFields.SiteFieldsExporter(context),
                new SitePolicy.SitePolicyExporter(context),
                new SiteProperties.SitePropertiesExporter(context),
                new TermGroup.ExportTermGroup(context)
            });
        }
예제 #12
0
파일: ConnectEcm.cs 프로젝트: KKPBank/SLM
        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();
                }
            }
        }
예제 #13
0
        /// <summary> Return the preconfigured SP.ClientContext to use. </summary>
        private SP.ClientContext getSpClientContext(bool forceNewContext = false)
        {
            if (forceNewContext)
            {
                if (m_spContext != null)
                {
                    m_spContext.Dispose();
                }
                m_spContext = null;
            }

            if (m_spContext == null)
            {
                if (m_spWebUrl == null)
                {
                    m_spWebUrl = findCorrectWebPath(m_orgUrl, m_userInfo, out m_spContext);
                    if (m_spWebUrl == null)
                    {
                        throw new System.Net.WebException(Strings.SharePoint.NoSharePointWebFoundError(m_orgUrl.ToString()));
                    }
                }
                else
                {
                    // would query: testUrlForWeb(m_spWebUrl, userInfo, true, out m_spContext);
                    m_spContext             = CreateNewContext(m_spWebUrl);
                    m_spContext.Credentials = m_userInfo;
                }
                if (m_spContext != null && m_useContextTimeoutMs > 0)
                {
                    m_spContext.RequestTimeout = m_useContextTimeoutMs;
                }
            }
            return(m_spContext);
        }
예제 #14
0
        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);
        }
        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();
            }
        }
예제 #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);
        }
        //
        // GET: /Home/
        public ActionResult Index()
        {
            Sp.ClientContext context = new Sp.ClientContext("https://shapingcloud1.sharepoint.com/sites/bikeshow");
            context.ExecutingWebRequest += wrapper.ClientContextExecutingWebRequest;

            SessionsAndSpeakersView view = new SessionsAndSpeakersView();

            var viewItems = GetItemsFromView(context, "Speakers", "Site");
            view.Speakers = new List<Dictionary<String, Object>>();
            foreach (var item in viewItems)
            {
                var speaker = item.FieldValues;
                view.Speakers.Add(speaker);
            }

            viewItems = GetItemsFromView(context, "Sessions", "Site");
            view.Sessions = new List<Dictionary<String, Object>>();
            foreach(var item in viewItems)
            {
                var session = item.FieldValues;
                view.Sessions.Add(session);
            }

            return View(view);
        }
예제 #18
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);
        }
예제 #19
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);
 }
예제 #20
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);
 }
예제 #21
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);
            }
        }
예제 #22
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("FunctionOCR trigger function processed a request.");

            string validationToken = GetValidationToken(req);

            if (validationToken != null)
            {
                log.LogInformation($"---- Processing Registration");
                var myResponse = req.CreateResponse(HttpStatusCode.OK);
                myResponse.Content = new StringContent(validationToken);
                return(myResponse);
            }

            var myContent = await req.Content.ReadAsStringAsync();

            var allNotifications = JsonConvert.DeserializeObject <ResponseModel <NotificationModel> >(myContent).Value;

            if (allNotifications.Count > 0)
            {
                log.LogInformation($"---- Processing Notifications");
                string siteUrl = ConfigurationManager.AppSettings["whSiteListUrl"];
                foreach (var oneNotification in allNotifications)
                {
                    ClientContext SPClientContext = LoginSharePoint(siteUrl);
                    GetChanges(SPClientContext, oneNotification.Resource, log);
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
예제 #23
0
 public UDPInterface(Document extDoc, Autodesk.Revit.ApplicationServices.Application extApp, SP.ClientContext extContext)
 {
     // initialize class variables from injected arguments
     _doc     = extDoc;
     _context = extContext;
     _app     = extApp;
     InitializeComponent();
 }
예제 #24
0
        public RecipeList()
        {
            InitializeComponent();
            RecipesListView.MultiSelect = false;

            Context     = new SP.ClientContext("http://sp2019vm/");
            RecipesList = Context.Web.Lists.GetByTitle("Recipe List");
        }
예제 #25
0
        private SP.ClientContext GetClientContext(string webUrl)
        {
            SP.ClientContext ctx = new SP.ClientContext(webUrl);
            if (txtUser.Text != "")
            {
                string domain = "";
                string user   = "";
                if (txtUser.Text.Replace('/', '\\').Contains('\\'))
                {
                    string[] tmp = txtUser.Text.Split('\\');
                    domain = tmp[0];
                    user   = tmp[1];
                }
                else
                {
                    user = txtUser.Text;
                }
                string password = txtPwd.Text;

                if (chkLoginOnline.Checked)
                {
                    System.Security.SecureString secpwd = new System.Security.SecureString();
                    for (int i = 0; i < password.Length; i++)
                    {
                        secpwd.AppendChar(password[i]);
                    }
                    //ClientAuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
                    //FormsAuthenticationLoginInfo creds = new FormsAuthenticationLoginInfo(User, Password);
                    SharePointOnlineCredentials creds = new SharePointOnlineCredentials(user, secpwd);
                    ctx.Credentials = creds;
                }
                else
                {
                    ctx.Credentials = new System.Net.NetworkCredential(user, txtPwd.Text, domain);
                }
            }
            if (string.IsNullOrEmpty(ProxyUrl) == false)
            {
                ctx.ExecutingWebRequest += (sen, args) =>
                {
                    System.Net.WebProxy myProxy = new System.Net.WebProxy(ProxyUrl);
                    string domain = "";
                    string user   = "";
                    if (ProxyUser.Replace('/', '\\').Contains('\\'))
                    {
                        string[] tmp = ProxyUser.Split('\\');
                        domain = tmp[0];
                        user   = tmp[1];
                    }
                    // myProxy.Credentials = new System.Net.NetworkCredential(ProxyUser, ProxyPwd, domain);
                    myProxy.Credentials                      = System.Net.CredentialCache.DefaultCredentials;
                    myProxy.UseDefaultCredentials            = true;
                    args.WebRequestExecutor.WebRequest.Proxy = myProxy;
                };
            }

            return(ctx);
        }
        public CSOMSharePointRepository(string Url)
        {
            string userName = WebConfigurationManager.AppSettings["ServiceAccount"].ToString();
            string password = WebConfigurationManager.AppSettings["ServicePassword"].ToString();

            context                      = new SP.ClientContext(Url);
            context.Credentials          = new NetworkCredential(userName, password);
            context.ExecutingWebRequest += context_ExecutingWebRequest;
        }
예제 #27
0
        public static List <Employee> GetEnterEstimate(string month, string year, string listname, string siteUrl)
        {
            List <Employee> _returnEmployee = new List <Employee>();

            try
            {
                using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl))
                {
                    if (context != null)
                    {
                        MSC.List SalesEstimateEmployee = context.Web.Lists.GetByTitle(listname);
                        MSC.ListItemCollectionPosition itemPosition = null;

                        string fromday = year + "-" + month + "-" + "1";
                        string Today   = year + "-" + month + "31";

                        while (true)
                        {
                            MSC.CamlQuery camlQuery = new MSC.CamlQuery();
                            camlQuery.ListItemCollectionPosition = itemPosition;
                            camlQuery.ViewXml  = @"<View><Query><Where>
                                                    <Eq><FieldRef Name='Date' />
                                                    <Value IncludeTimeValue='FLASE' Type='DateTime'>" + fromday + "</Value></Eq>";
                            camlQuery.ViewXml += @" </Where></Query>
                                                    <RowLimit>5000</RowLimit>
                                                     <FieldRef Name='ID'/>
                                                    <FieldRef Name='EmployeeName'/>
                                                    <FieldRef Name='Author'/>
                                                    <FieldRef Name='Created'/>
                                                </View>";
                            MSC.ListItemCollection Items = SalesEstimateEmployee.GetItems(camlQuery);
                            context.Load(Items);
                            context.ExecuteQuery();
                            itemPosition = Items.ListItemCollectionPosition;

                            foreach (MSC.ListItem item in Items)
                            {
                                _returnEmployee.Add(new Employee
                                {
                                    EmployeeName = Convert.ToString((item["EmployeeName"] as Microsoft.SharePoint.Client.FieldUserValue).LookupValue),
                                    EmployeeID   = Convert.ToString((item["EmployeeName"] as Microsoft.SharePoint.Client.FieldUserValue).LookupId)
                                });
                            }
                            if (itemPosition == null)
                            {
                                break; // TODO: might not be correct. Was : Exit While
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(_returnEmployee);
        }
예제 #28
0
 public static SP.ListItemCollection GetViewItemsFromList(SP.ClientContext context, SP.List list, SP.View view)
 {
     SP.ListItemCollection items = null;
     SP.CamlQuery          query = new SP.CamlQuery();
     query.ViewXml = view.ViewQuery;
     items         = list.GetItems(query);
     context.Load(items);
     context.ExecuteQuery();
     return(items);
 }
예제 #29
0
 public static void GetFieldsFromList(SP.ClientContext context, SP.List list)
 {
     context.Load(list.Fields);
     context.ExecuteQuery();
     foreach (SP.Field field in list.Fields)
     {
         // TODO do something with the fields
         Console.Write(field.InternalName);
     }
 }
예제 #30
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);
        }
예제 #31
0
 private void DeleteExistingActions(Microsoft.SharePoint.Client.ClientContext clientContext, Web web)
 {
     for (int i = 0; i < web.UserCustomActions.Count - 1; i++)
     {
         if (!String.IsNullOrEmpty(web.UserCustomActions[i].Name) && web.UserCustomActions[i].Name.Equals("SiteInformationApp", StringComparison.InvariantCultureIgnoreCase))
         {
             web.UserCustomActions[i].DeleteObject();
         }
     }
     clientContext.ExecuteQuery();
 }
예제 #32
0
 public void ConnectSharePointOnline()
 {
     using (SP.ClientContext context = new SP.ClientContext(siteUrl))
     {
         context.Credentials = new SP.SharePointOnlineCredentials(userName, securePass);
         SP.Web web = context.Web;
         context.Load(web);
         context.ExecuteQuery();
         Console.WriteLine("Web Title is " + web.Title);
     }
 }
        /// <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;
            }
        }
        /// <summary>
        /// Uses the direct method to get the web URL from a folder URL.
        /// </summary>
        /// <param name="url">Folder URL.</param>
        /// <param name="username">Username for SharePoint authentication.</param>
        /// <param name="password">Password for SharePoint authentication.</param>
        /// <returns>The web URL if found. Null otherwise (or if the specified URL is not a folder).</returns>
        private string GetWebUrlFromFolderUrl(string url, string username, string password)
        {
            string methodName = "SharePointManager2013.GetWebUrlFromFolderUrl";

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

                return SP.Web.WebUrlFromFolderUrlDirect(context, new Uri(url)).OriginalString;
            }
            catch (Exception e)
            {
                Logger.Error(string.Format("{0}: Could not find folder with URL {1}.", methodName, url), e);
                return null;
            }
        }
        /// <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;
            }
        }
예제 #36
0
        /// <summary> Return the preconfigured SP.ClientContext to use. </summary>
        private SP.ClientContext getSpClientContext(bool forceNewContext = false)
        {
            if (forceNewContext)
            {
                if (m_spContext != null) m_spContext.Dispose();
                m_spContext = null;
            }

            if (m_spContext == null)
            {
                if (m_spWebUrl == null)
                {
                    m_spWebUrl = findCorrectWebPath(m_orgUrl, m_userInfo, out m_spContext);
                    if (m_spWebUrl == null)
                        throw new System.Net.WebException(Strings.SharePoint.NoSharePointWebFoundError(m_orgUrl.ToString()));
                }
                else
                {
                    // would query: testUrlForWeb(m_spWebUrl, userInfo, true, out m_spContext);
                    m_spContext = new ClientContext(m_spWebUrl);
                    m_spContext.Credentials = m_userInfo;
                }
                if (m_spContext != null && m_useContextTimeoutMs > 0)
                    m_spContext.RequestTimeout = m_useContextTimeoutMs;
            }
            return m_spContext;
        }
예제 #37
0
 /// <summary>
 /// Проверяет доступность SharePoint сайта и его функционала
 /// </summary>
 /// <returns>Полная информация - была ли ошибка, какова она</returns>
 public ReturnCode ПроверитьДоступность()
 {
     try
     {
         _портал = new SP.ClientContext(_ссылкаПортала);
         var списки = ПолучитьСписки();
         if (списки == null || списки.Count == 0) throw new Exception(ОшибкаСписки);
     }
     catch (Exception ex) { return new ReturnCode() { Result = false, ErrorCode = -1, ErrorMessage = ex.Message, ErrorException = ex }; }
     return new ReturnCode() { Result = true, ErrorCode = 0, ErrorMessage = "", ErrorException = new Exception() };
 }
예제 #38
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));
            }
        }