private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            // Set the file name and get the output directory
            var fileName      = "ProductPlanImportTemplate" + ".xlsx";
            var baseDirectory = @"C:\" + Constants.ApplicationName + @"\templates\";
            var filePath      = Path.Combine(baseDirectory, fileName);

            try
            {
                if (!Directory.Exists(baseDirectory))
                {
                    Directory.CreateDirectory(baseDirectory);
                }

                // Create the file using the FileInfo object
                //var file = new FileInfo(filePath);
                var file = CommonHelpers.GetUniqueFile(filePath);

                using (var applicationDbContext = new ApplicationDbContext())
                {
                    using (var package = new ExcelPackage(file))
                    {
                        // add a new worksheet to the empty workbook
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Plans");

                        var properties = new string[] { "Machine", "Employee", "Product", "Expected Quantity" };
                        for (var i = 0; i < properties.Length; i++)
                        {
                            worksheet.Cells[1, i + 1].Value = properties[i];
                            worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
                            worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue);
                            worksheet.Cells[1, i + 1].Style.Font.Bold = true;
                        }
                        worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

                        // --------- DataValidations goes here -------------- //
                        //https://social.msdn.microsoft.com/Forums/vstudio/en-US/cdaf187c-df21-4cd9-9c05-7e94abb03f04/create-excel-sheet-with-drop-down-list-using-epplus?forum=exceldev

                        #region Machine Validation

                        var lstMachines = applicationDbContext.Machines
                                          .Where(x => !x.IsDeleted)
                                          .Select(x => new MachineViewModel
                        {
                            Id   = x.Id,
                            Name = x.Name,
                            Code = x.Code,
                        })
                                          .OrderBy(x => x.Name)
                                          .ToList();

                        if (lstMachines.Count > 0)
                        {
                            // int FromRow, int FromCol, int ToRow, int ToCol
                            var ddMachines = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 1, 10000, 1].Address);
                            ddMachines.AllowBlank = false; //Set to true if blank value is accepted

                            foreach (var machine in lstMachines)
                            {
                                ddMachines.Formula.Values.Add(machine.Name + " - " + machine.Code);
                            }
                        }

                        // Or load from another sheet
                        //package.Workbook.Worksheets.Add("OtherSheet");
                        //list1.Formula.ExcelFormula = "OtherSheet!A1:A4";
                        #endregion

                        #region Employee Validation

                        var lstEmployees = applicationDbContext.Employees
                                           .Where(x => !x.IsDeleted)
                                           .Select(x => new EmployeeViewModel
                        {
                            Id          = x.Id,
                            Code        = x.Code,
                            DisplayName = x.DisplayName,
                            FirstName   = x.FirstName,
                            MiddleName  = x.MiddleName,
                            LastName    = x.LastName,
                        })
                                           .OrderBy(x => x.DisplayName)
                                           .ToList();

                        if (lstEmployees.Count > 0)
                        {
                            // int FromRow, int FromCol, int ToRow, int ToCol
                            var ddEmployees = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 2, 10000, 2].Address);
                            ddEmployees.AllowBlank = true; //Set to true if blank value is accepted

                            foreach (var employee in lstEmployees)
                            {
                                ddEmployees.Formula.Values.Add(employee.DisplayName + " - " + employee.Code);
                            }
                        }

                        #endregion

                        #region Product Validation

                        var lstProducts = applicationDbContext.Products
                                          .Where(x => !x.IsDeleted)
                                          .Select(x => new ProductViewModel
                        {
                            Id   = x.Id,
                            Name = x.Name,
                            Code = x.Code,
                        })
                                          .OrderBy(x => x.Name)
                                          .ToList();

                        if (lstProducts.Count > 0)
                        {
                            // int FromRow, int FromCol, int ToRow, int ToCol
                            var ddProducts = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 3, 10000, 3].Address);
                            ddProducts.AllowBlank = false; //Set to true if blank value is accepted

                            foreach (var product in lstProducts)
                            {
                                ddProducts.Formula.Values.Add(product.Name + " - " + product.Code);
                            }
                        }

                        #endregion

                        #region Expected Quantity Validation
                        //var ivExpectedQuantity = worksheet.DataValidations.AddIntegerValidation(worksheet.Cells[2, 4, 10000, 4].Address);
                        //ivExpectedQuantity.AllowBlank = true;
                        #endregion

                        // end
                        package.Save();
                    }
                }

                MessageBox.Show("Successfully download template at " + baseDirectory, Constants.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                var msg = ex.GetAllExceptionInfo();
                log.Error(msg, ex);
                MessageBox.Show("Cannot download template file", Constants.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #2
0
        /// <summary>
        /// Excecutes command.
        /// </summary>
        /// <param name="args"></param>
        protected override void _Execute(params object[] args)
        {
            try
            {
                OptimizeAndEditPage schedulePage = (OptimizeAndEditPage)App.Current.MainWindow.GetPage(PagePaths.SchedulePagePath);
                Schedule            schedule     = schedulePage.CurrentSchedule;

                // Get selected orders.
                Collection <Order> selectedOrders = _GetOrdersWhichCanBeMovedFromSelection(schedulePage.SelectedItems);
                selectedOrders = RoutingCmdHelpers.GetOrdersIncludingPairs(schedule, selectedOrders) as Collection <Order>;
                bool keepViolOrdrsUnassigned = false;

                Debug.Assert(args[0] != null);
                ICollection <Route> targetRoutes = args[0] as ICollection <Route>;
                Debug.Assert(targetRoutes != null);

                string routeName = args[1] as string;

                if (_CheckRoutingParams(schedule, targetRoutes, selectedOrders))
                {
                    SolveOptions options = new SolveOptions();
                    options.GenerateDirections            = App.Current.MapDisplay.TrueRoute;
                    options.FailOnInvalidOrderGeoLocation = false;

                    _SetOperationStartedStatus((string)App.Current.FindResource(ASSIGN_ORDERS), (DateTime)schedule.PlannedDate);

                    // Start "Assign to best other route" operation.
                    OperationsIds.Add(App.Current.Solver.AssignOrdersAsync(schedule, selectedOrders,
                                                                           targetRoutes, null,
                                                                           keepViolOrdrsUnassigned,
                                                                           options));
                    // Set solve started message
                    string infoMessage = RoutingMessagesHelper.GetAssignOperationStartedMessage(selectedOrders, routeName);

                    if (!string.IsNullOrEmpty(infoMessage))
                    {
                        App.Current.Messenger.AddInfo(infoMessage);
                    }
                }
            }
            catch (RouteException e)
            {
                if (e.InvalidObjects != null) // If exception throw because any Routes or Orders are invalid
                {
                    _ShowSolveValidationResult(e.InvalidObjects);
                }
                else
                {
                    _ShowErrorMsg(RoutingCmdHelpers.FormatRoutingExceptionMsg(e));
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                if ((e is LicenseException) || (e is AuthenticationException) || (e is CommunicationException))
                {
                    CommonHelpers.AddRoutingErrorMessage(e);
                }
                else
                {
                    throw;
                }
            }
        }
Example #3
0
        public IHttpActionResult PostQuestionnaireQuestions([FromBody] QuestionnaireQuestionsRequest request)
        {
            QuestionaireQuestionResponse response = new QuestionaireQuestionResponse();

            try
            {
                if (CommonHelpers.ValidateRequest(request.UserToken))
                {
                    List <QuestionDetail> QuestionAnswerList = new List <QuestionDetail>();
                    DBAgent = new DataAccessProvider(DataAccessProvider.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"], ConfigurationManager.AppSettings["DBUserName"], ConfigurationManager.AppSettings["DBPassword"]);
                    DBAgent.ClearParams();
                    DBAgent.AddParameter("@ParamQuestionnaireID", request.QuestionnaireID);
                    DBAgent.AddParameter("@ParamPQID", request.PQID);
                    string data = DBAgent.ExecuteStoredProcedure("dbo.spGetAllQuestionAnswersForQuestionnaire");
                    if (data.Length > 0)
                    {
                        DataSet ds = CommonHelpers.GetDataSetFromXml(data);
                        if (ds.Tables.Count > 0)
                        {
                            int            CurrentQuestionID = 0;
                            QuestionDetail qd = null;

                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                if (CurrentQuestionID != int.Parse(dr["QuestionID"].ToString()))
                                {
                                    if (qd != null)
                                    {
                                        //Save Previous Question
                                        QuestionAnswerList.Add(qd);
                                    }

                                    //New Question
                                    qd = new QuestionDetail();
                                    qd.QuestionText   = dr["QuestionText"].ToString();
                                    qd.QuestionID     = dr["QuestionID"].ToString();
                                    CurrentQuestionID = int.Parse(dr["QuestionID"].ToString());
                                }

                                AnswerDetail ans = new AnswerDetail();
                                ans.AnswerID       = dr["AnswerID"].ToString();
                                ans.AnswerText     = dr["AnswerText"].ToString();
                                ans.SelectedAnswer = bool.Parse(dr["SelectedAnswer"].ToString());
                                ans.AnswerPoints   = int.Parse(dr["AnswerPoints"].ToString());
                                qd.QuestionAnswers.Add(ans);
                            }

                            QuestionAnswerList.Add(qd); //Adding last Question

                            response.QuestionAnswerList = QuestionAnswerList;
                        }
                    }
                    else
                    {
                        response.ErrorMessage = "No Data";
                    }
                }
                else
                {
                    response.ErrorMessage = "Invalid Request";

                    DBAgent = new DataAccessProvider(DataAccessProvider.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"], ConfigurationManager.AppSettings["DBUserName"], ConfigurationManager.AppSettings["DBPassword"]);
                    DBAgent.ClearParams();
                    DBAgent.AddParameter("@ParamRefID", request.PQID);
                    DBAgent.AddParameter("@ParamRefType", "PQID");
                    DBAgent.AddParameter("@ParamAction", "IR");
                    DBAgent.AddParameter("@ParamComment", "Invalid Request from Mobile App - QuestionnaireQuestionsController - " + request.UserToken);
                    DBAgent.ExecuteNonQuery("dbo.spAddUserAction");
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
                CommonHelpers.writeLogToFile("API: PostQuestionnaireQuestions - QuestionnaireQuestionsController.cs", ex.Message + Environment.NewLine + ex.StackTrace);
            }


            return(Ok(response));
        }
Example #4
0
        /// <returns>'True' if any information was sent, 'false' otherwise.</returns>
        private bool _DeployRoutes(
            IEnumerable <TrackingDevice> devices,
            IEnumerable <Route> routes,
            DateTime plannedDate)
        {
            Debug.Assert(devices != null);
            Debug.Assert(routes != null);

            plannedDate = plannedDate.Date;

            var newStops     = new List <DM.Stop>();
            var updatedStops = new List <DM.Stop>();

            var deployedRoutes = new List <Route>();
            var deployedStops  = new List <Stop>();

            // Get all non deleted stops for current routes for planned date.
            var existingStops =
                _trackingService.GetNotDeletedStops(devices.Select(x => x.ServerId), plannedDate);

            foreach (var route in routes)
            {
                // check if route has associated device
                MobileDevice device = TrackingHelper.GetDeviceByRoute(route);
                if (device == null)
                {
                    continue;
                }

                // check if device belongs to devices with tracking id
                TrackingDevice td = _FindDevice(devices, device);
                if (td == null)
                {
                    continue;
                }

                // Get all stops for current route.
                var currentDateStops = existingStops.Where(stop => stop.DeviceID == td.ServerId);

                // Get id's of non deleted stops.
                var stopsToDelete = currentDateStops.
                                    Where(stop => stop.Deleted == DM.DeletionStatus.NotDeleted).
                                    ToDictionary(stop => stop.ObjectID);

                // Get version number for sended stops.
                var version = _GetNewVersion(currentDateStops);

                // Prepare stops to be deployed.
                var sortedStops   = CommonHelpers.GetSortedStops(route);
                var trackingStops = _CreateTrackingStops(
                    td.ServerId,
                    version,
                    plannedDate,
                    sortedStops);
                trackingStops = trackingStops.ToList();

                // Add stop to either new stops or updated stops collection.
                foreach (var item in trackingStops.ToIndexed())
                {
                    var trackingStop  = item.Value;
                    var existingStop  = stopsToDelete.Remove(trackingStop.ObjectID);
                    var stopsToDeploy = existingStop ? updatedStops : newStops;
                    stopsToDeploy.Add(trackingStop);

                    if (!existingStop)
                    {
                        deployedStops.Add(sortedStops[item.Index]);
                    }
                }

                // Deletes from tracking service stops which were deleted locally.
                // When stop is moved to other route we treat it as a deletion from an old route
                // and adding to the new one.
                foreach (var stopToDelete in stopsToDelete.Values)
                {
                    stopToDelete.Deleted = DM.DeletionStatus.Deleted;
                    updatedStops.Add(stopToDelete);
                }

                // We need a list of both new and updated stops in order to apply common properties
                // like arrival delays.
                var allStops = new List <DM.Stop>(trackingStops);

                TrackingHelper.ApplyArrivalDelayToStops(
                    _solver.SolverSettings.ArriveDepartDelay, allStops);

                deployedRoutes.Add(route);
            }

            // We must sent route settings, barriers only if we have stops to update.
            if (newStops.Count > 0 || updatedStops.Count > 0)
            {
                // Update route settings.
                var routeSettings = _SerializeRouteSettings();
                _trackingService.UpdateRouteSettings(plannedDate, routeSettings);

                _UpdateRouteTable(routes, devices, plannedDate);

                // Update barriers for planned date.
                _UpdateBarriers(plannedDate);

                _trackingService.UpdateStops(newStops, updatedStops);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #5
0
 private static string GetReferringService(HttpActionExecutedContext httpActionExecutedContext)
 {
     return(CommonHelpers.GetReferringService(httpActionExecutedContext.Request.Headers));
 }
Example #6
0
        public void IsPalindromeListTestCase3()
        {
            var list = CommonHelpers.GetLinkedListFromArray(new[] { 1, 1, 2, 1 });

            PalindromeLinkedList.IsPalindrome(list).Should().BeFalse();
        }
Example #7
0
        LDAPService()
        {
            var connectionString = CommonHelpers.GetCnn(CommonHelpers.CnnStringNameAD).ConnectionString;

            this.DomainsUrl = Fwk.Security.ActiveDirectory.DirectoryServicesBase.DomainsUrl_Get_FromSp_all(connectionString);
        }
        public IHttpActionResult PostPatientVerificaiton([FromBody] PatientVerifiactionRequest request)
        {
            PatientVerificationResponse response = new PatientVerificationResponse();

            try
            {
                if (CommonHelpers.ValidateRequest(request.UserToken))
                {
                    if (!request.LogVerificaiton)
                    {
                        DBAgent = new DataAccessProvider(DataAccessProvider.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"], ConfigurationManager.AppSettings["DBUserName"], ConfigurationManager.AppSettings["DBPassword"]);
                        DBAgent.ClearParams();
                        DBAgent.AddParameter("@ParamPatientID", request.PatientID);
                        string data = DBAgent.ExecuteStoredProcedure("dbo.spGetPatientDetails");
                        if (data.Length > 0)
                        {
                            DataSet ds = CommonHelpers.GetDataSetFromXml(data);
                            if (ds.Tables.Count > 0)
                            {
                                DataRow dr = ds.Tables[0].Rows[0];
                                response.PatientFirstName = dr["PatientFirstName"].ToString();
                                response.PatientLastName  = dr["PatientLastName"].ToString();
                                response.DOB           = dr["FormattedDOB"].ToString();
                                response.MaskedName    = dr["MaskedName"].ToString();
                                response.PhysicianName = dr["PhysicianName"].ToString();
                                response.AccountNumber = dr["PatientAccountNumber"].ToString();
                            }
                            else
                            {
                                response.ErrorMessage = "No Data";
                            }
                        }
                        else
                        {
                            response.ErrorMessage = "No Data";
                        }
                    }
                    else
                    {
                        DBAgent = new DataAccessProvider(DataAccessProvider.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"], ConfigurationManager.AppSettings["DBUserName"], ConfigurationManager.AppSettings["DBPassword"]);
                        DBAgent.ClearParams();
                        DBAgent.AddParameter("@ParamRefID", request.PatientID);
                        DBAgent.AddParameter("@ParamRefType", "PatientInfo");
                        DBAgent.AddParameter("@ParamAction", "VR");
                        DBAgent.AddParameter("@ParamComment", "Patient Verificaiton from Mobile App");
                        DBAgent.ExecuteNonQuery("dbo.spAddUserAction");
                    }
                }
                else
                {
                    response.ErrorMessage = "Invalid Request";

                    DBAgent = new DataAccessProvider(DataAccessProvider.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"], ConfigurationManager.AppSettings["DBUserName"], ConfigurationManager.AppSettings["DBPassword"]);
                    DBAgent.ClearParams();
                    DBAgent.AddParameter("@ParamRefID", request.PatientID);
                    DBAgent.AddParameter("@ParamRefType", "PatientID");
                    DBAgent.AddParameter("@ParamAction", "IR");
                    DBAgent.AddParameter("@ParamComment", "Invalid Request from Mobile App - PatientVerification - " + request.UserToken);
                    DBAgent.ExecuteNonQuery("dbo.spAddUserAction");
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
                CommonHelpers.writeLogToFile("API: PostPatientVerificaiton - PatientVerificaitonController.cs", ex.Message + Environment.NewLine + ex.StackTrace);
            }
            return(Ok(response));
        }
Example #9
0
 public void SetValue(string key, string value)
 {
     fileContent = CommonHelpers.BlobSetValue(fileContent, key, value);
     Save();
 }
Example #10
0
        //保存进Excel文件
        private void btnNewExcel_Click(object sender, RoutedEventArgs e)
        {
            string filepath;

            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.FileName = string.Format("r{0}", CommonHelpers.GetTimeStamp(DateTime.Now));
            saveFileDialog.Filter   = "xls files(*.xls)|*.xls|xlsx files(*.xlsx)|*.xlsx";
            System.Windows.Forms.DialogResult result = saveFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                filepath = saveFileDialog.FileName;
                //读取文件,准备数据,仅适用于格口数据导出的txt文件
                string[,] data = new string[203, 32];
                data[0, 0]     = "";
                data[1, 0]     = "no";
                for (int i = 1; i < 202; i++)
                {
                    data[i + 1, 0] = i.ToString();
                }
                using (StreamReader sr = new StreamReader(txtFilePath.Text.Trim()))
                {
                    int col = 1;
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (line.Contains("count"))
                        {
                            continue;
                        }
                        else
                        {
                            string[] s = line.Split('\t');
                            if (s[1] == "")
                            {
                                data[0, col] = s[0];
                            }
                            else if (s[1] == "no")
                            {
                                data[1, col] = s[0];
                            }
                            else
                            {
                                int portcode;
                                try
                                {
                                    portcode = int.Parse(s[1]);
                                    data[portcode + 1, col] = s[0];
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }
                            if (line.Contains("no"))
                            {
                                col++;
                            }
                        }
                    }
                }
                Write2Excel(filepath, data);
                MessageBox.Show("数据生成成功!");
            }
            else
            {
                return;
            }
        }
Example #11
0
        protected override void _Execute(params object[] args)
        {
            AsyncOperationInfo info = null;

            // Check whether operation can be started.
            if (!_CanBuildRoutesBeStarted(out info)) // If BuildRoutes operation cannot be started - show warning and return.
            {
                Debug.Assert(info != null);          // Must be defined in _CanBuildRoutesBeStarted method.
                App.Current.MainWindow.MessageWindow.AddWarning(
                    string.Format((string)App.Current.FindResource(ALREADY_BUILDING_ROUTES_MESSAGE_RESOURCE), info.Schedule.PlannedDate.Value.ToShortDateString()));
                return;
            }

            try
            {
                Schedule schedule = _optimizeAndEditPage.CurrentSchedule;

                var inputParams = _GetBuildRoutesParameters(schedule);
                var routes      = inputParams.TargetRoutes;
                var orders      = inputParams.OrdersToAssign;

                if (_CheckRoutingParams(schedule, routes, orders))
                {
                    SolveOptions options = new SolveOptions();
                    options.GenerateDirections            = App.Current.MapDisplay.TrueRoute;
                    options.FailOnInvalidOrderGeoLocation = false;

                    _SetOperationStartedStatus((string)App.Current.FindResource(BUILD_ROUTES_STRING), (DateTime)schedule.PlannedDate);

                    OperationsIds.Add(App.Current.Solver.BuildRoutesAsync(
                                          schedule,
                                          options,
                                          inputParams));

                    // set solve started message
                    string infoMessage = _FormatSuccesSolveStartedMsg(schedule, inputParams);
                    if (!string.IsNullOrEmpty(infoMessage))
                    {
                        App.Current.Messenger.AddInfo(infoMessage);
                    }
                }
            }
            catch (RouteException e)
            {
                if (e.InvalidObjects != null) // if exception throw because any Routes or Orders are invalid
                {
                    _ShowSolveValidationResult(e.InvalidObjects);
                }
                else
                {
                    _ShowErrorMsg(RoutingCmdHelpers.FormatRoutingExceptionMsg(e));
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                if ((e is LicenseException) || (e is AuthenticationException) || (e is CommunicationException))
                {
                    CommonHelpers.AddRoutingErrorMessage(e);
                }
                else
                {
                    throw;
                }
            }
        }
Example #12
0
 public void WhenEnvNotNullAndExists_ShouldThrowInvalidCastException()
 {
     //Act
     Should.Throw <InvalidCastException>(() => CommonHelpers.GetValueFromEnv <int>(nameof(WhenEnvNotNullAndExists_ShouldThrowInvalidCastException), false));
 }
Example #13
0
 public void WhenEnvNameNull_ShouldThrowException()
 {
     Should.Throw <ArgumentNullException>(() => CommonHelpers.GetEnvironmentVariable(""));
 }
Example #14
0
 public void WhenEnvNotExists_ShouldThrowException()
 {
     Should.Throw <ArgumentNullException>(() => CommonHelpers.GetEnvironmentVariable("TESTE"));
 }
Example #15
0
        public static void Main(string[] args)
        {
            // TODO: REMOVE AFTER RESHARPER FIX BUG https://youtrack.jetbrains.com/issue/RSRP-466882
            if (args.Contains("--disablePipedInput"))
            {
                DisablePipedInput   = true;
                IsSilentModeEnabled = false;
            }

            // TODO: REMOVE AFTER RESHARPER FIX BUG https://youtrack.jetbrains.com/issue/RSRP-466882

            Logger = new QpUpdateLoggingWrapper();
            Logger.Info($"QuantumArt DbUpdate for QP8 version 6.0. Version: {CommonHelpers.GetAssemblyVersion()}. Args: {args.ToJsonLog()}");

            try
            {
                ConsoleHelpers.SetupConsole();
                ConsoleHelpers.PrintHelloMessage();
                ConsoleHelpers.ReadFromStandardInput();

                var selectedMode = ConsoleHelpers.GetUtilityMode(args);
                Logger.SetLogLevel(VerboseLevel);

                var argsParser = ConsoleArgsProcessorFactory.Create(selectedMode);
                var settings   = argsParser.ParseConsoleArguments(args);
                Logger.Debug($"Parsed settings: {settings.ToJsonLog()}");

                var factory = new WebApplicationFactory <Startup>();
                factory.CreateDefaultClient();
                var dataProcessor = DataProcessorFactory.Create(
                    settings, factory.Server.Host.Services, factory.CreateClient()
                    );

                if (Console.IsInputRedirected && !DisablePipedInput)
                {
                    dataProcessor.Process(StandardInputData);
                }
                else
                {
                    dataProcessor.Process();
                }

                Logger.Debug("Processing successfuly finished..");
                ConsoleHelpers.ExitProgram(ExitCode.Success);
            }
            catch (OptionException ex)
            {
                Logger.Error($"Some params to qpupdate utility was wrong. Option name: \"{ex.OptionName}\"", ex);
                ConsoleHelpers.ExitProgram(ExitCode.Error);
            }
            catch (XmlDbUpdateLoggingException ex)
            {
                Logger.Warn("Some problems were countered while updating database", ex);
                ConsoleHelpers.ExitProgram(ExitCode.DbUpdateError);
            }
            catch (XmlDbUpdateReplayActionException ex)
            {
                Logger.Error("There was a problem while replaying xml db update process", ex);
                ConsoleHelpers.ExitProgram(ExitCode.Error);
            }
            catch (Exception ex)
            {
                Logger.Fatal("There was an unexpected exception in xml db updater", ex);
                ConsoleHelpers.ExitProgram(ExitCode.Error);
            }
        }
Example #16
0
 public string GetValue(string key)
 {
     return(CommonHelpers.BlobGetValue(fileContent, key));
 }
Example #17
0
        private async void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(nameEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Please enter a name", "Ok");
                    return;
                }
                else if (string.IsNullOrEmpty(lastNameEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Please enter a last name", "Ok");
                    return;
                }
                else if (string.IsNullOrEmpty(idNumberEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Please enter a id number", "Ok");
                    return;
                }
                else if (string.IsNullOrEmpty(passwordEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Please enter a password", "Ok");
                    return;
                }
                else if (string.IsNullOrEmpty(emailEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Please enter a email", "Ok");
                    return;
                }
                else if (!Validators.ValidateStringIsNumber(idNumberEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Id number should be a number", "Ok");
                    return;
                }
                else if (!Validators.ValidateStringFourToEightCharacters(passwordEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Password should be between 4 and 8 characteres", "Ok");
                    return;
                }
                else if (!Validators.ValidateStringEmail(emailEditText.Text))
                {
                    DiaglogService.ShowMessage(this, "Warining", "Please enter a valid email", "Ok");
                    return;
                }
                var user = new UserForAddDto()
                {
                    Name     = nameEditText.Text,
                    LastName = lastNameEditText.Text,
                    IdTypeID = idTypeSelected.Id,
                    IdNumber = idNumberEditText.Text,
                    Password = passwordEditText.Text,
                    Email    = emailEditText.Text
                };
                DiaglogService.ShowLoading(this);
                var response = await apiService.PostAsync <UserForAddDto>(Settings.ApiUrl, Settings.Prefix, "/Users/AddUser", user, Settings.TokenType, Settings.Token);

                DiaglogService.StopLoading();
                if (response.IsSuccess)
                {
                    Toast.MakeText(this, "User added correctly", ToastLength.Long).Show();
                    SetResult(Result.Ok);
                    Finish();
                }
                else
                {
                    Toast.MakeText(this, "Fail to add user - " + response.Message, ToastLength.Long).Show();
                }
            }
            catch (Exception ex)
            {
                DiaglogService.StopLoading();
                Toast.MakeText(this, CommonHelpers.GetErrorMessage("Fail to add user - ", ex), ToastLength.Long).Show();
            }
        }
        static void Main(string[] args)
        {
            using (var conn = new SqlConnection(CommonHelpers.GetConnectionString()))
            {
                conn.Open();

                #region Deleted everything
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                        DELETE FROM [dbo].[UserInRoles] WHERE 1 = 1;
                        DELETE FROM [dbo].[Rights] WHERE 1 = 1;
                        DELETE FROM [dbo].[Roles] WHERE 1 = 1;
                        DELETE FROM [dbo].[Users] WHERE 1 = 1;
                        DELETE FROM [dbo].[Functions] WHERE 1 = 1;
                        ";
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Everything deleted");
                }
                #endregion

                #region Create roles
                var roleNames = new string[] { "Admin", "User" };
                var roles     = new List <Role>();
                foreach (var name in roleNames)
                {
                    var role = new Role()
                    {
                        RoleName = name
                    };

                    #region Create functions and rights
                    for (var i = 0; i < 10; i++)
                    {
                        role.Rights.Add(new Right()
                        {
                            Function = new Function()
                            {
                                FunctionName = name + "Function" + (i + 1)
                            }
                        });
                    }
                    #endregion

                    Console.WriteLine("Creating role \"" + name + "\"");

                    var repo = role.CreateRepository(conn);
                    repo.InsertOrUpdate(role);

                    roles.Add(role);
                }
                #endregion

                #region Create users
                for (var i = 0; i < 90; i++)
                {
                    var user = new User()
                    {
                        UserName  = "******" + (i + 1),
                        Email     = "user_" + (i + 1) + "@email.com",
                        FirstName = (i + 1) + " first name",
                        LastName  = (i + 1) + " last name",
                        BirthDate = DateTime.Now
                    };
                    user.Roles.Add(roles[i % roles.Count]);

                    Console.WriteLine("Creating user \"" + user.UserName + "\"");
                    var repo = user.CreateRepository(conn);
                    repo.InsertOrUpdate(user);
                }
                #endregion
            }

            Console.ReadKey();
        }
Example #19
0
        /// <summary>
        /// Logins the process.
        /// </summary>
        public void LoginProcess()
        {
            //MobileNumber = "9770789763";
            //Password = "******";

            if (IsValid())
            {
                List <LoginModel> loginModel = null;
                Task.Factory.StartNew(() =>
                {
                    ISyncServices syncService = new SyncServices();
                    loginModel = syncService.ValidateUser(MobileNumber, Password);
                }).ContinueWith((obj) =>
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (loginModel != null && loginModel.Count > 0)
                        {
                            //saving to local
                            DependencyService.Get <IPersistStoreServices>().SaveUserData(loginModel[0]);
                            CommonHelpers.UserId = loginModel[0].mobile;
                            App.Current.MainPage = new NavigationPage(new Views.MainPage());
                        }

                        else
                        {
                            CommonHelpers.ShowAlert(AppResources.ResourceManager.GetString("validationError"));
                        }
                    });
                });
            }
            else
            {
                CommonHelpers.ShowAlert(AppResources.ResourceManager.GetString("validationError"));
            }


            /// <summary>
            /// checks for
            /// Is the credentials are valid.
            /// </summary>
            /// <returns><c>true</c>, if valid was ised, <c>false</c> otherwise.</returns>
            bool IsValid()
            {
                bool isValid = true;

                if (string.IsNullOrEmpty(MobileNumber))
                {
                    isValid = false;
                }
                else
                {
                    if (MobileNumber.Length != 10)
                    {
                        CommonHelpers.ShowAlert(AppResources.ResourceManager.GetString("invalidMobileNoError"));
                        isValid = false;
                    }
                    else
                    {
                        isValid = true;
                    }
                }
                if (string.IsNullOrEmpty(Password))
                {
                    isValid = false;
                }

                return(isValid);
            }
        }
 public ZonePolygonSymbol()
 {
     ControlTemplate = CommonHelpers.LoadTemplateFromResource(
         "ESRI.ArcLogistics.App.Symbols.ZonePolygonSymbol.xaml");
 }
        protected override void _Execute(params object[] args)
        {
            try
            {
                ICollection <Route> routes = _GetRoutesFromSelection(_schedulePage.SelectedItems);

                // get unlocked routes from selected routes
                // and all orders assigned to converting routes
                List <Order> orders = new List <Order>();
                foreach (Route route in routes)
                {
                    if (!route.IsLocked)
                    {
                        // get assigned orders
                        List <Order> routeOrders = new List <Order>();
                        foreach (Stop stop in route.Stops)
                        {
                            if (stop.StopType == StopType.Order)
                            {
                                routeOrders.Add(stop.AssociatedObject as Order);
                            }
                        }
                        orders.AddRange(routeOrders);
                    }
                }

                // get current schedule
                Schedule schedule = _schedulePage.CurrentSchedule;

                if (_CheckRoutingParams(schedule, routes, orders))
                {
                    SolveOptions options = new SolveOptions();
                    options.GenerateDirections            = App.Current.MapDisplay.TrueRoute;
                    options.FailOnInvalidOrderGeoLocation = false;

                    _SetOperationStartedStatus((string)App.Current.FindResource("SequenceRoutes"), (DateTime)schedule.PlannedDate);

                    OperationsIds.Add(App.Current.Solver.SequenceRoutesAsync(schedule, routes, options));

                    // set solve started message
                    string infoMessage = _FormatSuccesSolveStartedMsg(schedule, routes.Count);
                    if (!string.IsNullOrEmpty(infoMessage))
                    {
                        App.Current.Messenger.AddInfo(infoMessage);
                    }
                }
            }
            catch (RouteException e)
            {
                if (e.InvalidObjects != null) // if exception throw because any Routes or Orders are invalid
                {
                    _ShowSolveValidationResult(e.InvalidObjects);
                }
                else
                {
                    _ShowErrorMsg(RoutingCmdHelpers.FormatRoutingExceptionMsg(e));
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                if ((e is LicenseException) || (e is AuthenticationException) || (e is CommunicationException))
                {
                    CommonHelpers.AddRoutingErrorMessage(e);
                }
                else
                {
                    throw;
                }
            }
        }
Example #22
0
 public string Get()
 {
     return(CommonHelpers.GetVersionNumber());
 }
Example #23
0
 public override int GetHashCode()
 {
     return(CommonHelpers.CalcHashCode(Key, Value));
 }
 protected string IncorrectUseOfApi()
 {
     return(CommonHelpers.IncorrectUsageOfApi());
 }
Example #25
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            try
            {
                if (!StatsdClientWrapper.IsEnabled)
                {
                    return;
                }

                var stopwatch = actionExecutedContext.Request.Properties[StopwatchKey] as Stopwatch;

                if (stopwatch == null)
                {
                    return;
                }

                var elapsedMilliseconds = (int)stopwatch.ElapsedMilliseconds;
                stopwatch.Reset();

                var actionName = string.IsNullOrEmpty(SuppliedActionName)
                                    ? actionExecutedContext.ActionContext.ActionDescriptor.ActionName
                                    : SuppliedActionName;

                var apiVersion = GetApiVersion(actionExecutedContext);

                var httpVerb = actionExecutedContext.Request.Method.ToString();

                int statusCode = 0;
                var otEndpoint = string.Format("{0}-{1}", actionName, apiVersion).ToLower();
                if (actionExecutedContext.Response != null)
                {
                    // controller returns HttpResponseMessage or threw a HttpResponseException

                    statusCode = (int)actionExecutedContext.Response.StatusCode;

                    // Look for endpoint name in the response headers, if one exists we will use it to
                    // publish metircs.  If not will default to action name and will set the header
                    // value as such for upstream services.
                    IEnumerable <string> headerValues;
                    if (actionExecutedContext.Response.Headers.TryGetValues(StatsdConstants.OtEndpoint, out headerValues))
                    {
                        otEndpoint = string.Format("{0}-{1}", headerValues.FirstOrDefault() ?? actionName, apiVersion).ToLower();
                    }
                    else
                    {
                        actionExecutedContext.Response.Headers.Add(StatsdConstants.OtEndpoint, otEndpoint);
                    }
                }
                else if (actionExecutedContext.Exception != null)
                {
                    // controllers threw exception that is not typeof(HttpResponseException)

                    if (CommonHelpers.ExceptionToStatusCode != null)
                    {
                        var statusCodeEnum = CommonHelpers.ExceptionToStatusCode(actionExecutedContext.Exception,
                                                                                 actionExecutedContext);
                        statusCode = (int)statusCodeEnum;
                        actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(statusCodeEnum);
                        actionExecutedContext.Response.Headers.Add(StatsdConstants.OtEndpoint, otEndpoint);
                    }
                }


                var status = CommonHelpers.GetHighlevelStatus(IsSuccessStatusCode(statusCode));
                // not being able to read status code will result in status code being set to undefined
                var statusCodeString = statusCode == 0
                    ? StatsdConstants.Undefined
                    : statusCode.ToString(CultureInfo.InvariantCulture);
                var metricName = string.Format(
                    "{0}.{1}.{2}.{3}.{4}.{5}",
                    StatsdConstants.HttpRequestIn,
                    GetReferringService(actionExecutedContext),
                    otEndpoint,
                    status,
                    httpVerb,
                    statusCodeString).Replace('_', '-').ToLower();

                StatsdClientWrapper.Timer(metricName, elapsedMilliseconds);
                StatsdClientWrapper.Counter(metricName);

                EnrichResponseHeaders(actionExecutedContext);
            }
            finally
            {
                base.OnActionExecuted(actionExecutedContext);
            }
        }
 /// <summary>
 /// Set control state.
 /// </summary>
 private void _SetControlState()
 {
     _cellLabel.Text = CommonHelpers.ConvertBarrierEffect(_barrier);
 }
        void UpdateUserDetail()
        {
            //string password = "";
            //if (txt_NewPassword.Text.Trim() == "")
            //{
            //    password = txt_OldPassword.Text.Trim();
            //}
            //else
            //{
            //    password = txt_NewPassword.Text.Trim();
            //}
            try
            {
                //SqlConnection con = new SqlConnection(strcon);
                //if (con.State == ConnectionState.Closed)
                //{
                //    con.Open();
                //}

                //String query = "UPDATE Users set FirstName=@FirstName, LastName=@LastName, DateOfBirth=@DateOfBirth,Address=@Address,PostalCode=@PostalCode,PhoneNumber=@PhoneNumber,Password=@Password,ConfirmPassword=@ConfirmPassword where EmailAddress = @EmailAddress";
                //SqlCommand cmd = new SqlCommand(query, con);

                //cmd.Parameters.AddWithValue("@FirstName", txt_FirstName.Text.Trim());
                //cmd.Parameters.AddWithValue("@LastName", txt_LastName.Text.Trim());
                //cmd.Parameters.AddWithValue("@DateOfBirth", txt_DOB.Value.Trim());
                //cmd.Parameters.AddWithValue("@Address", txt_FullAddress.Text.Trim());
                //cmd.Parameters.AddWithValue("@PostalCode", txt_PostalCode.Text.Trim());
                //cmd.Parameters.AddWithValue("@PhoneNumber", txt_PhnNo.Text.Trim());
                //cmd.Parameters.AddWithValue("@EmailAddress", Session["UserName"].ToString().Trim());
                //cmd.Parameters.AddWithValue("@Password", password);
                //cmd.Parameters.AddWithValue("@ConfirmPassword", password);


                string firstName    = txt_FirstName.Text;
                string lasttName    = txt_LastName.Text;
                string DOB          = txt_DOB.Value;
                string phoneNumber  = txt_PhnNo.Text;
                string fullAddress  = txt_FullAddress.Text;
                string emailAddress = txt_Email.Text;
                string postalCode   = txt_PostalCode.Text;
                string newPassword  = txt_NewPassword.Text;
                //string newConfirmPassword = txt_NewConfirmPassword.Text;
                //string departmentType = dropdown_Department.SelectedValue;
                //string accessType = dropdown_AccessType.SelectedValue;
                SqlConnection con = new SqlConnection(strcon);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                string update = "update users  set "
                                //+"EmailAddress = '"+emailAddress+"'"
                                //+ "ConfirmPassword = '******'"
                                + " FirstName = '" + firstName + "' "
                                + " ,LastName = '" + lasttName + "' "
                                + " ,DateOfBirth = '" + DOB + "' "
                                + " ,PhoneNumber = '" + phoneNumber + "' "
                                + " ,Address = '" + fullAddress + "' "
                                + " ,PostalCode = '" + postalCode + "' ";
                //+ " ,RoleId = " + accessType
                //+ " ,DeptId = " + departmentType;
                if (!string.IsNullOrEmpty(newPassword))
                {
                    update += " ,Password= '******' ";
                }
                string where = " where EmailAddress = '" + Session["UserName"].ToString() + "' ";
                string     finalQuery = update + where;
                SqlCommand cmd        = new SqlCommand(finalQuery, con);
                int        result     = cmd.ExecuteNonQuery();
                con.Close();
                if (result > 0)
                {
                    Response.Write("<script>alert('Your Details Updated Successfully');</script>");
                    getUserDetail();
                }
                else
                {
                    Response.Write("<script>alert('Invaid entry');</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "');</script>");
            }
        }
        public List <CorrespondenceView> GetNotesForClientByUserId(string clientUserId, int noteType)
        {
            List <CorrespondenceView> result = new List <CorrespondenceView>();
            var client           = db.Clients.SingleOrDefault(c => c.ClientId == clientUserId);
            var clientId         = db.Clients.SingleOrDefault(c => c.ClientId == clientUserId).ClientId;
            var relevantNoteType = noteType;

            foreach (var note in db.Notes.Where(n => n.ClientId == clientId &&
                                                n.NoteType == relevantNoteType && db.NoteLinks.Where(l => l.NoteId2 == n.NoteId).Count() == 0))
            {
                var adviser  = db.Advisers.FirstOrDefault(ad => ad.AdviserId.ToString() == note.AccountId);
                var resource = note.Attachments.FirstOrDefault();
                #region create correspondence payload skeleton first
                CorrespondenceView item = new CorrespondenceView()
                {
                    adviserId       = adviser.AdviserNumber.ToString(),
                    adviserName     = adviser.FirstName + " " + adviser.LastName,
                    clientId        = note.ClientId,
                    clientName      = client.ClientType == BusinessLayerParameters.clientType_person ? client.FirstName + " " + client.LastName : client.EntityName,
                    date            = note.DateCreated,
                    noteId          = note.NoteId,
                    path            = resource == null ? "" : System.Web.VirtualPathUtility.ToAbsolute(resource.Path),
                    subject         = note.Subject,
                    typeName        = CommonHelpers.GetEnumDescription((NoteTypes)note.NoteType),
                    type            = resource == null ? "" : resource.AttachmentType,
                    conversations   = new List <CorrespondenceConversation>(),
                    actionsRequired = note.FollowupActions,
                    assetClass      = note.AssetClass,
                    completionDate  = note.DateCompleted,
                    productClass    = note.ProductClass
                };
                #endregion
                #region inject the initial conversation

                CorrespondenceConversation initial = new CorrespondenceConversation()
                {
                    content    = note.Body,
                    createdOn  = note.DateCreated,
                    senderRole = note.SenderRole,
                    senderName = note.SenderRole == BusinessLayerParameters.correspondenceSenderRole_adviser ? adviser.FirstName + " " + adviser.LastName
                    : (client.ClientType == BusinessLayerParameters.clientType_person ? client.FirstName + " " + client.LastName : client.EntityName)
                };
                item.conversations.Add(initial);
                #endregion
                #region insert all other conversations
                foreach (var subnote in db.NoteLinks.Where(n => n.NoteId1 == note.NoteId))
                {
                    var subNoteContent = db.Notes.SingleOrDefault(n => n.NoteId == subnote.NoteId2);
                    CorrespondenceConversation conversation = new CorrespondenceConversation()
                    {
                        content    = subNoteContent.Body,
                        senderRole = subNoteContent.SenderRole,
                        createdOn  = subNoteContent.DateCreated,
                        senderName = subNoteContent.SenderRole == BusinessLayerParameters.correspondenceSenderRole_adviser ? adviser.FirstName + " " + adviser.LastName
                        : (client.ClientType == BusinessLayerParameters.clientType_person ? client.FirstName + " " + client.LastName : client.EntityName)
                    };
                    item.conversations.Add(conversation);
                }


                #endregion
                item.conversations = item.conversations.OrderBy(s => s.createdOn).ToList();
                result.Add(item);
            }
            return(result);
        }
Example #29
0
        public PatientListResponse PostPatientList([FromBody] PatientListRequest request)
        {
            PatientListResponse response = new PatientListResponse();

            try
            {
                if (CommonHelpers.ValidateRequest(request.UserToken))
                {
                    DBAgent = new DataAccessProvider(DataAccessProvider.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"], ConfigurationManager.AppSettings["DBUserName"], ConfigurationManager.AppSettings["DBPassword"]);
                    DBAgent.ClearParams();
                    if (!String.IsNullOrEmpty(request.AccountNumber))
                    {
                        DBAgent.AddParameter("@ParamAccountNumber", request.AccountNumber);
                    }
                    string data = DBAgent.ExecuteStoredProcedure("dbo.spGetPatientListByAccount");
                    if (data.Length > 0)
                    {
                        DataSet ds = CommonHelpers.GetDataSetFromXml(data);
                        if (ds.Tables.Count > 0)
                        {
                            DataTable dTable = ds.Tables[0];
                            //response.PatientListDataTable = dTable;

                            ArrayList             PatientList        = new ArrayList();
                            List <PatientDetails> PatientDetailsList = new List <PatientDetails>();
                            foreach (DataRow dr in dTable.Rows)
                            {
                                string PatientNameRow = String.Format("{0}, {1} ({2} - {3})", dr["PatientLastName"], dr["PatientFirstName"], dr["PatientAccountNumber"], dr["PatientDOB"]);
                                PatientList.Add(String.Format("{0}, {1} ({2} - {3})", dr["PatientLastName"], dr["PatientFirstName"], dr["PatientAccountNumber"], dr["PatientDOB"]));
                                PatientDetailsList.Add(new PatientDetails(PatientNameRow, dr["PatientID"].ToString()));
                            }

                            response.PatientList        = PatientList;
                            response.PatientDetailsList = PatientDetailsList;
                        }
                        else
                        {
                            response.ErrorMessage = "No Data";
                        }
                    }
                    else
                    {
                        response.ErrorMessage = "No Data";
                    }
                }
                else
                {
                    response.ErrorMessage = "Invalid Request";

                    DBAgent = new DataAccessProvider(DataAccessProvider.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"], ConfigurationManager.AppSettings["DBUserName"], ConfigurationManager.AppSettings["DBPassword"]);
                    DBAgent.ClearParams();
                    DBAgent.AddParameter("@ParamRefID", request.LoginID);
                    DBAgent.AddParameter("@ParamRefType", "Users");
                    DBAgent.AddParameter("@ParamAction", "IR");
                    DBAgent.AddParameter("@ParamComment", "Invalid Requestv from Mobile App - PatientListController - " + request.UserToken);
                    DBAgent.ExecuteNonQuery("dbo.spAddUserAction");
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
                CommonHelpers.writeLogToFile("API: PostPatientList - PatientListController.cs", ex.Message + Environment.NewLine + ex.StackTrace);
            }
            return(response);
        }
Example #30
0
 private void UIElement_OnKeyDown(object sender, KeyEventArgs e)
 {
     CommonHelpers.OnKeyDownHandler(sender, e);
 }