//Validate section and display asterix's for unanswered questions.
 private void validate()
 {
     bool[] valid = SharedFunctions.validateS6(Convert.ToInt32(Context.Request["AppID"]));
     if (valid[0])
     {
         btnS6.Style.Add("color", "Green");
         mand1.Visible = false; //Hide mandatory label.
     }
     else
     {
         btnS6.Style.Add("color", "Red");
         mand1.Visible = true; //Show mandatory label.
     }
 }
        public static bool IsAccessedFromAppointment(string screenID)
        {
            string[] logActionsMobileScreens =
            {
                ID.ScreenID.LOG_ACTION_START_TRAVEL_SRV_MOBILE,
                ID.ScreenID.LOG_ACTION_START_STAFF_MOBILE,
                ID.ScreenID.LOG_ACTION_START_STAFF_ASSIGNED_MOBILE,
                ID.ScreenID.LOG_ACTION_COMPLETE_SERVICE_MOBILE,
                ID.ScreenID.LOG_ACTION_COMPLETE_TRAVEL_MOBILE
            };

            return(screenID == SharedFunctions.SetScreenIDToDotFormat(ID.ScreenID.APPOINTMENT) ||
                   Array.Exists(logActionsMobileScreens, x => SharedFunctions.SetScreenIDToDotFormat(x) == screenID));
        }
        Result Execute()
        {
            SharedFunctions.DisplayLocalServerInfo(_state);
            Console.WriteLine($"{Environment.NewLine}############# TEXT MESSAGE EVENT LOG #############{Environment.NewLine}");
            foreach (var textMessage in _conversation.Messages)
            {
                Console.WriteLine(textMessage + Environment.NewLine);
            }

            Console.WriteLine(Environment.NewLine + Resources.Prompt_ReturnToPreviousMenu);
            Console.ReadLine();

            return(Result.Ok());
        }
Exemple #4
0
        public async Task Run1()
        {
            Console.WriteLine("Day 1 - puzzle 1");
            var masses = await SharedFunctions.GetDoublesFromInput("day1-1.txt");

            double result = 0;

            Array.ForEach(masses, mass =>
            {
                result += Math.Floor(mass / 3) - 2;
            });

            Console.WriteLine($"Result is: {result}");
        }
        public void CmdAnalyze_SamplePdf_GetTextAndQrCode()
        {
            // arrange
            var analyzerViewModel = new AnalyzerViewModel(new IronOcrProvider());

            analyzerViewModel.FilePath = SharedFunctions.GetPathToSamplePdf();

            // act
            analyzerViewModel.CmdAnalyze.Execute();

            // assert
            Assert.That(analyzerViewModel.ExtractedText, Contains.Substring(SharedValues.OCR_TEXT_PART));
            Assert.That(analyzerViewModel.QrCodeValue, Contains.Substring(SharedValues.QR_CODE_VALUE_PART));
        }
Exemple #6
0
        public Result DisplayMenu()
        {
            if (_state.DoNotRefreshMainMenu)
            {
                return(Result.Ok());
            }
            SharedFunctions.DisplayLocalServerInfo(_state);

            PopulateMenu();
            ConsoleMenu.DisplayTieredMenu(TieredMenu);
            Console.WriteLine(ValidRangeOfMenuItemNumbers());

            return(Result.Ok());
        }
Exemple #7
0
        /// <summary>
        /// Handles the CellValueChanged event of the MISelectionGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Windows.Forms.DataGridViewCellEventArgs"/> instance containing the event data.</param>
        private void MISelectionGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (this.edit)
                {
                    this.edit = false;

                    this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.FieldNumColumn.ColumnName].Value   = Convert.ToByte(this.fieldNum);
                    this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.MICodeIDColumn.ColumnName].Value   = this.miscCodeId;
                    this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.IsCommitedColumn.ColumnName].Value = false;

                    if (string.IsNullOrEmpty(this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.MIChoiceIDColumn.ColumnName].Value.ToString()))
                    {
                        this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.MIChoiceIDColumn.ColumnName].Value = 0;
                    }

                    if (string.IsNullOrEmpty(this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.ItemValueColumn.ColumnName].Value.ToString()))
                    {
                        this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.ItemValueColumn.ColumnName].Value = 0;
                    }
                    else
                    {
                        decimal outDecimal;
                        decimal maxItemValue = 9999999999999999.99M;
                        decimal.TryParse(this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.ItemValueColumn.ColumnName].Value.ToString(), out outDecimal);
                        if (outDecimal > maxItemValue)
                        {
                            MessageBox.Show(SharedFunctions.GetResourceString("F36012_MaxValue"), SharedFunctions.GetResourceString("Log"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.MISelectionGridView.Rows[e.RowIndex].Cells[this.miscImprovementCatalogChoiceDataSet.GetMiscCatalogChoice.ItemValueColumn.ColumnName].Value = 0;
                        }
                    }

                    if (this.MISelectionGridView.OriginalRowCount >= this.MISelectionGridView.NumRowsVisible)
                    {
                        if (!Convert.ToBoolean(this.currentFieldCatalogChoiceDataSet.GetMiscCatalogChoice.Rows[this.currentFieldCatalogChoiceDataSet.GetMiscCatalogChoice.Rows.Count - 1][this.MISelectionGridView.EmptyRecordColumnName]))
                        {
                            this.currentFieldCatalogChoiceDataSet.GetMiscCatalogChoice.Rows.Add(this.currentFieldCatalogChoiceDataSet.GetMiscCatalogChoice.NewRow());
                            this.currentFieldCatalogChoiceDataSet.GetMiscCatalogChoice.Rows[this.currentFieldCatalogChoiceDataSet.GetMiscCatalogChoice.Rows.Count - 1][this.MISelectionGridView.EmptyRecordColumnName] = true;
                            this.MISelectionGridVerticalScroll.Visible = false;
                            TerraScanCommon.SetDataGridViewPosition(this.MISelectionGridView, e.RowIndex + 1);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.ManageException(ex, ExceptionManager.ActionType.Display, this.ParentForm);
            }
        }
Exemple #8
0
        public async Task DeleteObservationAsync_ReturnsUnauthorised_WhenRequestingUserIsNotObservationOwner(int id, int birdId)
        {
            //Arrange
            var requestingUser = GetUser("Any");
            var model          = GetTestObservationViewModel(id, birdId, requestingUser);

            var mockUnitOfWork  = new Mock <IUnitOfWork>();
            var mockBirdRepo    = new Mock <IBirdRepository>();
            var mockUserManager = SharedFunctions.InitialiseMockUserManager();
            var mockObsRepo     = new Mock <IObservationRepository>();

            mockObsRepo.Setup(o => o.GetObservationAsync(It.IsAny <int>(), It.IsAny <bool>()))
            .ReturnsAsync(GetTestObservation(0, new ApplicationUser {
                UserName = "******"
            }));
            var mockObsPositionRepo = new Mock <IObservationPositionRepository>();
            var mockObsNotesRepo    = new Mock <IObservationNoteRepository>();

            var controller = new ObservationController(
                _mapper
                , _systemClock
                , mockUnitOfWork.Object
                , mockBirdRepo.Object
                , _logger.Object
                , mockUserManager.Object
                , mockObsRepo.Object
                , mockObsPositionRepo.Object
                , mockObsNotesRepo.Object);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = SharedFunctions.GetTestClaimsPrincipal(requestingUser.UserName)
                }
            };

            // Act
            var result = await controller.DeleteObservationAsync(id);

            // Assert
            string expectedMessage = "Requesting user is not allowed to delete this observation";

            var objectResult = Assert.IsType <UnauthorizedObjectResult>(result);

            Assert.Equal(StatusCodes.Status401Unauthorized, objectResult.StatusCode);
            var actual = Assert.IsType <string>(objectResult.Value);

            Assert.Equal(expectedMessage, actual);
        }
Exemple #9
0
        public async Task PutObservationAsync_ReturnsBadRequest_WhenObservationNotFound(int id, int birdId)
        {
            //Arrange
            var model          = GetTestObservationEditViewModel(id, birdId);
            var requestingUser = GetUser("Any");

            var mockUnitOfWork = new Mock <IUnitOfWork>();
            var mockBirdRepo   = new Mock <IBirdRepository>();
            //mockBirdRepo.Setup(b => b.GetBirdAsync(It.IsAny<int>()))
            //    .Returns(Task.FromResult<Bird>(null));
            var mockUserManager = SharedFunctions.InitialiseMockUserManager();
            //mockUserManager.Setup(um => um.FindByNameAsync(It.IsAny<string>()))
            //                .ReturnsAsync(requestingUser);
            var mockObsRepo = new Mock <IObservationRepository>();

            mockObsRepo.Setup(obs => obs.GetObservationAsync(It.IsAny <int>(), It.IsAny <bool>()))
            .Returns(Task.FromResult <Observation>(null));
            var mockObsPositionRepo = new Mock <IObservationPositionRepository>();
            var mockObsNotesRepo    = new Mock <IObservationNoteRepository>();

            var controller = new ObservationController(
                _mapper
                , _systemClock
                , mockUnitOfWork.Object
                , mockBirdRepo.Object
                , _logger.Object
                , mockUserManager.Object
                , mockObsRepo.Object
                , mockObsPositionRepo.Object
                , mockObsNotesRepo.Object);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = SharedFunctions.GetTestClaimsPrincipal(requestingUser.UserName)
                }
            };

            // Act
            var result = await controller.PutObservationAsync(id, model);

            // Assert
            var objectResult = Assert.IsType <ObjectResult>(result);

            Assert.Equal(StatusCodes.Status500InternalServerError, objectResult.StatusCode);
            var actual = Assert.IsType <string>(objectResult.Value);

            Assert.Equal($"observation with id '{model.ObservationId}' was not found.", actual);
        }
Exemple #10
0
        protected virtual void _(Events.FieldUpdated <FSSetup, FSSetup.contractPostTo> e)
        {
            if (e.Row == null)
            {
                return;
            }

            FSSetup fsSetupRow = (FSSetup)e.Row;

            if (fsSetupRow.ContractPostTo != (string)e.OldValue)
            {
                SharedFunctions.ValidatePostToByFeatures <FSSetup.contractPostTo>(e.Cache, fsSetupRow, fsSetupRow.ContractPostTo);
            }
        }
        protected virtual void AppointmentInqFilter_StaffMemberID_FieldDefaulting(PXCache cache, PXFieldDefaultingEventArgs e)
        {
            if (e.Row == null)
            {
                return;
            }

            int?employeeID = SharedFunctions.GetCurrentEmployeeID(cache);

            if (employeeID != null)
            {
                e.NewValue = employeeID;
            }
        }
Exemple #12
0
        public async Task GetSearchNetworkAsync_ReturnsNotFoundWithstringObject_WhenRepositoryReturnsNullUser()
        {
            var options = this.CreateUniqueClassOptions <ApplicationDbContext>();

            using (var context = new ApplicationDbContext(options))
            {
                //You have to create the database
                context.Database.EnsureClean();
                context.Database.EnsureCreated();
                //context.SeedDatabaseFourBooks();

                //context.ConservationStatuses.Add(new ConservationStatus { ConservationList = "Red", Description = "", CreationDate = DateTime.Now, LastUpdateDate = DateTime.Now });

                context.Users.Add(SharedFunctions.CreateUser("testUser1"));
                context.Users.Add(SharedFunctions.CreateUser("testUser2"));

                context.SaveChanges();

                context.Users.Count().ShouldEqual(2);

                // Arrange
                var userManager = SharedFunctions.InitialiseUserManager(context);
                // Arrange
                var mockUnitOfWork = new Mock <IUnitOfWork>();
                var mockRepo       = new Mock <INetworkRepository>();

                var controller = new NetworkController(_mapper, mockUnitOfWork.Object, _logger.Object, mockRepo.Object, userManager);

                controller.ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        User = SharedFunctions.GetTestClaimsPrincipal("example name")
                    }
                };

                string searchCriterion = "Test string";

                // Act
                var result = await controller.GetSearchNetworkAsync(searchCriterion);

                // Assert
                var objectResult = result as ObjectResult;
                Assert.NotNull(objectResult);
                Assert.IsType <ObjectResult>(result);
                Assert.Equal(StatusCodes.Status500InternalServerError, objectResult.StatusCode);
                Assert.IsType <string>(objectResult.Value);
                Assert.Equal("requesting user not found", objectResult.Value);
            }
        }
Exemple #13
0
        public ScriptScreen()
        {
            containerTexture              = IO.LoadSingleTexture(SCRIPTSCREEN_ROOT_DIRECTORY + "container");
            containerTopBorderTexture     = IO.LoadSingleTexture(SCRIPTSCREEN_ROOT_DIRECTORY + "container_top_border");
            containerBottomBorderTexture  = IO.LoadSingleTexture(SCRIPTSCREEN_ROOT_DIRECTORY + "container_bottom_border");
            containerPosition             = new Vector2(CONTAINER_X, 0);
            containerTopBorderPosition    = new Vector2(CONTAINER_BORDER_X, 0);
            containerBottomBorderPosition = new Vector2(CONTAINER_BORDER_X, CONTAINER_BOTTOM_Y);

            scriptFont = IO.LoadFont("Data/Global/ScriptFont");
            String scriptContent = Bundle.Texts["script"];

            textLines = SharedFunctions.LayoutString(scriptContent, TEXT_WIDTH, scriptFont);
        }
Exemple #14
0
        static void Main(string[] args)
        {
            Draft draft = new Draft();

            var x = SharedFunctions.SetQuartil(10, 100);

            ///SharedFunctions.CheckRange(Convert.ToInt16(draft.Quartils), 50, draft.ReferenceMinValue, draft.ReferenceMaxValue);


            var quart = SharedFunctions.GetQuartil(50, x);

            Console.WriteLine(draft.Quartils.ToList()[1][0] + " " + draft.Quartils.ToList()[1][1]);
            Console.ReadKey();
        }
Exemple #15
0
        protected virtual void _(Events.RowSelected <FSSetup> e)
        {
            if (e.Row == null)
            {
                return;
            }

            FSSetup fsSetupRow = (FSSetup)e.Row;
            PXCache cache      = e.Cache;

            EquipmentSetupMaint.EnableDisable_Document(cache, fsSetupRow);
            SharedFunctions.ValidatePostToByFeatures <FSSetup.contractPostTo>(cache, fsSetupRow, fsSetupRow.ContractPostTo);
            FSPostTo.SetLineTypeList <FSSetup.contractPostTo>(e.Cache, e.Row);
        }
        Result Execute()
        {
            var deleteServerInfo = SharedFunctions.PromptUserYesOrNo(_state, Resources.Prompt_DeleteSelectedServerInfo);

            if (!deleteServerInfo)
            {
                return(Result.Ok());
            }

            _state.RemoteServerSelected = false;
            _state.Settings.RemoteServers.Remove(_state.SelectedServerInfo);

            return(_state.SaveSettingsToFile());
        }
        Result Execute()
        {
            SharedFunctions.DisplayLocalServerInfo(_state);
            Console.WriteLine($"{Environment.NewLine}############ SERVER REQUEST EVENT LOG ############{Environment.NewLine}");
            foreach (var serverEvent in _eventLog)
            {
                Console.WriteLine(serverEvent.ToString());
            }

            Console.WriteLine(Environment.NewLine + Resources.Prompt_ReturnToPreviousMenu);
            Console.ReadLine();

            return(Result.Ok());
        }
Exemple #18
0
        public ActionResult RegisterUser(UserProfileModel userProfileModel)
        {
            var serialization      = new Serialization();
            var userRegistration   = new UserRegistration();
            var HashCriteria       = new Hashtable();
            var HashCriteriaUser   = new Hashtable();
            var actualCriteria     = string.Empty;
            var actualCriteriaUser = string.Empty;

            if (ModelState.IsValid)
            {
                HashCriteria.Add("Email", userProfileModel.Email);
                actualCriteria = serialization.SerializeBinary((object)HashCriteria);
                var emailresult = userRegistration.CheckForUserName(actualCriteria);
                var emailexist  = Convert.ToBoolean(serialization.DeSerializeBinary(Convert.ToString(emailresult)));
                if (!emailexist)
                {
                    HashCriteriaUser.Add("Name", userProfileModel.Name);
                    HashCriteriaUser.Add("Email", userProfileModel.Email);
                    HashCriteriaUser.Add("Address", userProfileModel.Address);
                    HashCriteriaUser.Add("CompanyName", userProfileModel.CompanyName);
                    string password = CipherTool.Encrypt(Convert.ToString(userProfileModel.Password));
                    HashCriteriaUser.Add("Password", password);
                    HashCriteriaUser.Add("Gender", userProfileModel.Gender);
                    //Role ID = 4 if for register user
                    HashCriteriaUser.Add("RoleId", 4);
                    actualCriteriaUser = serialization.SerializeBinary((object)HashCriteriaUser);
                    var result = Convert.ToString(userRegistration.SaveUserProfile(actualCriteriaUser));
                    var userID = Convert.ToInt64(serialization.DeSerializeBinary(Convert.ToString(emailresult)));
                    Session["ProfileImage"] = null;
                    SharedFunctions sharedFunctions = new SharedFunctions();
                    sharedFunctions.SendEmail(userProfileModel.Email, Convert.ToString(EmailTemplates.Registration), "Pixere : Registered Successfully", userProfileModel);
                    //Auto Login the user after sign up
                    LoginModel loginModel = new LoginModel();
                    loginModel.UserName = userProfileModel.Email;
                    loginModel.Password = userProfileModel.Password;
                    var url = new
                    {
                        Url  = loginModel,
                        type = "Url"
                    };
                    return(Json(url, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    ModelState.AddModelError("", "Sorry, user with email id already exists");
                }
            }
            return(PartialView("_UserRegistration", userProfileModel));
        }
        protected virtual void ARTran_UOM_FieldUpdating(PXCache cache, PXFieldUpdatingEventArgs e)
        {
            if (e.Row == null || SharedFunctions.isFSSetupSet(Base) == false)
            {
                return;
            }

            ARTran arTranRow = (ARTran)e.Row;

            if (IsLineCreatedFromAppSO(Base, Base.Document.Current, arTranRow, typeof(ARTran.uOM).Name) == true)
            {
                throw new PXSetPropertyException(TX.Error.NO_UPDATE_ALLOWED_DOCLINE_LINKED_TO_APP_SO);
            }
        }
        protected override void FSServiceContract_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
        {
            base.FSServiceContract_RowSelected(cache, e);

            if (e.Row == null)
            {
                return;
            }

            var fsServiceContractRow = (FSServiceContract)e.Row;

            PXUIFieldAttribute.SetEnabled <FSServiceContract.scheduleGenType>(cache, e.Row, fsServiceContractRow.HasProcessedSchedule == false);
            SharedFunctions.ServiceContractDynamicDropdown(cache, fsServiceContractRow);
        }
        public static void InsertFSSODetFromOpportunity(ServiceOrderEntry graphServiceOrder,
                                                        PXCache cacheOpportunityProducts,
                                                        CRSetup crSetupRow,
                                                        CROpportunityProducts crOpportunityProductRow,
                                                        FSxCROpportunityProducts fsxCROpportunityProductsRow,
                                                        InventoryItem inventoryItemRow)
        {
            if (graphServiceOrder == null ||
                crOpportunityProductRow == null ||
                fsxCROpportunityProductsRow == null ||
                inventoryItemRow == null)
            {
                return;
            }

            if (inventoryItemRow.StkItem == true)
            {
                //Insert a new SODet line
                FSSODetPart fsSODetPartRow = new FSSODetPart();

                UpdateFSSODetFromOpportunity(graphServiceOrder.ServiceOrderDetParts.Cache,
                                             fsSODetPartRow,
                                             crOpportunityProductRow,
                                             fsxCROpportunityProductsRow,
                                             SharedFunctions.GetLineTypeFromInventoryItem(inventoryItemRow));

                SharedFunctions.CopyNotesAndFiles(cacheOpportunityProducts,
                                                  graphServiceOrder.ServiceOrderDetParts.Cache,
                                                  crOpportunityProductRow, graphServiceOrder.ServiceOrderDetParts.Current,
                                                  crSetupRow.CopyNotes,
                                                  crSetupRow.CopyFiles);
            }
            else
            {
                //Insert a new SODet line
                FSSODetService fsSODetServiceRow = new FSSODetService();

                UpdateFSSODetFromOpportunity(graphServiceOrder.ServiceOrderDetServices.Cache,
                                             fsSODetServiceRow,
                                             crOpportunityProductRow,
                                             fsxCROpportunityProductsRow,
                                             SharedFunctions.GetLineTypeFromInventoryItem(inventoryItemRow));

                SharedFunctions.CopyNotesAndFiles(cacheOpportunityProducts,
                                                  graphServiceOrder.ServiceOrderDetServices.Cache,
                                                  crOpportunityProductRow, graphServiceOrder.ServiceOrderDetServices.Current,
                                                  crSetupRow.CopyNotes,
                                                  crSetupRow.CopyFiles);
            }
        }
Exemple #22
0
        // TO IMPLEMENT CO:TFS 8095 – Provide Year default for 1102 when called from 11002.
        /// <summary>
        /// GET THE ROLL YEAR
        /// </summary>
        private int GetYear()
        {
            CommentsData getYearDataSet = new CommentsData();

            getYearDataSet = this.form1505Control.WorkItem.GetConfigDetails("TR_RollYear");
            int tempRollYear = -1;

            int.TryParse(getYearDataSet.GetCommentsConfigDetails.Rows[0][getYearDataSet.GetCommentsConfigDetails.ConfigurationValueColumn].ToString(), out tempRollYear);
            if (tempRollYear.Equals(0))
            {
                MessageBox.Show(SharedFunctions.GetResourceString("InvalidFieldYear"), "TerraScan T2", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(tempRollYear);
        }
Exemple #23
0
        public async Task PutObservationAsync_ReturnsBadRequest_OnIdNotEqualModelId()
        {
            //Arrange
            int birdId         = 1;
            int id             = 1;
            int modelId        = 2;
            var model          = GetTestObservationEditViewModel(modelId, birdId);
            var requestingUser = GetUser("Any");

            var mockUnitOfWork = new Mock <IUnitOfWork>();
            var mockBirdRepo = new Mock <IBirdRepository>();
            var mockUserManager = SharedFunctions.InitialiseMockUserManager();
            var mockObsRepo = new Mock <IObservationRepository>(); var mockObsPositionRepo = new Mock <IObservationPositionRepository>();
            var mockObsNotesRepo = new Mock <IObservationNoteRepository>();
            //mockObsRepo.Setup(o => o.GetObservationsAsync(It.IsAny<Expression<Func<Observation, bool>>>()))
            //           .ThrowsAsync(new InvalidOperationException());

            var controller = new ObservationController(
                _mapper
                , _systemClock
                , mockUnitOfWork.Object
                , mockBirdRepo.Object
                , _logger.Object
                , mockUserManager.Object
                , mockObsRepo.Object
                , mockObsPositionRepo.Object
                , mockObsNotesRepo.Object);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = SharedFunctions.GetTestClaimsPrincipal(requestingUser.UserName)
                }
            };

            // Act
            var result = await controller.PutObservationAsync(id, model);

            // Assert
            string expectedMessage = "An error occurred (id)";

            var objectResult = Assert.IsType <BadRequestObjectResult>(result);

            Assert.Equal(StatusCodes.Status400BadRequest, objectResult.StatusCode);
            var actual = Assert.IsType <string>(objectResult.Value);

            Assert.Equal(expectedMessage, actual);
        }
Exemple #24
0
        private void CommentButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                object[] optionalParameter;

                if (!this.ZoningSaveButton.Enabled)
                {
                    if (Convert.ToBoolean(TerraScanCommon.GetFormInfo(this.currentFormId).openPermission))
                    {
                        optionalParameter = new object[] { this.currentFormId, this.currentKeyId, 25003 };

                        Form commentForm = new Form();
                        commentForm     = this.form3040Control.WorkItem.Services.Get <TerraScan.Infrastructure.Interface.Services.IFormEngineService>().GetForm(9075, optionalParameter, this.form3040Control.WorkItem);
                        commentForm.Tag = this.currentFormId;

                        if (commentForm != null)
                        {
                            commentForm.ShowDialog();

                            // Code Need to be Modified to Set the Text For Attachmnent/Comment Button (Get the Count,Flag From Attachment/Comment Form Makin Public Propertis.
                            AdditionalOperationCountEntity additionalOperationCountEnt;
                            additionalOperationCountEnt = new AdditionalOperationCountEntity(-999, -999, false);
                            additionalOperationCountEnt.CommentCount = Convert.ToInt32(TerraScanCommon.GetValue(commentForm, "CommentCount"));
                            additionalOperationCountEnt.HighPriority = Convert.ToBoolean(TerraScanCommon.GetValue(commentForm, "HighPriorityFlag"));
                            this.SetText(additionalOperationCountEnt);
                        }
                    }
                    else
                    {
                        MessageBox.Show(SharedFunctions.GetResourceString("OpenPermission"), ConfigurationWrapper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show(SharedFunctions.GetResourceString("Unsaved changes exists"), ConfigurationWrapper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.ManageException(ex, ExceptionManager.ActionType.Display, this.ParentForm);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
Exemple #25
0
        /// <summary>
        /// Saves the copy account details.
        /// </summary>
        private void SaveCopyAccountDetails()
        {
            int rollyear = 0;

            ////Checking Rollyear is empty and roll year should not be zero
            if (string.IsNullOrEmpty(this.RollYearTextBox.Text.Trim()))
            {
                MessageBox.Show(SharedFunctions.GetResourceString("RequiredField"), ConfigurationWrapper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.RollYearTextBox.Focus();
                return;
            }

            if (this.RollYearTextBox.Text.Equals("0"))
            {
                MessageBox.Show(SharedFunctions.GetResourceString("RequiredField"), ConfigurationWrapper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.RollYearTextBox.Focus();
                return;
            }

            ////Checking Subfund combo should not be null
            if (string.IsNullOrEmpty(this.SubFundCombo.Text.ToString()))
            {
                MessageBox.Show(SharedFunctions.GetResourceString("RequiredField"), ConfigurationWrapper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.SubFundCombo.Focus();
                return;
            }

            ////Try Parse rollyear value
            if (!string.IsNullOrEmpty(this.RollYearTextBox.Text.Trim()))
            {
                int.TryParse(this.RollYearTextBox.Text.ToString(), out rollyear);
            }

            ////DB Call for save
            this.copyaccountDataset = this.form1504Control.WorkItem.F1504_SaveCopyAccountDetails(rollyear, this.SubFundCombo.Text.Trim(), this.DescriptionTextBox.Text.Trim(), this.FunctionTextBox.Text.Trim(), this.BarsTextBox.Text.Trim(), this.ObjectTextBox.Text.Trim(), this.LineTextBox.Text.Trim(), TerraScanCommon.UserId.ToString());

            ////Message will  be thrown based on the retrun value
            int keyValue = 0;

            if (this.copyaccountDataset.F1504_SaveCopyAccount.Rows.Count > 0)
            {
                if (!string.IsNullOrEmpty(this.copyaccountDataset.F1504_SaveCopyAccount.Rows[0][0].ToString()))
                {
                    int.TryParse(this.copyaccountDataset.F1504_SaveCopyAccount.Rows[0][0].ToString(), out keyValue);
                }

                this.ShowMessageBasedOnResultValue(keyValue, this.copyaccountDataset.F1504_SaveCopyAccount.Rows[0][1].ToString());
            }
        }
Exemple #26
0
        /// <summary>
        /// Checks the errors.
        /// </summary>
        /// <param name="formNo">The form no.</param>
        /// <returns>sliceValidationFields</returns>
        private SliceValidationFields CheckErrors(int formNo)
        {
            SliceValidationFields sliceValidationFields = new SliceValidationFields();

            sliceValidationFields.FormNo = formNo;

            if (string.IsNullOrEmpty(this.AgencyNameTextBox.Text.Trim()))
            {
                DialogResult result = MessageBox.Show(SharedFunctions.GetResourceString("15004RequiredFieldMissing"), "TerraScan T2 - Missing Required Fields", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (result == DialogResult.OK)
                {
                    this.AgencyNameTextBox.Focus();
                    sliceValidationFields.DisableNewMethod     = true;
                    sliceValidationFields.RequiredFieldMissing = false;
                    sliceValidationFields.ErrorMessage         = string.Empty;
                }
            }
            else if (!string.IsNullOrEmpty(this.EmailContactATextBox.Text.Trim()) && !this.CheckValidEmailID(this.EmailContactATextBox.Text.Trim()))
            {
                this.EmailContactATextBox.Focus();
                sliceValidationFields.RequiredFieldMissing = true;
                sliceValidationFields.ErrorMessage         = SharedFunctions.GetResourceString("EmailValidation");
            }
            else if (!string.IsNullOrEmpty(this.EmailContactBTextBox.Text.Trim()) && !this.CheckValidEmailID(this.EmailContactBTextBox.Text.Trim()))
            {
                this.EmailContactBTextBox.Focus();
                sliceValidationFields.RequiredFieldMissing = true;
                sliceValidationFields.ErrorMessage         = SharedFunctions.GetResourceString("EmailValidation");
            }
            else if (!this.CheckDuplicateAgency())
            {
                DialogResult result = MessageBox.Show(SharedFunctions.GetResourceString("DuplicateAgencyExists"), "TerraScan T2 - Duplicate Agency", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    sliceValidationFields.DisableNewMethod     = false;
                    sliceValidationFields.RequiredFieldMissing = false;
                    sliceValidationFields.ErrorMessage         = string.Empty;
                }
                else
                {
                    this.AgencyNameTextBox.Focus();
                    sliceValidationFields.DisableNewMethod     = true;
                    sliceValidationFields.RequiredFieldMissing = false;
                    sliceValidationFields.ErrorMessage         = string.Empty;
                }
            }

            return(sliceValidationFields);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        baseUrl = SharedFunctions.GetInstanceUrl(Request.Url.Scheme, Request.Url.Authority, Request.ApplicationPath.TrimEnd('/'));
        pageUrl = SharedFunctions.GetWebMethodPath(Request.Path);

        DateTime?startDateBridge;
        var      date = PXContext.GetBusinessDate();

        startDateBridge = (date != null) ? date : PXTimeZoneInfo.Now;

        // Date
        try
        {
            if (!String.IsNullOrEmpty(Request.QueryString["Date"]))
            {
                startDateBridge = Convert.ToDateTime(Request.QueryString["Date"]);
            }
        }
        catch (Exception)
        {
        }

        startDate = ((DateTime)startDateBridge).ToString("MM/dd/yyyy h:mm:ss tt", new CultureInfo("en-US"));

        // Filter By RefNbr
        RefNbr = Request.QueryString["RefNbr"];

        // External CustomerID
        CustomerID = Request.QueryString["CustomerID"];

        // External SMEquipmentID
        SMEquipmentID = Request.QueryString["SMEquipmentID"];

        // Load Appointment's ToolTip to be used in index.aspx
        StreamReader streamReader = new StreamReader(Server.MapPath("../../Shared/templates/TooltipAppointment.html"));

        toolTipTemplateAppointment = streamReader.ReadToEnd();
        streamReader.Close();

        // Load Service Order's ToolTip to be used in index.aspx
        streamReader = new StreamReader(Server.MapPath("../../Shared/templates/TooltipServiceOrder.html"));
        toolTipTemplateServiceOrder = streamReader.ReadToEnd();
        streamReader.Close();

        // Load Appointment's Body to be used in index.aspx
        streamReader            = new StreamReader(Server.MapPath("../../Shared/templates/EventBodyTemplate.html"));
        appointmentBodyTemplate = streamReader.ReadToEnd();
        streamReader.Close();
    }
        public async Task GetUserProfileAsync_ReturnsOkObjectResultWithUserProfileViewModel_WhenRequestedUserIsRequestingUser()
        {
            var options = this.CreateUniqueClassOptions <ApplicationDbContext>();

            using (var context = new ApplicationDbContext(options))
            {
                //You have to create the database
                context.Database.EnsureClean();
                context.Database.EnsureCreated();
                //context.SeedDatabaseFourBooks();

                context.Users.Add(SharedFunctions.CreateUser("testUser1"));
                context.Users.Add(SharedFunctions.CreateUser("testUser2"));

                context.SaveChanges();

                context.Users.Count().ShouldEqual(2);

                // Arrange
                var userManager = SharedFunctions.InitialiseUserManager(context);
                var controller  = new UserProfileController(_mapper, _logger.Object, userManager);

                string requestedUsername = "******";

                string requesterUsername = requestedUsername;

                controller.ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        User = SharedFunctions.GetTestClaimsPrincipal(requesterUsername)
                    }
                };

                // Act
                var result = await controller.GetUserProfileAsync(requestedUsername);

                // Assert
                var objectResult = result as ObjectResult;
                Assert.NotNull(objectResult);
                Assert.IsType <OkObjectResult>(result);
                Assert.True(objectResult is OkObjectResult);
                Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
                Assert.IsType <UserProfileViewModel>(objectResult.Value);

                var model = objectResult.Value as UserProfileViewModel;
                Assert.Equal(requestedUsername, model.UserName);
            }
        }
        public async Task PostUnfollowUserAsync_Returns_500_On_Internal_Error()
        {
            //var options = this.CreateUniqueClassOptions<ApplicationDbContext>();

            //using (var context = new ApplicationDbContext(options))
            //{
            //    //You have to create the database
            //    context.Database.EnsureClean();
            //    context.Database.EnsureCreated();
            //    //context.SeedDatabaseFourBooks();

            //    //context.ConservationStatuses.Add(new ConservationStatus { ConservationList = "Red", Description = "", CreationDate = DateTime.Now, LastUpdateDate = DateTime.Now });

            //    context.Users.Add(SharedFunctions.CreateUser("testUser1"));
            //    context.Users.Add(SharedFunctions.CreateUser("testUser2"));

            //    context.SaveChanges();

            //    context.Users.Count().ShouldEqual(2);

            //    // Arrange
            UserManager<ApplicationUser> userManager = null; //to cause internal error
            var mockRepo = new Mock<INetworkRepository>();
            mockRepo.Setup(repo => repo.Follow(It.IsAny<ApplicationUser>(), It.IsAny<ApplicationUser>()))
                .Verifiable();

            var mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.Setup(x => x.CompleteAsync())
                .ThrowsAsync(new InvalidOperationException());

            var controller = new NetworkController(_mapper, mockUnitOfWork.Object, _logger.Object, mockRepo.Object, userManager);

            string requestingUser = "******";

            string userToUnfollow = "testUser2";

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext() { User = SharedFunctions.GetTestClaimsPrincipal(requestingUser) }
            };

            // Act
            var result = await controller.PostUnfollowUserAsync(SharedFunctions.GetTestNetworkUserViewModel(userToUnfollow));

            // Assert
            var objectResult = Assert.IsType<ObjectResult>(result);
            Assert.Equal(StatusCodes.Status500InternalServerError, objectResult.StatusCode);
            Assert.Equal($"an unexpected error occurred", objectResult.Value);
        }
        public bool SendContactRequestEmail(long commentID, bool IsContactBroker)
        {
            var    serialization            = new Serialization();
            var    sharedFunctions          = new SharedFunctions();
            var    emailNotifications       = new EmailNotifications();
            var    outgoingEmailLogModel    = new OutgoingEmailLogModel();
            var    HashCriteriaNotification = new Hashtable();
            string actualCriteriaNotification;

            HashCriteriaNotification.Add("ID", commentID);
            actualCriteriaNotification = serialization.SerializeBinary((object)HashCriteriaNotification);
            var resultEmail = emailNotifications.GetNotificationDetails(actualCriteriaNotification);

            outgoingEmailLogModel = (OutgoingEmailLogModel)(serialization.DeSerializeBinary(Convert.ToString(resultEmail)));
            outgoingEmailLogModel.ExternalEmail = System.Configuration.ConfigurationManager.AppSettings["ExternalEmail"];
            //For schedule consulations end email to law
            var scheduleConsulationEmail = System.Configuration.ConfigurationManager.AppSettings["ScheduleConsulationEmail"];

            if (IsContactBroker)
            {
                if (outgoingEmailLogModel.DealName == null || outgoingEmailLogModel.DealName == "")
                {
                    sharedFunctions.SendEmail(outgoingEmailLogModel.EmailTo, Convert.ToString(EmailTemplates.ContactBrokerUnlikeListing), "Synoptek : " + outgoingEmailLogModel.MessageSender + " wants to contact you.", null, outgoingEmailLogModel);
                }
                else
                {
                    sharedFunctions.SendEmail(outgoingEmailLogModel.EmailTo, Convert.ToString(EmailTemplates.ContactBroker), "Synoptek : " + outgoingEmailLogModel.MessageSender + " wants to contact you for - " + outgoingEmailLogModel.DealName, null, outgoingEmailLogModel);
                }
            }
            else
            {
                //Added by Jyotibala P. for public user set Emailto is external address specified in web.config
                if (string.IsNullOrWhiteSpace(outgoingEmailLogModel.EmailTo))
                {
                    if (scheduleConsulationEmail != null && scheduleConsulationEmail != "")
                    {
                        outgoingEmailLogModel.EmailTo = scheduleConsulationEmail;
                    }
                    outgoingEmailLogModel.DealName     = "Portal";
                    outgoingEmailLogModel.ReceiverName = "Admin";
                    sharedFunctions.SendEmail(outgoingEmailLogModel.EmailTo, Convert.ToString(EmailTemplates.ScheduleConsultation), "Synoptek : User needs consultation", null, outgoingEmailLogModel);
                }
                else
                {
                    sharedFunctions.SendEmail(outgoingEmailLogModel.EmailTo, Convert.ToString(EmailTemplates.ScheduleConsultation), "Synoptek : " + outgoingEmailLogModel.MessageSender + " needs consultation for - " + outgoingEmailLogModel.DealName, null, outgoingEmailLogModel);
                }
            }
            return(true);
        }