Exemplo n.º 1
1
        public static void BatchDeleteItems(SPList splTask, SPQuery query,SPWeb web)
        {
            // Set up the variables to be used.
            StringBuilder methodBuilder = new StringBuilder();
            string batch = string.Empty;
            string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                "<Batch onError=\"Return\">{0}</Batch>";

            string methodFormat = "<Method ID=\"{0}\">" +
                "<SetList Scope=\"Request\">{1}</SetList>" +
                "<SetVar Name=\"ID\">{2}</SetVar>" +
                "<SetVar Name=\"Cmd\">Delete</SetVar>" +
                "</Method>";

            // Get the list containing the items to update.
            //PList list = WorkFlowUtil.GetWorkflowList(listName);

            // Query to get the unprocessed items.

            SPListItemCollection unprocessedItems = splTask.GetItems(query);

            // Build the CAML delete commands.
            foreach (SPListItem item in unprocessedItems)
            {
                methodBuilder.AppendFormat(methodFormat, "1", item.ParentList.ID, item.ID.ToString());
            }

            // Put the pieces together.
            batch = string.Format(batchFormat, methodBuilder.ToString());

            // Process the batch of commands.
            string batchReturn = web.ProcessBatchData(batch.ToString());
        }
 public static SPFieldLookupValueCollection GetLookFieldIDS(string lookupValues, SPList lookupSourceList)
 {
     SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();
     string[] lookups = lookupValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
     foreach (string lookupValue in lookups)
     {
         SPQuery query = new Microsoft.SharePoint.SPQuery();
         query.Query = String.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", lookupValue);
         SPListItemCollection listItems = lookupSourceList.GetItems(query);
         foreach (Microsoft.SharePoint.SPListItem item in listItems)
         {
             SPFieldLookupValue value = new SPFieldLookupValue(item.ID.ToString());
             lookupIds.Add(value);
             break;
         }
     }
     return lookupIds;
 }
Exemplo n.º 3
0
        internal SPListItemCollection GetListItemCollection(SPList spList, string keyOne, string valueOne, string keyTwo, string valueTwo, string keyThree, string valueThree)
        {
            // Return list item collection based on the lookup field

            SPField spFieldOne = spList.Fields[keyOne];
            SPField spFieldTwo = spList.Fields[keyTwo];
            SPField spFieldThree = spList.Fields[keyThree];
            var query = new SPQuery
            {
                Query = @"<Where>
                          <And>
                             <And>
                                <Eq>
                                   <FieldRef Name=" + spFieldOne.InternalName + @" />
                                   <Value Type=" + spFieldOne.Type.ToString() + @">" + valueOne + @"</Value>
                                </Eq>
                                <Eq>
                                   <FieldRef Name=" + spFieldTwo.InternalName + @" />
                                   <Value Type=" + spFieldTwo.Type.ToString() + @">" + valueTwo + @"</Value>
                                </Eq>
                             </And>
                             <Eq>
                                <FieldRef Name=" + spFieldThree.InternalName + @" />
                                <Value Type=" + spFieldThree.Type.ToString() + @">" + valueThree + @"</Value>
                             </Eq>
                          </And>
                       </Where>"
            };

            return spList.GetItems(query);
        }
 public static void CheckandAddEntry(SPList configurationList, Guid ProjectGuid, Project Project_Svc)
 {
     try
     {
         // Checking whether the project id is already available.
         var query = new SPQuery
         {
             Query =
                 @"<Where><Eq><FieldRef Name='" + ProjectUIDFieldName + "' /><Value Type='Text'>" + ProjectGuid.ToString() + "</Value></Eq></Where>"
         };
         var ProjectItemCollection = configurationList.GetItems(query);
         if (ProjectItemCollection.Count == 0)
         {
             configurationList.ParentWeb.Site.RootWeb.AllowUnsafeUpdates = true;
             SPListItem item = configurationList.Items.Add();
             //first project name
             item["Title"] = Project_Svc.GetProjectNameFromProjectUid(ProjectGuid, DataStoreEnum.WorkingStore);
             item[GroupFieldName] = DefaultGroupValue;
             item[ProjectUIDFieldName] = ProjectGuid.ToString();
             item.Update();
             configurationList.ParentWeb.Site.RootWeb.Update();
         }
     }
     catch (Exception ex)
     {
         ErrorLog("Error at adding configuration item to the list due to " + ex.Message, EventLogEntryType.Error);
     }
 }
Exemplo n.º 5
0
 public static string GenerateValidImageName(string fileName, SPList pictureLibrary)
 {
     //Check if new image name validates
     int i = 0;
     string temp = fileName;
     string extention = Path.GetExtension(fileName);
     SPQuery query = new SPQuery(pictureLibrary.DefaultView);
     SPListItemCollection imageCollection;
     do
     {
         i++;
         query.ViewFields = "<Where><Eq><FieldRef Name='LinkFilename' /><Value Type='Computed'>" + fileName + "</Value></Eq></Where>";
         imageCollection = pictureLibrary.GetItems(query);
         if (imageCollection.Count > 0)
         {
             fileName = temp;
             string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName) + " " + i;
             fileName = fileNameWithoutExtension + extention;
         }
         else {
             break;
         }
     } while (imageCollection.Count > 0);
     return fileName;
 }
        private static SPListItemCollection GetCostsFromMonth(SPList costs, SPListItemCollection delegationsForSelectedMonth)
        {
            StringBuilder delegationIDBuilder = new StringBuilder();
            foreach (SPListItem delegationItem in delegationsForSelectedMonth)
            {
                delegationIDBuilder.AppendFormat("<Value Type='Lookup'>{0}</Value>", delegationItem["ID"]);
            }

            string costsForSelectedDelagationsQueryString = string.Format(
                "<Where>" +
                    "<In>" +
                        "<FieldRef Name='{0}' LookupId='TRUE'/>" +
                            "<Values>" +
                                "{1}" +
                            "</Values>" +
                    "</In>" +
                "</Where>",
                DelegationsFields.Delegation.Name,
                delegationIDBuilder);

            SPQuery costsForSelectedDelegationsQuery = new SPQuery();
            costsForSelectedDelegationsQuery.Query = costsForSelectedDelagationsQueryString;

            SPListItemCollection monthlyCosts = costs.GetItems(costsForSelectedDelegationsQuery);
            return monthlyCosts;
        }
Exemplo n.º 7
0
		// Executes the expression tree that is passed to it. 
		internal static object Execute(SPList list, Expression expression, bool isEnumerable)
		{
			// The expression must represent a query over the data source. 
			if (!IsQueryOverDataSource(expression))
				throw new InvalidProgramException("No query over the data source was specified.");

			var caml = (new CamlTranslator()).Translate(null, expression);

			var query = new SPQuery();

			var viewFieldsXml = caml.Element(Tags.ViewFields);
			var rowLimitXml = caml.Element(Tags.RowLimit);
			var queryXml = caml.Elements()
				.Where(n => n.Name != Tags.ViewFields && n.Name != Tags.RowLimit)
				.ToList();

			query.Query = (new XElement(Tags.Query, queryXml)).Value;
			if (viewFieldsXml != null)
			{
				query.ViewFields = viewFieldsXml.Value;
				query.ViewFieldsOnly = true;
			}
			if (rowLimitXml != null)
			{
				query.RowLimit = (int)rowLimitXml.Value;
			}

			return list.GetItems(query);
		}
Exemplo n.º 8
0
        private static void CleanList(SPList list)
        {
            if (list == null)
                throw new ArgumentNullException("list");

            SPQuery spQuery = CreateGetAllItemsQuery();

            int batchNumber = 1;

            while (true)
            {
                // get ids of items to be deleted
                SPListItemCollection items = list.GetItems(spQuery);
                if (items.Count <= 0)
                    break;

                string batchDeleteXmlCommand = GetBatchDeleteXmlCommand(list, items);

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                RunDeleteBatch(list, batchDeleteXmlCommand);

                stopwatch.Stop();

                Console.WriteLine(string.Format("Processed batch #{0} of {1} items in {2} second(s)", batchNumber, BatchSize, stopwatch.ElapsedMilliseconds / 1000.0));
                batchNumber++;
            }
        }
Exemplo n.º 9
0
        private SPListItem GetValue(SPWeb web, SPList list, string keyStr, ref int returnValue)
        {
            SPQuery spQueryConfig = new SPQuery
            {
                Query = "<Where>" +
                        "<Eq><FieldRef Name='Title' /><Value Type='Text'>" + keyStr + "</Value></Eq>" +
                        "</Where>",
                RowLimit = 1
            };
            var configItems = list.GetItems(spQueryConfig);
            if (configItems != null && configItems.Count > 0)
            {
                try
                {
                    int diff = DateTime.Now.DayOfWeek - DayOfWeek.Monday;
                    if (diff < 0)
                    {
                        diff += 7;
                    }
                    var startWeekDate = DateTime.Now.AddDays(-1 * diff).Date;

                    var dateModified = Convert.ToDateTime(Convert.ToString(configItems[0]["Modified"]));
                    if (keyStr.Equals("YesterdayNumBer") && dateModified.Date < DateTime.Now.Date)
                    {
                        var itemToUpdate = configItems[0];
                        var yNumber = GetValue(list, "DayNumBer");
                        itemToUpdate["Value"] = yNumber;
                        web.AllowUnsafeUpdates = true;
                        itemToUpdate.Update();
                        returnValue = yNumber;
                        return configItems[0];
                    }
                    if (keyStr.Equals("DayNumBer") && dateModified.Date < DateTime.Now.Date)
                    {
                        returnValue = 1;
                        return configItems[0];
                    }
                    if (keyStr.Equals("WeekNumBer") && dateModified.Date < startWeekDate)
                    {
                        returnValue = 1;
                        return configItems[0];
                    }
                    if (keyStr.Equals("MonthNumBer") && dateModified.Date < (new DateTime(DateTime.Now.Year,DateTime.Now.Month,1)).Date)
                    {
                        returnValue = 1;
                        return configItems[0];
                    }
                    returnValue = Convert.ToInt32(configItems[0]["Value"]);
                    return configItems[0];
                }
                catch (SPException) { }
                catch (Exception) { }
            }

            returnValue = 1;
            return null;
        }
        private static bool SetKeyInternal(string category, string key, string value, string description)
        {
            // first let's trim the supplied values..
            category = category.Trim();
            key      = key.Trim();

            bool changed = false;

            // no value found, proceed with query..
            SPSecurity.RunWithElevatedPrivileges(
                delegate
            {
                SPList configStoreList = TryGetConfigStoreListFromContext();

                if (configStoreList != null)
                {
                    try
                    {
                        SPListItemCollection items = configStoreList.GetItems(CompoundSingleQuery(category, key));
                        SPListItem currentItem;

                        if (items != null && items.Count == 1)
                        {
                            // Modify
                            currentItem = items[0];
                        }
                        else
                        {
                            // Add
                            currentItem = configStoreList.Items.Add();
                            currentItem[FIELD_CATEGORY] = category;
                            currentItem[FIELD_KEY]      = key;
                        }

                        currentItem[FIELD_VALUE]       = value;
                        currentItem[FIELD_DESCRIPTION] = description;
                        currentItem.Update();

                        //configStoreList.ParentWeb.AllowUnsafeUpdates = true;
                        configStoreList.Update();
                        //configStoreList.ParentWeb.AllowUnsafeUpdates = false;
                        changed = true;
                    }
                    finally
                    {
                        // disposals are required..
                        configStoreList.ParentWeb.Site.Dispose();
                        configStoreList.ParentWeb.Dispose();
                    }
                }
            });

            return(changed);
        }
Exemplo n.º 11
0
        private static List <string> GetFilteredTitlesForSubWeb(SPList list, SPQuery query)
        {
            var items = list.GetItems(query);

            if (items.Count == 0)
            {
                return(new List <string>());
            }

            return((from SPListItem item in items select item.Title).ToList());
        }
        private static SPFile GetSPFile(SPList list)
        {
            SPQuery query = GetSPQuery(list);
            SPListItemCollection items = list.GetItems(query);

            if (items.Count == 1)
            {
                return(items[0].File);
            }
            return(null);
        }
Exemplo n.º 13
0
        private static void GetOrderLines(SPList orderLineList, SalesOrder salesOrder)
        {
            var lineQuery = new SPQuery();
            lineQuery.Query = "<Where><Eq><FieldRef Name='SalesOrder' LookupId='TRUE' /><Value Type='Lookup' >" + salesOrder.SalesOrderId + "</Value></Eq></Where>";
            var orderLines = orderLineList.GetItems(lineQuery);

            foreach (SPListItem line in orderLines)
            {
                salesOrder.Lines.Add(new OrderLine { Product = line.Title, Price = (double)line["Price"], Quantity = Convert.ToInt32(line["Quantity"]) });
            }
        }
        /// <summary>
        /// 从SharePoint列表获取数据
        /// </summary>
        /// <param name="listName">列表名称</param>
        /// <param name="query">Caml查询语句</param>
        /// <returns></returns>
        private SPListItemCollection GetDataFromList(string listName, string query)
        {
            SPListItemCollection items = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite spSite = new SPSite(SPContext.Current.Site.ID)) //找到网站集
                    {
                        using (SPWeb spWeb = spSite.OpenWeb(SPContext.Current.Web.ID))
                        {
                            SPList spList = spWeb.Lists.TryGetList(listName);

                            if (spList != null)
                            {
                                if (query != "")
                                {
                                    SPQuery qry = new SPQuery();
                                    qry.Query   = query;
                                    items       = spList.GetItems(qry);
                                }
                                else
                                {
                                    items = spList.GetItems();
                                }
                            }
                            else
                            {
                                divErr.InnerHtml = "指定的列表“" + listName + "”不存在!";
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    divErr.InnerHtml = ex.ToString();
                }
            });
            return(items);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 根据需要从计算所得的某天起生成计算所得天数的例行计划,并填入planList列表
        /// </summary>
        /// <param name="LogList">执行历史列表</param>
        /// <param name="rPlanList">例行计划列表</param>
        /// <param name="siteUrl">网站地址</param>
        /// <param name="planList">生成计划保存的列表</param>
        /// <param name="days">用户设置的天数</param>
        private void MakeRoutinePlan(string LogList, string rPlanList, string siteUrl, string planList, int days)
        {
            SPUser currentUser = SPContext.Current.Site.OpenWeb().CurrentUser;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    int k = 0;
                    using (SPSite spSite = new SPSite(siteUrl)) //找到网站集
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {
                            spWeb.AllowUnsafeUpdates = true;

                            SPList spList = spWeb.Lists.TryGetList(rPlanList);
                            if (spList != null)
                            {
                                SPListItemCollection rPlanListItems = spList.GetItems();
                                if (rPlanListItems.Count > 0)
                                {
                                    Dictionary <int, string> dict = GetChecked(cblPlans);
                                    foreach (KeyValuePair <int, string> kv in dict)
                                    {
                                        int planId               = kv.Key;
                                        string planTitle         = kv.Value;
                                        SPListItem rPlanListItem = rPlanListItems.GetItemById(planId);
                                        ArrayList leftdays       = SetLog(spWeb, LogList, days, currentUser, planId, planTitle);
                                        if (cbWeekEnd.Checked)//跳过周末
                                        {
                                            ArrayList workDays = QueryWeekDays(leftdays);
                                            writeToPlan(spWeb, planList, workDays, currentUser, rPlanListItem);
                                        }
                                        else
                                        {
                                            writeToPlan(spWeb, planList, leftdays, currentUser, rPlanListItem);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                lbErr.Text = "“" + rPlanList + "”列表不存在!";
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    lbErr.Text = "行号 " + ex.StackTrace + ":" + ex.ToString();
                }
            });
        }
Exemplo n.º 16
0
        internal IEnumerable <T> TryGetCachedModel <T>(ISPListItemAdapter source, string fieldName, params int[] lookupIds)
        {
            List <T>      collection  = new List <T>();
            SPObjectCache cache       = this.Manager.ObjectCache;
            SPFieldLookup lookupField = cache.GetField(source.WebId, source.ListId, fieldName) as SPFieldLookup;

            if (lookupField != null)
            {
                if (hashtable == null)
                {
                    hashtable = new Hashtable();
                }
                Guid       listId           = lookupField.LookupList == "Self" ? source.ListId : new Guid(lookupField.LookupList);
                List <int> lookupIdsToQuery = new List <int>();

                foreach (int id in lookupIds)
                {
                    LookupKey key = new LookupKey(listId, id);
                    if (hashtable.ContainsKey(key))
                    {
                        object cachedItem = hashtable[key];
                        if (cachedItem is T)
                        {
                            collection.Add((T)cachedItem);
                        }
                    }
                    else
                    {
                        lookupIdsToQuery.Add(id);
                    }
                }
                if (lookupIdsToQuery.Count > 0)
                {
                    ISPModelManagerInternal manager = hashtable.EnsureKeyValue(typeof(T), () => (ISPModelManagerInternal)SPModel.GetDefaultManager(typeof(T), this.manager.Site.RootWeb, cache));
                    SPList  list  = cache.GetList(lookupField.LookupWebId, listId);
                    SPQuery query = new SPQuery {
                        Query = Caml.EqualsAny(SPBuiltInFieldName.ID, lookupIdsToQuery).ToString()
                    };

                    foreach (SPListItem item in list.GetItems(query))
                    {
                        object model = manager.TryCreateModel(new SPListItemAdapter(item, cache), false);
                        hashtable[new LookupKey(listId, item.ID)] = model;
                        if (model is T)
                        {
                            collection.Add((T)model);
                        }
                        cache.AddListItem(item);
                    }
                }
            }
            return(collection);
        }
 protected void GetSiteNames()
 {
     #region Fetching Site Names and DocLibrary Name
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         using (SPSite site1 = new SPSite("http://win-njfp7te48bn/sites/HVEDev"))
         {
             using (SPWeb web1 = site1.OpenWeb())
             {
                 SPSecurity.RunWithElevatedPrivileges(delegate()
                 {
                     using (SPSite siteLogList = new SPSite("http://win-njfp7te48bn/sites/HVEDev"))
                     {
                         using (SPWeb webLogList = siteLogList.OpenWeb())
                         {
                             SPList logList = webLogList.Lists["TimerLogList"]; //Documents
                             try
                             {
                                 SPList list     = web1.Lists["DocLibLocations"];
                                 SPQuery myQuery = new SPQuery();
                                 myQuery.ViewXml = @"<View>
                                             <Query>
                                                 <FieldRef Name='SiteName' />
                                                 <FieldRef Name='DocLibName' />
                                             </Query>
                                        </View>";
                                 SPListItemCollection myItems = list.GetItems(myQuery);
                                 dtAudit.Columns.Add("DocName");
                                 dtAudit.Columns.Add("DocLocation");
                                 dtAudit.Columns.Add("DownloadCount");
                                 SPListItem logListItems = logList.Items.Add();
                                 logListItems["Title"]   = "Step 1 :- Fetching Site Names and DocLibrary Name";
                                 logListItems.Update();
                                 foreach (SPListItem item in myItems)
                                 {
                                     DocViewCounts(item["SiteName"].ToString(), item["DocLibName"].ToString());
                                 }
                                 //Literal1.Text = htmlStr1.ToString();
                             }
                             catch (Exception ee)
                             {
                                 SPListItem logListItems = logList.Items.Add();
                                 logListItems["Title"]   = "1:- GetSiteNames :- " + ee.Message;
                                 logListItems.Update();
                             }
                         }
                     }
                 });
             }
         }
     });
     #endregion
 }
Exemplo n.º 18
0
        private void CheckForQuickLaunchField(SPWeb spWeb)
        {
            spWeb.AllowUnsafeUpdates = true;

            SPList list = spWeb.Lists.TryGetList(INSTALLED_APPS);

            if (list != null)
            {
                if (!list.Fields.ContainsFieldWithInternalName("QuickLaunchOrder"))
                {
                    SPFieldNumber fldQuickLaunchOrder = (SPFieldNumber)list.Fields.CreateNewField(SPFieldType.Number.ToString(), "QuickLaunchOrder");

                    fldQuickLaunchOrder.Title         = "QuickLaunchOrder";
                    fldQuickLaunchOrder.DisplayFormat = SPNumberFormatTypes.NoDecimal;
                    fldQuickLaunchOrder.Indexed       = false;
                    list.Fields.Add(fldQuickLaunchOrder);
                    list.Update();

                    fldQuickLaunchOrder       = list.Fields["QuickLaunchOrder"] as SPFieldNumber;
                    fldQuickLaunchOrder.Title = "QuickLaunchOrder";
                    fldQuickLaunchOrder.ShowInListSettings = true;
                    fldQuickLaunchOrder.DefaultValue       = "1000";
                    fldQuickLaunchOrder.ShowInDisplayForm  = true;
                    fldQuickLaunchOrder.ShowInNewForm      = true;
                    fldQuickLaunchOrder.ShowInEditForm     = true;
                    fldQuickLaunchOrder.Hidden             = false;
                    fldQuickLaunchOrder.Update();

                    SPView tdefaultList = list.DefaultView;
                    tdefaultList.ViewFields.Add("QuickLaunchOrder");
                    tdefaultList.Update();

                    int     index = 0;
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><IsNull><FieldRef Name='EXTID'/></IsNull></Where><OrderBy><FieldRef Name='Title'/></OrderBy>";

                    foreach (SPListItem li in list.GetItems(query))
                    {
                        if (spWeb.ParentWeb == null && li["Title"].ToString().Equals("Global My Workplace", StringComparison.InvariantCultureIgnoreCase))
                        {
                            li["QuickLaunchOrder"] = "-1";
                        }
                        else
                        {
                            li["QuickLaunchOrder"] = index++;
                        }
                        li.Update();
                    }
                }
            }

            spWeb.AllowUnsafeUpdates = false;
        }
Exemplo n.º 19
0
 protected void Page_Load(object sender, EventArgs e)
 {
     currentList = SPContext.Current.Web.Lists[new Guid(Context.Request["List"])];
     SPView defView = currentList.DefaultView;
     items = currentList.GetItems(defView);
     if (!Page.IsPostBack)
         PopulatePage();
     this.TemplatesList.SelectedIndexChanged += new EventHandler(TemplatesList_SelectedIndexChanged);
     this.DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);
     this.ImageButton1.Click += new System.Web.UI.ImageClickEventHandler(ImageButton1_Click);
    
 }
        public List <StatisticsItem> GetUserStatistics(string userId)
        {
            List <StatisticsItem> result = new List <StatisticsItem>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(Settings.SiteURL))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList list = web.GetList("/Lists/" + Settings.ListName);

                            string internalUserField =
                                _listWorker.GetFieldInternalName(web, list.ID, Settings.UserFieldName);
                            string internalDateField =
                                _listWorker.GetFieldInternalName(web, list.ID, Settings.DateFieldName);
                            string internalValueField =
                                _listWorker.GetFieldInternalName(web, list.ID, Settings.ValueFieldName);

                            SPQuery query = new SPQuery();
                            query.Query   = string.Concat(
                                "<Where><Eq>",
                                "<FieldRef Name='" + internalUserField + "' LookupId='True'/>",
                                "<Value Type='User'>" + userId + "</Value>",
                                "</Eq></Where>",
                                "<OrderBy>",
                                "<FieldRef Name='" + internalDateField + "' Ascending='True' />",
                                "</OrderBy>"
                                );

                            SPListItemCollection items = list.GetItems(query);

                            foreach (SPListItem e in items)
                            {
                                result.Add(new StatisticsItem
                                {
                                    Date  = e[internalDateField].ToString(),
                                    User  = e[internalUserField].ToString(),
                                    Value = e[internalValueField].ToString()
                                });
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            return(result);
        }
Exemplo n.º 21
0
        private IList <Tag> GetITags()
        {
            rrLock.EnterUpgradeableReadLock();

            try
            {
                //Attempt to reload if the settings store is null and a load hasn't been attempted, or if the last load interval is exceeded.
                //in the case of a refresh, then _settingStore will be null and missingSettings will be false.
                if ((tags == null) || (DateTime.Now.Subtract(lastLoad).TotalSeconds) > cacheInterval)
                {
                    rrLock.EnterWriteLock();
                    try
                    {
                        if (tags == null)
                        {
                            tags = new List <Tag>();
                            SPWeb currentWeb = SPContext.Current.Web;
                            SPWeb rootWeb    = currentWeb.Site.RootWeb;

                            SPList MasterPageLib = rootWeb.GetCatalog(SPListTemplateType.MasterPageCatalog);//.GetList("_catalogs/masterpage");

                            SPQuery oQuery = new SPQuery();
                            oQuery.Query = string.Format("<Where><Contains><FieldRef Name=\"FileLeafRef\" /><Value Type=\"File\">.master</Value></Contains></Where><OrderBy><FieldRef Name=\"FileLeafRef\" /></OrderBy>");
                            SPListItemCollection colListItems = MasterPageLib.GetItems(oQuery);

                            foreach (SPListItem masterPageItem in colListItems)
                            {
                                Tag tag = Tag.CreateTag();
                                tag.UniqueId    = masterPageItem.UniqueId;
                                tag.Id          = masterPageItem.ID;
                                tag.Name        = masterPageItem.Name;
                                tag.Title       = tag.Name.Replace(".master", "").TrimEnd();
                                tag.Description = tag.Title + "description";
                                //TODO
                                //pageLayout.Description = pageLayoutItem["MasterPageDescription"].ToString();
                                tag.Url = masterPageItem.Url;

                                tags.Add(tag);
                            }
                        }
                    }
                    finally
                    {
                        rrLock.ExitWriteLock();
                    }
                }
                return(tags);
            }
            finally
            {
                rrLock.ExitUpgradeableReadLock();
            }
        }
Exemplo n.º 22
0
        private SPListItemCollection GetActions(string title, SPList targetList)
        {
            SPQuery query = new SPQuery();

            query.Query      = "<Where><Eq><FieldRef Name='Temp_x0020_Title' /><Value Type='Text'>" + title + "</Value></Eq></Where>";
            query.ViewFields = string.Concat(
                "<FieldRef Name='Temp_x0020_Title' />",
                "<FieldRef Name='_x0035__x0020_Whys_x0020_Title' />");
            query.ViewFieldsOnly = true;

            return(targetList.GetItems(query));
        }
Exemplo n.º 23
0
        /// <summary>
        ///     Get value content of a specific list
        /// </summary>
        /// <param name="spListName"></param>
        /// <param name="spQueryStr"></param>
        /// <param name="spFieldName"></param>
        /// <returns></returns>
        public string GetSharePointListItem(string spListName, string spQueryStr, string spFieldName, bool displayTitle)
        {
            try
            {
                string spListContentItem = "";

                using (SPWeb web = SPContext.Current.Web)
                {
                    SPList  spList  = web.Lists[spListName];
                    SPQuery spQuery = new SPQuery();
                    spQuery.Query = spQueryStr;
                    SPListItemCollection spListItems = spList.GetItems(spQuery);

                    if (spListItems.Count >= 1)
                    {
                        foreach (SPListItem item in spListItems)
                        {
                            if (displayTitle)
                            {
                                string strDate = "";
                                string title   = "";

                                if (spListName.ToString().ToLower() == "news")
                                {
                                    DateTime dat = Convert.ToDateTime(item["PublishDate"].ToString());
                                    strDate = "<div class='NewsDate'>" + dat.Day.ToString() + " " + getMonthName(dat.Month) + " " + dat.Year.ToString() + "</div><br>";
                                }

                                title = strDate + "<div class='NewsItemTitle'>" + item["Title"].ToString() + "</div><br>";

                                spListContentItem = title + item[spFieldName].ToString();
                            }
                            else
                            {
                                spListContentItem = item[spFieldName].ToString();
                            }
                        }
                    }
                }

                return(spListContentItem);
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper();
                objErr.logErrorEmail(APP_NAME, err, "Error at GetSharePointListItem function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);

                return(string.Empty);
            }
        }
Exemplo n.º 24
0
        public static void MoveDateUserToMultiUser(string siteUrl, string listName, string sourceColumn, string destinationColumn)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    if (!string.IsNullOrEmpty(siteUrl))
                    {
                        using (SPSite spSite = new SPSite(siteUrl))
                        {
                            using (SPWeb spWeb = spSite.RootWeb)
                            {
                                SPList spList = spWeb.Lists.TryGetList(listName);
                                if (spList != null)
                                {
                                    SPQuery spQuery = new SPQuery()
                                    {
                                        RowLimit = 100,
                                        Query    = "<Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where>",
                                    };

                                    do
                                    {
                                        SPListItemCollection items = spList.GetItems(spQuery);
                                        foreach (SPListItem item in items)
                                        {
                                            var userFieldValue = item[item.Fields.GetFieldByInternalName(sourceColumn).Id] + string.Empty;
                                            if (!string.IsNullOrEmpty(userFieldValue))
                                            {
                                                SPFieldUserValueCollection multiUserFieldValue = new SPFieldUserValueCollection(spWeb, userFieldValue);
                                                item[item.Fields.GetFieldByInternalName(destinationColumn).Id] = multiUserFieldValue;
                                                item.SystemUpdate(true);
                                            }
                                        }

                                        spQuery.ListItemCollectionPosition = items.ListItemCollectionPosition;
                                    }while (spQuery.ListItemCollectionPosition != null);
                                }
                                else
                                {
                                    Console.WriteLine(string.Format("Cannot find the list '{0}'", listName));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("");
                    Console.WriteLine(ex.Message);
                }
            });
        }
        private DataTable GetListTable(string search, string groupName)
        {
            SPField searchField        = list.Fields[new Guid(groupName)];
            SPListItemCollection items = null;

            if (!string.IsNullOrEmpty(search))
            {
                SPQuery query = new SPQuery();

                if (searchField.Type == SPFieldType.DateTime)
                {
                    search = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(search));
                }

                string valueType = searchField.TypeAsString;
                if (searchField.Type == SPFieldType.Calculated)
                {
                    valueType = "Text";
                }

                query.ViewAttributes = "Scope=\"Recursive\"";
                query.Query          = string.Format("<Where><{0}><FieldRef ID=\"{1}\"/><Value Type=\"{2}\">{3}</Value></{0}></Where>"
                                                     , searchOperator ?? "Eq"
                                                     , searchField.Id.ToString()
                                                     , valueType
                                                     , search);

                items = list.GetItems(query);
            }
            else
            {
                items = list.Items;
            }

            if (items.Count > propertyBag.MaxSearchResults)
            {
                this.PickerDialog.ErrorMessage = LookupFieldWithPickerHelper.GetResourceString("lookupWithPickerSearchResultExceededMessage");
                return(dataTable);
            }

            foreach (SPListItem item in items)
            {
                DataRow row = dataTable.NewRow();
                foreach (DataColumn col in dataTable.Columns)
                {
                    SPField field = item.Fields[new Guid(col.ColumnName)];
                    row[col] = field.GetFieldValueAsText(item[field.Id]);
                }
                dataTable.Rows.Add(row);
            }

            return(dataTable);
        }
Exemplo n.º 26
0
        protected override void CreateChildControls()
        {
            SPList  list  = SPContext.Current.Web.Lists["News"];
            SPQuery query = new SPQuery()
            {
                Query = "<Query><Where><Eq><FieldRef Name=\"URL\" /><Value Type=\"URL\">cat</Value></Eq></Where><OrderBy><FieldRef Name=\"Created\" Ascending=\"True\" /></OrderBy></Query>"
            };

            SPView view = list.Views["testView"];  // This view would define Postion > 0

            SPListItemCollection items = list.GetItems(query);
        }
        private SurveyTemplateAdmin GetCurrentTemplate(HttpContext context)
        {
            SurveyTemplateAdmin stThis = null;
            string strList             = context.Request["List"] == null ? mcstrTemplateList : context.Request["List"];



            using (SPWeb web = SPContext.Current.Web)
            {
                try
                {
                    SPList lst = web.Lists.TryGetList(strList);

                    if (lst != null)
                    {
                        SPListItem lsi = null;

                        if (context.Request["TemplateID"] == null)
                        {
                            SPQuery qry = new SPQuery();
                            qry.RowLimit = 1;
                            qry.Query    = @"<OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>";
                            SPListItemCollection lic = lst.GetItems(qry);
                            if (lic.Count == 1)
                            {
                                lsi = lic[0];
                            }
                        }
                        else
                        {
                            lsi = lst.GetItemByUniqueId(new Guid(context.Request["TemplateID"]));
                        }

                        if (lsi != null)
                        {
                            stThis = new SurveyTemplateAdmin(lsi);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode        = 500;
                        context.Response.StatusDescription = "DWF Survey: Specified List Not Found";
                    }
                }
                catch (Exception ex)
                {
                    context.Response.StatusCode        = 500;
                    context.Response.StatusDescription = "DWF Survey: " + ex.Message;
                }
            }

            return(stThis);
        }
Exemplo n.º 28
0
        protected void DoSearch_Click(object sender, EventArgs e)
        {
            string strQuery = "";

            strQuery = "<OrderBy><FieldRef Name='Title' Ascending='FALSE' /></OrderBy>";
            List <string> conditions = new List <string>();

            String filter = "";

            String searchText = SearchBox.Text;

            if (searchText != "")
            {
                filter = "<Or><Contains><FieldRef Name='BaseName'/><Value Type='Text'>" + searchText + "</Value></Contains><Contains><FieldRef Name='Title'/><Value Type='Text'>" + searchText + "</Value></Contains></Or>";
            }


            if (!String.IsNullOrEmpty(filter))
            {
                strQuery = strQuery + "<Where>" + filter + "</Where>";
            }

            SPList  List  = manager.Libraries.ProtectedMasterLibrary.List;
            SPQuery query = new SPQuery();

            query.Query = string.Format(strQuery);

            WBLogging.Debug("The query filter being used: \n" + query.Query);

            SPFolder protectedLibraryRootFolder = manager.Libraries.ProtectedMasterLibrary.List.RootFolder;

            /*
             * WBTerm functionalArea = workBox.OwningTeam.FunctionalArea(workBox.FunctionalAreasTaxonomy)[0];
             *
             * WBLogging.Debug("Looking for folder: \n" + functionalArea.Name);
             *
             * SPFolder functionalAreaFolder = protectedLibraryRootFolder.WBxGetFolderPath(functionalArea.Name);
             *
             * if (functionalAreaFolder == null) WBLogging.Debug("functionalAreaFolder == null");
             * else
             * {
             *  WBLogging.Debug("Adding folder filter to query of: " + functionalAreaFolder.Name);
             * //    query.Folder = functionalAreaFolder;
             * }
             */


            SPListItemCollection items = List.GetItems(query);

            WBLogging.Debug("Found items: " + items.Count);

            RenderFoundRecords(items);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Populate Data Array Literal control with data from the Cases list
        /// </summary>
        private void PopulatePieDataArray(Literal litPieDataArray)
        {
            String        strArray = "";
            StringBuilder sb       = new StringBuilder();

            SPList listCases = GetList(SPContext.Current.Web, "Cases");

            if (listCases != null)
            {
                List <string> bureauList = GetChoiceFieldValues(listCases, "Bureau IG");

                if (bureauList != null && bureauList.Count > 0)
                {
                    int           intResultCount = 0;
                    StringBuilder sb2            = new StringBuilder();

                    for (int a = 0; a < bureauList.Count; a++)
                    {
                        int    intBureauCount = 0;
                        String strBureau      = bureauList[a];

                        sb.Append("// Iterating through BureauIG.  BureauIG: " + strBureau);
                        sb.Append(Environment.NewLine);
                        SPQuery queryStatus = new SPQuery
                        {
                            Query = "<Where><Eq><FieldRef Name='BureauIG' /><Value Type='Choice'>" + strBureau + "</Value></Eq></Where>"
                        };
                        SPListItemCollection listCaseItems = listCases.GetItems(queryStatus);
                        if (listCaseItems != null && listCaseItems.Count > 0)
                        {
                            sb.Append("// Cases Bureau Query Returned Results. ");
                            sb.Append(Environment.NewLine);
                            intResultCount++;
                            intBureauCount = listCaseItems.Count;
                            sb2.Append("['" + strBureau + "', " + intBureauCount + "]");
                            sb2.Append(",");
                        }
                    }
                    if (intResultCount > 0)
                    {
                        sb.Append("pieData = [");
                        sb.Append(Environment.NewLine);
                        sb2.Length = sb2.Length - 1;
                        sb.Append(sb2.ToString());
                        sb.Append(Environment.NewLine);
                        sb.Append("];");
                    }
                }
            }

            strArray             = sb.ToString();
            litPieDataArray.Text = strArray;
        }
Exemplo n.º 30
0
        protected override SPListItem FindListItem(SPList list, SPFolder folder, ListItemDefinition listItemModel)
        {
            var definition = listItemModel.WithAssertAndCast <ComposedLookItemDefinition>("model", value => value.RequireNotNull());

            // first by Name
            var items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query  = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Name'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", definition.Name)
            });

            if (items.Count > 0)
            {
                return(items[0]);
            }

            // by Title?
            items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query  = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Title'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", definition.Title)
            });

            if (items.Count > 0)
            {
                return(items[0]);
            }

            return(null);
        }
Exemplo n.º 31
0
        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPListItem currentItem = properties.ListItem;
                    string     EmailBody   = currentItem["Anakoinoseis"].ToString();
                    var        body1       = EmailBody.Split(new[] { ";" }, StringSplitOptions.None);
                    var        email       = "";
                    currentItem["E_x002d_mail_x0020_Body"] = "";
                    for (int i = body1.Length; i > 1; i -= 2)
                    {
                        email = currentItem["E_x002d_mail_x0020_Body"].ToString();
                        var body = body1[i - 1].Split(new[] { "#" }, StringSplitOptions.None);
                        currentItem["E_x002d_mail_x0020_Body"] = email + body[1] + "<br>";
                    }
                    base.EventFiringEnabled = false;
                    currentItem.Update();
                    base.EventFiringEnabled = true;
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                WriteLogFile(web, "Start sending emails");
                SPList groups = web.GetList("/greek/test/Lists/Expand Groups");
                SPListItemCollection items = groups.GetItems();
                foreach (SPListItem item in items)
                {
                    string name = item["User"].ToString();
                    name = name.Substring(3, name.Length - 3);
                    string email = web.EnsureUser(name).Email;

                    StringDictionary headers = new StringDictionary();
                    headers.Add("from", "*****@*****.**");
                    headers.Add("to", email);
                    headers.Add("subject", properties.ListItem["E-mail Subject"].ToString());
                    headers.Add("fAppendHtmlTag", "True"); //To enable HTML format

                    System.Text.StringBuilder strMessage = new System.Text.StringBuilder();
                    strMessage.Append(properties.ListItem["E-mail Body"].ToString());
                    SPUtility.SendEmail(web, headers, strMessage.ToString());

                    string message = "Email sent to " + name;
                    WriteLogFile(web, message);
                }
                WriteLogFile(web, "End sending emails");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int LCID = HttpContext.Current.Request.Url.Segments.Contains("fra/") ? 1036 : 1033;

            System.Text.StringBuilder sb = new StringBuilder();
            //Load the images and links from the List
            string smiconList = "SMIcon";

            //Shireeh Added run with elevated to avoid annonymous access issue
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        try
                        {
                            SPList list    = web.Lists.TryGetList(smiconList);
                            SPQuery oQuery = new SPQuery();
                            SPListItemCollection collListItems;
                            oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" +
                                           "<OrderBy><FieldRef Name='ItemOrder' /></OrderBy>";
                            collListItems = list.GetItems(oQuery);
                            if (sb != null & list != null && list.Items.Count > 0)
                            {
                                sb.Append("<div class= \"SMIconTitleRow\"><h3 class=\"background-accent margin-bottom-medium\" style\"width:100% !important; vertical-align:middle;\">");
                                sb.Append((LCID == 1033 ? this.SMIConLinksHeaderEn : this.SMIConLinksHeaderFr));
                                sb.Append("</h3></div><div class=\"SMIconLinkRow\"><div class= \"float-left\">");
                                sb.Append("&nbsp; &nbsp;");
                                foreach (SPListItem item in collListItems)
                                {
                                    string link = LCID == 1036 ? "FraLink" : "ENGLink";
                                    String img  = LCID == 1036 ? "FraIcon" : "ENGIcon";
                                    sb.Append("<a id=\"" + item.Title + "\" href=\"" + item[link].ToString().Split(',')[0] + "\" style=\"" + "stylename" + "\">" + "<img ID=\"" + "img" + item.Title + "\" runat=\"server\" src=\"" + item[img].ToString().Split(',')[0] + "\" /></a> ");
                                }
                                sb.Append("</div></div>");
                                sb.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"/Style Library/SideImageLink/SideImageLink.css\"/>");
                            }
                            Literal1.Text = sb.ToString();
                        }        //end try
                        catch
                        {
                        }
                        finally
                        {
                            site.Dispose();
                            web.Dispose();
                        }
                    }    //web
                }        //site
            });
        }
        protected void btnReject_Click(object sender, EventArgs e)
        {
            var         closeLink        = (Control)sender;
            GridViewRow row              = (GridViewRow)closeLink.NamingContainer;
            int         index            = row.RowIndex;
            string      IssueNo          = row.Cells[0].Text;
            TextBox     Comments         = (TextBox)gvIssueAdminView.Rows[index].FindControl("txtcomments");
            string      ApproverComments = Comments.Text.Trim();

            if (!string.IsNullOrEmpty(ApproverComments))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite Osite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb Oweb = Osite.OpenWeb())
                        {
                            SPList Olist   = Oweb.Lists[Utilities.IssueTrackerListName];
                            var Ospquery   = new SPQuery();
                            Ospquery.Query = @"<Where><Eq><FieldRef Name='Issue_x0020_No' /><Value Type='Text'>" + IssueNo + "</Value></Eq></Where>";
                            SPListItemCollection Olistcollection = Olist.GetItems(Ospquery);
                            foreach (SPListItem item in Olistcollection)
                            {
                                string Author           = item["Author"].ToString();
                                string[] AuthorEmail    = Author.Split('#');
                                SPUser user             = SPContext.Current.Web.EnsureUser(AuthorEmail[1]);
                                item["Comments"]        = Comments.Text;
                                item["Issue Status"]    = "Rejected";
                                Oweb.AllowUnsafeUpdates = true;
                                item.Update();
                                Oweb.AllowUnsafeUpdates = false;
                                Utilities.SendNotification(Oweb, user.Email + ";", "New Leave Application Issue has been assigned.", IssueNo, "Yes");
                                DataBind();
                            }
                        }
                    }
                });
            }
            else
            {
                lblerror.Text = "Please Enter Comments";
            }

            DataBind();
            foreach (GridViewRow currentrow in gvIssueAdminView.Rows)
            {
                PeopleEditor ppAuthorNew = (PeopleEditor)currentrow.FindControl("txtAssignTo");
                ppAuthorNew.Accounts.Clear();
                ppAuthorNew.Entities.Clear();
                ppAuthorNew.ResolvedEntities.Clear();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            List <SPListItem> matchingItems = new List <SPListItem>();

            using (var parentWeb = new SPSite("https://rivernet2ndev.trg.com/sites/litman/Matters").OpenWeb())
            {
                foreach (SPWeb web in parentWeb.Webs)
                {
                    SPList list = web.Lists.TryGetList("Pnotes");
                    try
                    {
                        list.Fields.GetField("Body");
                        list.Fields.GetField("Title");
                    }
                    catch { continue; }

                    if (list != null)
                    {
                        SPQuery query = new SPQuery
                        {
                            Query = @"<Where><Geq><FieldRef Name='Modified' /><Value Type='DateTime'><Today Offset='-180' /></Value></Geq></Where>"
                        };

                        foreach (SPListItem item in list.GetItems(query))
                        {
                            matchingItems.Add(item);
                        }
                    }
                }
            }

            //List<object> tableItems = new List<object>();
            //foreach (var item in matchingItems)
            //{
            //    var displayItem =
            //        new
            //        {
            //            Item = item["Title"],
            //            Matter = item.Web.Name,
            //            Created = item["Created"],
            //            Modified = item["Modified"],
            //            Author = item["Created By"],
            //            webName = item["Body"]
            //        };
            //    tableItems.Add(displayItem);
            //}
            //if (tableItems.Count == 0)
            //    tableItems.Add(new { Result = "No results were found." });
            //Results.DataSource = tableItems;
            Results.DataSource = matchingItems;
            Results.DataBind();
        }
Exemplo n.º 35
0
        private string getRiskStatus(string project)
        {
            try
            {
                string status = "green";

                SPQuery query = new SPQuery();
                query.Query = "<Where><Eq><FieldRef Name='Project'/><Value Type='Text'>" + project + "</Value></Eq></Where>";

                foreach (SPListItem liTask in riskList.GetItems(query))
                {
                    string   tskStatus = "";
                    DateTime dtDue     = DateTime.Now;
                    try
                    {
                        tskStatus = liTask[MyRiskState].ToString();
                    }
                    catch { }
                    try
                    {
                        dtDue = DateTime.Parse(liTask["DueDate"].ToString());
                    }
                    catch { }

                    if (arrRisks.Contains(tskStatus))
                    {
                        totalRisks++;
                        int newValue = (int)arrRisks[tskStatus] + 1;
                        arrRisks[tskStatus] = newValue;
                    }

                    //if (tskStatus == "Active")
                    //{
                    //    issue_active++;
                    //    if (status == "green")
                    //        status = "yellow";
                    //    if (dtDue < DateTime.Now)
                    //        status = "red";
                    //}
                    //else if (tskStatus == "Postponed")
                    //    issue_postponed++;
                    //else if (tskStatus == "Closed")
                    //    issue_closed++;
                }

                return(status);
            }
            catch
            {
                return("");
            }
        }
Exemplo n.º 36
0
 private static void UpdateDocuments()
 {
     try
     {
         using (SPSite site = new SPSite(ConfigurationManager.AppSettings["SharePointSiteUrl"]))
         {
             Console.WriteLine("Successfully connected to site at " + site.Url);
             using (SPWeb web = site.OpenWeb())
             {
                 Console.WriteLine("Successfully opened SPWeb at " + web.Url);
                 string  targetFileExtension = ConfigurationManager.AppSettings["TargetFileExtension"];
                 SPList  documentLibrary     = web.Lists[ConfigurationManager.AppSettings["LibraryName"]];
                 SPQuery query = new SPQuery();
                 query.ViewXml           = Util.GetViewQuery();
                 query.QueryThrottleMode = SPQueryThrottleOption.Override;
                 do
                 {
                     SPListItemCollection items = documentLibrary.GetItems(query);
                     int totalItems             = items.Count;
                     Console.WriteLine("Processing items " + (query.ListItemCollectionPosition != null ? query.ListItemCollectionPosition.ToString() : "0") + " to " + query.ListItemCollectionPosition + totalItems);
                     query.ListItemCollectionPosition = items.ListItemCollectionPosition;
                     for (int i = 0; i < items.Count; i++)
                     {
                         SPListItem item = items[i];
                         try
                         {
                             string currentFileName            = item[SPBuiltInFieldId.FileLeafRef].ToString();
                             string currentFileNameNoExtension = System.IO.Path.GetFileNameWithoutExtension(currentFileName);
                             string newFileName     = currentFileNameNoExtension + "." + targetFileExtension;
                             var    currentEditor   = item["Editor"];
                             var    currentModified = item["Modified"];
                             SPFile file            = item.File;
                             item.File.MoveTo(item.ParentList.RootFolder.Url + "/" + newFileName, true);
                             file.Item["Editor"]   = currentEditor;
                             file.Item["Modified"] = currentModified;
                             file.Item.UpdateOverwriteVersion();
                             Console.WriteLine("Document updated. ItemId=" + file.Item.ID);
                         }
                         catch (Exception fileUpdateException)
                         {
                             Util.LogError(string.Format("There was an error updating item with ID {0}. Exception details: {1}", item.ID, fileUpdateException.Message));
                         }
                     }
                 }while (query.ListItemCollectionPosition != null);
             }
         }
     }
     catch (Exception ex)
     {
         Util.LogError(string.Format("Error connecting to SharePoint. Exception details: {0}", ex.Message));
     }
 }
Exemplo n.º 37
0
        private static void GetUserStateFromPlan(string userName, string planList, string siteUrl, string[] stateIndexs)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite spSite = new SPSite(siteUrl)) //找到网站集
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {
                            spWeb.AllowUnsafeUpdates = true;

                            SPList spList = spWeb.Lists.TryGetList(planList);
                            if (spList != null)
                            {
                                SPQuery qry = new SPQuery();
                                qry.Query   = @"<Where><Eq><FieldRef Name='Author' LookupId='True' /><Value Type='Text'>" + userName + "</Value></Eq></Where>";
                                SPListItemCollection pListItems = spList.GetItems(qry);
                                //var results = from t in spList.Items.Cast<SPListItem>()                                              select new { t.Fields("Author")};
                                //var disresults = Enumerable.Distinct(results);
                                if (pListItems.Count > 0)
                                {
                                    DataTable dt = pListItems.GetDataTable();
                                    for (int i = 0; i < stateIndexs.Length; i++)
                                    {
                                        string benchmarkList  = ConfigurationSettings.AppSettings["BenchmarkList"].ToString();
                                        DataTable dtBenchmark = GetBenchmarkByIndex(stateIndexs[i], siteUrl, benchmarkList);
                                        if (dtBenchmark.Rows.Count > 0)
                                        {
                                            for (int j = 0; j <= dtBenchmark.Rows.Count; j++)
                                            {
                                                string aType     = dtBenchmark.Rows[j]["活动类别"].ToString();
                                                string selectStr = "操作类别 ='" + aType + "'";
                                                DataRow[] drs    = dt.Select(selectStr);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("列表“" + planList + "”不存在!");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            });
        }
Exemplo n.º 38
0
        public static SPListItemCollection GetWebRegistrySiteByURL(SPWeb web, string url)
        {
            SPQuery query = new SPQuery()
            {
                Query      = @"<Where><Eq><FieldRef Name='SiteRelativeUrl' /><Value Type='Text'>" + url + @"</Value></Eq></Where>",
                ViewFields = @"<FieldRef Name='CreatedDate' /><FieldRef Name='Template' /><FieldRef Name='SiteRelativeUrl' />",
                RowLimit   = QueryLimit
            };
            SPList list = web.Lists.TryGetList(Constants.WebRegistry.ListTitle);
            SPListItemCollection items = list.GetItems(query);

            return(items);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Gets the id of the last item in each library
        /// </summary>
        /// <param name="list">Library/List name in SharePoint</param>
        /// <returns>Last ID of the item</returns>
        static int GetNextID(SPList list)
        {
            SPListItemCollection items = list.GetItems(
                new SPQuery
            {
                Query          = Q.OrderBy(false, "ID"),
                ViewFields     = "<FieldRef Name=\"ID\"/>",
                ViewAttributes = Q.ScopeRecursive
            }
                );

            return(items[0].ID + 1);
        }
Exemplo n.º 40
0
        private void CargarAcreedor()
        {
            SPWeb  app   = SPContext.Current.Web;
            SPList Lista = app.Lists["Acreedores"];

            app.AllowUnsafeUpdates = true;
            SPQuery oQuery = new SPQuery();

            oQuery.Query = "<OrderBy>  <FieldRef Name = 'Nombre' Ascending = 'TRUE'/> </OrderBy>";
            SPListItemCollection items = Lista.GetItems(oQuery);

            util.CargaDDL(ddlAcreedor, items.GetDataTable(), "Nombre", "ID");
        }
        private void generataSliderHTML(StringBuilder sb, SPList list, int lcid)
        {
            SPQuery oQuery = new SPQuery();
            SPListItemCollection collListItems;

            oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" +
                                        "<OrderBy><FieldRef Name='ItemOrder' /></OrderBy>";
            collListItems = list.GetItems(oQuery);

            if (sb != null & list != null && list.Items.Count > 0)
            {
                sb.Append("<div class=\"span-2\"> ");
                int i = 1;
                sb.Append("<ul class=\"list-bullet-none\">");
                foreach (SPListItem item in collListItems)
                {
                    if (i <= 3)
                    {
                        if (i == 1 && lcid == 1033)
                            //--sb.Append("<li class=\"personLinkRow\"><div class= \"float-left\">" + item["English Link Text"] + "</br><a style=\"color: white !important;\" href=\"" + item["English Url"] + "\"> </div><div class=\"align-right\">" + "<img class=\"float-right\"  height: 45px;\" src=\"" + item.File.ServerRelativeUrl + "\" /> </a>");
                        //if (i == 2 && lcid == 1033)
                            sb.Append("<a style=\"color: white !important;\" href=\"" + item["English Url"] + "\"> <li class=\"webLinkRow\"><div class= \"float-left\">" + item["English Link Text"] + "</br><b>" + item["English Description"] + "</b></div><div class=\"align-right\">" + "<img class=\"float-right\"   src=\"" + item.File.ServerRelativeUrl + "\" />");
                        if (i == 2 && lcid == 1033)
                            sb.Append("<a style=\"color: white !important;\" href=\"" + item["English Url"] + "\"> <li class=\"phoneLinkRow\"><div class= \"float-left\">" + item["English Link Text"] + "</br><b>" + item["English Description"] + "</b></div><div class=\"align-right\">" + "<img class=\"float-right sideImageLinksSizes\" src=\"" + item.File.ServerRelativeUrl + "\" />");
                        if (i == 3 && lcid == 1033)
                            sb.Append("<a style=\"color: white !important;\" href=\"" + item["English Url"] + "\"> <li class=\"notepadLinkRow\"><div class= \"float-left\">" + item["English Link Text"] + "</br><b>" + item["English Description"] + "</b></div><div class=\"align-right\">" + "<img class=\"float-right\" src=\"" + item.File.ServerRelativeUrl + "\" />");

                        else
                        {
                            if (i == 1 && lcid == 1036)
                                //--sb.Append("<li class=\"personLinkRow\"><div class= \"float-left\">" + item["French Link Text"] + "</br><a style=\"color: white !important;\" href=\"" + item["French Url"] + "\"> </div><div class=\"align-right\">" + "<img class=\"float-right\"  height: 45px;\" src=\"" + item.File.ServerRelativeUrl + "\" /></a>");
                            //if (i == 2 && lcid == 1036)
                                sb.Append("<a style=\"color: white !important;\" href=\"" + item["French Url"] + "\"> <li class=\"webLinkRow\"><div class= \"float-left\">" + item["French Link Text"] + "</br><b>" + item["French Description"] + "</b></div><div class=\"align-right\">" + "<img class=\"float-right\"   src=\"" + item.File.ServerRelativeUrl + "\" />");
                            if (i == 2 && lcid == 1036)
                                sb.Append("<a style=\"color: white !important;\" href=\"" + item["French Url"] + "\"> <li class=\"phoneLinkRow\"><div class= \"float-left\">" + item["French Link Text"] + "</br><b>" + item["French Description"] + "</b></div><div class=\"align-right\">" + "<img class=\"float-right sideImageLinksSizes\" src=\"" + item.File.ServerRelativeUrl + "\" /><");
                            if (i == 3 && lcid == 1036)
                                sb.Append("<a style=\"color: white !important;\" href=\"" + item["French Url"] + "\"> <li class=\"notepadLinkRow\"><div class= \"float-left\">" + item["French Link Text"] + "</br><b>" + item["French Description"] + "</b></div><div class=\"align-right\">" + "<img class=\"float-right\" src=\"" + item.File.ServerRelativeUrl + "\" />");

                        }

                        sb.Append("</li> </a> <div class=\"clear\" class=\"sideImageLinksBottomClear;\"></div>");
                        i++;
                    }
                    else
                        break;
                }
                sb.Append("</ul>");
                sb.Append("</div>");

            }
        }
Exemplo n.º 42
0
        public static void Save_or_Update_Objs_EvalNotes(string login_name_to_convert_to_SPUser, string Active_Rate_Goals_Year, EvalNotes evalnotes)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite oSite             = new SPSite(SPContext.Current.Web.Url);
                SPWeb spWeb              = oSite.OpenWeb();
                spWeb.AllowUnsafeUpdates = true;
                SPList spList            = spWeb.GetList(SPUrlUtility.CombineUrl(spWeb.ServerRelativeUrl, "lists/" + "ObjsEvalNotes"));
                SPUser user              = SPContext.Current.Web.EnsureUser(login_name_to_convert_to_SPUser);
                string strEmpDisplayName = user.Name;

                #region Check if there is already a record for same Employee

                SPQuery qry = new SPQuery();
                qry.Query   =
                    @"   <Where>
                                          <And>
                                             <Eq>
                                                <FieldRef Name='Emp' />
                                                <Value Type='User'>" + strEmpDisplayName + @"</Value>
                                             </Eq>
                                             <Eq>
                                                <FieldRef Name='ObjsYear' />
                                                <Value Type='Text'>" + Active_Rate_Goals_Year + @"</Value>
                                             </Eq>
                                          </And>
                                       </Where>";
                SPListItemCollection results = spList.GetItems(qry);

                #endregion Check if there is already a record for same Employee

                if (results.Count > 0)
                {
                    SPListItem oListItem = spList.GetItemById(int.Parse(results[0]["ID"].ToString()));
                    oListItem["Note_ReasonForRating1or5"] = evalnotes.ReasonForRating1or5;
                    oListItem["Note_RecommendedCourses"]  = evalnotes.RecommendedCourses;
                    oListItem.Update();
                }
                else
                {
                    SPListItem oListItem  = spList.AddItem();
                    oListItem["Emp"]      = SPContext.Current.Web.EnsureUser(login_name_to_convert_to_SPUser);
                    oListItem["ObjsYear"] = Active_Rate_Goals_Year;
                    oListItem["Note_ReasonForRating1or5"] = evalnotes.ReasonForRating1or5;
                    oListItem["Note_RecommendedCourses"]  = evalnotes.RecommendedCourses;
                    oListItem.Update();
                }

                spWeb.AllowUnsafeUpdates = false;
            });
        }
        protected override SPListItem FindListItem(SPList list, SPFolder folder, ListItemDefinition listItemModel)
        {
            var definition = listItemModel.WithAssertAndCast<ComposedLookItemDefinition>("model", value => value.RequireNotNull());

            // first by Name
            var items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Name'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", definition.Name)
            });

            if (items.Count > 0)
                return items[0];

            // by Title?
            items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Title'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", definition.Title)
            });

            if (items.Count > 0)
                return items[0];

            return null;
        }
Exemplo n.º 44
0
        internal SPListItemCollection GetListItemCollection(SPList spList, string key, string value)
        {
            // Return list item collection based on the lookup field

            SPField spField = spList.Fields[key];
            var query = new SPQuery
            {
                Query = @"<Where>
                        <Eq>
                            <FieldRef Name='" + spField.InternalName + @"'/><Value Type='" + spField.Type.ToString() + @"'>" + value + @"</Value>
                        </Eq>
                        </Where>"
            };

            return spList.GetItems(query);
        }
Exemplo n.º 45
0
        protected virtual SPListItem FindListItem(SPList list, SPFolder folder, ListItemDefinition listItemModel)
        {
            var items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Title'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", listItemModel.Title)
            });

            if (items.Count > 0)
                return items[0];

            return null;
        }
Exemplo n.º 46
0
        ///sTitle, sAssignedTo
        /// <summary>
        /// 检测list里是否存在重复的ID记录
        /// </summary>
        /// <param name="splCompletedTasks"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool isUnique(SPList splTask, string id)
        {
            SPQuery query = new SPQuery();
                query.Query = string.Format(@"
                                                <Where>
                                                     <Eq>
                                                         <FieldRef Name='ID' />
                                                         <Value Type='Counter'>{0}</Value>
                                                      </Eq>
                                                </Where>", id);

                int iCount = splTask.GetItems(query).Count;
                if (iCount > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
        }
        private void generataSliderHTML(StringBuilder sb, SPList list, int lcid)
        {
            SPQuery oQuery = new SPQuery();
            SPListItemCollection collListItems;

            oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" +
                                        "<OrderBy><FieldRef Name='ItemOrder' /></OrderBy>";
            collListItems = list.GetItems(oQuery);

            if (sb != null & list != null && list.Items.Count > 0)
            {
                sb.Append("<div class=\"span-2\" style=\"margin: 0 0 0 0;padding: 0 0 0 0;\"> ");
                int i = 1;

                foreach (SPListItem item in collListItems)
                {
                    if (i <= 1)
                    {
                        if (i == 1 && lcid == 1033)
                            //sb.Append(" <div class=\"personLinkRow\" style=\"focus:block; display:block;  cursor:pointer; margin: 0 0 0 0;padding: 0 0 0 0; \"><a style=\"color: white !important;\" href=\"" + item["English Url"] + "\"><div class=\"align-right\" onclick=\"location.href='" + item["English Url"] + "';\" style=\"focus:block; display:block;  cursor:pointer; margin: 0 0 0 0;padding: 0 0 0 0; \" >" + "<img class=\"float-left\"  src=\"" + item.File.ServerRelativeUrl + "\" />");
                            sb.Append(" <div class=\"personLinkRow\" style=\"focus:block; display:block;  cursor:pointer; margin: 0 0 0 0;padding: 0 0 0 0; \" onclick=\"location.href='" + item["English Url"] + "';\"  ><a style=\"color: white !important;\" href=\"" + item["English Url"] + "\">");
                        else
                        {
                            if (i == 1 && lcid == 1036)
                               // sb.Append("<li class=\"personLinkRow\"><div class= \"float-left\" onclick=\"location.href='" + item["French Url"] + "';\" >" + item["French Link Text"] + "</br><a style=\"color: white !important;\" href=\"" + item["French Url"] + "\"> </div><div class=\"align-right\" onclick=\"location.href='" + item["French Url"] + "';\" >" + "<img class=\"float-right\"  height: 45px;\" src=\"" + item.File.ServerRelativeUrl + "\" /></a>");
                                //sb.Append("<div class=\"personLinkRow\" style=\"focus:block; display:block;  cursor:pointer; margin: 0 0 0 0;padding: 0 0 0 0; \" ><a style=\"color: white !important;\" href=\"" + item["French Url"] + "\"><div class=\"align-right\" onclick=\"location.href='" + item["French Url"] + "';\" style=\"focus:block; display:block;  cursor:pointer; margin: 0 0 0 0;padding: 0 0 0 0; \" >" + "<img class=\"float-left\"  src=\"" + item.File.ServerRelativeUrl + "\" /> ");
                                sb.Append(" <div class=\"personLinkRow\" style=\"focus:block; display:block;  cursor:pointer; margin: 0 0 0 0;padding: 0 0 0 0; \" onclick=\"location.href='" + item["French Url"] + "';\"  ><a style=\"color: white !important;\" href=\"" + item["French Url"] + "\">");
                            }

                        sb.Append("</a></div><div class=\"clear\" class=\"sideImageLinksBottomClear;\"></div>");
                        i++;
                    }
                    else
                        break;
                }

                sb.Append("</div>");

            }
        }
Exemplo n.º 48
0
        private static string GetQueryForCurrentUserReplies(SPList discussionBoard, SPUser currentUser, DateTime recentDate)
        {
            string query = null;

            if (discussionBoard != null)
            {
                SPQuery qry = new SPQuery();
                qry.Query = string.Format(@"<Where>
                                        <And>
                                            <And>
                                                <Eq>
                                                    <FieldRef Name='ContentType' />
                                                    <Value Type='Computed'>Message</Value>
                                                </Eq>
                                                <Eq>
                                                    <FieldRef Name='Author' LookupId='True' />
                                                    <Value Type='Integer'>{0}</Value>
                                                </Eq>
                                            </And>
                                            <Geq>
                                                <FieldRef Name = 'Modified' />
                                                <Value Type ='DateTime'>{1}</Value>
                                            </Geq>
                                        </And>
                                   </Where>", currentUser.ID, Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(recentDate));
                //qry.ViewFields = @"<FieldRef Name='ReplyNoGif' />";
                qry.ViewAttributes = "Scope='RecursiveAll'";
                SPListItemCollection listItems = discussionBoard.GetItems(qry);
                if (listItems.Count > 0)
                {
                    string queryText = @"<Eq>
                                             <FieldRef Name='ContentType' />
                                             <Value Type='Computed'>Discussion</Value>
                                          </Eq>";
                    List<string> threads = new List<string>();
                    foreach (SPListItem message in listItems)
                    {
                        string thread = Convert.ToString(message["ReplyNoGif"]);
                        //thread = thread.Substring(0, 46);
                        if (!threads.Contains(thread))
                        {
                            threads.Add(thread);

                        }
                    }

                    if (threads.Count == 1)
                    {
                        queryText = "<And>" + queryText + "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + "/" + threads[0] + "</Value></Eq></And>";
                    }
                    else
                    {
                        string tempQuery = "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + "/" + threads[0] + "</Value></Eq>";
                        for (int i = 1; i < threads.Count; i++)
                        {
                            tempQuery = "<Or>" +
                                                "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + "/" + threads[i] + "</Value></Eq>" +
                                                tempQuery +
                                        "</Or>";
                        }
                        queryText = "<And>" + tempQuery + "</And>";
                    }
                    queryText = "<Where>" + queryText + "</Where>";
                    query = queryText;
                }
            }
            return query;
        }
Exemplo n.º 49
0
 /// <summary>
 /// Determines whether [is list item exist] [the specified list].
 /// </summary>
 /// <param name="list">The list.</param>
 /// <param name="query">The query.</param>
 /// <returns>
 /// 	<c>true</c> if [is list item exist] [the specified list]; otherwise, <c>false</c>.
 /// </returns>
 private bool IsListItemExist(SPList list, SPQuery query)
 {
     bool blnItemExist = false;
     SPListItemCollection listitems = list.GetItems(query);
     if((listitems != null) && (listitems.Count <= 0))
     {
         blnItemExist = false;
     }
     else
     {
         blnItemExist = true;
     }
     return blnItemExist;
 }
Exemplo n.º 50
0
        private static SPListItemCollection GetListItemsByQuery(SPList list, string queryFormat, params string[] values)
        {
            SPQuery query = new SPQuery();
            query.Query = string.Format(queryFormat, values);

            return list.GetItems(query);
        }
        private bool TryGetSelectedAlbum(SPList albumLibary, out SPFolder folder)
        {
            var foldersQuery = new SPQuery
            {
                Query = QueryResources.AlbumsQueryText
            };

            folder = albumLibary.GetItems(foldersQuery)
                                .Cast<SPListItem>()
                                .Select(x => x.Folder)
                                .FirstOrDefault(x => x.Name.Equals(SelectedAlbumName, StringComparison.CurrentCultureIgnoreCase));

            return folder != null;
        }
Exemplo n.º 52
0
 private void GetAvailableValues3(SPList lookupList, string fId, ListBox ddl, string parentValue)
 {
     string caml = @"<Where><Eq><FieldRef Name='ParentName' LookupId='TRUE' /><Value Type='Lookup'>" + parentValue + "</Value></Eq></Where><OrderBy><FieldRef Name='Title' /></OrderBy>";
     var query = new SPQuery()
     {
         Query = caml
     };
     var items = lookupList.GetItems(query);
     if (items != null && items.Count > 0)
     {
         foreach (SPListItem item in items)
         {
             ddl.Items.Add(new ListItem("------------ " + item[fId].ToString(), item.ID.ToString()));
             GetAvailableValues3(lookupList, fId, ddl, item.ID.ToString());
         }
     }
 }
Exemplo n.º 53
0
        private static string GetQueryForRecentPosts(SPList discussionBoard, DateTime recentDate)
        {
            // All this is currently built, then you will see a recent discussion table appear even if there is no recent discussion
            //            string query = null;

            //            if (discussionBoard != null)
            //            {

            //                query = String.Format(@"<Where>
            //                                          <And>
            //                                            <Eq>
            //                                                <FieldRef Name='ContentType' />
            //                                                <Value Type='Computed'>Discussion</Value>
            //                                            </Eq>
            //                                           <Geq><FieldRef Name = 'Modified' /><Value Type ='DateTime'>{0}</Value></Geq>
            //                                          </And>
            //                                        </Where>
            //                                        <OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>", Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(recentDate));

            //            }
            //            return query;

            // This is simlar to GetQueryForCurrentUserReplies but we are not looking for replies made by the current user
            string query = null;

            if (discussionBoard != null)
            {
                SPQuery qry = new SPQuery();
                qry.Query = string.Format(@"<Where>
                                              <Or>
                                                <And>
                                                    <Eq>
                                                        <FieldRef Name='ContentType' />
                                                        <Value Type='Computed'>Message</Value>
                                                    </Eq>
                                                    <Geq>
                                                        <FieldRef Name = 'Modified' />
                                                        <Value Type ='DateTime'>{0}</Value>
                                                    </Geq>
                                                </And>
                                                <And>
                                                    <Eq>
                                                        <FieldRef Name='ContentType' />
                                                        <Value Type='Computed'>Discussion</Value>
                                                    </Eq>
                                                    <Geq><FieldRef Name = 'Modified' /><Value Type ='DateTime'>{0}</Value></Geq>
                                                </And>
                                              </Or>
                                   </Where>", Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(recentDate));
                //qry.ViewFields = @"<FieldRef Name='ReplyNoGif' />";
                qry.ViewAttributes = "Scope='RecursiveAll'";
                SPListItemCollection listItems = discussionBoard.GetItems(qry);
                if (listItems.Count > 0)
                {
                    string queryText = @"<Eq>
                                             <FieldRef Name='ContentType' />
                                             <Value Type='Computed'>Discussion</Value>
                                          </Eq>";
                    List<string> threads = new List<string>();
                    foreach (SPListItem message in listItems)
                    {

                        string thread = String.Empty;

                        if (message.ContentType.Name == "Message")
                        {
                            thread = Convert.ToString(message["ReplyNoGif"]).TrimStart('/');
                        }
                        else if (message.ContentType.Name == "Discussion")
                        {
                            thread = Convert.ToString(message["FileRef"]).TrimStart('/');
                        }
                        thread = "/" + thread;

                        if (!threads.Contains(thread))
                        {
                            threads.Add(thread);
                        }

                    }

                    if (threads.Count == 1)
                    {
                        queryText = "<And>" + queryText + "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + threads[0] + "</Value></Eq></And>";
                    }
                    else
                    {
                        string tempQuery = "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + threads[0] + "</Value></Eq>";
                        for (int i = 1; i < threads.Count; i++)
                        {
                            tempQuery = "<Or>" +
                                                "<Eq><FieldRef Name='FileRef' /><Value Type='Text'>" + threads[i] + "</Value></Eq>" +
                                                tempQuery +
                                        "</Or>";
                        }
                        queryText = "<And>" + queryText + tempQuery + "</And>";
                    }
                    queryText = "<Where>" + queryText + "</Where>";
                    query = queryText;
                }
            }
            return query;
        }
Exemplo n.º 54
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            GetListItemInfo();
            GetAssociationInfo();

            if (!Page.IsPostBack)
            {

                string agendaID = listItem["AgendaID"].ToString();
                string agendaType = string.Empty;
                string originatingAGMOffice = string.Empty;

                boardAgendas = SPContext.Current.Web.Site.RootWeb.Lists["Board Agenda"];

                SPQuery query = new SPQuery()
                {
                    Query = string.Format(@"<Query>
                                              <Where>
                                                <Eq>
                                                  <FieldRef Name='ID' />
                                                  <Value Type='Counter'>{0}</Value>
                                                </Eq>
                                              </Where>
                                            </Query>", agendaID)
                };

                foreach (SPListItem item in boardAgendas.GetItems(query))
                {
                    if (item["ID"].ToString() == agendaID)
                    {
                        agendaType = item["Agenda Type"].ToString();
                        originatingAGMOffice = item["AGM Office"].ToString();
                        break;
                    }
                }

                if (agendaType == "Procurement Resolution")
                {
                    chk_agm_legal.Checked = true;
                    chk_agm_finance.Checked = true;
                    chk_agm_contracts.Checked = true;
                    chk_executive_director.Checked = true;

                    if (originatingAGMOffice == "AGM-Audit")
                        chk_agm_audit.Checked = true;
                    else if (originatingAGMOffice == "AGM-Bus Operations")
                        chk_agm_busoperations.Checked = true;
                    else if (originatingAGMOffice == "AGM-Communications and External Affairs")
                        chk_agm_communications.Checked = true;
                    else if (originatingAGMOffice == "AGM-Planning")
                        chk_agm_planning.Checked = true;
                    else if (originatingAGMOffice == "AGM-Police")
                        chk_agm_police.Checked = true;
                    else if (originatingAGMOffice == "AGM-Rail Operations")
                        chk_agm_railoperations.Checked = true;
                    else if (originatingAGMOffice == "AGM-Safety and QA")
                        chk_agm_safety.Checked = true;
                    else if (originatingAGMOffice == "AGM-Technology")
                        chk_agm_it.Checked = true;

                }
            }
        }
        private string renderSection(SPFolder folderItem, SPList cLFFooterNavigation)
        {
            string sectionHTML = string.Empty;
            string sectionHeaderHTML = string.Empty;
            SPQuery oQuery = new SPQuery();
            oQuery.Folder = folderItem;
            // get only those links with a NavURL
            oQuery.Query = "<Where><IsNotNull><FieldRef Name='NavURL'/></IsNotNull></Where>" +
                           "<OrderBy><FieldRef Name='RowOrder' /></OrderBy>";
            SPListItemCollection collListItems;

            try
            {
                collListItems = cLFFooterNavigation.GetItems(oQuery);

                foreach (SPListItem childItem in collListItems)
                {
                    // if the childItem has the same title as the folderItem then this is the
                    // link associated with the section
                    // if no child item has the same title then the section is rendered with only a title
                    if (childItem["NavURL"] != null)
                    {
                        if (childItem.Title == folderItem.Name)
                        {
                            sectionHeaderHTML = childItem["NavURL"].ToString();
                        }
                        else
                        {
                            // then it is a link... add it to the section URL
                            sectionHTML += "<li><a href=\"" + childItem["NavURL"].ToString() + "\">" + childItem.Title + "</a></li>";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex.Message + " " + ex.StackTrace);
            }

            if (string.IsNullOrEmpty(sectionHeaderHTML))
            {
                // then there is no link for this header... just put out the text
                sectionHeaderHTML = "<h4 class=\"gcwu-col-head\">" + folderItem.Name + "</h4>";
            }
            else
            {
                // add in the link
                sectionHeaderHTML = "<h4 class=\"gcwu-col-head\"><a href=\"" + sectionHeaderHTML + "\">" + folderItem.Name + "</a></h4>";

            }

            // wrap the list of child items if there are any
            sectionHTML = (string.IsNullOrEmpty(sectionHTML)) ? string.Empty : "<ul>" + sectionHTML + "</ul>";

            return "<section><div class=\"span-2\">" + sectionHeaderHTML + sectionHTML + "</div></section>";
        }
        private void AddAlbumItemControls(SPList albumLibrary, SPFolder fromFolder)
        {
            var picturesQuery = new SPQuery
            {
                Query = QueryResources.TopLevelPhotosQueryText,
            };

            if(fromFolder != null)
            {
                picturesQuery.Folder = fromFolder;
            }

            var itemCount = 0;
            foreach (SPListItem curPicture in albumLibrary.GetItems(picturesQuery))
            {
                Controls.Add(new AlbumItem
                {
                    ThumbNailUrl = curPicture["ows_EncodedAbsThumbnailUrl"].ToString(),
                    LazyImageLoadEnabled = this.LazyLoadingEnabled,
                    Type = AlbumItem.AlbumItemType.Photo,
                    //ItemUrl = curPicture["ows_EncodedAbsUrl"].ToString()
                    ItemUrl = curPicture["ows_EncodedAbsWebImgUrl"].ToString()
                });
                itemCount++;
            }

            Controls.Add(new SimplePager { PageSize = ImagesPerPage > 0 ? (uint)ImagesPerPage : 0, TotalItems = (uint)itemCount});
        }
        private List<Contributor> GetContributors(SPList keyPeopleList)
        {
            SPQuery query = new SPQuery()
               {
                   Query = @"<Query>
                          <Where>
                            <Eq>
                              <FieldRef Name='IsContributor' />
                              <Value Type='Boolean'>1</Value>
                            </Eq>
                          </Where>
                        </Query>"
               };

            contributors = new List<Contributor>();

            foreach (SPListItem item in keyPeopleList.GetItems(query))
            {
                if ((item["KeyPerson"] != null) && (item["IsContributor"] != null))
                {
                    if (item["IsContributor"].ToString() == "True")
                    {
                        string contributorName = item["KeyPerson"].ToString();

                        Contributor contributor = GetSPUser(item, "Key Person");
                        if (contributor != null)
                        {
                            contributors.Add(contributor);
                        };
                    }
                }

            }

            return contributors;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            GetListItemInfo();
            GetAssociationInfo();

            //Get the Agenda Type
            string agendaID = listItem["AgendaID"].ToString();
            string agendaType = string.Empty;
            string originatingAGMOffice = string.Empty;

            boardAgendas = SPContext.Current.Web.Site.RootWeb.Lists["Board Agenda"];
            executives = SPContext.Current.Web.Site.RootWeb.Lists["Executives"];

            SPQuery query = new SPQuery()
            {
                Query = string.Format(@"<Query>
                                              <Where>
                                                <Eq>
                                                  <FieldRef Name='ID' />
                                                  <Value Type='Counter'>{0}</Value>
                                                </Eq>
                                              </Where>
                                            </Query>", agendaID)
            };

            foreach (SPListItem item in boardAgendas.GetItems(query))
            {
                if (item["ID"].ToString() == agendaID)
                {
                    agendaType = item["Agenda Type"].ToString();
                    originatingAGMOffice = item["AGM Office"].ToString();

                    break;
                }
            }

            signatories = new List<Signatory>();

            if ((agendaType == "Procurement Resolution") || (agendaType == "Non-Procurement Resolution")
                || (agendaType == "Briefing"))
            {
                // Get the Officer of the originating AGM office
                signatories.Add(GetAGMOfficer(originatingAGMOffice));
                // Get his boss based on if its CBSS or DGM
                signatories.Add(GetAGMOfficeSupervisor(originatingAGMOffice));
                //Also get the GM
                signatories.Add(GetAGMOfficer("GM"));
            }

            if ((agendaType == "Procurement Resolution") || (agendaType == "Non-Procurement Resolution"))
            {
                if (originatingAGMOffice != "AGM-Legal Services")
                    signatories.Add(GetAGMOfficer("AGM-Legal Services"));
            }
            gvContributors.DataSource = signatories;
            gvContributors.DataBind();
        }
Exemplo n.º 59
0
        private static DataTable GetSAPItemsDT(SPList list)
        {
            DataTable dt = null;
            SPQuery query;

            switch (list.Title)
            {
                case SPListName.TravelExpenseClaim:
                    DataTable sourceDT = list.Items.GetDataTable();
                    var matches = from dr in sourceDT.AsEnumerable()
                                  where HasPostToSAP(dr, list)
                                  select dr;
                    dt = matches.AsDataView().ToTable();
                    break;
                case SPListName.EmployeeExpenseClaim:
                    query = new SPQuery();
                    query.Query = @" <Where>
                                      <IsNotNull>
                                         <FieldRef Name='SAPNumber' />
                                      </IsNotNull>
                                   </Where>";
                    dt = list.GetItems(query).GetDataTable();
                    break;
                case SPListName.CreditCardClaim:
                    query = new SPQuery();
                    query.Query = @" <Where>
                                          <Or>
                                             <IsNotNull>
                                                <FieldRef Name='SAPNo' />
                                             </IsNotNull>
                                             <IsNotNull>
                                                <FieldRef Name='SAPUSDNo' />
                                             </IsNotNull>
                                          </Or>
                                       </Where>";
                    dt = list.GetItems(query).GetDataTable();
                    break;
                default:
                    query = new SPQuery();
                    query.Query = @" <Where>
                                      <IsNotNull>
                                         <FieldRef Name='SAPNo' />
                                      </IsNotNull>
                                   </Where>";
                    dt = list.GetItems(query).GetDataTable();
                    break;
            }

            return dt;
        }
        private void AddAlbumControls(SPList albumLibrary)
        {
            var albumsQuery = new SPQuery
            {
                Query = QueryResources.AlbumsQueryText,
            };

            var albumGroups =
                albumLibrary.GetItems(albumsQuery).Cast<SPListItem>().GroupBy(x => x["Start Date"] == null ? "Timeless" : x.GetFormattedValue("Album Year"))
                            .OrderByDescending(x => x.Key).ToList();

            //HACK: Get the albums with no date value at the end of the the list instead of the begining.
            var timelessPhotos = albumGroups.FirstOrDefault(x => x.Key == "Timeless");
            if(timelessPhotos != null)
            {
                albumGroups.Remove(timelessPhotos);
                albumGroups.Add(timelessPhotos);
            }

            var uploadControlHtml = GenerateUploadControlHtml(albumLibrary);
            var addAlbumControlHtml = GenerateAddAlbumControHtml(albumLibrary);
            var topHtml = String.Format(@"<div class='titleRow'>
                                            <span id='albumTitle'>Photos</span>
                                            {0}
                                            {1}
                                          </div>", uploadControlHtml, addAlbumControlHtml);
            Controls.Add(new LiteralControl(topHtml));

            var headerHtml = new StringBuilder(String.Format(@"<div class='albumHeader' data-albums-visible-for-groups='{0}'>Albums: ", AlbumsPerGroup), 250);
            foreach(var albumGroup in albumGroups.Select(x => x.Key))
            {
                headerHtml.AppendFormat(@"<span class='albumNav groupName selectable'>{0}</span>", albumGroup.Replace(",", String.Empty));
            }
            headerHtml.Append("</div>");
            Controls.Add(new LiteralControl(headerHtml.ToString()));

            foreach (var curAlbum in albumGroups)
            {
                var albumGroup = new AlbumGroup { GroupName = curAlbum.Key.Replace(",", String.Empty) };

                foreach(var album in curAlbum)
                {
                    //THANKS SHAREPOINT
                    var thumbNailUrlField = album["Album Thumbnail URL"];
                    var thumbNailUrl = thumbNailUrlField != null
                                           ? new SPFieldUrlValue(thumbNailUrlField.ToString()).Url
                                           : DefaultAlbumImage ?? String.Empty;

                    albumGroup.AddAlbum(new Album
                    {
                        AlbumName = album.Folder.Name,
                        ThumbNailUrl = thumbNailUrl,
                        LazyImageLoadEnabled = this.LazyLoadingEnabled,
                        Type = Album.AlbumType.Photo,
                        ItemsCount = album.Folder.ItemCount, //This will include sub-folders in the count, but they shouldn't be there.
                    });
                }

                Controls.Add(albumGroup);
            }
        }