Exemplo n.º 1
0
        public EnsureUserResult EnsureUser(EnsureUserQuery query)
        {
            DisableCaching();
            var result = new EnsureUserResult {
                RosterLookupId = -1,
                Key            = "",
                DisplayText    = ""
            };

            try {
                RosterConfigService configProvider = new RosterConfigService();
                ListMetadataField   field          = configProvider.GetField(query.FieldMetedataId.ToGuid());

                DbFieldUser dbFld = field.GetDbField() as DbFieldUser;
                var         user  = dbFld.EnsureUser(XDocument.Parse(query.XmlText));

                result.DisplayText    = user.DisplayText;
                result.Key            = user.Key;
                result.RosterLookupId = user.RosterLookupId;
            }
            catch (Exception ex) {
                HandleException(ex);
            }

            return(result);
        }
        private List <RosterEvent> GetTimesheetsByStatus(int statusId)
        {
            var dataService = new RosterDataService();
            var query       = new QueryParams();
            var listFields  = new RosterConfigService().GetList(TableIDs.TIMESHEET_ROSTERS).ListMetadataFields;

            // add filter by WorkerId
            var workerFld = listFields.FirstOrDefault(item => item.InternalName == FieldNames.WORKER_PERSON_ID);

            query.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(workerFld, CompareType.Equal, ConcateOperator.And, this.WorkerId, null));

            // add filter by StatusId
            var statusFld = listFields.FirstOrDefault(item => item.InternalName == FieldNames.STATUS_ID);

            query.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(statusFld, CompareType.Equal, ConcateOperator.And, statusId, null));

            // add filter according period displayed by Calendar
            var calendarPeriod = Utils.GetCalendarViewPeriod(SPContext.Current.Web.GetDateOptions(Request), "week");
            var startDateFld   = listFields.FirstOrDefault(item => item.InternalName == FieldNames.START_DATE);
            var endDateFld     = listFields.FirstOrDefault(item => item.InternalName == FieldNames.END_DATE);

            query.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(startDateFld, CompareType.LessOrEqual, ConcateOperator.And, calendarPeriod.Item2, null));
            query.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(endDateFld, CompareType.MoreOrEqual, ConcateOperator.And, calendarPeriod.Item1, null));

            // get timesheets
            return(dataService.ListRosterEvents(TableIDs.TIMESHEET_ROSTERS, query));
        }
Exemplo n.º 3
0
        public listView <Entity> MetadataView(string version, ICollection <abstractSearch> filter, QueryDisplayParams query)
        {
            DisableCaching();
            var result = new listView <Entity>();

            try
            {
                var listId = filter.filterTextValue("listId").ToGuid();
                result.page = new pager <Entity>();
                var service = new RosterConfigService();
                var content = service.GetViews(listId);
                result.total = content.Count();
                content.Take(query.currentPageSize).Skip(query.currentPageNum * query.currentPageSize).ToList().ForEach(item =>
                {
                    result.page.pageItems.Add(new Entity
                    {
                        Key    = item.Id.ToSafeString(),
                        Name   = item.Name,
                        Fields = item.ToNamed()
                    });
                });
            }
            catch (Exception ex)
            {
                result.message.message      = ex.Message;
                result.message.messageLevel = messageLevelEnum.critical;
                //HandleException(ex);
            }
            return(result);
        }
Exemplo n.º 4
0
        private ListItem[] GetDbFields()
        {
            var result = new List <ListItem>();
            var editor = holderExtraSettings.FindControl(EDITOR_CONTROL_ID) as IDbFieldEditor;

            if (editor == null)
            {
                return(result.ToArray());
            }
            var fld = editor.GetField(txtColName.Text);

            if (fld == null)
            {
                return(result.ToArray());
            }
            lbNoFields.Visible        = true;
            ddlTableFieldName.Visible = false;
            lbNoFields.Text           = string.Format("There are no existing fields of selected type ({0}). The new field will be created.", fld.SqlType);

            var rosterConfigService = new RosterConfigService();

            var lists          = new List <ListMetadataField>();
            var dependentLists = ReferenceListsGuids;

            if (dependentLists.IsEmpty())
            {
                return(result.ToArray());
            }

            var existingFields = List.ListMetadataFields.Select(item => item.InternalName).ToList();

            dependentLists.ForEach(listId =>
            {
                var list = rosterConfigService.GetList(listId);
                if (list != null)
                {
                    lists.AddRange(list.ListMetadataFields.Where(item =>
                                                                 item.FieldType == fld.SqlType && !existingFields.Contains(item.InternalName)));
                }
            });
            if (!lists.Any())
            {
                return(result.ToArray());
            }
            var grouped = lists.GroupBy(item => item.InternalName).ToList();

            if (!grouped.IsEmpty())
            {
                grouped.ForEach(group =>
                {
                    var itemName = string.Format("{0} ({1})", @group.Key,
                                                 string.Join(",",
                                                             @group.Select(x => string.Format("{0} - {1}", x.FieldName, x.ListMetadata.Name))));
                    result.Add(new ListItem(itemName, @group.Key));
                });
                lbNoFields.Visible        = false;
                ddlTableFieldName.Visible = true;
            }
            return(result.ToArray());
        }
Exemplo n.º 5
0
        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);
            }
        }
Exemplo n.º 6
0
        public itemView <Roster.Services.Group> MetadataItem(string version, string id)
        {
            DisableCaching();
            var result = new itemView <Group>();

            try
            {
                var service = new RosterConfigService();
                var content = service.GetLists().FirstOrDefault(_ => _.Id == id.ToGuid());
                if (content != null)
                {
                    result.item = new Group {
                        Key = content.Id.ToSafeString(), Name = content.Name, Fields = new List <Entity>()
                    };
                    content.ListMetadataFields.ToList().ForEach(item =>
                    {
                        result.item.Fields.Add(new Entity {
                            Key = content.Id.ToSafeString(), Name = content.Name, Fields = item.ToNamed()
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                result.message.message      = ex.Message;
                result.message.messageLevel = messageLevelEnum.critical;
                //HandleException(ex);
            }
            return(result);
        }
Exemplo n.º 7
0
        private List <Tuple <string, string> > GetCriteria(LookupQuery query)
        {
            var whereCriteria = new List <Tuple <string, string> >();

            if (query.ParentKeyValue.ToInt() != 0)
            {
                var rosterConfigService = new RosterConfigService();
                var field = rosterConfigService.GetField(query.MetadataId.ToGuid());
                if (field == null)
                {
                    throw new Exception(string.Format("Field '{0}' not found", query.MetadataId));
                }
                var dbfield = field.GetDbField() as DbFieldLookup;
                if (dbfield != null)
                {
                    var list = rosterConfigService.GetList(field.ListMetadataId);
                    if (list == null)
                    {
                        throw new Exception(string.Format("List '{0}' not found", field.ListMetadataId));
                    }
                    var parentField =
                        list.ListMetadataFields.FirstOrDefault(item => item.InternalName == dbfield.DependentParent);
                    if (parentField != null)
                    {
                        if (dbfield.DependentParentField == parentField.DataSourceKey)
                        {
                            whereCriteria.Add(new Tuple <string, string>(dbfield.FilterByField, query.ParentKeyValue.ToSafeString()));
                        }
                        else
                        {
                            var parentResults = BLExtensions.SourceContent(parentField.DataSource,
                                                                           parentField.DataSourceKey.ToSafeString(),
                                                                           parentField.DataSourceField, parentField.DataSourceType,
                                                                           new List <Tuple <string, string> >
                            {
                                new Tuple <string, string>(parentField.DataSourceKey.ToSafeString(),
                                                           query.ParentKeyValue.ToSafeString())
                            });
                            if (!parentResults.IsEmpty())
                            {
                                var firstOrDefault = parentResults.FirstOrDefault();
                                if (firstOrDefault != null)
                                {
                                    var parentResult = (firstOrDefault.Item2 as IDictionary <string, object>);
                                    if (parentResult.ContainsKey(dbfield.DependentParentField))
                                    {
                                        whereCriteria.Add(new Tuple <string, string>(dbfield.FilterByField, parentResult[dbfield.DependentParentField].ToSafeString()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(whereCriteria);
        }
Exemplo n.º 8
0
        /// <summary>
        /// We have just created a new Default view. Ok. Now remove IsDefault flag from previous default view
        /// </summary>
        /// <param name="newDefaultViewId"></param>
        private void RemoveDefaultFlagsFromOtherViews(Guid newDefaultViewId)
        {
            var allViews = new RosterConfigService().GetViews(this.List.Id);

            foreach (ViewMetadata vw in allViews.Where(x => x.Id != newDefaultViewId))
            {
                vw.IsDefault = false;
                new RosterConfigService().SaveView(vw);
            }
        }
Exemplo n.º 9
0
        public RosterEventResult RosterEvents(RosterEventQuery query)
        {
            DisableCaching();
            var result = new RosterEventResult
            {
                Page  = query.Page,
                Items = new List <RosterEventResultItem>()
            };

            try
            {
                var list = new RosterConfigService().GetList(query.ListId);
                if (list == null)
                {
                    throw new Exception(string.Format("List '{0}' not found", query.ListId));
                }

                var fieldId = list.ListMetadataFields.FirstOrDefault(item => item.InternalName == FieldNames.ROSTER_EVENT_ID);
                if (fieldId == null)
                {
                    throw new Exception("Field 'RosterEventId' not found");
                }

                var fieldTitle = list.ListMetadataFields.FirstOrDefault(item => item.InternalName == FieldNames.ROSTER_EVENT_TITLE);
                if (fieldTitle == null)
                {
                    throw new Exception("Field 'Title' not found");
                }
                result.Page = query.Page;
                var queryParams = new QueryParams {
                    SkipRows = 0, TakeRows = PageSize
                };
                queryParams.SelectCriteria.AddRange(new[] { fieldId, fieldTitle });
                queryParams.OrderCriteria.Add(new Tuple <ListMetadataField, SortDirection, string>
                                                  (fieldTitle, SortDirection.Ascending, fieldTitle.InternalName));
                queryParams.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>
                                                  (fieldTitle, CompareType.Contains, ConcateOperator.And, query.Query, null));
                var content = new RosterDataService().ListRosterEventProperties(list.Id, queryParams);
                foreach (var properties in content)
                {
                    var id    = properties.First(item => item.Key == fieldId.InternalName).Value;
                    var value = properties.First(item => item.Key == fieldTitle.InternalName).Value;
                    result.Items.Add(new RosterEventResultItem {
                        id = id.ToSafeString(), text = value.ToSafeString()
                    });
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            return(result);
        }
        private ListItem[] SetFieldItemsByDependence()
        {
            var result = new List <ListItem>();
            var list   = new RosterConfigService().GetList(_metadataId);

            if (list != null)
            {
                result.AddRange(list.ListMetadataFields.Where(item => item.DataSourceType != 0).Select(x =>
                                                                                                       new ListItem(x.FieldName, x.InternalName)).ToArray());
            }

            return(result.ToArray());
        }
Exemplo n.º 11
0
        public void SaveMasterAsTemplate(SaveAsTemplateQuery query)
        {
            DisableCaching();

            try
            {
                // set flag IsTemplate for Master roster
                var _confService = new RosterConfigService();
                var _dataService = new RosterDataService();
                _dataService.SetAsTemplate(query.MasterId);

                // init filter by MasterRosterId
                var plannedRostersList = _confService.GetList(TableIDs.PLANNED_ROSTERS);
                var queryPar           = new QueryParams();
                var masterRosterFld    = plannedRostersList.ListMetadataFields.FirstOrDefault(item => item.InternalName == FieldNames.MASTER_ROSTER_ID);
                queryPar.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(masterRosterFld, CompareType.Equal, ConcateOperator.And, query.MasterId, null));

                // get Planned rosters by MasterRosterId
                var plannedRosters = _dataService.ListRosterEvents(plannedRostersList.Id, queryPar);

                // limit access to Planned rosters inside Template
                int rosterAdminGroupId = new RoleService().GetGroupIdForRole(Roster.Presentation.Constants.Role.RosterAdmins, SPContext.Current.Web);
                foreach (RosterEvent re in plannedRosters)
                {
                    List <AccessControlItem> reRights = _confService.GetItemAccessControls(re.Id);

                    // clear old
                    if (reRights != null && reRights.Any())
                    {
                        reRights.ForEach(ipItm => _confService.DeleteAccessControlItem(ipItm.Id));
                    }

                    // add 'Edit' to RosterAdmins
                    _confService.SaveAccessControlItem(new AccessControlItem {
                        AccessRight = (int)AccessRight.Write, Id = Guid.NewGuid(),
                        ItemId      = re.Id, ListMetadataId = plannedRostersList.Id,
                        TrusteeId   = rosterAdminGroupId
                    });

                    // add 'Read' to Everyone
                    _confService.SaveAccessControlItem(new AccessControlItem
                    {
                        AccessRight = (int)AccessRight.Read, Id = Guid.NewGuid(),
                        ItemId      = re.Id, ListMetadataId = plannedRostersList.Id,
                        TrusteeId   = RoleService.ACCOUNT_ID_EVERYONE
                    });
                }
            } catch (Exception ex) {
                HandleException(ex);
            }
        }
Exemplo n.º 12
0
        public ListResult List(ListQuery query)
        {
            DisableCaching();
            var result = new ListResult
            {
                Page  = query.Page,
                Items = new List <ListResultItem>()
            };

            try
            {
                var view  = new RosterConfigService().GetView(query.ViewId);
                var field = view.ListMetadata.ListMetadataFields.FirstOrDefault(item => item.Id == query.FieldId);
                if (field == null)
                {
                    throw  new Exception(string.Format("Field {0} not found", query.FieldId));
                }
                if (field.FieldType() == SPFieldType.Choice)
                {
                    result.Items.AddRange(field.FieldValues().Where(
                                              item => item.Contains(query.Query)).Select(item => new ListResultItem {
                        id = item, text = item
                    }).ToList());
                }
                else
                {
                    result.Page = query.Page;
                    var queryParams = new QueryParams {
                        SkipRows = 0, TakeRows = 1, Dictinct = true
                    };
                    queryParams.SelectCriteria.Add(field);
                    queryParams.OrderCriteria.Add(new Tuple <ListMetadataField, SortDirection, string>
                                                      (field, SortDirection.Ascending, query.DisplayField.ExtractField()));
                    queryParams.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>
                                                      (field, CompareType.Contains, ConcateOperator.And, query.Query, query.DisplayField.ExtractField()));
                    var content = new RosterDataService().ListRosterEventProperties(view.ListMetadataId, queryParams);
                    foreach (var value in content.Select(properties => properties.First(item => item.Key == query.DisplayField).Value))
                    {
                        result.Items.Add(new ListResultItem {
                            id = value.ToSafeString(), text = value.ToSafeString()
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            return(result);
        }
Exemplo n.º 13
0
        public static void SyncList(Guid listId)
        {
            var configProvider = new RosterConfigService();
            var mappingSetting = configProvider.GetMappingByList(listId.ToString());

            if (mappingSetting == null)
            {
                return;
            }
            var dataProvider = new RosterDataService();
            {
                var list      = SPContext.Current.SPList(listId);
                var listitems = list.ListItems(mappingSetting.Key,
                                               String.Join("$", mappingSetting.ListMappingFields.Select(item => item.ItemName).ToList()), true);

                dataProvider.SaveRows(mappingSetting, listitems);
            }
        }
        private ListItem[] SetFieldItemsByDependenceField()
        {
            var result = new List <ListItem>();

            if (ddl_DependentParent == null)
            {
                return(result.ToArray());
            }
            var listParent = new RosterConfigService().GetList(_metadataId);

            if (listParent == null)
            {
                return(result.ToArray());
            }
            var item = listParent.ListMetadataFields.FirstOrDefault(i => i.InternalName == ddl_DependentParent.SelectedValue);

            if (item == null)
            {
                return(result.ToArray());
            }
            if (item.DataSourceType == (int)LookupSourceType.SpList)
            {
                var list = SPContext.Current.Web.Lists[item.DataSource.ToGuid()];
                if (list != null)
                {
                    var idField = list.Fields.Cast <SPField>().FirstOrDefault(f => item.DataSourceKey.ToGuid() == f.Id);
                    if (idField != null)
                    {
                        result.Add(new ListItem(idField.Title, idField.Id.ToString("B").ToUpper()));
                    }
                    result.AddRange(list.Fields.Cast <SPField>().Where(f => item.DataSourceField.Split('$')
                                                                       .Contains(f.Id.ToString("B").ToUpper())).Select(x => new ListItem(x.Title, x.Id.ToString("B").ToUpper())));
                }
            }
            else
            {
                result.Add(new ListItem(item.DataSourceKey, item.DataSourceKey));
                result.AddRange(item.DataSourceField.Split('$').Select(x => new ListItem(x, x)));
            }
            return(result.ToArray());
        }
Exemplo n.º 15
0
 public override void ItemDeleting(SPItemEventProperties properties)
 {
     base.ItemDeleting(properties);
     try
     {
         var configProvider = new RosterConfigService(properties.Web);
         var mappingSetting = configProvider.GetMappingByList(properties.ListId.ToString());
         if (mappingSetting == null)
         {
             return;
         }
         var dataProvider = new RosterDataService(properties.Web);
         {
             dataProvider.Delete(mappingSetting.TableName, mappingSetting.Key, properties.ListItemId);
         }
     }
     catch (Exception ex)
     {
         LogHelper.Instance.ErrorULS("ItemDeleting error", ex);
     }
 }
Exemplo n.º 16
0
 public override void ItemUpdated(SPItemEventProperties properties)
 {
     base.ItemUpdated(properties);
     try
     {
         var configProvider = new RosterConfigService(properties.Web);
         var mappingSetting = configProvider.GetMappingByList(properties.ListId.ToString());
         if (mappingSetting == null)
         {
             return;
         }
         var dataProvider = new RosterDataService(properties.Web);
         {
             dataProvider.SaveRow(mappingSetting, properties.ListItem.ToSyncObject(mappingSetting));
         }
     }
     catch (Exception ex)
     {
         LogHelper.Instance.ErrorULS("ItemUpdated error", ex);
     }
 }
Exemplo n.º 17
0
        public GetContentTypeResult GetContentTypeByRosterId(GetContentTypeQuery query)
        {
            DisableCaching();
            var result = new GetContentTypeResult();

            try
            {
                var dataService = new RosterDataService();
                {
                    var roster = dataService.GetRosterEvent(query.RosterId);
                    if (roster != null)
                    {
                        var rosterProps = roster.RosterEventDictionary;
                        if (rosterProps.ContainsKey(FieldNames.CONTENT_TYPE_ID))
                        {
                            int ctId = rosterProps[FieldNames.CONTENT_TYPE_ID].ToInt();

                            var ct = new RosterConfigService().GetContentType(ctId);
                            if (ct != null)
                            {
                                result.DispItemUrl   = ct.DispItemUrl;
                                result.EditItemUrl   = ct.EditItemUrl;
                                result.NewItemUrl    = ct.NewItemUrl;
                                result.Name          = ct.Name;
                                result.Id            = ct.Id;
                                result.IsDefault     = ct.IsDefault;
                                result.IsOnNewAction = ct.IsOnNewAction;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

            return(result);
        }
Exemplo n.º 18
0
        public void SaveRosterItemData(SaveItemDataQuery query)
        {
            DisableCaching();
            try
            {
                if (query == null)
                {
                    throw new ArgumentNullException("query");
                }

                var rosterConfigService = new RosterConfigService();
                if (!rosterConfigService.HasRights(query.ItemId, query.ListId, AccessRight.Write))
                {
                    throw new Exception("You don't have permissions to modify current roster");
                }

                var rosterDataService = new RosterDataService();
                rosterDataService.SaveRosterEventItem(query.ListId, query.ItemId, query.FieldName, query.Value);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Exemplo n.º 19
0
        protected override void CreateChildControls()
        {
            RosterConfigService configProvider = new RosterConfigService();
            var lists = configProvider.GetLists();

            ddlCatalogs          = new DropDownList();
            ddlCatalogs.ID       = "catalogSelector";
            ddlCatalogs.CssClass = "lists_control";
            ddlCatalogs.Attributes.Add("onchange", "UpdateViewsList(this);");
            ddlCatalogs.Items.AddRange(lists.Select(x => new ListItem(x.Name, x.Id.ToString())).ToArray());

            ddlViews          = new DropDownList();
            ddlViews.ID       = "viewSelector";
            ddlViews.CssClass = "views_control";
            ddlViews.Items.AddRange(lists.SelectMany(x => x.ViewMetadatas).Select(v => new ListItem(v.Name, v.Id.ToString())).ToArray());

            hidAllViewsInfo       = new HiddenField();
            hidAllViewsInfo.ID    = "hidAllViewsHierarchy";
            hidAllViewsInfo.Value = new JavaScriptSerializer().Serialize(lists.Select(x => new { list = x.Id, views = x.ViewMetadatas.Select(v => new { viewId = v.Id, viewName = v.Name }) }));

            txtRelationFld    = new TextBox();
            txtRelationFld.ID = "txtRelationField";

            txtFilterOperators    = new TextBox();
            txtFilterOperators.ID = "txtFilterOperators";

            txtCalendarWidth    = new TextBox();
            txtCalendarWidth.ID = "txtCalendarWidth";

            txtCalendarHeight    = new TextBox();
            txtCalendarHeight.ID = "txtCalendarHeight";

            chEditMode      = new CheckBox();
            chEditMode.ID   = "chEditMode";
            chEditMode.Text = "Edit mode? (GridView only)";

            chDisplayPrepopulated      = new CheckBox();
            chDisplayPrepopulated.ID   = "chDisplayPrepopulated";
            chDisplayPrepopulated.Text = "Display pre-populated? (CalendarView only)";

            this.Controls.Add(ddlCatalogs);
            this.Controls.Add(ddlViews);
            this.Controls.Add(hidAllViewsInfo);
            this.Controls.Add(txtRelationFld);
            this.Controls.Add(txtFilterOperators);
            this.Controls.Add(txtCalendarWidth);
            this.Controls.Add(txtCalendarHeight);
            this.Controls.Add(chEditMode);
            this.Controls.Add(chDisplayPrepopulated);
            ScriptLink.Register(this.Page, "/_layouts/15/Roster.Presentation/js/cascadeSelection.view.js", true);

            //setting the last set values as current values on custom toolpart
            ExternalListViewWebPart wp = (ExternalListViewWebPart)this.ParentToolPane.SelectedWebPart;

            if (wp != null)
            {
                this.ddlCatalogs.SelectedValue     = wp.CatalogId;
                this.ddlViews.SelectedValue        = wp.ViewName;
                this.txtRelationFld.Text           = wp.RelationField;
                this.txtFilterOperators.Text       = wp.FilterOperators;
                this.txtCalendarWidth.Text         = wp.CalendarWidth;
                this.txtCalendarHeight.Text        = wp.CalendarHeight;
                this.chEditMode.Checked            = wp.EditMode;
                this.chDisplayPrepopulated.Checked = wp.DisplayPrepopulated;
            }

            base.CreateChildControls();
        }
Exemplo n.º 20
0
        private List <VersionDetails> _getDataSource()
        {
            var versions    = new List <VersionDetails>();
            var dataService = new RosterDataService();
            var rosterEvent = dataService.GetRosterEvent(this.ItemId.Value);
            var listId      = ListId.HasValue ? ListId.Value :
                              (rosterEvent.EventTypeId == 0) ? TableIDs.PLANNED_ROSTERS : TableIDs.WORKING_ROSTERS;
            var allListFields = new RosterConfigService().GetList(listId).ListMetadataFields.Select(fld => fld.GetDbField());
            // get history items
            var historyInfo = dataService.ListTrackData(this.ItemId.Value);

            string[] excludeFields = new string[] { FieldNames.ID, FieldNames.ROSTER_EVENT_ID,
                                                    FieldNames.CONTENT_TYPE_ID, FieldNames.MODIFIED, FieldNames.MODIFIED_BY };
            for (int k = 0; k < historyInfo.Count; k++)
            {
                var currentVersionTrackData = historyInfo[k].TrackDataDictionary;
                var fldModifiedByText       = string.Empty;
                var fldModifiedBy           = allListFields.FirstOrDefault(f => f.InternalName.Equals(FieldNames.MODIFIED_BY));
                if (fldModifiedBy != null)
                {
                    if (currentVersionTrackData.ContainsKey(FieldNames.MODIFIED_BY))
                    {
                        fldModifiedByText = fldModifiedBy.GetFieldValueAsText(currentVersionTrackData[FieldNames.MODIFIED_BY]);
                    }
                }
                var vd = new VersionDetails(historyInfo[k], fldModifiedByText);
                if (k == historyInfo.Count - 1)
                {
                    foreach (string fldName in currentVersionTrackData.Keys.Where(ke => !excludeFields.Contains(ke)))
                    {
                        var fld = allListFields.FirstOrDefault(f => f.InternalName.Equals(fldName));
                        if (fld == null)
                        {
                            continue;
                        }
                        vd.Changes.Add(new ChangeInfo
                        {
                            FieldName  = fld.DisplayName,
                            FieldValue = fld.GetFieldValueAsText(currentVersionTrackData[fldName])
                        });
                    }
                }
                else
                {
                    var prevVersionTrackData = historyInfo[k + 1].TrackDataDictionary;
                    foreach (string fldName in currentVersionTrackData.Keys.Where(ke => !excludeFields.Contains(ke)))
                    {
                        if (!prevVersionTrackData.ContainsKey(fldName) || (prevVersionTrackData.ContainsKey(fldName) &&
                                                                           prevVersionTrackData.GetValue(fldName).ToSafeString() != currentVersionTrackData[fldName].ToSafeString()))
                        {
                            var fld = allListFields.FirstOrDefault(f => f.InternalName.Equals(fldName));
                            if (fld == null)
                            {
                                continue;
                            }
                            vd.Changes.Add(new ChangeInfo
                            {
                                FieldName  = fld.DisplayName,
                                FieldValue = fld.GetFieldValueAsText(currentVersionTrackData[fldName])
                            });
                        }
                    }
                }
                if (vd.Changes.Count() == 0)
                {
                    vd.Changes.Add(new ChangeInfo {
                        FieldName = "No changes", FieldValue = string.Empty
                    });
                }
                versions.Add(vd);
            }
            return(versions);
        }
        public SPCalendarItemCollection SelectDataForCalendar(short calendarType, Tuple <DateTime, DateTime> calendarPeriod, string calendarScope, out object rostersForColoring)
        {
            var query        = new QueryParams();
            var listFields   = this.m_view.ListMetadata.ListMetadataFields;
            var startDateFld = listFields.FirstOrDefault(item => item.InternalName == FieldNames.START_DATE);
            var endDateFld   = listFields.FirstOrDefault(item => item.InternalName == FieldNames.END_DATE);

            // set filter according period displayed by Calendar
            query.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(startDateFld, CompareType.LessOrEqual, ConcateOperator.And, calendarPeriod.Item2, null));
            query.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(endDateFld, CompareType.MoreOrEqual, ConcateOperator.And, calendarPeriod.Item1, null));

            // add filter
            if (this.m_GridFilterExpression != null && this.m_GridFilterExpression.WhereCriteria.Any())
            {
                query.WhereCriteria.AddRange(this.m_GridFilterExpression.WhereCriteria);
            }

            // extract Roster data
            RosterDataService _dataSrv = new RosterDataService();
            //List<RosterEvent> rosters = (this.m_view.ListMetadataId == Roster.Common.TableIDs.TIMESHEET_ROSTERS && this.displayPrepopulatedRosters) ?
            //    _dataSrv.ViewTimesheetEvents(this.m_view.Id, query, calendarPeriod) : _dataSrv.ViewRosterEvents(this.m_view.Id, query);
            List <RosterEvent> rosters = _dataSrv.ViewRosterEvents(this.m_view.Id, query);

            // expant recurrent events
            var tZone = SPContext.Current.Web.RegionalSettings.TimeZone;
            List <ExpandedRosterEvent> expandedEvents = RecurrenceItemExpander.Expand(rosters, null, calendarPeriod.Item1, calendarPeriod.Item2,
                                                                                      FieldNames.START_DATE, FieldNames.END_DATE, tZone).ToList();

            // send Object to output for coloring
            if (!this.m_view.GetDerializedDynamicColourSettings().IsEmpty)
            {
                if (this.dynColoring_OriginalRosterId != Guid.Empty && !rosters.Any(r => r.Id == this.dynColoring_OriginalRosterId))
                {
                    List <RosterEvent> rosters_dynColor = rosters;
                    RosterEvent        origRoster       = _dataSrv.GetRosterEvent(this.dynColoring_OriginalRosterId); // !! don't return all properties

                    // get events around Orig.Roster
                    var queryDyn = new QueryParams();
                    queryDyn.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(startDateFld, CompareType.LessOrEqual, ConcateOperator.And, origRoster.GetEndDate(), null));
                    queryDyn.WhereCriteria.Add(new Tuple <ListMetadataField, CompareType, ConcateOperator, object, string>(endDateFld, CompareType.MoreOrEqual, ConcateOperator.And, origRoster.GetStartDate(), null));
                    rosters_dynColor.AddRange(_dataSrv.ViewRosterEvents(this.m_view.Id, queryDyn));

                    rosters_dynColor   = rosters_dynColor.GroupBy(r => r.Id).Select(g => g.First()).ToList();              // remove duplicates
                    rostersForColoring = RecurrenceItemExpander.Expand(rosters_dynColor, null, calendarPeriod.Item1, calendarPeriod.Item2,
                                                                       FieldNames.START_DATE, FieldNames.END_DATE, tZone); // for dynamic coloring

                    // add original Roster (only for Dynamic colour-coding)
                    expandedEvents.Add(new ExpandedRosterEvent(rosters_dynColor.First(r => r.Id == this.dynColoring_OriginalRosterId), true, tZone));
                }
                else
                {
                    rostersForColoring = expandedEvents; // for dynamic coloring
                }
            }
            else
            {
                rostersForColoring = rosters;        // for static coloring
            }

            // get default DispForm url and default EventTypeId for rosters
            string defaultDispFormUrl = string.Format("{0}/{1}&ListId={2}", SPContext.Current.Web.ServerRelativeUrl.TrimEnd('/'),
                                                      this.m_view.ListMetadata.DispItemUrl.TrimStart('/'), SPEncode.UrlEncode(this.m_view.ListMetadataId.ToString("B").ToUpper()));
            var    matchEventType         = Regex.Match(defaultDispFormUrl, @"EventType=(?<eType>\d+)");
            int    defaultEventType       = matchEventType.Success ? matchEventType.Groups["eType"].Value.ToInt() : -1;
            string eventTitleFieldName    = this.m_view.GetEventTitleFieldName(calendarScope);
            string eventLocationFieldName = this.m_view.GetEventLocationFieldName(calendarScope);

            // init some variables for Working Rosters which are displayed on TIMESHEET view
            string workingRoster_DispFormUrl           = string.Empty;
            string workingRosterEventTitleFieldName    = string.Empty;
            string workingRosterEventLocationFieldName = string.Empty;

            if (this.m_view.ListMetadataId == Roster.Common.TableIDs.TIMESHEET_ROSTERS)
            {
                var workingRosterList = new RosterConfigService().GetList(Roster.Common.TableIDs.WORKING_ROSTERS);
                workingRoster_DispFormUrl = string.Format("{0}/{1}&ListId={2}", SPContext.Current.Web.ServerRelativeUrl.TrimEnd('/'),
                                                          workingRosterList.DispItemUrl.TrimStart('/'), SPEncode.UrlEncode(workingRosterList.Id.ToString("B").ToUpper()));

                var workingRosterView = workingRosterList.ViewMetadatas.FirstOrDefault(x => x.Name == ViewNames.WORKING_ROSTERS_FOR_TIMESHEETS);
                workingRosterEventTitleFieldName    = (workingRosterView != null) ? workingRosterView.GetEventTitleFieldName(calendarScope) : FieldNames.START_DATE;
                workingRosterEventLocationFieldName = (workingRosterView != null) ? workingRosterView.GetEventLocationFieldName(calendarScope) : FieldNames.END_DATE;
            }

            // init Calendar Items
            var items = new SPCalendarItemCollection();

            items.AddRange(expandedEvents.Select(x => new SPCalendarItem()
            {
                DisplayFormUrl = (defaultEventType == x.EventTypeId) ? defaultDispFormUrl : workingRoster_DispFormUrl,
                CalendarType   = calendarType,
                ItemID         = x.InstanceID,
                StartDate      = x.StartDate,
                EndDate        = x.EndDate,
                hasEndDate     = true,
                Title          = ((IDictionary <string, object>)x.OriginalItem.RosterEventProperties)[(defaultEventType == x.EventTypeId) ? eventTitleFieldName : workingRosterEventTitleFieldName].ToString(),
                Location       = ((IDictionary <string, object>)x.OriginalItem.RosterEventProperties)[(defaultEventType == x.EventTypeId) ? eventLocationFieldName : workingRosterEventLocationFieldName].ToString(),
                IsAllDayEvent  = x.OriginalItem.GetIsAllDayEvent(),
                IsRecurrence   = x.OriginalItem.GetIsRecurrence()
            }).ToList());

            return(items);
        }
Exemplo n.º 22
0
        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);
            }
        }
Exemplo n.º 23
0
        public itemView <bool> SaveRosterEventItem(string version, string listId, int eventTypeId, Entity item)
        {
            DisableCaching();
            var result = new itemView <bool>();

            try
            {
                var service = new RosterDataService();
                var config  = new RosterConfigService();
                var list    = config.GetList(listId.ToGuid());
                var entity  = new RosterEvent
                {
                    Id                    = item.Key.ToGuid(),
                    EventTypeId           = eventTypeId,
                    RosterEventProperties = item.Fields.NamedToExpando()
                };
                if (!entity.RosterEventDictionary.ContainsKey("ContentTypeId"))
                {
                    entity.RosterEventDictionary.Add("ContentTypeId", 1);
                }
                if (!entity.RosterEventDictionary.ContainsKey("CreatedBy"))
                {
                    entity.RosterEventDictionary.Add("CreatedBy",
                                                     DbFieldUser.GetUserRosterId(SPContext.Current.Web.CurrentUser));
                }
                if (!entity.RosterEventDictionary.ContainsKey("Created"))
                {
                    entity.RosterEventDictionary.Add("Created", DateTime.Now);
                }
                if (!entity.RosterEventDictionary.ContainsKey("ModifiedBy"))
                {
                    entity.RosterEventDictionary.Add("ModifiedBy",
                                                     DbFieldUser.GetUserRosterId(SPContext.Current.Web.CurrentUser));
                }
                if (!entity.RosterEventDictionary.ContainsKey("Modified"))
                {
                    entity.RosterEventDictionary.Add("Modified", DateTime.Now);
                }
                if (!entity.RosterEventDictionary.ContainsKey("Id"))
                {
                    entity.RosterEventDictionary.Add("Id", entity.Id);
                }
                if (!entity.RosterEventDictionary.ContainsKey("RosterEventId"))
                {
                    entity.RosterEventDictionary.Add("RosterEventId", entity.Id);
                }
                var fields = list.ListMetadataFields.ToList();
                fields.ForEach(_ =>
                {
                    if (!entity.RosterEventDictionary.ContainsKey(_.InternalName))
                    {
                        if (_.ClrType == typeof(DateTime))
                        {
                            entity.RosterEventDictionary.Add(_.InternalName, null);
                        }
                        else if (_.ClrType == typeof(Guid))
                        {
                            entity.RosterEventDictionary.Add(_.InternalName, null);
                        }
                        else if (_.ClrType == typeof(Int32))
                        {
                            entity.RosterEventDictionary.Add(_.InternalName, null);
                        }
                        else
                        {
                            entity.RosterEventDictionary.Add(_.InternalName, _.ClrType.DefaultValue());
                        }
                    }
                });
                service.SaveRosterEvent(entity, list.Id);
                result.item = true;
            }
            catch (Exception ex)
            {
                //HandleException(ex);
                result.message.message      = ex.Message;
                result.message.messageLevel = messageLevelEnum.critical;
            }
            return(result);
        }
Exemplo n.º 24
0
        protected override void CreateChildControls()
        {
            Controls.Clear();

            // REQUIRED
            label_Required = new Label {
                ID = "lblRequired", Text = @"Require that this column contains information:"
            };

            radioList_Required = new RadioButtonList {
                ID = "rListRequired",
                RepeatDirection = RepeatDirection.Horizontal
            };
            radioList_Required.Items.AddRange(new[] { new ListItem("Yes", "1"), new ListItem("No", "0") });
            radioList_Required.SelectedValue = "0";

            // ALLOW SELECTION
            label_AllowSelection = new Label {
                ID = "lblAllowSelection", Text = @"Allow selection of:"
            };

            radioList_AllowSelection = new RadioButtonList {
                ID = "rListAllowSelection",
                RepeatDirection = RepeatDirection.Horizontal
            };
            radioList_AllowSelection.Items.AddRange(new[] { new ListItem("People Only", "RadSelectionPeopleOnly"), new ListItem("People and Groups", "RadSelectionPeopleAndGroups") });
            radioList_AllowSelection.SelectedValue = "RadSelectionPeopleOnly";

            // CHOOSE FROM
            label_ChooseFrom = new Label {
                ID = "lblChooseFrom", Text = @"Choose from:"
            };

            radioList_ChooseFrom = new RadioButtonList {
                ID = "rListChooseFrom",
                RepeatDirection = RepeatDirection.Vertical
            };
            radioList_ChooseFrom.Items.AddRange(new[] { new ListItem("All Users", "RadChooseFromAllPeopleGroups"), new ListItem("SharePoint Group", "RadChooseFromGroup") });
            foreach (ListItem li in radioList_ChooseFrom.Items)
            {
                li.Attributes.Add(HtmlTextWriterAttribute.Onchange.ToString(), "ChooseFromChanged();");
            }
            radioList_ChooseFrom.SelectedValue = "RadChooseFromAllPeopleGroups";

            // GROUPS
            ddl_Groups = new DropDownList {
                ID = "ddlLookupGroups", Width = 283, Enabled = false
            };
            ddl_Groups.Attributes.CssStyle.Add(HtmlTextWriterStyle.MarginLeft, "22px");
            ddl_Groups.Items.AddRange(SPContext.Current.Web.SiteGroups.OfType <SPGroup>().Select(g => new ListItem(g.Name, g.ID.ToString())).ToArray());

            // Main Display field
            label_LookupMainDispField = new Label {
                ID = "lblLookupMainDispField", Text = @"Show field:"
            };
            ddl_LookupMainDispField = new DropDownList {
                ID = "ddlLookupMainDispField", Width = 200
            };
            var tblColumns = new RosterConfigService().TablesFields(this.ListId);

            foreach (string colName in tblColumns)
            {
                var li = new ListItem(colName);
                li.Selected = colName.Equals("DisplayName");
                ddl_LookupMainDispField.Items.Add(li);
            }

            Controls.Add(label_Required);
            Controls.Add(radioList_Required);
            Controls.Add(label_AllowSelection);
            Controls.Add(radioList_AllowSelection);
            Controls.Add(label_ChooseFrom);
            Controls.Add(radioList_ChooseFrom);
            Controls.Add(ddl_Groups);

            Controls.Add(label_LookupMainDispField);
            Controls.Add(ddl_LookupMainDispField);
        }
        protected void btnBulkSendToNAV_Click(object sender, EventArgs e)
        {
            try
            {
                var config = SPContext.Current.GetNavWebServiceConnection();
                if (config.IsEmpty())
                {
                    throw new Exception("NAV connection info has not been specified!");
                }

                if (!IsCurrentUserAManagerForWorker())
                {
                    throw new Exception("Only Manager can Send timesheets to NAV for current user!");
                }

                // get timesheets to Send to NAV
                var approvedRosters = this.GetTimesheetsByStatus(10); // 10 = 'Approved'
                if (!approvedRosters.Any())
                {
                    throw new Exception("There is nothing to send to NAV");
                }

                // get mapping
                var _mappingSettings = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <List <Roster.Presentation.Layouts.MapElem> >(config.Mapping);

                var calendarPeriod = Utils.GetCalendarViewPeriod(SPContext.Current.Web.GetDateOptions(Request), "week");
                var listDbFields   = new RosterConfigService().GetList(TableIDs.TIMESHEET_ROSTERS).ListMetadataFields.Select(fld => fld.GetDbField());

                // init Servicea
                CreateTimeSheetLines_Service srv = new CreateTimeSheetLines_Service();
                srv.Url         = config.CreateTimesheetUrl;
                srv.Credentials = new NetworkCredential(config.User, config.Password);
                ProcessTimeSheets procSrv = new ProcessTimeSheets();
                procSrv.Url         = config.ProcessTimesheetsUrl;
                procSrv.Credentials = new NetworkCredential(config.User, config.Password);

                Dictionary <Guid, string> errors = new Dictionary <Guid, string>();
                List <Guid> successIDs           = new List <Guid>();
                foreach (var roster in approvedRosters)
                {
                    string batchNo = Guid.NewGuid().ToString("N").Substring(0, 20);
                    try
                    {
                        var newLine = new CreateTimeSheetLines();
                        // generic values
                        newLine.Key = "0";
                        newLine.External_Time_Sheet_No            = batchNo;
                        newLine.Time_Sheet_Starting_Date          = calendarPeriod.Item1.Date;
                        newLine.Time_Sheet_Starting_DateSpecified = true;
                        // fill Line from timesheet roster
                        newLine.FillFromRoster(roster, listDbFields, _mappingSettings);

                        // create entry in NAV temp table
                        srv.Create(ref newLine);
                        // process timesheet entry
                        procSrv.ProcessTimeSheet(batchNo, false);

                        successIDs.Add(roster.Id);
                    }
                    catch (Exception ex)
                    {
                        errors.Add(roster.Id, ex.Message);
                    }
                }

                // init StoredProcedure params
                var paramCollection = new List <Tuple <string, object> >();
                paramCollection.Add(new Tuple <string, object>("@id", String.Join(",", successIDs)));
                paramCollection.Add(new Tuple <string, object>("@reason", string.Format("Bulk submit to NAV at {0}", DateTime.Now.ToString())));
                paramCollection.Add(new Tuple <string, object>("@message", ""));
                // set new STATUS
                string message = new RosterDataService().ExecuteProcedure("[dbo].[SubmitedToNAV]", paramCollection);

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

                txtNotification.Value = "Success";
            }
            catch (Exception ex)
            {
                txtErrorMsg.Value = ex.Message;
            }
        }
Exemplo n.º 26
0
        public static MigrateResult MigrateItems(MigrateQuery query)
        {
            MigrateResult result = new MigrateResult {
                Success = true
            };

            try
            {
                bool needValidation            = (string.IsNullOrEmpty(query.PaginInfo));
                RosterConfigService _configSrv = new RosterConfigService();
                SPList       shpList           = SPContext.Current.Web.Lists[new Guid(query.Mapping.ListId)];
                ListMetadata dbList            = _configSrv.GetList(new Guid(query.Mapping.TableId));
                var          dbList_Fields     = dbList.ListMetadataFields;
                var          _globalMapping    = _configSrv.GetMapping();

                // collect and validate
                MigrationMapping mapping = new MigrationMapping(shpList, dbList);
                mapping.ContentTypeMapping.AddRange(query.Mapping.ContentTypeMapping.Select(m => new MigrationCtMappingElem {
                    ListCtId = m.ListCtId, TableCtId = m.TableCtId.ToInt()
                }));
                foreach (var mItm in query.Mapping.FieldMapping)
                {
                    ListMetadataField dbField   = dbList_Fields.FirstOrDefault(fld => fld.InternalName.Equals(mItm.TableColumnName));
                    SPField           listField = shpList.Fields.GetFieldByInternalName(mItm.ListFieldName);

                    if (needValidation && dbField.DataSourceType == (int)LookupSourceType.Table && !(listField is SPFieldUser))
                    {
                        SPFieldLookup shpFieldLookup = listField as SPFieldLookup;
                        if (shpFieldLookup == null)
                        {
                            throw new Exception("You cannot map non-lookup field " + mItm.ListFieldName + " to Lookup column");
                        }
                        var _lookupFieldMapping = _globalMapping.FirstOrDefault(m => m.ListName == new Guid(shpFieldLookup.LookupList).ToString());
                        if (_lookupFieldMapping == null || _lookupFieldMapping.TableName != dbField.DataSource)
                        {
                            throw new Exception(listField.Title + " field error. Mapping does not exist or Lookup lists don't match!");
                        }
                    }

                    bool listField_isMultiple =
                        (listField.Type == SPFieldType.Lookup && (listField as SPFieldLookup).AllowMultipleValues) ||
                        (listField.Type == SPFieldType.User && (listField as SPFieldLookup).AllowMultipleValues) ||
                        (listField.TypeAsString == "DualLookup" && (listField as SPFieldLookup).AllowMultipleValues);
                    mapping.FieldMapping.Add(new MigrationMappingElem {
                        ListField   = listField, AllowMultipleValues = listField_isMultiple,
                        TableColumn = dbField, TableDbColumn = dbField.GetDbField()
                    });
                }

                if (needValidation)
                {
                    var repeatedShPFields = mapping.FieldMapping.GroupBy(x => x.TableColumn.InternalName).Where(gr => gr.Count() > 1).Select(gr => gr.Key);
                    if (repeatedShPFields.Any())
                    {
                        throw new Exception("Following DB columns selected more than once: " + string.Join(",", repeatedShPFields));
                    }
                }

                double step        = Math.Round(((LIST_ROW_LIMIT * 100) / (double)mapping.List.ItemCount), 2);
                string _pagingInfo = Migrate(query.PaginInfo, mapping);
                result.PagingInfo   = (string)_pagingInfo ?? string.Empty;
                result.CurrentIndex = (_pagingInfo == null) ? 100 : query.CurrentIndex + step;
            }
            catch (Exception ex) {
                result.Success      = false;
                result.ErrorMessage = ex.Message;
            }

            return(result);
        }