//同一个人只能进行一次报名
        private int  CheckEntroll(SPItemEventProperties properties, string loginName)
        {
            string internalName = properties.List.Fields["学号/工号"].InternalName;
            SPItemEventDataCollection afterData = properties.AfterProperties;

            if (afterData[internalName].ToString().Trim() != loginName)
            {
                return(1);
            }
            if (!Common.IsMatching(loginName))
            {
                return(2);
            }
            SPList  spList = properties.List;
            SPQuery query  = new SPQuery();

            query.ViewAttributes = "Scope='RecursiveAll'";
            query.Query          = "<Where><Eq><FieldRef Name='" + internalName + "' /><Value Type='Text'>" + loginName + "</Value></Eq></Where>";
            SPListItemCollection listItems = spList.GetItems(query);

            if (listItems.Count > 0)
            {
                return(3);
            }
            else
            {
                return(0);
            }
        }
예제 #2
0
        public static ServiceResult UpdateCityWeatherData(ICityWeatherClient cityWeatherClient,
                                                          SPWeb web, string docUrl, SPItemEventDataCollection cityItemProps)
        {
            var result = new ServiceResult();

            try
            {
                var itemName = (string)cityItemProps["Title"];

                var position = new Position()
                {
                    Lat = Decimal.Parse((string)cityItemProps[CityItemFields.Latitude]),
                    Lon = Decimal.Parse((string)cityItemProps[CityItemFields.Longitude]),
                };

                var csvContent = cityWeatherClient.GetCityWeatherCSV(position);

                //check doc hash
                if (string.IsNullOrEmpty(docUrl) ||
                    csvContent.GetHashCodeSafe() != GetCityItemWeatherContent(web, docUrl).GetHashCodeSafe())
                {
                    cityItemProps[CityItemFields.DocumentRef] = SaveCityDocument(web, itemName, csvContent);
                }

                result.Result = true;
            }
            catch (Exception e)
            {
                result.Message = e.GetAggregatedExceptionMessage();
            }

            return(result);
        }
        private void ValidateUniqueCompositeKey(SPItemEventProperties properties, string[] compositeKeyFields)
        {
            // If the receiver isn't created with the data we need exit quickly (for performance reasons)
            if (string.IsNullOrEmpty(properties.ReceiverData))
            {
                return;
            }


            SPItemEventDataCollection aftProps  = properties.AfterProperties;
            ListItemValidator         validator = new ListItemValidator();

            bool result = validator.MatchingFieldsExistInList(properties.List, aftProps, compositeKeyFields);

            if (result)
            {
                StringBuilder errorMessage = new StringBuilder();
                errorMessage.Append("Duplicate entry.  The same composite key exists with the Field=Value: ");
                for (int looper = 0; looper < compositeKeyFields.Length; looper++)
                {
                    string key = compositeKeyFields[looper];
                    errorMessage.Append(key).Append('=').Append(aftProps[key]);
                    if (looper + 1 != compositeKeyFields.Length)
                    {
                        errorMessage.Append(", ");
                    }
                }
                properties.ErrorMessage = errorMessage.ToString();
                properties.Cancel       = true;
            }
        }
        private SPItemEventProperties CreateMockSpItemEventProperties(string title, string code, DateTime enrollmentDate, DateTime startDate, DateTime endDate, float courseCost)
        {
            //Create any mock objects we'll need here
            SPItemEventProperties spItemEventProperties = RecorderManager.CreateMockedObject <SPItemEventProperties>();
            SPWeb web = RecorderManager.CreateMockedObject <SPWeb>();
            SPItemEventDataCollection afterProperties = RecorderManager.CreateMockedObject <SPItemEventDataCollection>();

            //record our main expectations
            using (RecordExpectations recorder = RecorderManager.StartRecording())
            {
                object obj = spItemEventProperties.AfterProperties;
                recorder.Return(afterProperties).RepeatAlways();

                afterProperties["Title"] = string.Empty;
                afterProperties["TrainingCourseCode"] = string.Empty;

                spItemEventProperties.OpenWeb();
                recorder.Return(web);

                obj = spItemEventProperties.ListItem[new Guid(Fields.TrainingCourseCode)];
                recorder.Return("12345678").RepeatAlways();
            }

            //Record our expectations for our AfterProperties collection
            MockHelper.RecordSPItemEventDataCollection(afterProperties, "Title", title);
            MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseCode", code);
            MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseEnrollmentDate", enrollmentDate);
            MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseStartDate", startDate);
            MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseEndDate", endDate);
            MockHelper.RecordSPItemEventDataCollection(afterProperties, "TrainingCourseCost", courseCost);

            return(spItemEventProperties);
        }
예제 #5
0
        //ad用户个数 不能超过字符串中用户数
        private bool CheckAdUser(SPItemEventProperties properties)
        {
            string     adUserDispName           = "AuthorName";// GetDispNameByInternalName(properties.List, "AuthorName");
            SPListItem splItem                  = properties.ListItem;
            SPItemEventDataCollection afterData = properties.AfterProperties;

            if (afterData[adUserDispName] != null && afterData[adUserDispName].ToString() != "")
            {
                //SPFieldUserValueCollection adUsers = afterData[adUserDispName] as SPFieldUserValueCollection;//此处为空值
                int    adCount         = GetAdUserCount(afterData[adUserDispName].ToString().ToLower());
                string authorsDispName = "Authors";// GetDispNameByInternalName(properties.List, "Authors");
                if (afterData[authorsDispName] != null && afterData[authorsDispName].ToString() != "" || afterData[authorsDispName].ToString() == "")
                {
                    if (afterData[authorsDispName].ToString() == "")
                    {
                        return(false);
                    }
                    string txtAuthors = afterData[authorsDispName].ToString().Trim().Replace(";", ";");
                    txtAuthors = txtAuthors.TrimEnd(';');
                    string[] users = Regex.Split(txtAuthors, ";");
                    if (users.Length < adCount)//用户个数小于Ad个数
                    {
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                }
            }
            return(true);
        }
예제 #6
0
 /// <summary>
 /// RecordSPItemEventDataCollection mocks the Get behavior of the
 /// SPItemEventDataCollection collection.
 /// </summary>
 /// <param name="properties">A mocked instance of an SPItemEventDataCollection object</param>
 /// <param name="fieldName">the name of the SPField that will be used as the indexer</param>
 /// <param name="value">the mocked value to return</param>
 public static void RecordSPItemEventDataCollection(SPItemEventDataCollection properties, string fieldName, object value)
 {
     using (RecordExpectations recorder = RecorderManager.StartRecording())
     {
         object val = properties[fieldName];
         recorder.Return(value).RepeatAlways().WhenArgumentsMatch();
     }
 }
        public Dictionary <string, string> GetFieldsAndValues(SPItemEventDataCollection data, IEnumerable <string> compositeKeyFields)
        {
            Dictionary <string, string> fieldsAndValues = new Dictionary <string, string>();

            foreach (string compositeKeyField in compositeKeyFields)
            {
                SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(data[compositeKeyField].ToString());
                fieldsAndValues.Add(compositeKeyField, fieldLookupValue.LookupId.ToString());
            }
            return(fieldsAndValues);
        }
        private static void Initalize(SPItemEventDataCollection afterProperties, ITrainingCourseRepository repository, SPWeb web, out string title, out string code, out DateTime enrollmentDate, out DateTime startDate, out DateTime endDate, out float cost)
        {
            title          = ((string)afterProperties[repository.GetFieldName(new Guid(Fields.Title), web)]).Trim();
            code           = ((string)afterProperties[repository.GetFieldName(new Guid(Fields.TrainingCourseCode), web)]).Trim();
            enrollmentDate = Convert.ToDateTime(afterProperties[repository.GetFieldName(new Guid(Fields.TrainingCourseEnrollmentDate), web)]).ToUniversalTime();;
            startDate      = Convert.ToDateTime(afterProperties[repository.GetFieldName(new Guid(Fields.TrainingCourseStartDate), web)]).ToUniversalTime();;
            endDate        = Convert.ToDateTime(afterProperties[repository.GetFieldName(new Guid(Fields.TrainingCourseEndDate), web)]).ToUniversalTime();
            cost           = Convert.ToSingle(afterProperties[repository.GetFieldName(new Guid(Fields.TrainingCourseCost), web)]);

            afterProperties[repository.GetFieldName(new Guid(Fields.Title), web)] = title;
            afterProperties[repository.GetFieldName(new Guid(Fields.TrainingCourseCode), web)] = code;
        }
예제 #9
0
        /// <summary>
        /// 任务(操作和作品合成任务名称)和日程(人+操作+作品)
        /// </summary>
        /// <param name="properties"></param>

        public override void ItemAdding(SPItemEventProperties properties)
        {
            if (properties.List.Fields.ContainsField("操作") && properties.List.Fields.ContainsField("作品"))
            {
                SPItemEventDataCollection afterData = properties.AfterProperties;
                SPList myList         = properties.OpenWeb().Lists[properties.ListId];
                string nameFieldOper  = myList.Fields.GetField("操作").InternalName;
                string nameFieldWorks = myList.Fields.GetField("作品").InternalName;

                string newValue = afterData[nameFieldOper].ToString() + afterData[nameFieldWorks];
                properties.AfterProperties.ChangedProperties.Add("Title", newValue);
            }
        }
        public static SPFieldLookupValue GetFieldAsSPLookup(this SPItemEventDataCollection afterProperties, string fieldName)
        {
            SPFieldLookupValue spflv = null;

            try
            {
                string fieldValue = afterProperties[fieldName] as string;
                spflv = new SPFieldLookupValue(fieldValue);
            }
            catch (Exception x)
            {
                throw x;
            }
            return(spflv);
        }
        public bool MatchingFieldsExistInList(SPList list, SPItemEventDataCollection data, IEnumerable <string> compositeKeyFields)
        {
            Dictionary <string, string> fields = GetFieldsAndValues(data, compositeKeyFields);


            SPListItemCollection listItems = list.GetItems(BuildQuery(list, fields));

            if (listItems != null && listItems.Count > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #12
0
        private void GetAssignedToAndSupervisor(SPListItem item, SPItemEventDataCollection afterProperties, SPWeb caseWeb, ref SPUser assignedToUser,
                                                ref SPUser prevAssignedToUser, ref SPUser supervisorUser, ref SPUser prevSupervisorUser)
        {
            // Check if we the AssignedTo or AssignedToSupervisor was modified
            if (!string.IsNullOrEmpty(afterProperties["AssignedTo"].ToString()))
            {
                assignedToUser     = afterProperties.GetFieldAsSPUser("AssignedTo", caseWeb);
                prevAssignedToUser = item.GetFieldAsSPUser(eCaseConstants.FieldGuids.OOTB_ASSIGNEDTO);
            }

            //if (!string.IsNullOrEmpty(afterProperties["AssignedToSupervisor"].ToString()))
            //{

            //    supervisorUser = afterProperties.GetFieldAsSPUser("AssignedToSupervisor", caseWeb);
            //    prevSupervisorUser = item.GetFieldAsSPUser(eCaseConstants.FieldGuids.ECASES_LIST_ASSIGNEDTOSUPERVISOR);
            //}
        }
        public static SPListItem GetFieldLookupAsSPListItem(this SPItemEventDataCollection afterProperties, string fieldName, SPList parentList)
        {
            SPListItem item = null;

            try
            {
                SPFieldLookup      spfl  = parentList.Fields.GetFieldByInternalName(fieldName) as SPFieldLookup;
                SPFieldLookupValue spflv = afterProperties.GetFieldAsSPLookup(fieldName);
                item = spflv.GetListItem(spfl);
            }
            catch (Exception x)
            {
                throw x;
            }

            return(item);
        }
 public override void ItemUpdated(SPItemEventProperties properties)
 {
     try
     {
         if (properties.List.BaseTemplate.ToString() == "20002")
         {
             EventFiringEnabled = false;
             SPItemEventDataCollection before = properties.BeforeProperties;
             SPItemEventDataCollection after  = properties.AfterProperties;
             ////Add code for event ItemUpdated in WebSitePageEventHandler
             EventFiringEnabled = true;
         }
     }
     catch (Exception ex)
     {
         EventFiringEnabled = true;
         ex.ToString();
     }
 }
        /// <summary>
        /// Converts the AfterProperties contents of a field to an SPUser using SPFieldUserValue and EnsureUserProperly as necessary.
        /// </summary>
        /// <param name="afterProperties">AfterProperties collection, typically from SPItemEventProperties</param>
        /// <param name="fieldName">the name of the field in AfterProperties.  If not found, null is returned</param>
        /// <param name="web">the web in which the SPFieldUserValue resides, typically properties.Web</param>
        /// <returns>An SPUser object that represents the stored user</returns>
        public static SPUser GetFieldAsSPUser(this SPItemEventDataCollection afterProperties, string fieldName, SPWeb web)
        {
            SPUser user = null;

            try
            {
                string           fieldValue = afterProperties[fieldName] as string;
                SPFieldUserValue fuv        = new SPFieldUserValue(web, fieldValue);
                if (fuv.User != null)
                {
                    user = fuv.User;
                }
                else
                {
                    user = web.EnsureUserProperly(fuv.LookupValue);
                }
            }
            catch (Exception x)
            {
                throw x;
            }

            return(user);
        }
        private int GetNewLookupValue(SPItemEventDataCollection dataCollection, string compositeKeyField)
        {
            SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(dataCollection[compositeKeyField].ToString());

            return(fieldLookupValue.LookupId);
        }
예제 #17
0
        // Methods
        private List <string> AllIndexesOf(string oldStr, string value, out string str, SPItemEventDataCollection item)
        {
            List <string> list = new List <string>();

            str = "";
            string newValue = "";

            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentException("the string to find may not be empty", "value");
            }
            List <int> list2      = new List <int>();
            int        num        = 0;
            int        startIndex = 0;

            while (true)
            {
                startIndex = oldStr.IndexOf(value, startIndex);
                if (startIndex == -1)
                {
                    str = oldStr;
                    return(list);
                }
                int    index = oldStr.IndexOf("}}", (int)(startIndex + 1));
                string str3  = oldStr.Substring(startIndex + 2, (index - startIndex) - 2);
                oldStr = oldStr.Replace(oldStr.Substring(startIndex, (index - startIndex) + 2), newValue);
                list.Add(str3);
                num++;
                startIndex += value.Length;
            }
        }
예제 #18
0
        private string CalculateValue(SPWeb web, SPItemEventDataCollection item, string listName, string fields, string filters, string func, string items)
        {
            SPListItemCollection items2;
            float         num2;
            SPList        list  = web.GetList("/Lists/" + listName);
            SPQuery       query = new SPQuery();
            string        str   = "";
            string        s     = "";
            List <string> list2 = this.AllIndexesOf(filters, "{{", out str, item);

            string[] strArray = fields.Split(new char[] { ',' });
            if (filters != "")
            {
                query.Query          = str;
                query.ViewAttributes = "Scope='RecursiveAll'";
            }
            string str5 = func;

            switch (str5)
            {
            case "خالی":
            case "":
                str5 = items;
                if ((str5 == null) || (str5 != "Current"))
                {
                    return(s);
                }
                return(item[strArray[0]].ToString());

            case "Max":
                switch (items)
                {
                case "Current":
                {
                    float num = 0f;
                    foreach (string str3 in strArray)
                    {
                        if (float.Parse(item[str3].ToString()) > num)
                        {
                            num = float.Parse(item[str3].ToString());
                        }
                    }
                    return(num.ToString());
                }

                case "All":
                    items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                    return(items2[0][strArray[0]].ToString());

                case "Current&All":
                    items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                    num2   = float.Parse(item[strArray[0]].ToString());
                    if (num2 <= float.Parse(s))
                    {
                        return(s);
                    }
                    return(num2.ToString());
                }
                return(s);

            case "Min":
                switch (items)
                {
                case "Current":
                {
                    float num3 = 0f;
                    foreach (string str3 in strArray)
                    {
                        if (float.Parse(item[str3].ToString()) > num3)
                        {
                            num3 = float.Parse(item[str3].ToString());
                        }
                    }
                    return(num3.ToString());
                }

                case "All":
                    items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                    return(items2[0][strArray[0]].ToString());

                case "Current&All":
                    items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                    s      = items2[0][strArray[0]].ToString();
                    num2   = float.Parse(item[strArray[0]].ToString());
                    if (num2 >= float.Parse(s))
                    {
                        return(s);
                    }
                    return(num2.ToString());
                }
                return(s);

            case "Count":
                items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                s      = items2.Count.ToString();
                if (items == "Current&All")
                {
                    s = (float.Parse(s) + 1f).ToString();
                }
                return(s);

            case "First":
                items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                return(items2[0][strArray[0]].ToString());

            case "Last":
                items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                return(items2[items2.Count - 1][strArray[0]].ToString());

            case "Sum":
                float num4;
                switch (items)
                {
                case "Current":
                    num4 = 0f;
                    foreach (string str3 in strArray)
                    {
                        num4 += float.Parse(item[str3].ToString());
                    }
                    return(num4.ToString());

                case "All":
                    num4   = 0f;
                    items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                    foreach (SPListItem item2 in items2)
                    {
                        num4 += float.Parse(item[strArray[0]].ToString());
                    }
                    return(num4.ToString());

                case "Current&All":
                {
                    num4   = 0f;
                    items2 = (filters != "") ? list.GetItems(query) : list.GetItems(new string[0]);
                    foreach (SPListItem item2 in items2)
                    {
                        num4 += float.Parse(item[strArray[0]].ToString());
                    }
                    float num7 = num4 + float.Parse(item[strArray[0]].ToString());
                    return(num7.ToString());
                }
                }
                return(s);
            }
            return(s);
        }
예제 #19
0
        /// <summary>
        /// 已更新项.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            string DYNAMIC_CAML_QUERY_GET_CHILD_NODE = "<Where><Eq><FieldRef Name='{0}' /><Value Type='LookupMulti'>{1}</Value></Eq></Where>";
            SPList myTask = properties.OpenWeb().Lists[properties.ListId];

            if (!myTask.Fields.ContainsFieldWithStaticName("ParentTask"))
            {
                return;
            }
            string tastTitle   = properties.ListItem["Title"].ToString();
            string parentTitle = "";

            if (properties.ListItem["ParentTask"] != null)
            {
                parentTitle = properties.ListItem["ParentTask"].ToString();
            }
            string nameField = myTask.Fields.GetField("完成百分比").InternalName;
            SPItemEventDataCollection beforeData = properties.BeforeProperties;

            if (beforeData[nameField].ToString() != properties.ListItem["nameField"].ToString())//百分比发生改变
            {
                StringBuilder        Query    = new StringBuilder();
                SPListItemCollection objItems = null;
                SPQuery objSPQuery;
                objSPQuery = new SPQuery();

                if (parentTitle == "")//父任务
                {
                    if (properties.ListItem["nameField"].ToString() == "100")
                    {
                        try
                        {
                            Query.Append(String.Format(DYNAMIC_CAML_QUERY_GET_CHILD_NODE, "ParentTask", tastTitle));
                            objSPQuery.Query = Query.ToString();
                            objItems         = myTask.GetItems(objSPQuery);
                            foreach (SPListItem objItem in objItems)
                            {
                                objItem[nameField] = 100;
                                objItem.Update();
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }

                else//当前为子任务
                {
                    try
                    {
                        int totalFinish = 0;
                        int count       = 0;
                        Query.Append(String.Format(DYNAMIC_CAML_QUERY_GET_CHILD_NODE, "ParentTask", parentTitle));
                        objSPQuery.Query = Query.ToString();
                        objItems         = myTask.GetItems(objSPQuery);
                        foreach (SPListItem objItem in objItems)
                        {
                            totalFinish += (int)objItem[nameField];
                            count       += 1;
                        }
                        totalFinish = totalFinish / count;

                        SPFieldLookupValue pValue = properties.ListItem["ParentTask"] as SPFieldLookupValue;
                        Query = new StringBuilder();
                        Query.Append(string.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='int'>{1}</Value></Eq></Where>", "ID", pValue.LookupId));
                        objSPQuery.Query = Query.ToString();
                        objItems         = myTask.GetItems(objSPQuery);
                        if (objItems.Count > 0)
                        {
                            objItems[0][nameField] = totalFinish;
                            objItems[0].Update();
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }