예제 #1
0
        public string GetNewsDetail(int id, string secretKey)
        {
            try
            {
                string jsonString = string.Empty;

                if (secretKey != null)
                {
                    byte[] data = Convert.FromBase64String(secretKey);
                    if (DataStatics.SecretKey == System.Text.Encoding.UTF8.GetString(data))
                    {
                        #region Retrieve News Detail
                        //NewsModel.News newsDetail = NewsService.QueryNewsDetails(id);

                        NewsModel.News news = new NewsModel.News();
                        Microsoft.SharePoint.Client.ListItemCollection coll = QueryListItems(NewsModel.newsSiteUrl, NewsModel.sayfalarListName, string.Format(NewsModel.newsDetailCamlQuery, id));
                        ListItem item = coll[0];
                        news.ID       = id;
                        news.Modified = Convert.ToDateTime(item["Modified"]);
                        news.Title    = item["Title"].ToString();
                        string[] metaInfo = item["MetaInfo"].ToString().Split('\n');
                        foreach (var i in metaInfo)
                        {
                            if (i.Contains("vti_cachedcustomprops"))
                            {
                                continue;
                            }
                            if (i.Contains("PublishingPageContent:SW"))
                            {
                                news.PublishingPageContent = HLP.TransformHtmlStringForMobile(i.Split('|')[1].Replace("\r", ""));
                            }
                        }
                        #endregion

                        System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        jsonString = jsonSerializer.Serialize(news);
                    }
                }

                return(jsonString);
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
예제 #2
0
        protected void btnCSOMGetHostWebList_Click(object sender, EventArgs e)
        {
            lblCSOMHostWebItems.Text = "";

            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                ClientContext clientContext = null;
                if (chkAppOnly.Checked)
                {
                    clientContext = spContext.CreateAppOnlyClientContextForSPHost();
                }
                else
                {
                    clientContext = spContext.CreateUserClientContextForSPHost();
                }

                using (clientContext)
                {
                    Web            web          = clientContext.Web;
                    ListCollection lists        = web.Lists;
                    List           selectedList = lists.GetByTitle(ddCSOMHostWebLists.SelectedValue);

                    CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(100);

                    Microsoft.SharePoint.Client.ListItemCollection listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load <ListCollection>(lists);
                    clientContext.Load <List>(selectedList);
                    clientContext.Load <Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();

                    if (listItems.Count == 0)
                    {
                        lblCSOMHostWebItems.Text = "(No items in list)";
                    }
                    foreach (Microsoft.SharePoint.Client.ListItem item in listItems)
                    {
                        lblCSOMHostWebItems.Text += item["Title"] + "<br/>";
                    }
                }
            }
            catch (Exception ex)
            {
                WriteException(ex);
            }
        }
예제 #3
0
        public EmployeeModel CheckNewEntry(string EMPCode, string attendance_date, string siteUrl)
        {
            int           returnVal      = 0;
            EmployeeModel employeeModels = new EmployeeModel();

            using (MSC.ClientContext context = GetContext(siteUrl))
            {
                //var dataDateValue = DateTime.Today;

                string dateValue = "";
                try
                {
                    var dataDateValue = Convert.ToDateTime(attendance_date);
                    dateValue = dataDateValue.ToString("dd-MM-yyyy");
                }
                catch (Exception ex)
                {
                    dateValue = "";
                }

                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'>" + dateValue + "</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);
        }
예제 #4
0
        public List <KanbanDataModels> GetSpKanbanDataObjects()
        {
            List <KanbanDataModels> kanbanItems = new List <KanbanDataModels>();

            System.Net.NetworkCredential creds            = new System.Net.NetworkCredential("*****@*****.**", "helloWorld55!");
            Microsoft.SharePoint.Client.ClientContext ctx = new Microsoft.SharePoint.Client.ClientContext("http://sp16.geek-ish.com/")
            {
                Credentials = creds
            };
            string listName = "ADA_Eligibility_Status4";//"ADA_Eligibility_Status"; //"TRAP Active Cases1"; //"DashboardSummaryCard";

            SP.ListItemCollection items = GetSpListItems(ctx, "http://sp16.geek-ish.com/", listName, string.Empty);
            if (items != null)
            {
                foreach (SP.ListItem li in items)
                {
                    KanbanDataModels kanbanItem = new KanbanDataModels();
                    {
                        double d;
                        int    i;
                        try
                        {
                            //kanbanItem.Id = li["ID"] == null ? string.Empty : li["ID"].ToString().Trim(); //"Task 1",
                            kanbanItem.Title   = li["Title"] == null ? string.Empty : li["Title"].ToString().Trim();                    //"Task  - 29001",
                            kanbanItem.Status  = li["Status"] == null ? string.Empty : ((SP.FieldLookupValue)li["Status"]).LookupValue; //li["Status"].ToString().Trim(); //"Open",
                            kanbanItem.Summary = li["Summary"] == null ? string.Empty : li["Summary"].ToString().Trim();                //"Analyze the new requirements gathered from the customer.",
                            //kanbanItem.Type = li["Type"] == null ? string.Empty : li["Type"].ToString().Trim(); //"Story",
                            kanbanItem.Priority = li["Priority"] == null ? string.Empty : li["Priority"].ToString().Trim();             //"Low",
                            //kanbanItem.Tags = li["Tags"] == null ? string.Empty : li["Tags"].ToString().Trim(); //"Analyze,Customer",
                            //kanbanItem.Estimate = double.TryParse(li["CompletionTime"] == null ? "0" : li["CompletionTime"].ToString().Trim(), out d) ? d : 0; //3.5,
                            kanbanItem.Assignee = li["Assignee"] == null ? string.Empty : ((SP.FieldLookupValue)li["Assignee"]).LookupValue;//li["Assignee"].ToString().Trim(); //"Cean Carter",
                            //kanbanItem.RankId = int.TryParse(li["RankId"] == null ? "0" : li["RankId"].ToString().Trim(), out i) ? i : 0; //1,
                            //kanbanItem.Color = li["Color"] == null ? string.Empty : li["Color"].ToString().Trim(); // "#008000",
                            //kanbanItem.ClassName = li["ClassName"] == null ? string.Empty : li["ClassName"].ToString().Trim(); // "e-story, e-low, e-nancy-davloio"
                        }
                        catch (Exception e)
                        {
                            Debug.Print(e.Message);
                        }

                        kanbanItems.Add(kanbanItem);
                    }
                }
            }

            return(kanbanItems);
        }
예제 #5
0
        /// <summary>
        /// 获取Item的集合
        /// </summary>
        /// <param name="siteURL">指定站点Uri</param>
        /// <param name="documentListName">指定文档库名称</param>
        /// <param name="name">指定字段引用</param>
        /// <param name="value">指定文件名称</param>
        /// <param name="rowLimit">指定限定限制</param>
        /// <returns>返回Item的集合</returns>
        Microsoft.SharePoint.Client.ListItemCollection GetListItemCollectionFromSP(string documentListName, string name, string value, int rowLimit)
        {
            //声明一个item的集合
            Microsoft.SharePoint.Client.ListItemCollection listItems = null;
            try
            {
                if (clientContext != null)
                {
                    //创建客户端对象模型
                    using (clientContext)
                    {
                        //设置默认凭据

                        //通过文档库名称获取文档库
                        Microsoft.SharePoint.Client.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);
                        //创建一个查询
                        CamlQuery camlQuery = new CamlQuery();
                        camlQuery.ViewXml =
                            @"<View>
                <Query>
                <Where>
                <Eq>
                <FieldRef Name=""" + name + @"""/>
                <Value Type="" + type + "">" + value + @"</Value>
                </Eq> </Where> 
                <RowLimit>" + rowLimit.ToString() + @"</RowLimit>
                </Query>
                </View>";
                        //通过查询获取item的集合
                        listItems = documentsList.GetItems(camlQuery);
                        //执行
                        clientContext.Load(documentsList);
                        clientContext.Load(listItems);
                        clientContext.ExecuteQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                MethodLb.CreateLog(this.GetType().FullName, "GetListItemCollectionFromSP", ex.ToString(), documentListName, name, value, rowLimit);
            }
            finally
            {
            }
            return(listItems);
        }
예제 #6
0
        public static void DeleteListItem(List spList, ClientContext ctx)
        {
            sp.ListItemCollection listItems = spList.GetItems(CamlQuery.CreateAllItemsQuery());
            ctx.Load(listItems, eachItem => eachItem.Include(item => item, item => item["ID"]));
            ctx.ExecuteQuery();
            var totalListItems = listItems.Count;

            if (totalListItems > 0)
            {
                for (var counter = totalListItems - 1; counter > -1; counter--)
                {
                    listItems[counter].DeleteObject();
                    ctx.ExecuteQuery();
                    Console.WriteLine("Row: " + counter + " Item Deleted");
                }
            }
        }
예제 #7
0
 private async Task CreateFolders(Microsoft.SharePoint.Client.ClientContext context, string job)
 {
     Microsoft.SharePoint.Client.ListItemCollection listitems = CandList.GetItems(Microsoft.SharePoint.Client.CamlQuery.CreateAllItemsQuery());
     context.Load(listitems);
     context.ExecuteQuery();
     CandID = "";
     if (listitems.Count > 0)
     {
         CandID = Convert.ToString(get_nextCandidateID(listitems) + 1);
     }
     else
     {
         CandID = "1000";
     }
     docFolder = CreateFolderInternal(context.Web, documentList.RootFolder, CandID + "_" + candidate_name + "/" + job);
     await Task.Delay(1000);
 }
예제 #8
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;
            }
        }
        public void UpdateItemByQuery(string ListName, TEntity Item, ICamlQuery Query)
        {
            try
            {
                SP.Web       web   = context.Web;
                SP.List      list  = web.Lists.GetByTitle(ListName);
                SP.CamlQuery query = (SP.CamlQuery)Query.ExecuteQuery();

                SP.ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                if (items != null)
                {
                    foreach (SP.ListItem item in items)
                    {
                        var properties = typeof(TEntity).GetProperties();

                        foreach (var property in properties)
                        {
                            if (property.Name != "ID" && property.Name != "Created" && property.Name != "Author")
                            {
                                item[property.Name] = property.GetValue(Item);
                            }
                        }

                        item.Update();
                        context.Load(item);
                    }
                    context.ExecuteQuery();
                }
                else
                {
                    throw new Exception("Item does not exist");
                }
            }
            catch (InvalidCastException ex)
            {
                throw new Exception(ex.Message + ". Data model types are invalid, please verify that models are strongly typed and match the SharePoint list column types.", new InvalidCastException());
            }
            catch (Exception ex)
            {
                throw new Exception("Error updating SharePoint list data: " + ex.Message);
            }
        }
예제 #10
0
        private SP.ListItemCollection GetProjects()
        {
            // get projects from sharepoint
            SP.ListItemCollection projects = GetItemsFromSharepointList(
                SharepointConstants.Links.projectList,
                SharepointConstants.Views.allItems
                );

            if (projects == null)
            {
                MessageBox.Show("Error: no projects available in Sharepoint.");
                return(null);
            }

            // store the projects in cache
            SharepointConstants.Cache.projects = projects;
            return(projects);
        }
예제 #11
0
        public static void getLibFiles(string libName)
        {
            try
            {
                Web web = context.Web;
                Microsoft.SharePoint.Client.List list = web.Lists.GetByTitle(libName);
                Console.WriteLine("Library Name:- " + libName);
                CamlQuery query = new CamlQuery();
                query.ViewXml = "<View Scope=\"RecursiveAll\"><Query></Query><RowLimit>5000</RowLimit></View>";
                countImgPdf   = 0;
                do
                {
                    Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);
                    context.Load(items, i => i.Include(itm => itm.FileSystemObjectType), i => i.ListItemCollectionPosition);
                    context.ExecuteQuery();

                    foreach (Microsoft.SharePoint.Client.ListItem listItem in items)
                    {
                        if (listItem.FileSystemObjectType.ToString() != "Folder")
                        {
                            context.Load(listItem, i => i.File);
                            context.ExecuteQuery();
                            if (listItem.File.Name.Substring(listItem.File.Name.LastIndexOf('.') + 1).ToUpper() == "PDF")
                            {
                                //ClientResult<System.IO.Stream> data = listItem.File.OpenBinaryStream();
                                FileInformation data = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, listItem.File.ServerRelativeUrl);
                                context.Load(listItem.File);
                                context.ExecuteQuery();

                                objPDF.fileName = listItem.File.Name;
                                objPDF.fileUrl  = listItem.File.ServerRelativeUrl;
                                Console.WriteLine(objPDF.fileName);
                                getImagePdf(data);
                            }
                        }
                    }
                    query.ListItemCollectionPosition = items.ListItemCollectionPosition;
                } while (query.ListItemCollectionPosition != null);
            }
            catch (Exception error)
            {
                Console.WriteLine(error.Message);
            }
        }
예제 #12
0
        protected void btnGetTasks_Click(object sender, EventArgs e)
        {
            string SiteCollectionURL = txtSiteCollection.Text;

            CLOM.ClientContext  context = new CLOM.ClientContext(SiteCollectionURL);
            CLOM.Web            site    = context.Web;
            CLOM.ListCollection lists   = site.Lists;
            var taskList = context.Web.Lists.GetByTitle("Tasks");

            CLOM.CamlQuery          query      = new CamlQuery();
            CLOM.ListItemCollection myTaskList = taskList.GetItems(query);
            context.Load(myTaskList);
            context.ExecuteQuery();

            foreach (CLOM.ListItem tmpTaskItem in myTaskList)
            {
                lblTasks.Text += tmpTaskItem.FieldValues.Values.ElementAt(2).ToString() + "<br/>";
            }
        }
예제 #13
0
        /* It includes methods related to SampleEntity */
        #endregion

        #region Methods
        public static List <Campaign> QueryLatestCampaignsLight()
        {
            try
            {
                List <Campaign>       camps = new List <Campaign>();
                SP.ListItemCollection coll  = DAT.DataQuery.QueryListItems(CampaignModel.campaignsSiteUrl, CampaignModel.sayfalarListName, CampaignModel.campaignsLightCamlQuery);
                if (coll.Count > 0)
                {
                    foreach (SP.ListItem item in coll)
                    {
                        Campaign camp = new Campaign();

                        string[] metaInfo = item["MetaInfo"].ToString().Split('\n');
                        foreach (var i in metaInfo)
                        {
                            if (i.Contains("vti_cachedcustomprops"))
                            {
                                continue;
                            }
                            if (i.Contains("CampaignEndDate"))
                            {
                                camp.CampaignEndDate = Convert.ToDateTime(i.Split('|')[1].Replace("\r", ""));
                            }
                        }

                        if (camp.CampaignEndDate >= DateTime.Now)
                        {
                            camp.Created = Convert.ToDateTime(item["Created"]);
                            camp.ID      = Convert.ToInt32(item["ID"]);
                            camp.Title   = item["Title"].ToString();
                            camps.Add(camp);
                        }
                    }
                }

                return(camps);
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
        public IEnumerable <TEntity> GetItemsByQuery(string ListName, ICamlQuery Query)
        {
            try
            {
                List <TEntity> entityItems = new List <TEntity>();
                SP.Web         web         = context.Web;
                SP.List        list        = web.Lists.GetByTitle(ListName);

                SP.CamlQuery query = (SP.CamlQuery)Query.ExecuteQuery();

                SP.ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                foreach (SP.ListItem item in items)
                {
                    var properties = typeof(TEntity).GetProperties();

                    TEntity entry = new TEntity();

                    foreach (var property in properties)
                    {
                        if (item[property.Name] != null)
                        {
                            var i = item[property.Name];
                            property.SetValue(entry, item[property.Name]);
                        }
                    }

                    entityItems.Add(entry);
                }

                return(entityItems);
            }
            catch (InvalidCastException ex)
            {
                throw new Exception(ex.Message + ". Data model types are invalid, please verify that models are strongly typed and match the SharePoint list column types.", new InvalidCastException());
            }
            catch (Exception ex)
            {
                throw new Exception("Error updating SharePoint list data: " + ex.Message);
            }
        }
예제 #15
0
        private static List <Tuple <string, Stream> > GetXmlFilesFromList()
        {
            List <Tuple <string, Stream> > inputFileStreams = new List <Tuple <string, Stream> >();  // XML files (item1=Name, item2=Data)

            spClient.ClientContext spCtx = LoginCsom();

            spClient.Web myWeb = spCtx.Web;
            spClient.FolderCollection   myFolders = myWeb.Folders;
            spClient.List               myList    = spCtx.Web.Lists.GetByTitle(SpListName);
            spClient.ListItemCollection allItems  = myList.GetItems(spClient.CamlQuery.CreateAllItemsQuery());
            spCtx.Load(myWeb);
            spCtx.Load(myFolders);
            spCtx.Load(allItems);
            spCtx.ExecuteQuery();

            foreach (spClient.ListItem oneItem in allItems)
            {
                spClient.AttachmentCollection allAttachments = oneItem.AttachmentFiles;
                spCtx.Load(allAttachments);
                spCtx.ExecuteQuery();

                foreach (spClient.Attachment oneAttachment in allAttachments)
                {
                    spClient.File myXmlFile = myWeb.GetFileByServerRelativeUrl(oneAttachment.ServerRelativeUrl);
                    spClient.ClientResult <Stream> myXmlData = myXmlFile.OpenBinaryStream();
                    spCtx.Load(myXmlFile);
                    spCtx.ExecuteQuery();

                    using (MemoryStream mStream = new MemoryStream())
                    {
                        if (myXmlData != null)
                        {
                            myXmlData.Value.CopyTo(mStream);
                            byte[]       myBinFile = mStream.ToArray();
                            MemoryStream xmlStream = new MemoryStream(myBinFile);
                            inputFileStreams.Add(Tuple.Create(myXmlFile.Name, (Stream)xmlStream));
                        }
                    }
                }
            }

            return(inputFileStreams);
        }
예제 #16
0
        private void Load(string listName)
        {
            oList = context.Web.Lists.GetByTitle(listName);

            CamlQuery camlQuery = new CamlQuery();

            camlQuery.ViewXml = @"<View><RowLimit>100</RowLimit></View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            context.Load(collListItem, items => items.Include(item => item.Id, item => item.DisplayName, item => item.FieldValuesForEdit));
            context.ExecuteQuery();

            //foreach (ListItem oListItem in collListItem)
            //{

            //}
            Seeding();
            //Update();
        }
예제 #17
0
 public static Announcement QueryAnnouncementDetails(int announcementId)
 {
     try
     {
         Announcement ann = new Announcement();
         Microsoft.SharePoint.Client.ListItemCollection coll = DAT.DataQuery.QueryListItems(AnnouncementModel.announcementsSiteUrl, AnnouncementModel.sayfalarListName, string.Format(AnnouncementModel.announcementDetailCamlQuery, announcementId));
         SP.ListItem item = coll[0];
         ann.ID      = announcementId;
         ann.Created = Convert.ToDateTime(item["Created"]);
         ann.Title   = item["Title"].ToString();
         ann.PublishingPageContent = HLP.TransformHtmlString(item["PublishingPageContent"].ToString());
         return(ann);
     }
     catch (Exception ex)
     {
         EXP.RedirectToErrorPage(ex.Message);
         return(null);
     }
 }
예제 #18
0
        public static List <Advert> QueryAdvertDetailForService(int id, string category)
        {
            try
            {
                List <Advert>         adverts = new List <Advert>();
                SP.ListItemCollection coll    = DAT.DataQuery.QueryListItems(BillBoardModel.advertsSiteUrl, BillBoardModel.sayfalarListName, string.Format(BillBoardModel.advertDetailForServiceCamlQuery, category, id));
                if (coll.Count > 0)
                {
                    var    item = coll[0];
                    Advert adv  = new Advert();
                    adv.Category    = category;
                    adv.ID          = id;
                    adv.Title       = item["Title"].ToString();
                    adv.Price       = Convert.ToDecimal(item["Price"]);
                    adv.Created     = Convert.ToDateTime(item["Created"]);
                    adv.Description = item["GenericDescription"].ToString();
                    adv.Detail      = item["GenericDetail"].ToString();

                    // Retrieve Images
                    List <string> imageServerUrls = DAT.DataQuery.QueryFolderFileUrls(BillBoardModel.advertsSiteUrl, BillBoardModel.goruntulerListName, id.ToString());
                    if (imageServerUrls.Count > 0)
                    {
                        List <string> urlPaths = new List <string>();

                        foreach (var imgUrl in imageServerUrls)
                        {
                            urlPaths.Add(HLP.ResizeAndSaveRemoteImageToLocalForService(imgUrl, 200, 100, 14, adv.GetType().Name.ToString() + id));
                        }

                        adv.ImageUrls = urlPaths;
                    }

                    adverts.Add(adv);
                }

                return(adverts);
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
예제 #19
0
        //public static string WrapHomePageBanners(string redirectPath, string bannerImageVirtualPath)
        //{
        //    try
        //    {
        //        //string wrapTextForHomePage = "<div><a href=\"{0}\"><img src=\"data:image/png:base64,{1}\" width=\"0\" height=\"0\" border=\"0\" alt=\"\"/></a></div>";
        //        string wrapText = "<div><a href=\"{0}\"><img src=\"{1}\" width=\"0\" height=\"0\" border=\"0\" alt=\"\"/></a></div>";
        //        return string.Format(wrapText, redirectPath, bannerImageVirtualPath);
        //    }
        //    catch (Exception ex)
        //    {
        //        EXP.RedirectToErrorPage(ex.Message);
        //        return null;
        //    }
        //}

        public static List <Banner> QueryLatestBannersForXml(int amount)
        {
            try
            {
                List <Banner>         banners = new List <Banner>();
                SP.ListItemCollection coll    = DAT.DataQuery.QueryListItems(BannerModel.bannersSiteUrl, BannerModel.bannersListName, BannerModel.latestBannersCamlQuery);
                if (coll.Count > 0)
                {
                    foreach (SP.ListItem item in coll)
                    {
                        Banner bnnr = new Banner();

                        string[] metaInfo = item["MetaInfo"].ToString().Split('\n');
                        foreach (var i in metaInfo)
                        {
                            if (i.Contains("TargetFrame"))
                            {
                                bnnr.IsExternalLink = Convert.ToBoolean(i.Split('|')[1].Replace("\r", "")); break;
                            }
                            ;
                        }
                        bnnr.ID       = Convert.ToInt32(item["ID"]);
                        bnnr.Title    = item["Title"].ToString();
                        bnnr.ImageUrl = item["FileLeafRef"].ToString();
                        var    linkUrl_  = (SP.FieldUrlValue)item["URL"];
                        string linkUrl__ = Convert.ToString(linkUrl_.Url);
                        if (linkUrl__.Contains(DAT.DataStatics.saportHostURL))
                        {
                            bnnr.IsExternalLink = false;
                        }
                        bnnr.LinkUrl = linkUrl_.Url;
                        banners.Add(bnnr);
                    }
                }

                return(banners);
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
예제 #20
0
파일: SPUtility.cs 프로젝트: TheDMon/Misc
        public List <ChangeRequest> ReadData()
        {
            // creates a new SharePoint context
            // passing the parameters
            ClientContext clientContext = new ClientContext(siteUrl);

            clientContext.Credentials = SetCredentials();

            // selects the list by title
            SP.List list = clientContext.Web.Lists.GetByTitle(listTitle);

            // requests the item collection, without filters
            SP.ListItemCollection itemCollection = list.GetItems(new CamlQuery());

            // loads the item collection object in the context object
            clientContext.Load(itemCollection);

            // executes everything that was loaded before (the itemCollection)
            clientContext.ExecuteQuery();

            // iterates the list printing the title of each list item
            List <ChangeRequest> lstChanges = new List <ChangeRequest>();

            foreach (SP.ListItem item in itemCollection)
            {
                var change = new ChangeRequest();
                change.ID                   = (int)item["ID"];
                change.Application          = item["Application_x0020_Name"].ToString().Trim();
                change.Title                = item["Title"].ToString().Trim();
                change.SOW                  = item["SOW_x0020_Number"] != null ? item["SOW_x0020_Number"].ToString().Trim() : "";
                change.Assignee             = item["Assignee"] != null ? item["Assignee"].ToString().Trim() : "";
                change.Status               = item["Status"] != null ? item["Status"].ToString().Trim(): "";
                change.ResolutionMethod     = item["ECC_x002f_CCP_x002f_ECCDC_x0023_"] != null ? item["ECC_x002f_CCP_x002f_ECCDC_x0023_"].ToString().Trim() : "";
                change.ActualResolutionDate = (System.DateTime?)item["Actual_x0020_Resolution_x0020_Da"];
                change.Created              = (System.DateTime)item["Created"];
                change.Modified             = (System.DateTime)item["Modified"];
                change.Resolved             = item["Resolved_x0020_Date"] != null && item["Resolved_x0020_Date"].ToString() != "" ? (DateTime)item["Resolved_x0020_Date"] : (DateTime?)null;

                lstChanges.Add(change);
            }

            return(lstChanges);
        }
예제 #21
0
        public static List <Campaign> QueryAllCampaignsForXml(int amount)
        {
            try
            {
                List <Campaign>       camps = new List <Campaign>();
                SP.ListItemCollection coll  = DAT.DataQuery.QueryListItems(CampaignModel.campaignsSiteUrl, CampaignModel.sayfalarListName, string.Format(CampaignModel.campaignsLimitedCamlQuery, amount * 3));
                if (coll.Count > 0)
                {
                    foreach (SP.ListItem item in coll)
                    {
                        Campaign camp     = new Campaign();
                        string[] metaInfo = item["MetaInfo"].ToString().Split('\n');
                        foreach (var i in metaInfo)
                        {
                            if (i.Contains("vti_cachedcustomprops"))
                            {
                                continue;
                            }
                            if (i.Contains("CampaignEndDate"))
                            {
                                camp.CampaignEndDate = Convert.ToDateTime(i.Split('|')[1].Replace("\r", ""));
                            }
                            if (i.Contains("ListImage"))
                            {
                                camp.ListImage = HLP.TransformImgHtmlStringAndGetBase64(i.Split('|')[1].Replace("\r", ""));
                                //camp.ListImage = "../temp/" + HLP.TransformHtmlStringAndGetFileName(i.Split('|')[1].Replace("\r", ""));
                                break;
                            }
                        }
                        camp.ID    = Convert.ToInt32(item["ID"]);
                        camp.Title = item["Title"].ToString();
                        camps.Add(camp);
                    }
                }

                return(camps.Take(amount).ToList());
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
예제 #22
0
        protected void btnScenario_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                var folder = clientContext.Web.Lists.GetByTitle("Web Part Gallery").RootFolder;
                clientContext.Load(folder);
                clientContext.ExecuteQuery();

                //upload the "userprofileinformation.webpart" file
                using (var stream = System.IO.File.OpenRead(
                           Server.MapPath("~/userprofileinformation.webpart")))
                {
                    FileCreationInformation fileInfo = new FileCreationInformation();
                    fileInfo.ContentStream = stream;
                    fileInfo.Overwrite     = true;
                    fileInfo.Url           = "userprofileinformation.webpart";
                    File file = folder.Files.Add(fileInfo);
                    clientContext.ExecuteQuery();
                }

                // Let's update the group for just uploaded web part
                var       list      = clientContext.Web.Lists.GetByTitle("Web Part Gallery");
                CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(100);
                Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(camlQuery);
                clientContext.Load(items);
                clientContext.ExecuteQuery();
                foreach (var item in items)
                {
                    // Just random group name to differentiate it from the rest
                    if (item["FileLeafRef"].ToString().ToLowerInvariant() == "userprofileinformation.webpart")
                    {
                        item["Group"] = "App Script Part";
                        item.Update();
                        clientContext.ExecuteQuery();
                    }
                }

                lblStatus.Text = string.Format("App script part has been added to web part gallery. You can find 'User Profile Information' script part under 'App Script Part' group in the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString());
            }
        }
        public TEntity GetItemById(string ListName, int Id)
        {
            try
            {
                TEntity      entry = new TEntity();
                SP.Web       web   = context.Web;
                SP.List      list  = web.Lists.GetByTitle(ListName);
                SP.CamlQuery query = new SP.CamlQuery();
                query.ViewXml = @"<View>  
                                        <Query> 
                                           <Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + Id + @"</Value></Eq></Where> 
                                        </Query> 
                                  </View>";

                SP.ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                if (items.Count > 0)
                {
                    SP.ListItem item       = items[0];
                    var         properties = typeof(TEntity).GetProperties();
                    foreach (var property in properties)
                    {
                        if (item[property.Name] != null)
                        {
                            property.SetValue(entry, item[property.Name]);
                        }
                    }
                }

                return(entry);
            }
            catch (InvalidCastException ex)
            {
                throw new Exception(ex.Message + ". Data model types are invalid, please verify that models are strongly typed and match the SharePoint list column types.", new InvalidCastException());
            }
            catch (Exception ex)
            {
                throw new Exception("Error updating SharePoint list data: " + ex.Message);
            }
        }
        private void Load(string listName)
        {
            oList = context.Web.Lists.GetByTitle(listName);

            CamlQuery camlQuery = new CamlQuery();

            camlQuery.ViewXml = @"<View><RowLimit>100</RowLimit></View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            context.Load(collListItem, items => items.Include(item => item.Id, item => item.DisplayName, item => item.FieldValuesForEdit));
            context.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                ProjectList.Add(new Project()
                {
                    Id          = oListItem.Id,
                    ProjectName = oListItem.FieldValuesForEdit.FieldValues["ProjectName"],
                    Description = oListItem.FieldValuesForEdit.FieldValues["ProjDescription"],
                    StartDate   = DateTime.Parse(oListItem.FieldValuesForEdit.FieldValues["StartDate"].ToString()),
                    EndDate     = DateTime.Parse(oListItem.FieldValuesForEdit.FieldValues["_EndDate"].ToString()),
                    StateList   = new ObservableCollection <string>()
                    {
                        "Signed", "Design", "Development", "Maintenance", "Closed"
                    },
                    State = oListItem.FieldValuesForEdit.FieldValues["State"],
                    //Leader =
                    //Leader = oListItem.FieldValuesForEdit.FieldValues["FirstName"],
                    //Languages = new ObservableCollection<Language>()
                    //{
                    //    new Language() { LanguageName = ScreenConstants.CSharp, IsChecked = IsContain(lang, ScreenConstants.CSharp) },
                    //    new Language() { LanguageName = ScreenConstants.FSharp, IsChecked = IsContain(lang, ScreenConstants.FSharp)},
                    //    new Language() { LanguageName = ScreenConstants.VisualBasic, IsChecked = IsContain(lang, ScreenConstants.VisualBasic)},
                    //    new Language() { LanguageName = ScreenConstants.Java, IsChecked = IsContain(lang, ScreenConstants.Java)},
                    //    new Language() { LanguageName = ScreenConstants.Jquery, IsChecked = IsContain(lang, ScreenConstants.Jquery)},
                    //    new Language() { LanguageName = ScreenConstants.AngularJS, IsChecked = IsContain(lang, ScreenConstants.AngularJS)},
                    //    new Language() { LanguageName = ScreenConstants.Other, IsChecked = IsContain(lang, ScreenConstants.Other)}
                    //}
                });
            }
            employeeGrid.ItemsSource = ProjectList;
        }
예제 #25
0
        private SP.ListItem GetLinkedProject()
        {
            // get all linked projects
            SP.ListItemCollection linkedProjects = GetItemsFromSharepointList(
                SharepointConstants.Links.linkedProjectList,
                SharepointConstants.Views.allItems
                );
            if (linkedProjects.Count == 0)
            {
                //return null;
            }

            // see if the current project is linked
            SP.ListItem linkedProject = SharepointMethods.GetItem(
                linkedProjects,
                SharepointConstants.ColumnHeaders.Title,
                _doc.Title
                );
            return(linkedProject);
        }
예제 #26
0
        public static Campaign QueryCampaignDetails(int campaignId)
        {
            try
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; // To avouid SSL Security - Certificate Error

                SP.ListItemCollection coll = DAT.DataQuery.QueryListItems(CampaignModel.campaignsSiteUrl, CampaignModel.sayfalarListName, string.Format(CampaignModel.campaignDetailCamlQuery, campaignId));
                SP.ListItem           item = coll[0];
                Campaign camp     = new Campaign();
                string[] metaInfo = item["MetaInfo"].ToString().Split('\n');
                foreach (var i in metaInfo)
                {
                    if (i.Contains("vti_cachedcustomprops"))
                    {
                        continue;
                    }
                    if (i.Contains("PublishingPageContent:SW"))
                    {
                        camp.PublishingPageContent = HLP.TransformHtmlString(i.Split('|')[1].Replace("\r", ""));
                    }
                    if (i.Contains("CampaignEndDate:SW"))
                    {
                        camp.CampaignEndDate = Convert.ToDateTime(i.Split('|')[1].Replace("\r", ""));
                    }
                    if (i.Contains("CampaignStartDate:SW"))
                    {
                        camp.CampaignStartDate = Convert.ToDateTime(i.Split('|')[1].Replace("\r", ""));
                    }
                }
                camp.ID    = Convert.ToInt32(item["ID"]);
                camp.Title = item["Title"].ToString();
                camp.PublishingPageContent = HttpUtility.HtmlDecode(camp.PublishingPageContent);

                return(camp);
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
예제 #27
0
        public static string CreateConnectionString(ClientContext clientContext)
        {
            string connectionString = "";

            try
            {
                List      sqlConfigList = clientContext.Web.Lists.GetByTitle("SQL Configuration");
                CamlQuery query         = new CamlQuery();
                query.ViewXml = @"<View>
                                <Query>
                                    <Where>
                                        <In>
                                            <FieldRef Name='Title'/>
                                            <Values>
                                                <Value Type='Text'>Server</Value>
                                                <Value Type='Text'>Database</Value>
                                                <Value Type='Text'>Integrated Security</Value>
                                            </Values>
                                        </In>
                                    </Where>
                                </Query>
                                <ViewFields>
                                    <FieldRef Name='Title'/>
                                    <FieldRef Name='Value1'/>
                                </ViewFields>
                            </View>";
                Microsoft.SharePoint.Client.ListItemCollection items = sqlConfigList.GetItems(query);

                clientContext.Load(items);
                clientContext.ExecuteQuery();
                foreach (Microsoft.SharePoint.Client.ListItem item in items)
                {
                    connectionString += item["Title"] + "=" + item["Value1"] + ";";
                }
            }
            catch (Exception ex)
            {
                WriteError(HttpContext.Current.Response, "Could not retrieve this App's settings. Please check the App's config! Message details:\n" + ex.Message);
            }
            return(connectionString);
        }
예제 #28
0
        public static List <Post> QueryAllLatestPostsLight(int amount)
        {
            try
            {
                List <Post>         posts      = new List <Post>();
                List <PostCategory> categories = DeserializeXMLToPostCategories(postCategoriesSaveFolder, postCategoriesSaveFileName);
                var postsOrdered = posts;
                if (categories != null)
                {
                    foreach (var category in categories)
                    {
                        SP.ListItemCollection catPosts = DAT.DataQuery.QueryListItems(string.Format(postsSiteUrl, category.CategoryName), postsListName, string.Format(getPostsCamlQueryLightLimited, amount));
                        if (catPosts.Count > 0)
                        {
                            foreach (SP.ListItem item in catPosts)
                            {
                                Post newPost = new Post()
                                {
                                    Id = Convert.ToInt32(item["ID"]), PublishedDate = Convert.ToDateTime(item["PublishedDate"]), CategoryName = category.CategoryName, Title = item["Title"].ToString()
                                };
                                posts.Add(newPost);
                            }
                        }
                    }

                    postsOrdered = (from x in posts orderby x.PublishedDate descending select x).ToList();
                    posts.Clear();
                    for (int i = 0; i < amount; i++)
                    {
                        posts.Add(postsOrdered[i]);
                    }
                }

                return(posts);
            }
            catch (Exception ex)
            {
                EXP.RedirectToErrorPage(ex.Message);
                return(null);
            }
        }
예제 #29
0
        public void DynamicGlobalFooter()
        {
            string             GlobalURL       = ConfigurationManager.AppSettings["GlobalSearchURL"];
            string             AccountUsername = ConfigurationManager.AppSettings["AccountUsername"];
            string             AccountPassword = ConfigurationManager.AppSettings["AccountPassword"];
            string             AccountDomain   = ConfigurationManager.AppSettings["AccountDomain"];
            string             WebTitle        = "TelkomDotNetFooter";
            HtmlGenericControl oCSS            = new HtmlGenericControl(); /*Set the Css from the Library Elements */

            using (ClientContext clientContext = new ClientContext(GlobalURL))
            {
                NetworkCredential Credentials = new NetworkCredential(AccountUsername, AccountPassword, AccountDomain); //Credentials does not expire

                clientContext.Credentials = Credentials;

                Web web = clientContext.Web;

                clientContext.Load(web);

                Microsoft.SharePoint.Client.List siteList1 = web.Lists.GetByTitle("Footer Templates");

                clientContext.Load(siteList1);

                CamlQuery camlQuery1 = new CamlQuery();


                camlQuery1.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + WebTitle + "</Value></Eq></Where></Query></View>";


                Microsoft.SharePoint.Client.ListItemCollection listCol1 = siteList1.GetItems(camlQuery1);

                clientContext.Load(listCol1);

                clientContext.ExecuteQuery();

                foreach (Microsoft.SharePoint.Client.ListItem oListItem1 in listCol1)
                {
                    Footer.InnerHtml += WebUtility.HtmlDecode(oListItem1["HTML"].ToString());
                }
            }
        }
예제 #30
0
        protected void BindListItems(Microsoft.SharePoint.Client.ListItemCollection items)
        {
            string outHtml = "<ul>";

            if (items.Count > 0)
            {
                foreach (Microsoft.SharePoint.Client.ListItem listItem in items)
                {
                    // We have all the list item data. For example, Title.
                    outHtml += string.Format("<li>{0}</li>", listItem["Title"]);
                }
            }
            else
            {
                outHtml += "<li>No items found</li>";
            }

            outHtml += "</ul>";

            listItemsContent.InnerHtml = outHtml;
        }