public void SaveRosterAsTemplate(ItemDataQuery query)
        {
            DisableCaching();

            try
            {
                // init source Roster
                var sourceRoster      = new RosterDataService().ListSingleRosterEvent(query.ListId, query.ItemId);
                var sourceRosterProps = sourceRoster.RosterEventDictionary;

                // create empty Template Roster
                RosterDataService _dataService = new RosterDataService();
                var newRosterTemplate          = _dataService.CreateRosterEvent(Roster.Common.TableIDs.TEMPLATE_ROSTERS, (int)RosterEventType.TemplateRosterEvent);

                // fill template Roster properties
                var rosterTemplateFields = new RosterConfigService().GetList(Roster.Common.TableIDs.TEMPLATE_ROSTERS).ListMetadataFields;
                foreach (var field in rosterTemplateFields)
                {
                    if (field.InternalName == FieldNames.ROSTER_EVENT_ID || field.InternalName == FieldNames.ID ||
                        !sourceRosterProps.ContainsKey(field.InternalName))
                    {
                        continue;
                    }

                    newRosterTemplate.RosterEventDictionary[field.InternalName] = sourceRosterProps[field.InternalName];
                }

                // save template Roster
                _dataService.SaveRosterEvent(newRosterTemplate, Roster.Common.TableIDs.TEMPLATE_ROSTERS);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Example #2
0
        public itemView <Entity> CreateRosterEventItem(string version, string listId, int eventTypeId)
        {
            DisableCaching();
            var result = new itemView <Entity>();

            try
            {
                result.item = new Entity();
                var service = new RosterDataService();
                var content = service.CreateRosterEvent(listId.ToGuid(), eventTypeId);
                result.item.Key    = content.Id.ToSafeString();
                result.item.Fields = content.RosterEventProperties.ExpandoToNamed();
            }
            catch (Exception ex)
            {
                result.message.message      = ex.Message;
                result.message.messageLevel = messageLevelEnum.critical;
                //HandleException(ex);
            }
            return(result);
        }
Example #3
0
        private static string Migrate(string pagingInfo, MigrationMapping mapping)
        {
            string  _pagingInfo = null;
            SPQuery query       = new SPQuery {
                RowLimit   = LIST_ROW_LIMIT,
                ViewFields = "<FieldRef Name='ContentTypeId'/>" + String.Join("", mapping.FieldMapping.Select(m => string.Format("<FieldRef Name='{0}'/>", m.ListField.InternalName))),
                Query      = "<OrderBy><FieldRef Name='ID'/></OrderBy>"
            };

            if (!string.IsNullOrEmpty(pagingInfo))
            {
                query.ListItemCollectionPosition = new SPListItemCollectionPosition(pagingInfo);
            }
            Dictionary <int, int> usersCache = new Dictionary <int, int>();

            usersCache.Add(1073741823, 1); // System Account !!!!!!!

            int eventType = (mapping.Table.Id == TableIDs.PLANNED_ROSTERS) ? 0 : 1;
            RosterDataService _dataService = new RosterDataService();

            SPSecurity.RunWithElevatedPrivileges(delegate() {
                using (SPSite eSite = new SPSite(mapping.List.ParentWeb.Url))
                    using (SPWeb eWeb = eSite.OpenWeb())
                    {
                        Dictionary <int, string> errors = new Dictionary <int, string>();

                        SPListItemCollection items = eWeb.Lists[mapping.List.ID].GetItems(query);
                        foreach (SPListItem itm in items)
                        {
                            var rosterEvent = _dataService.CreateRosterEvent(mapping.Table.Id, eventType);

                            try
                            {
                                foreach (var mapEl in mapping.FieldMapping)
                                {
                                    if (itm[mapEl.ListField.InternalName] == null)
                                    {
                                        continue;
                                    }

                                    object _val = null;
                                    if (mapEl.ListField.Type == SPFieldType.Lookup || mapEl.ListField.TypeAsString == "DualLookup")
                                    {
                                        var lookupVal = (mapEl.AllowMultipleValues) ? itm.GetLookupValueCollection(mapEl.ListField)[0] : itm.GetLookupValue(mapEl.ListField);
                                        _val          = (lookupVal.LookupId.ToInt() == 0 || lookupVal.LookupValue == null) ? null : (int?)lookupVal.LookupId;
                                    }
                                    else if (mapEl.ListField.Type == SPFieldType.User)
                                    {
                                        SPFieldUserValue userVal = (mapEl.AllowMultipleValues) ?
                                                                   (itm[mapEl.ListField.InternalName] as SPFieldUserValueCollection)[0] : new SPFieldUserValue(eWeb, itm[mapEl.ListField.InternalName].ToString());
                                        if (usersCache.ContainsKey(userVal.LookupId))
                                        {
                                            // get value from cache
                                            _val = usersCache[userVal.LookupId];
                                        }
                                        else
                                        {
                                            var dbUserFld = mapEl.TableDbColumn as DbFieldUser;
                                            if (dbUserFld == null)
                                            {
                                                _val = userVal.LookupValue;
                                            }
                                            else
                                            {
                                                int _valInt = dbUserFld.EnsureUser(userVal).RosterLookupId;
                                                usersCache.Add(userVal.LookupId, _valInt);
                                                _val = _valInt;
                                            }
                                        }
                                    }
                                    else if (mapEl.ListField.Type == SPFieldType.MultiChoice)
                                    {
                                        SPFieldMultiChoiceValue vals = new SPFieldMultiChoiceValue(itm[mapEl.ListField.InternalName].ToString());
                                        List <string> choiceVals     = new List <string>();
                                        for (int k = 0; k < vals.Count; k++)
                                        {
                                            choiceVals.Add(vals[k]);
                                        }
                                        _val = choiceVals.ListToXml();
                                    }
                                    else
                                    {
                                        _val = itm[mapEl.ListField.InternalName];
                                    }
                                    rosterEvent.RosterEventDictionary[mapEl.TableColumn.InternalName] = _val;
                                }

                                rosterEvent.RosterEventDictionary[FieldNames.CONTENT_TYPE_ID] =
                                    mapping.ContentTypeMapping.Where(ct => ct.ListCtId == itm["ContentTypeId"].ToString()).Select(ct => ct.TableCtId).FirstOrDefault();
                                _dataService.SaveRosterEvent(rosterEvent, mapping.Table.Id);
                            }
                            catch (Exception ex)
                            {
                                //StringBuilder exMsg = new StringBuilder();
                                //exMsg.AppendFormat("Exception: {0};\nMessage: {1};\nStackTrace: {2}", ex.GetType().Name, ex.Message, ex.StackTrace);

                                //Exception innerEx = ex;
                                //while (innerEx.InnerException != null) {
                                //    innerEx = innerEx.InnerException;
                                //    exMsg.AppendFormat("\n\nInnerException: {0};\nMessage: {1};\nStackTrace: {2}", innerEx.GetType().Name, innerEx.Message, innerEx.StackTrace);
                                //}

                                errors.Add(itm.ID, "Error: " + ex.Message + ". Dict: " +
                                           String.Join(";", rosterEvent.RosterEventDictionary.Select(x => string.Format("[{0}]:{1}", x.Key, x.Value))));
                            }
                        }

                        if (errors.Any())
                        {
                            throw new Exception("Errors:<br/>" +
                                                String.Join("<br/>", errors.Select(er => string.Format("  ListItemID: {0}. {1}", er.Key, er.Value))));
                        }

                        _pagingInfo = items.ListItemCollectionPosition == null ? null : items.ListItemCollectionPosition.PagingInfo; //Paged=TRUE&p_ID=100
                    }
            });

            return(_pagingInfo);
        }
        public static void PublishRosterEvent(Guid itemId, int daysAhead)
        {
            var dataService = new RosterDataService();
            var item        = dataService.GetRosterEvent(itemId);

            if (item == null)
            {
                throw new Exception(string.Format("Roster with ID '{0}' does not exists!", itemId));
            }
            if (!item.GetIsRecurrence())
            {
                throw new Exception(string.Format("Unable to publish non recurrent Roster Event with ID '{0}'!", itemId));
            }
            var wrListFields = new RosterConfigService().GetList(TableIDs.WORKING_ROSTERS).ListMetadataFields;

            var plannedRosterProps = item.RosterEventDictionary;
            var publishPeriodStart = DateTime.Today;
            var publishPeriodEnd   = DateTime.Today.AddDays(daysAhead);
            var expandedEvents     = RecurrenceItemExpander.Expand(new List <RosterEvent> {
                item
            },
                                                                   null, publishPeriodStart, publishPeriodEnd,
                                                                   FieldNames.START_DATE, FieldNames.END_DATE,
                                                                   SPContext.Current.Web.RegionalSettings.TimeZone);
            var skipProps = new[]
            {
                FieldNames.START_DATE, FieldNames.END_DATE,
                FieldNames.RECURRENCE, FieldNames.ROSTER_EVENT_ID,
                FieldNames.ID, FieldNames.PARENT_ROSTER_ID
            };
            var expandedRosterEvents = expandedEvents as IList <ExpandedRosterEvent> ?? expandedEvents.ToList();

            publishPeriodStart = expandedRosterEvents.Min(expandedEvent => expandedEvent.StartDate);
            publishPeriodEnd   = expandedRosterEvents.Max(expandedEvent => expandedEvent.StartDate);

            #region Get Working Rosters from period to avoid duplicates

            // get required fields
            var startDateFld = wrListFields.FirstOrDefault(itm => itm.InternalName == FieldNames.START_DATE);
            var endDateFld   = wrListFields.FirstOrDefault(itm => itm.InternalName == FieldNames.END_DATE);
            var parentIdFld  = wrListFields.FirstOrDefault(itm => itm.InternalName == FieldNames.PARENT_ROSTER_ID);
            var rEventIdFld  = wrListFields.FirstOrDefault(itm => itm.InternalName == FieldNames.ROSTER_EVENT_ID);

            var qp = new QueryParams {
                SkipRows = 0, TakeRows = 500
            };
            qp.SelectCriteria.Add(startDateFld);
            qp.SelectCriteria.Add(rEventIdFld);
            qp.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>
                                     (parentIdFld, CompareType.Equal, ConcateOperator.And, itemId, null));
            qp.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>
                                     (startDateFld, CompareType.LessOrEqual, ConcateOperator.And, publishPeriodEnd, null));
            qp.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>
                                     (endDateFld, CompareType.MoreOrEqual, ConcateOperator.And, publishPeriodStart, null));

            var existingWorkRosters = dataService.ListRosterEventProperties(TableIDs.WORKING_ROSTERS, qp);
            var existingKeys        = existingWorkRosters.Select(wrProps => wrProps.FirstOrDefault(ff =>
                                                                                                   ff.Key == FieldNames.START_DATE)).Select(stKey => (DateTime)stKey.Value).ToList();

            #endregion

            foreach (var expEvent in expandedRosterEvents)
            {
                var startDate = expEvent.StartDate;
                var endDate   = expEvent.EndDate;
                if (existingKeys.Contains(startDate))
                {
                    continue;
                }                                                   // this WorkingRoster instance already published
                var newRoEv = dataService.CreateRosterEvent(TableIDs.WORKING_ROSTERS, (int)RosterEventType.WorkingRosterEvent);
                newRoEv.RosterEventDictionary[FieldNames.START_DATE]       = startDate;
                newRoEv.RosterEventDictionary[FieldNames.END_DATE]         = endDate;
                newRoEv.RosterEventDictionary[FieldNames.END_DATE]         = endDate;
                newRoEv.RosterEventDictionary[FieldNames.RECURRENCE]       = null;
                newRoEv.RosterEventDictionary[FieldNames.PARENT_ROSTER_ID] = itemId;
                foreach (var propName in plannedRosterProps.Keys.Where(propName => !skipProps.Contains(propName)))
                {
                    newRoEv.RosterEventDictionary[propName] = plannedRosterProps[propName];
                }
                dataService.SaveRosterEvent(newRoEv, TableIDs.WORKING_ROSTERS);
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var rosterEvent = (ControlMode == SPControlMode.New) ? _dataService.CreateRosterEvent(ListId, (int)EventType): Item;
                if (rosterEvent == null)
                {
                    throw new Exception("Roster event is empty");
                }
                foreach (var field in ListMetadataFields.Select(item => item.Item2))
                {
                    var uiControls = FieldControls.FirstOrDefault(item => item.Item2.ID == field.InternalName.ToString());
                    if (uiControls == null)
                    {
                        continue;
                    }
                    if (uiControls.Item3.ReadOnly)
                    {
                        if (Request.QueryString[field.InternalName] != null)
                        {
                            rosterEvent.RosterEventDictionary[field.InternalName] = Request.QueryString[field.InternalName];
                        }
                    }
                    else
                    {
                        rosterEvent.RosterEventDictionary[field.InternalName] = uiControls.Item2.Value;
                    }
                    if (uiControls.Item3.Required && string.IsNullOrWhiteSpace(uiControls.Item2.Value.ToSafeString()))
                    {
                        ErrorHolder.Controls.Add(new Label
                        {
                            Text = @"Please fill out all required fields", ForeColor = System.Drawing.Color.Red
                        });
                        return;
                    }
                }

                // set ContentType
                if (rosterEvent.RosterEventDictionary.ContainsKey(FieldNames.CONTENT_TYPE_ID))
                {
                    if (rosterEvent.RosterEventDictionary[FieldNames.CONTENT_TYPE_ID] == null)
                    {
                        rosterEvent.RosterEventDictionary[FieldNames.CONTENT_TYPE_ID] = ContentTypeId;
                    }
                }
                else
                {
                    rosterEvent.RosterEventDictionary.Add(FieldNames.CONTENT_TYPE_ID, ContentTypeId);
                }

                // set StartDate and EndDate for AllDayEvent
                if (rosterEvent.RosterEventDictionary.ContainsKey(FieldNames.ALL_DAY_EVENT) &&
                    rosterEvent.RosterEventDictionary.ContainsKey(FieldNames.START_DATE) &&
                    rosterEvent.RosterEventDictionary.ContainsKey(FieldNames.END_DATE))
                {
                    var allDayEventObj = rosterEvent.RosterEventDictionary[FieldNames.ALL_DAY_EVENT];
                    if (allDayEventObj != null && allDayEventObj.ToBoolean())
                    {
                        var startDt = rosterEvent.RosterEventDictionary[FieldNames.START_DATE];
                        var endDt   = rosterEvent.RosterEventDictionary[FieldNames.END_DATE];
                        if (startDt != null && endDt != null)
                        {
                            rosterEvent.RosterEventDictionary[FieldNames.START_DATE] = ((DateTime)startDt).Date;
                            rosterEvent.RosterEventDictionary[FieldNames.END_DATE]   = ((DateTime)endDt).Date.AddMinutes(1439);
                        }
                    }
                }

                // check by Master Roster - if it is a Template - NO new rosters
                var masterRosterId = (rosterEvent.RosterEventDictionary.ContainsKey(FieldNames.MASTER_ROSTER_ID)) ?
                                     rosterEvent.RosterEventDictionary[FieldNames.MASTER_ROSTER_ID] : null;
                if (ControlMode == SPControlMode.New && this.ListId == TableIDs.PLANNED_ROSTERS &&
                    masterRosterId != null && _dataService.IsTemplate(masterRosterId.ToInt()))
                {
                    throw new Exception("It is not possible to modify Roster Template!"); // do not allow ADD to Template
                }

                _dataService.SaveRosterEvent(rosterEvent, ListId);
                Utils.GoBackOnSuccess(this.Page, this.Context);
            }
            catch (Exception ex)
            {
                ErrorHolder.Controls.Add(new Label
                {
                    Text = ex.ToReadbleSrting("Saving Error"), ForeColor = System.Drawing.Color.Red
                });
            }
        }