Ejemplo n.º 1
0
        public void Describe(DescribeContext context)
        {
            Func <IShapeFactory, dynamic> formFactory =
                shapeFactory =>
            {
                var priorities    = this.basicDataService.GetPriorities().ToList();
                var statusRecords = this.basicDataService.GetStatusRecords().ToList().Select(c => new BasicDataRecordViewModel {
                    Id = c.Id, Name = c.Name
                }).ToList();
                var serviceRecords = this.basicDataService.GetServices().ToList();
                var projects       = this.projectService.GetProjects(null).AsPart <ProjectPart>().ToList();

                Collection <SelectListItem> prioritySelectList = new Collection <SelectListItem>();
                Collection <SelectListItem> statusSelectList   = new Collection <SelectListItem>();
                Collection <SelectListItem> serviceSelectList  = new Collection <SelectListItem>();
                Collection <SelectListItem> projectList        = new Collection <SelectListItem>();

                Converter.Fill(prioritySelectList, null, priorities);
                prioritySelectList.Insert(0, new SelectListItem());

                Converter.Fill(statusSelectList, null, statusRecords);
                statusSelectList.Insert(0, new SelectListItem());

                Converter.Fill(serviceSelectList, null, serviceRecords);
                serviceSelectList.Insert(0, new SelectListItem());

                Converter.Fill(projectList, projects);

                Collection <SelectListItem> dueDates = CRMHelper.GetDueDateItems(this.T);

                ContentItemSetPermissionsViewModel permissionsViewModel = this.contentOwnershipHelper.CreateModel();
                permissionsViewModel.Users.Insert(0, new SelectListItem());
                var t = this.Shape.Form(_main: this.Shape.CreateTicketActivity(
                                            Priorities: prioritySelectList,
                                            Projects: projectList,
                                            StatusList: statusSelectList,
                                            Services: serviceSelectList,
                                            DueDates: dueDates,
                                            Organization: permissionsViewModel
                                            ));

                return(t);
            };

            context.Form(CreateTicketActivityForm.Name, formFactory);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Lấy lịch sử login/logout theo thời gian
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        public object GetLoginHistory(DateTime from, DateTime to, bool isExport)
        {
            try
            {
                ManagementWarehouseEntities dbContext = new ManagementWarehouseEntities();
                List <MNG_HistoryLogin>     lst       = new List <MNG_HistoryLogin>();
                if (!isExport)
                {
                    lst = dbContext.MNG_HistoryLogin.Where(x => x.DateLogin >= from && x.DateLogin <= to).Take(500).ToList();
                    return(lst);
                }
                else
                {
                    lst = dbContext.MNG_HistoryLogin.Where(x => x.DateLogin >= from && x.DateLogin <= to).ToList();
                    #region Xuất excel
                    var valueConvert = CRMHelper.ToDataTable <MNG_HistoryLogin>(lst);

                    if (valueConvert.GetType() == typeof(string))
                    {
                        return new { status = "err-larger-data" }
                    }
                    ;
                    DataTable dt = valueConvert;
                    dt.Columns["UserName"].ColumnName  = "Tên đăng nhập";
                    dt.Columns["DateLogin"].ColumnName = "Ngày giờ đăng nhập";
                    dt.Columns["Status"].ColumnName    = "Trạng thái";
                    dt.Columns["IP"].ColumnName        = "IP";
                    dt.Columns.Remove("ID");
                    dt.Columns.Remove("FullName");
                    var valueConvertExcel = CRMHelper.ExportDatatableToExcel(dt, "Login history");
                    if (valueConvertExcel == "err")
                    {
                        return new { status = "err-convert-excel" }
                    }
                    ;
                    return(valueConvertExcel);

                    #endregion
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Ejemplo n.º 3
0
        public IEnumerable <ActivityStreamChangeItem> GetChangesDescriptions(ActiviyStreamWriterContext context)
        {
            if (!this.CanApply(context))
            {
                yield break;
            }

            var oldValues = context.Snapshot as IDictionary <string, object>;

            foreach (var part in context.ContentItem.Parts)
            {
                var oldPartValues = oldValues != null && oldValues.ContainsKey(part.PartDefinition.Name) ? oldValues[part.PartDefinition.Name] as IDictionary <string, object> : null;
                var oldPartFields = oldPartValues != null && oldPartValues.ContainsKey("Fields") ? oldPartValues["Fields"] as IDictionary <string, object> : null;

                foreach (var field in part.Fields)
                {
                    var oldValue = oldPartFields != null && oldPartFields.ContainsKey(field.Name) ? oldPartFields[field.Name] : string.Empty;
                    var newValue = CRMHelper.ReteriveField(part, field.Name);

                    if (oldValue == null && newValue != null)
                    {
                        string change = string.Format(CultureInfo.CurrentUICulture,
                                                      "{0} is set to {1}",
                                                      T(field.Name).Text,
                                                      newValue ?? T("[NULL]").Text);
                        yield return(new ActivityStreamChangeItem(change));
                    }
                    else if (newValue == null && oldValue != null)
                    {
                        string change = string.Format(CultureInfo.CurrentUICulture,
                                                      "{0} is changed to NULL",
                                                      T(field.Name).Text);
                        yield return(new ActivityStreamChangeItem(change));
                    }
                    else if (oldValue != null && newValue != null && oldValue.ToString() != newValue.ToString())
                    {
                        string change = string.Format(CultureInfo.CurrentUICulture,
                                                      "{0} is changed to '{1}'",
                                                      T(field.Name).Text,
                                                      newValue ?? T("[NULL]").Text);
                        yield return(new ActivityStreamChangeItem(change));
                    }
                }
            }
        }
        /// <summary>
        /// This method called when user navigated to this page.
        /// </summary>
        /// <param name="e"></param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);

            progressRing.IsActive = true;

            // If UserInfo is null, then initialize the helper
            if (CRMHelper.UserInfo == null)
            {
                await CRMHelper.Initialize();
            }

            // Retrieve EntityMetadataEx by using passed parameter (ObjectTypeCode)
            this.entityMetadataEx = CRMHelper.EntityMetadataExCollection.Where(x => x.EntityMetadata.ObjectTypeCode == (int)e.Parameter).First();
            Initialize();

            progressRing.IsActive = false;
        }
        /// <summary>
        /// This method called when user navigated to this page.
        /// </summary>
        /// <param name="e"></param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);

            progressRing.IsActive = true;

            // If UserInfo is null, then initialize the helper
            if (CRMHelper.UserInfo == null)
            {
                await CRMHelper.Initialize();
            }

            Initialize();

            // If there is a parameter, then this is called from BackGround Task
            if (e.Parameter != null)
            {
                // check if equivalent timezone info is available for CRM
                TimeZoneDefinition timeZoneDefinition = CRMHelper.TimeZones.
                                                        Where(x => x.UserInterfaceName == e.Parameter.ToString()).FirstOrDefault();
                if (timeZoneDefinition == null)
                {
                    return;
                }
                //Show message to confirm if user want to update TimeZone
                string        message = loader.GetString("ConfirmTimeZone");
                MessageDialog dialog  = new MessageDialog(message);
                dialog.Commands.Add(new UICommand(loader.GetString("Yes")));
                dialog.Commands.Add(new UICommand(loader.GetString("No")));
                dialog.DefaultCommandIndex = 1;
                dialog.CancelCommandIndex  = 1;
                var result = await dialog.ShowAsync();

                // If user wants to update TimeZone data, then do it.
                if (result.Label == loader.GetString("Yes"))
                {
                    CRMHelper.UserSettings.TimeZoneCode = timeZoneDefinition.TimeZoneCode;
                    cbTimeZones.SelectedItem            = timeZoneDefinition;
                    await SaveSettings();
                }
            }

            progressRing.IsActive = false;
        }
        /// <summary>
        /// This method is called when user clicks a record
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void lvList_ItemClick(object sender, ItemClickEventArgs e)
        {
            EntityReferenceCollection references = new EntityReferenceCollection();

            // Associate selections
            EntityReference refRecord = new EntityReference();

            refRecord.LogicalName = (string.IsNullOrEmpty((e.ClickedItem as ViewData).ActivityTypeName)) ?
                                    (CRMGrid.cbLookFor.SelectedItem as EntityMetadataEx).EntityMetadata.LogicalName : (e.ClickedItem as ViewData).ActivityTypeName;
            refRecord.Id = (e.ClickedItem as ViewData).Id;
            references.Add(refRecord);

            await CRMHelper.Associate(record.LogicalName, record.Id, new Relationship(relatedData.SchemaName), references);

            if (Frame.CanGoBack)
            {
                Frame.GoBack();
            }
        }
        /// <summary>
        /// Does Quick Find Search
        /// </summary>
        public async void DoSearch()
        {
            // Check Search Criteria
            if (string.IsNullOrEmpty(txtSearch.Text))
            {
                return;
            }

            // Start progress ring until records loaded.
            progressRing.IsActive = true;

            // Set the cbLookFor, cbLookIn and searchbox disabled until views/records loaded.
            cbLookFor.IsEnabled = false;
            cbLookIn.IsEnabled  = false;
            txtSearch.IsEnabled = false;

            // Clear data.
            this.lvList.ItemsSource = null;

            // Retrieve views by specifing search text, which should return 1 view (quick find view)
            // But do not set views to cbLookIn to let users select any views later on.
            views = await CRMHelper.RetrieveViews((int)CRMHelper.EntityMetadataExCollection.
                                                  Where(x => x.EntityMetadata.LogicalName == (cbLookFor.SelectedItem as EntityMetadataEx).EntityMetadata.LogicalName).
                                                  Select(x => x.EntityMetadata.ObjectTypeCode).FirstOrDefault(),
                                                  false, false, txtSearch.Text + "%");

            // Then retrieve record and assign to ListView
            if (views != null && views.Count != 0)
            {
                this.lvList.ItemsSource = await CRMHelper.RetrieveByFetchXmlForView(views[0], relatedData, primaryFieldName);
            }

            // Once record loaded, then enable comboboxes and search textbox.
            cbLookFor.IsEnabled = true;
            cbLookIn.IsEnabled  = true;
            txtSearch.IsEnabled = true;

            // Hide btnSearch and show btnCancelSearch only after finish searching
            btnSearch.Visibility       = Visibility.Collapsed;
            btnCancelSearch.Visibility = Visibility.Visible;

            progressRing.IsActive = false;
        }
        /// <summary>
        /// This methos update UserSettings
        /// </summary>
        /// <returns></returns>
        private async Task SaveSettings()
        {
            // Update User Settings.
            UserSettings userSettings = new UserSettings();

            userSettings.Id           = CRMHelper.UserSettings.Id;
            userSettings.PagingLimit  = int.Parse((cbRecordsPerView.SelectedItem as TextBlock).Text);
            userSettings.TimeZoneCode = (cbTimeZones.SelectedItem as TimeZoneDefinition).TimeZoneCode;

            // Call update
            await CRMHelper.UpsertRecord(userSettings);

            // Now update cache data
            CRMHelper.UserSettings.TimeZoneCode = userSettings.TimeZoneCode;
            CRMHelper.UserSettings.PagingLimit  = userSettings.PagingLimit;
            await Util.SaveToLocal(CRMHelper.UserSettings, "userSettings.dat");

            abAccept.IsEnabled = false;
        }
Ejemplo n.º 9
0
        public static T Convert <T>(IUser user)
            where T : UserViewModel, new()
        {
            UserPart userPart = user.As <UserPart>();

            var userModel = new T
            {
                UserId    = user.Id,
                Username  = user.UserName,
                Email     = user.Email,
                Fullname  = CRMHelper.GetFullNameOfUser(user),
                Thumbnail = ProjectHelper.GetThumbnailImageOfUser(user),
                SkypeId   = GetUserField(userPart, FieldNames.UserSkypeIdField),
                Tel       = GetUserField(userPart, FieldNames.UserTelField),
                Tags      = GetUserField(userPart, FieldNames.UserTags),
                Mobile    = GetUserField(userPart, FieldNames.UserMobileField)
            };

            return(userModel);
        }
        /// <summary>
        /// This method deletes a note record
        /// </summary>
        /// <returns></returns>
        public async System.Threading.Tasks.Task DeleteRecords()
        {
            // Show download message.
            var result = await Util.ShowConfirmMessage(loader.GetString("ConfirmDeleteNote"), loader.GetString("Yes"), loader.GetString("No"), 1);

            if (!result)
            {
                return;
            }

            progressRing.IsActive = true;

            // Delete selected notes.
            foreach (Annotation note in lvList.SelectedItems)
            {
                await CRMHelper.DeleteRecord(note);
            }

            progressRing.IsActive = false;
        }
        /// <summary>
        /// This method is called when user clicks Associate Button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void abAssociate_Click(object sender, RoutedEventArgs e)
        {
            EntityReferenceCollection references = new EntityReferenceCollection();

            // Associate selections
            foreach (ViewData item in CRMGrid.lvList.SelectedItems)
            {
                EntityReference refRecord = new EntityReference();
                refRecord.LogicalName = (string.IsNullOrEmpty(item.ActivityTypeName)) ? (CRMGrid.cbLookFor.SelectedItem as EntityMetadataEx).EntityMetadata.LogicalName : item.ActivityTypeName;
                refRecord.Id          = item.Id;
                references.Add(refRecord);
            }
            await CRMHelper.Associate(record.LogicalName, record.Id, new Relationship(relatedData.SchemaName), references);

            // Go back to original page
            if (Frame.CanGoBack)
            {
                Frame.GoBack();
            }
        }
        /// <summary>
        /// Invoked when LookFor combobox selection item changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void cbLookFor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            progressRing.IsActive = true;

            // Clear search criteria
            txtSearch.Text = "";
            // Clear data
            lvList.ItemsSource = null;
            // Show Search Button and Hide Cancel Button
            btnSearch.Visibility       = Visibility.Visible;
            btnCancelSearch.Visibility = Visibility.Collapsed;

            // Set the cbLookFor and searchbox disabled until views/records loaded.
            cbLookFor.IsEnabled = false;
            cbLookIn.IsEnabled  = false;
            txtSearch.IsEnabled = false;

            // Check if selected Entity is available for mobile, otherwise cannot retrieve data.
            EntityMetadataEx entityMetadata = CRMHelper.EntityMetadataExCollection.Where(x => x.EntityMetadata.LogicalName ==
                                                                                         ((sender as ComboBox).SelectedItem as EntityMetadataEx).EntityMetadata.LogicalName).FirstOrDefault();

            if (entityMetadata == null)
            {
                MessageDialog dialog = new MessageDialog(
                    String.Format(loader.GetString("NotValidForMobile"), ((sender as ComboBox).SelectedItem as EntityMetadata).DisplayName));
                await dialog.ShowAsync();

                // Reset the selection back to original
                (sender as ComboBox).SelectedItem = e.RemovedItems[0];

                return;
            }

            // Retrieve available view definitions depending on conditions.
            cbLookIn.ItemsSource = await CRMHelper.RetrieveViews(
                (int)entityMetadata.EntityMetadata.ObjectTypeCode, isRegarding, isLookup, txtSearch.Text);

            // Assign display name
            cbLookIn.DisplayMemberPath = "Name";
            cbLookIn.SelectedIndex     = cbLookIn_SelectedIndex;
        }
Ejemplo n.º 13
0
        public dynamic TakeSnapshot(ContentItem contentItem)
        {
            dynamic oldData           = new ExpandoObject();
            var     oldDataDictionary = oldData as IDictionary <string, object>;

            foreach (var part in contentItem.Parts)
            {
                dynamic partOldData = new ExpandoObject();
                oldDataDictionary.Add(part.PartDefinition.Name, partOldData);

                var fields = new Dictionary <string, object>();
                partOldData.Fields = fields;

                foreach (var field in part.Fields)
                {
                    fields[field.Name] = CRMHelper.ReteriveField(part, field.Name);
                }
            }

            return(oldData);
        }
Ejemplo n.º 14
0
        private CommentsViewModel.CRMCommentViewModel Convert(CRMCommentPartRecord record, IEnumerable <IUser> users)
        {
            var output = new CommentsViewModel.CRMCommentViewModel
            {
                IsEmail        = record.IsEmail,
                Subject        = record.Subject,
                BCC            = record.BCC,
                CC             = record.CC,
                CommentDateUtc = record.CommentDateUtc,
                CommentText    = record.CommentText,
                IsHtml         = record.IsHtml,
                User           = users.FirstOrDefault(c => c.Id == record.User.Id)
            };

            if (output.CommentDateUtc.HasValue && output.CommentDateUtc.Value.Kind == DateTimeKind.Utc)
            {
                output.CommentDateUtc = CRMHelper.SetSiteTimeZone(services, output.CommentDateUtc.Value);
            }

            return(output);
        }
Ejemplo n.º 15
0
        public virtual ActionResult Edit(int[] ids, string returnUrl)
        {
            var model = this.CreateEditPermissionsModel(ids);

            model.ReturnUrl = returnUrl;

            if (Request.IsAjaxRequest())
            {
                AjaxMessageViewModel ajaxMessageModel = new AjaxMessageViewModel {
                    IsDone = true
                };
                this.widgetService.GetWidgets(model, this.HttpContext);
                ajaxMessageModel.Html = CRMHelper.RenderPartialViewToString(this, "Edit", model);

                return(this.Json(ajaxMessageModel, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(View(model));
            }
        }
Ejemplo n.º 16
0
        public void Describe(DescribeContext context)
        {
            Func <IShapeFactory, dynamic> formFactory =
                shapeFactory =>
            {
                var priorities    = this.basicDataService.GetPriorities().ToList();
                var statusRecords = this.basicDataService.GetStatusRecords().ToList().Select(c => new BasicDataRecordViewModel {
                    Id = c.Id, Name = c.Name
                }).ToList();
                var serviceRecords = this.basicDataService.GetServices().ToList();

                Collection <SelectListItem> prioritySelectList = new Collection <SelectListItem>();
                Collection <SelectListItem> statusSelectList   = new Collection <SelectListItem>();
                Collection <SelectListItem> serviceSelectList  = new Collection <SelectListItem>();

                Converter.Fill(prioritySelectList, null, priorities);
                prioritySelectList.Insert(0, new SelectListItem());

                Converter.Fill(statusSelectList, null, statusRecords);
                statusSelectList.Insert(0, new SelectListItem());

                Converter.Fill(serviceSelectList, null, serviceRecords);
                serviceSelectList.Insert(0, new SelectListItem());

                Collection <SelectListItem> dueDates = CRMHelper.GetDueDateItems(this.T);

                var t = this.Shape.Form(
                    Id: "UpdateTicketForm",
                    _Parts: this.Shape.UpdateTicketActivity(
                        Priorities: prioritySelectList,
                        StatusList: statusSelectList,
                        Services: serviceSelectList,
                        DueDates: dueDates
                        ));

                return(t);
            };

            context.Form(UpdateTicketActivityForm.Name, formFactory);
        }
        /// <summary>
        /// This method called when user navigated to this page.
        /// </summary>
        /// <param name="e"></param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);

            progressRing.IsActive = true;

            // If UserInfo is null, then initialize the helper
            if (CRMHelper.UserInfo == null)
            {
                await CRMHelper.Initialize();
            }

            if (fields == null) // If fields are not yet has value, means just navigated to this page
            {
                // Check if there is any temporaryData
                object[] parameters = CRMHelper.temporaryData as object[];
                if (parameters.Count() != 3)
                {
                    new Exception("RecordModifyPage needs 3 parameters. Record, Fields, EntityMetadataEx");
                }
                this.record           = parameters[0] as Entity;               // record for update/related new
                this.fields           = parameters[1] as List <FormFieldData>; // form fields
                this.entityMetadataEx = parameters[2] as EntityMetadataEx;     // target entity
            }
            else // It has been restored of page back from lookup page
            {
                // Assign lookup value when retruning from lookup page.
                if (CRMHelper.temporaryData != null &&
                    CRMHelper.temporaryData.GetType().Equals(typeof(FormFieldData)))
                {
                    FormFieldData formfieldData = CRMHelper.temporaryData as FormFieldData;
                    fields.Where(x => x.FieldMetadata.LogicalName == formfieldData.FieldMetadata.LogicalName).First().FieldData = formfieldData.FieldData;
                }
            }

            // Then initialize page
            Initialize();

            progressRing.IsActive = false;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Fills the model with the businessUnits that the user has granted to view them
        /// </summary>
        private void FillBusinessUnitsAndUsers(SearchTicketsViewModel model, PostedTicketSearchViewModel postedSearchModel)
        {
            bool restrictToUserPermissions = !this.services.Authorizer.Authorize(Permissions.AdvancedOperatorPermission);

            this.businessUnitService.Fill(model.BusinessUnits, restrictToUserPermissions);

            var selectedBusinessUnits = postedSearchModel.BusinessUnits.ToList();

            // TeamIds of the search
            var teams = new List <int>();

            // set checkes of businessUnits
            model.BusinessUnits
            .ToList()
            .ForEach(c => c.Checked = selectedBusinessUnits.Count(d => d == c.BusinessUnitId) > 0);

            // set checks of teams
            model.BusinessUnits
            .SelectMany(c => c.Teams)
            .ToList()
            .ForEach(c => c.Checked = teams.Count(d => d == c.TeamId) > 0);

            IEnumerable <IUser> users = null;

            users = this.basicDataService.GetOperators().ToList();

            foreach (var user in users)
            {
                SearchTicketsViewModel.UserViewModel userViewModel = new SearchTicketsViewModel.UserViewModel
                {
                    Id                = user.Id,
                    Username          = CRMHelper.GetFullNameOfUser(user.As <UserPart>()),
                    Checked           = postedSearchModel.Users.Count(c => c == user.Id) > 0,
                    IsAdminOrOperator = true
                };

                model.Users.Add(userViewModel);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Delete current record
        /// </summary>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <bool> DeleteRecord()
        {
            // Display confirm message with Yes/No option
            var result = await Util.ShowConfirmMessage(loader.GetString("ConfirmDelete"), loader.GetString("Yes"), loader.GetString("No"), 1);

            // If user click no, then do nothing.
            if (!result)
            {
                return(false);
            }

            // Otherwise delete recrod(s). Show progress ring first.
            progressRing.IsActive = true;

            // Then delete
            await CRMHelper.DeleteRecord(Record);

            progressRing.IsActive = false;

            // Let page handle navigation
            return(true);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// This method called when user navigated to this page.
        /// </summary>
        /// <param name="e"></param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);

            progressRing.IsActive = true;

            // If UserInfo is null, then initialize the helper
            if (CRMHelper.UserInfo == null)
            {
                await CRMHelper.Initialize();
            }

            if (id == Guid.Empty) // If id does not have value, this is new page.
            {
                // Check if there is any temporaryData
                object[] parameters = CRMHelper.temporaryData as object[];
                this.id = Guid.Parse(parameters[0].ToString());
                this.entityMetadataEx = parameters[1] as EntityMetadataEx;
            }
            // if id has value, then this page is navigate back from another page.
            else
            {
                // Check parameter
                object[] parameters = CRMHelper.temporaryData as object[];
                // If first parameter is Entity, then this is back from Modify Page.
                // In this case, as record may have newer value, clear the cache.
                if (parameters != null && parameters.Count() == 1 && parameters[0].GetType().Equals(typeof(Entity)))
                {
                    fields = null;
                    record = null;
                }
            }

            // Initalize the page.
            Initialize();

            progressRing.IsActive = false;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This method is called when user clicks Add button in Related PivotItem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void abRelatedAdd_Click(object sender, RoutedEventArgs e)
        {
            // Get RelatedData to create related record
            RelatedData relatedData = entityMetadataEx.RelatedEntities.Where(x => x.ReferencingEntity == (CRMGrid.cbLookFor.SelectedItem as EntityMetadataEx).EntityMetadata.LogicalName).First();

            // Create Entity instance to created record, by fulling mapped values.
            Entity targetRecord = await CRMHelper.RetrieveRecordForRelated(record, relatedData, entityMetadataEx);

            // Make id to empty for sure (not mandatory?)
            targetRecord.Id = Guid.Empty;
            // Get Related entity's EntityMetadata
            EntityMetadataEx targetEntityMetadataEx = CRMHelper.EntityMetadataExCollection.Where(x => x.EntityMetadata.LogicalName == relatedData.ReferencingEntity).First();
            // Get fields for create form
            List <FormFieldData> targetFields = await CRMHelper.RetrieveFormFields(targetEntityMetadataEx);

            // Resets all the buttons
            ResetAppBarButtonDisplay();
            // Generate parameters. As this is new record, passing null for record object.
            object[] parameters = new object[] { targetRecord, targetFields, targetEntityMetadataEx };
            CRMHelper.temporaryData = parameters;
            // Then Navigate to RecordModifyPage
            Frame.Navigate(typeof(RecordModifyPage));
        }
Ejemplo n.º 22
0
        protected ActionResult CreateActionResult(int contentItemId, string view, object ajaxData, Func <object> createFullModel)
        {
            if (Request.IsAjaxRequest())
            {
                AjaxMessageViewModel ajaxMessageModel = new AjaxMessageViewModel {
                    Id = contentItemId, IsDone = ModelState.IsValid, Data = ajaxData
                };
                CRMHelper.AddModelStateErrors(this.ModelState, ajaxMessageModel);

                return(this.Json(ajaxMessageModel, JsonRequestBehavior.AllowGet));
            }
            else
            {
                object model = null;

                if (createFullModel != null)
                {
                    model = createFullModel();
                }

                return(this.View(view, model));
            }
        }
        private string GetContentItemPermissionChangeDescription(ContentItemPermissionDetailRecord record, string format, string accessType, ContentItem targetContentItem)
        {
            IUser user = record.User != null?
                         this.basicDataService.GetOperatorOrCustomerUser(record.User.Id) :
                             null;

            BusinessUnitPart businessUnit = record.BusinessUnit != null?
                                            this.basicDataService.GetBusinessUnits()
                                            .Select(c => c.As <BusinessUnitPart>())
                                            .FirstOrDefault(c => c.Record.Id == record.BusinessUnit.Id)
                                                : null;

            string contentItemDescription = this.contentItemDescriptorManager.GetDescription(targetContentItem);

            if (user != null)
            {
                string fullName = CRMHelper.GetFullNameOfUser(user);
                return(string.Format(
                           CultureInfo.CurrentUICulture,
                           T(format).Text,
                           accessType,
                           fullName,
                           contentItemDescription));
            }

            if (businessUnit != null)
            {
                return(string.Format(
                           CultureInfo.CurrentUICulture,
                           T(format).Text,
                           accessType,
                           businessUnit.Name + T(" group").Text,
                           contentItemDescription));
            }

            return(string.Empty);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Thêm mới CatType
        /// </summary>
        /// <param name="cat"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public object AddNewCatType(MNG_CatType cat, string userName)
        {
            try
            {
                #region HANDLER
                string[] value  = CRMHelper.RemoveUnicode(cat.CatTypeName).Split(' ');
                string   result = string.Empty;
                for (int i = 0; i < value.Count(); i++)
                {
                    result += value[i].Substring(0, 1);
                }
                if (result.Length > 5)
                {
                    result = result.Substring(0, 5);
                }

                if (!dbContext.MNG_Category.Any(x => x.CatTypeCode == result))
                {
                    cat.IsDeleted   = false;
                    cat.CatTypeCode = result;
                    dbContext.MNG_CatType.Add(cat);
                    dbContext.SaveChanges();
                }
                else
                {
                    return(MP_AjaxError.Exits);
                }
                return(MP_AjaxError.OK);

                #endregion
            }
            catch (System.Exception ex)
            {
                return(ex.Message);
            }
        }
Ejemplo n.º 25
0
        protected void FillStatusTimes(TicketViewModel model, TicketPart part, IEnumerable <StatusRecordViewModel> statusRecords)
        {
            CommonPart commonPart = part.As <CommonPart>();
            List <KeyValuePair <int, DateTime> > output = new List <KeyValuePair <int, DateTime> >();

            // creation time
            if (commonPart != null && commonPart.CreatedUtc.HasValue)
            {
                output.Add(new KeyValuePair <int, DateTime>(StatusRecord.NewStatus, CRMHelper.SetSiteTimeZone(this.orchardServices.WorkContext, commonPart.CreatedUtc.Value)));
            }

            var statusTimes = part.StatusTimes;

            foreach (var item in statusTimes)
            {
                var statusRecord = statusRecords.FirstOrDefault(c => c.Id == item.Key);
                if (statusRecord == null)
                {
                    continue;
                }

                int?statusTypeId = statusRecord.StatusTypeId.HasValue?
                                   statusRecord.StatusTypeId.Value:
                                   statusRecords
                                   .Where(c => c.OrderId <= statusRecord.OrderId && c.StatusTypeId.HasValue)
                                   .Select(c => c.StatusTypeId)
                                   .OrderByDescending(c => c)
                                   .FirstOrDefault();

                statusTypeId = statusTypeId ?? StatusRecord.NewStatus;
                output.Add(new KeyValuePair <int, DateTime>(statusTypeId.Value, CRMHelper.SetSiteTimeZone(this.orchardServices.WorkContext, item.Value)));
            }

            model.StatusTimes.Clear();
            model.StatusTimes.AddRange(output.OrderBy(c => c.Value));
        }
Ejemplo n.º 26
0
        public SidebarDashboardHandler(IContentManager contentManager, IRepository <LayoutRecord> layoutRepository)
        {
            OnPublished <SidebarDashboardPart>((context, part) =>
            {
                // portlet list
                var portletNames = string.IsNullOrEmpty(part.SidebarPortletList) ? new string[] { } : part.SidebarPortletList.Split(',');

                var portlets = contentManager.HqlQuery().ForType(Consts.SidebarProjectionPortletTemplateType, Consts.SidebarStaticPortletType).Where(c => c.ContentPartRecord <TitlePartRecord>(), c => c.In("Title", portletNames)).List().Select(c => c.As <TitlePart>());

                // current portlets
                var currentPortlets = contentManager.Query().Where <CommonPartRecord>(c => c.Container.Id == part.ContentItem.Id).List().Select(c => c.As <TitlePart>());

                // add new portlets
                int position = -1;
                foreach (var newPortlet in portletNames.Where(c => !currentPortlets.Any(d => d.Title == c)))
                {
                    position++;
                    var newPortletContentItemTemplate = portlets.FirstOrDefault(c => c.Title == newPortlet);
                    if (newPortletContentItemTemplate == null)
                    {
                        continue;
                    }
                    ContentItem newPortletContentItem = null;

                    if (newPortletContentItemTemplate.ContentItem.ContentType == Consts.SidebarProjectionPortletTemplateType)
                    {
                        newPortletContentItem = contentManager.Create(Consts.SidebarProjectionPortletType);
                        CRMHelper.Copy(layoutRepository, newPortletContentItemTemplate.As <ProjectionWithDynamicSortPart>().Record, newPortletContentItem.As <ProjectionWithDynamicSortPart>().Record);
                    }
                    else
                    {
                        newPortletContentItem = contentManager.Create(Consts.SidebarStaticPortletType);
                        newPortletContentItem.As <BodyPart>().Text = newPortletContentItemTemplate.As <BodyPart>().Text;
                    }

                    // Title
                    newPortletContentItem.As <TitlePart>().Title = newPortletContentItemTemplate.Title;

                    // Container
                    var newPortletCommon = newPortletContentItem.As <CommonPart>();

                    if (newPortletCommon.Container != null && newPortletCommon.Container.Id != part.ContentItem.Id)
                    {
                        continue;
                    }

                    newPortletCommon.Container = part.ContentItem;

                    ContainablePart containablePart = newPortletContentItem.As <ContainablePart>();
                    if (containablePart == null)
                    {
                        continue;
                    }

                    // Position
                    containablePart.Position = position;

                    // publish new portlet
                    contentManager.Publish(newPortletContentItem);
                }

                // delete portlets
                foreach (var portlet in currentPortlets.Where(c => !portletNames.Any(d => d == c.Title)))
                {
                    // Container
                    contentManager.Remove(portlet.ContentItem);
                }


                // set position
                foreach (var portlet in currentPortlets.Where(c => portletNames.Any(d => d == c.Title)))
                {
                    // Container
                    int index = portletNames.ToList().IndexOf(portlet.Title);

                    ContainablePart containablePart = portlet.As <ContainablePart>();
                    if (containablePart == null)
                    {
                        continue;
                    }

                    // Position
                    containablePart.Position = index;

                    // publish new portlet
                    contentManager.Publish(portlet.ContentItem);
                }
            });
        }
Ejemplo n.º 27
0
        private void SubstituteTicketProperties(EvaluateContext context)
        {
            context.For(ActivityTokenProvider.TicketKey, () => this.GetTicketPart(context))
            .Token("Status", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.StatusRecord == null)
                {
                    return(string.Empty);
                }

                var statusRecords = this.basicDataService.GetStatusRecords().ToList().Select(d => new BasicDataRecordViewModel {
                    Id = d.Id, Name = d.Name
                }).ToList();
                return(this.GetBasicDataRecordName(c.StatusRecord.Id, statusRecords));
            })
            .Token("Service", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.Service == null)
                {
                    return(string.Empty);
                }

                var records = this.basicDataService.GetServices().ToList();
                return(this.GetBasicDataRecordName(c.Record.Service.Id, records));
            })
            .Token("RequestingUserEmail", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.RequestingUser == null)
                {
                    return(string.Empty);
                }

                return(c.Record.RequestingUser.Email);
            })
            .Token("RequestingUserName", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.RequestingUser == null)
                {
                    return(string.Empty);
                }

                return(c.Record.RequestingUser.UserName);
            })
            .Token("RequestingUserFullName", contextParameter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.RequestingUser == null)
                {
                    return(string.Empty);
                }

                var userContentItem = contentManager.Get(c.Record.RequestingUser.Id);

                string fieldValue = CRMHelper.GetFullNameOfUser(userContentItem.As <UserPart>());

                return(fieldValue);
            })
            .Token("Priority", contextParamter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.PriorityRecord == null)
                {
                    return(string.Empty);
                }

                var records = this.basicDataService.GetPriorities().ToList();
                return(this.GetBasicDataRecordName(c.PriorityRecord.Id, records));
            })
            .Token("TicketType", contextParamter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null)
                {
                    return(string.Empty);
                }

                var records = this.basicDataService.GetTicketTypes().ToList();
                return(this.GetBasicDataRecordName(c.Record.TicketType.Id, records));
            })
            .Token("Number", contextParamter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null || c.Record.Identity == null)
                {
                    return(string.Empty);
                }

                return(c.Record.Identity.Id.ToString(CultureInfo.InvariantCulture));
            })
            .Token("Title", contextParsmeter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null)
                {
                    return(string.Empty);
                }

                return(c.Record.Title);
            })
            .Token("Id", contextParsmeter =>
            {
                var c = this.GetTicketPart(context);
                if (c == null)
                {
                    return(string.Empty);
                }

                return(c.Record.Id);
            });
        }
Ejemplo n.º 28
0
        public void Evaluate(EvaluateContext context)
        {
            // Title
            context.For(ActivityTokenProvider.TitkeKey, () => this.GetPart <TitlePart>(context))
            .Token("Title", c =>
            {
                TitlePart titlePart = this.GetPart <TitlePart>(context);

                if (titlePart == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(titlePart.Title);
                }
            });

            // User
            context.For(ActivityTokenProvider.UserKey, () => (UserPartRecord)context.Data[UserKey])
            .Token("Email", c =>
            {
                var part = (UserPartRecord)context.Data[UserKey];
                if (part == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(part.Email);
                }
            })
            .Token("Username", c =>
            {
                var part = (UserPartRecord)context.Data[UserKey];
                if (part == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(part.Email);
                }
            })
            .Token("FullName", contextParameter =>
            {
                var part = (UserPartRecord)context.Data[UserKey];
                if (part == null)
                {
                    return(string.Empty);
                }

                var userContentItem = contentManager.Get(part.Id);

                // Sometimes the passed UserRecord is not persisted in the database or it is a faked object,
                // so we have to check for nullability
                if (userContentItem != null)
                {
                    return(CRMHelper.GetFullNameOfUser(userContentItem.As <UserPart>()));
                }
                else
                {
                    return(part.UserName);
                }
            });

            // Ticket
            this.SubstituteTicketProperties(context);

            // Email
            this.SubstituteEmailProperties(context);

            // Team
            this.CheckForContentPartId <TeamPart>(context, TeamKey);

            // BusinessUnit
            this.CheckForContentPartId <BusinessUnitPart>(context, BusinessUnitKey);

            // CRMComment
            context.For(ActivityTokenProvider.CRMCommentKey, () => this.GetPart <CRMCommentPart>(context))
            .Token("CommentText", c =>
            {
                var part = this.GetPart <CRMCommentPart>(context);
                if (part == null)
                {
                    return(string.Empty);
                }
                else
                {
                    return(part.Record.CommentText);
                }
            });
        }
        /// <summary>
        /// This methods LoadData to control
        /// </summary>
        public void LoadData()
        {
            progressRing.IsActive = true;

            // Check if Create or Update
            // If there is no Record data, or data without id information, then it's for new Record
            if (Record == null || Record.Id == Guid.Empty)
            {
                isUpdate = false;
                // however, if Record is not null, then it is new operation for regarding item
                if (Record != null)
                {
                    isRegarding = true;
                }
            }
            foreach (var field in Fields)
            {
                if ((isUpdate && !(bool)field.FieldMetadata.IsValidForUpdate) || (!isUpdate && !(bool)field.FieldMetadata.IsValidForCreate))
                {
                    continue;
                }
                // do not show from field
                if (field.FieldMetadata.LogicalName == "from")
                {
                    continue;
                }
                if ((isUpdate || isRegarding) && field.FieldData == null)
                {
                    field.FieldData = (Record.Attributes.Contains(field.FieldMetadata.LogicalName)) ? Record.Attributes[field.FieldMetadata.LogicalName] : null;
                }
                if (field.FieldMetadata.LogicalName == "ownerid" && field.FieldData == null)
                {
                    EntityReference owner = new EntityReference(SystemUser.EntityLogicalName, (Guid)CRMHelper.UserInfo.SystemUserId);
                    owner.Name      = CRMHelper.UserInfo.FullName;
                    field.FieldData = owner;
                }
                // Put description field to txtDescription in second grid row.
                if (field.FieldMetadata.LogicalName == "description")
                {
                    var w = Window.Current.Bounds.Width;
                    txtDescription.Width       = w - 36;
                    txtDescription.DataContext = field;
                    Binding binding = new Binding();
                    binding.Path = new PropertyPath("FieldData");
                    binding.Mode = BindingMode.TwoWay;
                    txtDescription.SetBinding(TextBox.TextProperty, binding);
                    continue;
                }

                Grid grid = CRMHelper.GenerateField(field, isUpdate);

                if (grid.Children[1].GetType().Equals(typeof(LookupControl)))
                {
                    (grid.Children[1] as LookupControl).LookupControlButton_Click += LookupButton_Click;
                }
                if (grid.Children[1].GetType().Equals(typeof(ActivityPartyLookupControl)))
                {
                    (grid.Children[1] as ActivityPartyLookupControl).ActivityPartyDeleteButton_Click += ActivityPartyDelteButton_Click;
                    (grid.Children[1] as ActivityPartyLookupControl).ActivityPartyAddButton_Click    += ActivityPartyAddButton_Click;
                }
                if (grid == null)
                {
                    continue;
                }

                this.lvFields.Items.Add(grid);
            }

            progressRing.IsActive = false;
        }
        /// <summary>
        /// Saves Email record with Attachments.
        /// </summary>
        /// <returns></returns>
        public async Task Save()
        {
            Entity modifiedRecord;

            // If it is regarding, then pass all the record information which contains mapped data to modifiedrecord.
            if (isRegarding)
            {
                modifiedRecord = Record;
            }
            // Otherwise, create blank record
            else
            {
                modifiedRecord = new Entity();
            }
            modifiedRecord.LogicalName = EntityMetadataEx.EntityMetadata.LogicalName;

            // If update, then assign Id
            if (isUpdate)
            {
                modifiedRecord.Id = Record.Id;
            }
            foreach (var field in Fields)
            {
                // If no data changed, then no need to pass the value.
                if (isUpdate && field.FieldData == Record[field.FieldMetadata.LogicalName])
                {
                    continue;
                }
                // If required fields have no value, then show error message.
                if ((bool)field.FieldMetadata.IsValidForCreate && (field.FieldMetadata.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired ||
                                                                   field.FieldMetadata.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired) &&
                    field.FieldData == null)
                {
                    MessageDialog dialog = new MessageDialog(string.Format(loader.GetString("RequiredField"), field.FieldMetadata.DisplayName.UserLocalizedLabel.Label));
                    await dialog.ShowAsync();

                    lvFields.SelectedItem = ((lvFields.FindName("lbl" + field.FieldMetadata.LogicalName) as TextBlock).Parent as StackPanel).Parent;
                    lvFields.UpdateLayout();
                    lvFields.ScrollIntoView(lvFields.SelectedItem);
                    return;
                }
                // If value has been changed, then pass the data to modified record.
                modifiedRecord[field.FieldMetadata.LogicalName] = field.FieldData;
            }

            progressRing.IsActive = true;

            // Create/Update record and store the id back original record
            Record = await CRMHelper.UpsertRecord(modifiedRecord);

            // Now check attachments.
            foreach (ActivityMimeAttachment attachment in this.lvList.Items)
            {
                // Assign regarding activity. Attachment should have ObjectTypeCode already
                attachment.ObjectId = Record.ToEntityReference();
                // Then save it
                await CRMHelper.UpsertRecord(attachment);
            }

            progressRing.IsActive = false;
        }