protected override void OnRowDataBound(C1GridView grid, C1GridViewRowEventArgs e, ViajeDistribucionVo dataItem)
        {
            var ticket = dataItem;

            var cellEstado   = GridUtils.GetCell(e.Row, ViajeDistribucionVo.IndexEstado);
            var cellVehiculo = GridUtils.GetCell(e.Row, ViajeDistribucionVo.IndexVehiculo);
            var lblEstado    = cellEstado.FindControl("lblEstado") as ResourceLabel;
            var lnkIniciar   = cellEstado.FindControl("lnkIniciar") as ResourceLinkButton;
            var lnkCerrar    = cellEstado.FindControl("lnkCerrar") as ResourceLinkButton;
            var lnkReenviar  = cellEstado.FindControl("lnkReenviar") as ResourceLinkButton;
            var lnkAsociar   = cellEstado.FindControl("lnkAsociar") as ResourceLinkButton;
            var lnkCombinar  = cellEstado.FindControl("lnkCombinar") as ResourceLinkButton;
            var cbVehiculo   = cellVehiculo.FindControl("cbVehiculo") as DropDownList;

            if (!ticket.Nomenclado)
            {
                e.Row.BackColor = Color.LightCoral;
                grid.Columns[ViajeDistribucionVo.IndexNoNomencladas].Visible = true;
            }

            if (lnkCerrar == null || lnkIniciar == null || lblEstado == null || lnkReenviar == null || lnkAsociar == null || lnkCombinar == null)
            {
                return;
            }

            lnkCerrar.OnClientClick   = string.Concat("return confirm('", CultureManager.GetString("SystemMessages", "CONFIRM_OPERATION"), "');");
            lnkReenviar.OnClientClick = string.Concat("return confirm('", CultureManager.GetString("SystemMessages", "CONFIRM_OPERATION"), "');");

            switch (ticket.Estado)
            {
            case ViajeDistribucion.Estados.EnCurso:
                lnkIniciar.Visible     = false;
                lnkCerrar.Visible      = lnkReenviar.Visible = lblEstado.Visible = true;
                lblEstado.VariableName = "TICKETSTATE_CURRENT";
                break;

            case ViajeDistribucion.Estados.Anulado:
                lnkIniciar.Visible     = lnkCerrar.Visible = lnkReenviar.Visible = false;
                lblEstado.VariableName = "TICKETSTATE_ANULADO";
                lblEstado.Visible      = true;
                break;

            case ViajeDistribucion.Estados.Cerrado:
                lnkIniciar.Visible     = lnkCerrar.Visible = lnkReenviar.Visible = false;
                lblEstado.VariableName = "TICKETSTATE_CLOSED";
                lblEstado.Visible      = true;
                break;

            default:
                lnkIniciar.Visible     = dataItem.HasCoche;
                lnkCerrar.Visible      = lnkReenviar.Visible = false;
                lblEstado.Visible      = !lnkIniciar.Visible;
                lblEstado.VariableName = "TICKETSTATE_PROGRAMMED";
                break;
            }

            lnkAsociar.Visible  = !ticket.HasCoche;
            lnkCombinar.Visible = ticket.Estado == ViajeDistribucion.Estados.Pendiente && ticket.HasCoche;

            if (_editMode)
            {
                e.Row.Attributes.Remove("onclick");
                var vehiculos = DAOFactory.CocheDAO.GetList(new[] { ticket.IdEmpresa }, new[] { ticket.IdLinea }).OrderBy(c => c.Interno);

                cbVehiculo.Items.Add(new ListItem("Ninguno", "0"));
                foreach (var vehiculo in vehiculos)
                {
                    cbVehiculo.Items.Add(new ListItem(vehiculo.Interno, vehiculo.Id.ToString("#0")));
                }

                cbVehiculo.Attributes.Add("IdViaje", ticket.Id.ToString("#0"));
                cbVehiculo.SelectedValue = ticket.IdVehiculo.ToString("#0");
                cbVehiculo.Enabled       = ticket.Estado == ViajeDistribucion.Estados.Pendiente;
                cbVehiculo.AutoPostBack  = true;
                cbVehiculo.Enabled       = true;
            }
            else
            {
                cbVehiculo.Items.Add(ticket.IdVehiculo > 0
                                         ? new ListItem(ticket.Vehiculo, ticket.IdVehiculo.ToString("#0"))
                                         : new ListItem("Ninguno", "0"));
                cbVehiculo.Enabled = false;
            }
        }
Example #2
0
        public ResumenDeRutasVo(ViajeDistribucion viaje, Boolean estadoVerKm)
        {
            Id    = viaje.Id;
            Viaje = viaje;
            var dao = new DAOFactory();

            Ruta     = viaje.Codigo;
            Vehiculo = viaje.Vehiculo != null
                ? viaje.Vehiculo.Interno + " - "
                       + viaje.Vehiculo.Patente
                       + (viaje.Vehiculo.Dispositivo == null ? " (Sin dispositivo)" : string.Empty)
                       + (viaje.Vehiculo.Estado == Coche.Estados.EnMantenimiento ? " (En Taller)" : string.Empty)
                       + (viaje.Vehiculo.Estado == Coche.Estados.Inactivo ? " (Inactivo)" : string.Empty)
                       + (viaje.Vehiculo.Estado == Coche.Estados.Revisar ? " (Revisar)" : string.Empty)
                : "Ninguno";
            Inicio     = viaje.InicioReal.HasValue ? viaje.InicioReal.Value.ToDisplayDateTime() : (DateTime?)null;
            Fin        = viaje.Estado == ViajeDistribucion.Estados.Cerrado ? viaje.Fin.ToDisplayDateTime() : (DateTime?)null;
            Recepcion  = viaje.Recepcion.HasValue ? viaje.Recepcion.Value.ToDisplayDateTime() : (DateTime?)null;
            Entregas   = viaje.EntregasTotalCount;
            Realizados = viaje.EntregasCompletadosCount;
            Visitados  = viaje.EntregasVisitadosCount;
            Rechazados = viaje.EntregasNoCompletadosCount;
            EnSitio    = viaje.EntregasEnSitioCount;
            EnZona     = viaje.EntregasEnZonaCount;
            var total = Realizados + Visitados;

            PorcVisitados = Entregas > 0 ? Convert.ToDouble(total) / Convert.ToDouble(Entregas) : 0.00;
            Estado        = CultureManager.GetLabel(ViajeDistribucion.Estados.GetLabelVariableName(viaje.Estado));
            var kms       = 0.0;
            var recorrido = new TimeSpan(0);

            if (viaje.Vehiculo != null && viaje.InicioReal.HasValue)
            {
                switch (viaje.Estado)
                {
                case ViajeDistribucion.Estados.EnCurso:
                    if (estadoVerKm)
                    {
                        kms       = dao.CocheDAO.GetDistance(viaje.Vehiculo.Id, viaje.InicioReal.Value, DateTime.UtcNow);
                        recorrido = new TimeSpan(0, 0, (int)DateTime.UtcNow.Subtract(viaje.InicioReal.Value).TotalSeconds);
                    }
                    break;

                case ViajeDistribucion.Estados.Cerrado:
                    if (estadoVerKm)
                    {
                        if (viaje.InicioReal.Value < DateTime.Today)
                        {
                            var dmViaje = dao.DatamartViajeDAO.GetRecords(viaje.Id).FirstOrDefault();
                            if (dmViaje != null)
                            {
                                kms = dmViaje.KmTotales;
                            }
                        }
                        else
                        {
                            kms = dao.CocheDAO.GetDistance(viaje.Vehiculo.Id, viaje.InicioReal.Value, viaje.Fin);
                        }

                        recorrido = new TimeSpan(0, 0, (int)viaje.Fin.Subtract(viaje.InicioReal.Value).TotalSeconds);
                    }
                    break;
                }
            }
            Kms       = kms;
            Recorrido = recorrido;
        }
Example #3
0
        public static string ParseExpression(string tenant, string expression, List <DataSource> dataSources, ParameterInfo info)
        {
            if (string.IsNullOrWhiteSpace(expression))
            {
                return(string.Empty);
            }


            string logo = GetLogo();

            if (!string.IsNullOrWhiteSpace(logo))
            {
                //Or else logo will not be exported into excel.
                expression = expression.Replace("{LogoPath}", GetCurrentDomainName() + VirtualPathUtility.ToAbsolute(logo));
            }

            expression = expression.Replace("{PrintDate}", DateTime.Now.ToString(CultureManager.GetCurrentUiCulture()));

            foreach (var match in Regex.Matches(expression, "{.*?}"))
            {
                string word = match.ToString();

                if (word.StartsWith("{Meta.", StringComparison.OrdinalIgnoreCase))
                {
                    string sessionKey = RemoveBraces(word);
                    sessionKey = sessionKey.Replace("Meta.", "");
                    sessionKey = sessionKey.Trim();

                    string value = GetDictionaryValue(tenant, sessionKey);

                    expression = expression.Replace(word, value);
                }
                else if (word.StartsWith("{Query.", StringComparison.OrdinalIgnoreCase))
                {
                    string res      = RemoveBraces(word);
                    var    resource = res.Split('.');

                    string key = resource[1];

                    var parameter = info.Parameters.FirstOrDefault(x => x.Name.ToLower().Equals(key.ToLower()));

                    if (parameter != null)
                    {
                        string value = FormattingHelper.GetFormattedValue(parameter.Value);

                        var datasourceParameter = info.DataSourceParameters.FirstOrDefault(x => x.Name.Replace("@", "").ToLower().Equals(parameter.Name.ToLower()));

                        if (datasourceParameter != null)
                        {
                            string type = datasourceParameter.Type;
                            value = DataSourceParameterHelper.CastValue(value, type).ToString();
                        }

                        expression = expression.Replace(word, value);
                    }
                }
                else if (word.StartsWith("{i18n.", StringComparison.OrdinalIgnoreCase))
                {
                    string res      = RemoveBraces(word);
                    var    resource = res.Split('.');

                    string key = resource[1];

                    expression = expression.Replace(word, LocalizationHelper.Localize(key, false));
                }
                else if (word.StartsWith("{DataSource", StringComparison.OrdinalIgnoreCase) && word.ToLower(CultureInfo.InvariantCulture).Contains("runningtotalfieldvalue"))
                {
                    if (dataSources == null)
                    {
                        return(null);
                    }

                    string res      = RemoveBraces(word);
                    var    resource = res.Split('.');

                    int dataSourceIndex =
                        resource[0].ToLower(CultureInfo.InvariantCulture)
                        .Replace("datasource", "")
                        .Replace("[", "")
                        .Replace("]", "").To <int>();
                    int index =
                        resource[1].ToLower(CultureInfo.InvariantCulture)
                        .Replace("runningtotalfieldvalue", "")
                        .Replace("[", "")
                        .Replace("]", "").To <int>();

                    if (dataSourceIndex >= 0 && index >= 0)
                    {
                        var dataSource = dataSources.FirstOrDefault(x => x.Index.Equals(dataSourceIndex));

                        if (dataSource?.Data != null)
                        {
                            expression = expression.Replace(word,
                                                            GetSum(dataSource.Data, index)
                                                            .ToString(CultureInfo.InvariantCulture));
                        }
                    }
                }
                //else if (word.StartsWith("{Barcode", StringComparison.OrdinalIgnoreCase))
                //{
                //string res = RemoveBraces(word).Replace("Barcode(", "").Replace(")", "");
                //string barCodeValue = res;

                //    if (res.StartsWith("DataSource"))
                //    {
                //        barCodeValue = ParseDataSource("{" + res + "}", dataTableCollection);
                //    }

                //    string barCodeFormat = ConfigurationHelper.GetReportParameter("BarCodeFormat");
                //    string barCodeDisplayValue = ConfigurationHelper.GetReportParameter("BarCodeDisplayValue");
                //    string barCodeFontSize = ConfigurationHelper.GetReportParameter("BarCodeFontSize");
                //    string barCodeWidth = ConfigurationHelper.GetReportParameter("BarCodeWidth");
                //    string barCodeHeight = ConfigurationHelper.GetReportParameter("BarCodeHeight");
                //    string barCodeQuite = ConfigurationHelper.GetReportParameter("BarCodeQuite");
                //    string barCodeFont = ConfigurationHelper.GetReportParameter("BarCodeFont");
                //    string barCodeTextAlign = ConfigurationHelper.GetReportParameter("BarCodeTextAlign");
                //    string barCodeBackgroundColor = ConfigurationHelper.GetReportParameter("BarCodeBackgroundColor");
                //    string barCodeLineColor = ConfigurationHelper.GetReportParameter("BarCodeLineColor");

                //    string imageSource =
                //        "<img class='reportEngineBarCode' data-barcodevalue='{0}' alt='{0}' value='{0}' data-barcodeformat='{1}' data-barcodedisplayvalue='{2}' data-barcodefontsize='{3}' data-barcodewidth='{4}' data-barcodeheight='{5}' data-barcodefont='{6}' data-barcodetextalign='{7}' data-barcodebackgroundcolor='{8}' data-barcodelinecolor='{9}' data-barcodequite={10} />";
                //    imageSource = string.Format(CultureInfo.InvariantCulture, imageSource, barCodeValue,
                //        barCodeFormat, barCodeDisplayValue, barCodeFontSize, barCodeWidth, barCodeHeight,
                //        barCodeFont, barCodeTextAlign, barCodeBackgroundColor, barCodeLineColor, barCodeQuite);
                //    expression = expression.Replace(word, imageSource).ToString(CultureInfo.InvariantCulture);
                //}
                //else if (word.StartsWith("{QRCode", StringComparison.OrdinalIgnoreCase))
                //{
                //    string res = RemoveBraces(word).Replace("QRCode(", "").Replace(")", "");
                //    string qrCodeValue = res;

                //    if (res.StartsWith("DataSource"))
                //    {
                //        qrCodeValue = ParseDataSource("{" + res + "}", dataTableCollection);
                //    }

                //    string qrCodeRender = ConfigurationHelper.GetReportParameter("QRCodeRender");
                //    string qrCodeBackgroundColor = ConfigurationHelper.GetReportParameter("QRCodeBackgroundColor");
                //    string qrCodeForegroundColor = ConfigurationHelper.GetReportParameter("QRCodeForegroundColor");
                //    string qrCodeWidth = ConfigurationHelper.GetReportParameter("QRCodeWidth");
                //    string qrCodeHeight = ConfigurationHelper.GetReportParameter("QRCodeHeight");
                //    string qrCodeTypeNumber = ConfigurationHelper.GetReportParameter("QRCodeTypeNumber");

                //    string qrCodeDiv =
                //        "<div class='reportEngineQRCode' data-qrcodevalue={0} data-qrcoderender='{1}' data-qrcodebackgroundcolor='{2}' data-qrcodeforegroundcolor='{3}' data-qrcodewidth='{4}' data-qrcodeheight='{5}' data-qrcodetypenumber='{6}'></div>";
                //    qrCodeDiv = string.Format(CultureInfo.InvariantCulture, qrCodeDiv, qrCodeValue, qrCodeRender,
                //        qrCodeBackgroundColor, qrCodeForegroundColor, qrCodeWidth, qrCodeHeight, qrCodeTypeNumber);
                //    expression = expression.Replace(word, qrCodeDiv).ToString(CultureInfo.InvariantCulture);
                //
                //}
            }
            return(expression);
        }
Example #4
0
        /// <summary>
        /// Process the report and show it.
        /// </summary>
        /// <returns>A boolean value indicating the success or failure in the process.</returns>
        public override bool Execute()
        {
            if (!CheckNullAndFormatFilterVariablesValues())
            {
                return(false);
            }

            // Load filter variable values in the parameters collection
            foreach (ArgumentController lFilterVariable in InputFields)
            {
                object lFilterVariableValue = lFilterVariable.Value;
                ArgumentOVControllerAbstract lOVController = lFilterVariable as ArgumentOVControllerAbstract;
                if (lOVController != null)
                {
                    if (lOVController.Value != null)
                    {
                        lFilterVariableValue = lOVController.GetSupplementaryInfoText();
                    }
                }

                if (ReportParams.ContainsKey(lFilterVariable.Name))
                {
                    ReportParams[lFilterVariable.Name] = lFilterVariableValue;
                }
                else
                {
                    ReportParams.Add(lFilterVariable.Name, lFilterVariableValue);
                }
            }

            // Execute Filter Event initialization.
            ExecuteFilterEventArgs lExecuteFilterEventArgs = new ExecuteFilterEventArgs(this);

            try
            {
                // Get the data according the report definition.
                DataTable lDataTable = GetData();

                // Create the DataSet from the base DataTable, taking into account the DataSet structure.
                DataSet lDataSet = PrintingDriver.PrintToDataSets.GetData(lDataTable, mDataSetFile);

                if (GetReportType() == ReportTypes.CrystalReports)
                {
                    // Show 'Crystal' preview scenario.
                    ScenarioManager.LaunchCrystalReportPreviewScenario(lDataSet, ReportFile, ReportParams, PrintDirectly);
                }
                if (GetReportType() == ReportTypes.RDLC)
                {
                    // Show 'RDLC' preview scenario.
                    ScenarioManager.LaunchRDLReportPreviewScenario(lDataSet, ReportFile, ReportParams, PrintDirectly);
                }
            }
            catch (Exception exc)
            {
                Exception gettingDataException = new Exception(CultureManager.TranslateString(LanguageConstantKeys.L_ERROR_REPORT_GETTINGDATA, LanguageConstantValues.L_ERROR_REPORT_GETTINGDATA), exc);
                Presentation.ScenarioManager.LaunchErrorScenario(gettingDataException);

                // Indicate that an error has occurred during the report configuration.
                lExecuteFilterEventArgs.Success = false;
            }

            OnExecuteFilter(lExecuteFilterEventArgs);

            return(lExecuteFilterEventArgs.Success);
        }
Example #5
0
        protected void CreateGraphic(List <Pedido> list)
        {
            try
            {
                using (var helper = new FusionChartsMultiSeriesHelper())
                {
                    var boca   = DAOFactory.BocaDeCargaDAO.FindById(cbBocaDeCarga.Selected);
                    var inicio = GetInicioActividad(boca);
                    var fin    = GetFinActividad(boca);

                    var    tiempoPromedio = Convert.ToInt32(_tiempoCiclos.Sum() / CantidadTotal);
                    var    prev           = 0;
                    double maxValue       = boca.Rendimiento;
                    var    maxMixers      = CantidadMixers;

                    #region DataSet Rendimiento (Trendline)
                    var dataSetTrendLineRendimiento = new FusionChartsDataset();
                    dataSetTrendLineRendimiento.SetPropertyValue("seriesName", CultureManager.GetLabel("RENDIMIENTO"));
                    dataSetTrendLineRendimiento.SetPropertyValue("color", "c30000");
                    dataSetTrendLineRendimiento.SetPropertyValue("parentYAxis", "S");
                    dataSetTrendLineRendimiento.SetPropertyValue("showAnchors", "0");
                    dataSetTrendLineRendimiento.SetPropertyValue("alpha", "60");
                    dataSetTrendLineRendimiento.SetPropertyValue("lineThickness", "2");
                    helper.AddDataSet(dataSetTrendLineRendimiento);
                    #endregion

                    #region DataSet Volumen por Hora (Barras)
                    var dataSetVolumen = new FusionChartsDataset();
                    dataSetVolumen.SetPropertyValue("seriesName", CultureManager.GetLabel("PROGRAMACION_VOLUMEN_HORA"));
                    dataSetVolumen.SetPropertyValue("color", "6868c3");
                    dataSetVolumen.SetPropertyValue("parentYAxis", "P");
                    helper.AddDataSet(dataSetVolumen);
                    #endregion

                    #region DataSet Mixers Disponibles (Trendline)
                    var dataSetTrendLineMixers = new FusionChartsDataset();
                    dataSetTrendLineMixers.SetPropertyValue("seriesName", CultureManager.GetLabel("AVAILABLE_VEHICLES"));
                    dataSetTrendLineMixers.SetPropertyValue("color", "c39600");
                    dataSetTrendLineMixers.SetPropertyValue("parentYAxis", "S");
                    dataSetTrendLineMixers.SetPropertyValue("showAnchors", "0");
                    dataSetTrendLineMixers.SetPropertyValue("alpha", "60");
                    dataSetTrendLineMixers.SetPropertyValue("lineThickness", "2");
                    helper.AddDataSet(dataSetTrendLineMixers);
                    #endregion

                    #region DataSet Mixers Equivalentes (Linea)
                    var dataSetMixers = new FusionChartsDataset();
                    dataSetMixers.SetPropertyValue("seriesName", CultureManager.GetLabel("PROGRAMACION_MIXERS_EQUIVALENTES"));
                    dataSetMixers.SetPropertyValue("color", "009900");
                    dataSetMixers.SetPropertyValue("parentYAxis", "S");
                    dataSetMixers.SetPropertyValue("anchorSides", "10");
                    dataSetMixers.SetPropertyValue("anchorRadius", "3");
                    dataSetMixers.SetPropertyValue("anchorBorderColor", "009900");
                    helper.AddDataSet(dataSetMixers);
                    #endregion

                    #region Llenado de Categorias y Valores
                    for (var i = inicio; i <= fin; i = i.Add(TimeSpan.FromHours(1)))
                    {
                        var hora = Convert.ToInt32(i.Hours);
                        var val  = _volumenPorHora.ContainsKey(hora) ? _volumenPorHora[hora] : 0;
                        var mix  = (int)Math.Ceiling(1.0 * val / Carga);
                        var equi = (int)Math.Round((prev + mix) * tiempoPromedio / TiempoReferencia);


                        helper.AddCategory(FormatTimeSpan(i));
                        dataSetVolumen.addValue(val.ToString());
                        dataSetMixers.addValue(equi.ToString());

                        if (val > maxValue)
                        {
                            maxValue = val;
                        }
                        if (equi > maxMixers)
                        {
                            maxMixers = equi;
                        }

                        prev = mix;
                    }
                    #endregion

                    #region Calculo proporcional de maximos y trendlines
                    maxMixers++;
                    maxValue++;
                    var divlines = 1;
                    if (maxValue > maxMixers)
                    {
                        while (maxValue % maxMixers != 0)
                        {
                            maxValue++;
                        }
                        divlines = Convert.ToInt32(maxValue / maxMixers);
                    }
                    else
                    {
                        while (maxMixers % maxValue != 0)
                        {
                            maxMixers++;
                        }
                        divlines = Convert.ToInt32(maxMixers / maxValue);
                    }

                    var rend = boca.Rendimiento * maxMixers * 1.0 / maxValue;

                    for (var i = inicio; i <= fin; i = i.Add(TimeSpan.FromHours(1)))
                    {
                        dataSetTrendLineRendimiento.addValue(rend.ToString(CultureInfo.InvariantCulture));
                        dataSetTrendLineMixers.addValue(CantidadMixers.ToString());
                    }
                    #endregion

                    #region Valores de Cabecera
                    helper.AddConfigEntry("caption", "");
                    helper.AddConfigEntry("xAxisName", CultureManager.GetLabel("HORA"));
                    helper.AddConfigEntry("PyAxisName", CultureManager.GetLabel("VOLUMEN"));
                    helper.AddConfigEntry("SyAxisName", CultureManager.GetLabel("VEHICULOS"));
                    helper.AddConfigEntry("decimalPrecision", "0");
                    helper.AddConfigEntry("showValues", "0");
                    helper.AddConfigEntry("numberSuffix", "");
                    helper.AddConfigEntry("rotateNames", "1");
                    helper.AddConfigEntry("limitsDecimalPrecision", "0");
                    helper.AddConfigEntry("hoverCapSepChar", "-");
                    helper.AddConfigEntry("divLineAlpha", "60");
                    helper.AddConfigEntry("showAlternateHGridColor", "1");
                    helper.AddConfigEntry("alternateHGridColor", "d8d8d8");
                    helper.AddConfigEntry("alternateHGridAlpha", "60");
                    helper.AddConfigEntry("zeroPlaneThickness", "20");

                    helper.AddConfigEntry("numDivLines", (divlines - 1).ToString());
                    helper.AddConfigEntry("SyAxisMaxValue", maxMixers.ToString());
                    helper.AddConfigEntry("PyAxisMaxValue", maxValue.ToString());
                    #endregion

                    litGraph.Text = FusionCharts.RenderChartHTML("../../FusionCharts/FCF_MSColumn2DLineDY.swf", "", helper.BuildXml(), "Report", (sizeField.Width).ToString(), (sizeField.Heigth).ToString(), false);
                }
            }
            catch (Exception ex) { ShowError(ex); }
        }
Example #6
0
 protected void SetExcelSessionVars(string filename)
 {
     Session["TMP_FILE_NAME"] = filename;
     Session["CSV_FILE_NAME"] = CultureManager.GetMenu(Module.Name);
 }
Example #7
0
        private void RegisterJavascript()
        {
            string script = JSUtility.GetVar("culture", CultureManager.GetCurrent().Name);

            script += JSUtility.GetVar("language", CultureManager.GetCurrent().TwoLetterISOLanguageName);

            script += JSUtility.GetVar("jqueryUIi18nPath", this.Page.ResolveUrl("~/Scripts/jquery-ui/i18n/"));

            script += JSUtility.GetVar("today", string.Format(CultureManager.GetCurrent(), CultureManager.GetCurrent().DateTimeFormat.ShortDatePattern, DateTime.Now));
            script += JSUtility.GetVar("now", DateTime.Now.ToString(CultureManager.GetCurrent()));
            script += JSUtility.GetVar("date", DateTime.Now.ToString(CultureInfo.InvariantCulture));

            script += JSUtility.GetVar("reportTemplatePath", PageUtility.ResolveUrl(DbConfig.GetScrudParameter(AppUsers.GetCurrentUserDB(), "TemplatePath")));
            script += JSUtility.GetVar("reportExportTemplatePath", PageUtility.ResolveUrl(DbConfig.GetScrudParameter(AppUsers.GetCurrentUserDB(), "ExportTemplatePath")));
            script += JSUtility.GetVar("reportHeaderPath", PageUtility.ResolveUrl(DbConfig.GetScrudParameter(AppUsers.GetCurrentUserDB(), "HeaderPath")));

            script += JSUtility.GetVar("userId", AppUsers.GetCurrent().View.UserId);
            script += JSUtility.GetVar("user", AppUsers.GetCurrent().View.UserName);
            script += JSUtility.GetVar("officeCode", AppUsers.GetCurrent().View.OfficeCode);
            script += JSUtility.GetVar("office", AppUsers.GetCurrent().View.OfficeName);

            script += JSUtility.GetVar("applicationDates", JsonConvert.SerializeObject(DatePersister.GetFrequencyDates(AppUsers.GetCurrentUserDB(), AppUsers.GetCurrent().View.OfficeId.ToInt())), false);
            script += JSUtility.GetVar("metaView", JsonConvert.SerializeObject(AppUsers.GetCurrent().View), false);
            script += JSUtility.GetVar("overridePath", this.OverridePath);

            script += JSUtility.GetVar("shortDateFormat", CultureManager.GetShortDateFormat());
            script += JSUtility.GetVar("longDateFormat", CultureManager.GetLongDateFormat());

            script += JSUtility.GetVar("thousandSeparator", CultureManager.GetThousandSeparator());
            script += JSUtility.GetVar("decimalSeparator", CultureManager.GetDecimalSeparator());
            script += JSUtility.GetVar("currencyDecimalPlaces", CultureManager.GetCurrencyDecimalPlaces());
            script += JSUtility.GetVar("currencySymbol", CultureManager.GetCurrencySymbol());


            script += JSUtility.GetVar("today", DateTime.Now.ToShortDateString());

            script += JSUtility.GetVar("shortDateFormat", CultureManager.GetShortDateFormat());
            script += JSUtility.GetVar("thousandSeparator", CultureManager.GetThousandSeparator());
            script += JSUtility.GetVar("decimalSeparator", CultureManager.GetDecimalSeparator());
            script += JSUtility.GetVar("currencyDecimalPlaces", CultureManager.GetCurrencyDecimalPlaces());
            script += JSUtility.GetVar("baseCurrencyCode", AppUsers.GetCurrent().View.CurrencyCode);


            script += JSUtility.GetVar("catalog", AppUsers.GetCurrentUserDB());

            script += JSUtility.GetVar("update", this.Update());

            script += JSUtility.GetVar("firstStepsPending", this.Context.Session["FirstStepsPending"]);

            script += JSUtility.GetVar("datepickerFormat", jQueryUI.GetDatePickerFormat());
            script += JSUtility.GetVar("datepickerShowWeekNumber", jQueryUI.ShowWeekNumber());
            script += JSUtility.GetVar("datepickerWeekStartDay", jQueryUI.GetWeekStartDay());
            script += JSUtility.GetVar("datepickerNumberOfMonths", jQueryUI.GetNumberOfMonths());


            ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "MixERPMasterPage", script, true);
        }
Example #8
0
        protected override void OnRowDataBound(GridViewRowEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            foreach (TableCell cell in e.Row.Cells)
            {
                DataControlFieldCell dataControlField = cell as DataControlFieldCell;

                if (dataControlField != null)
                {
                    AutoGeneratedField field = dataControlField.ContainingField as AutoGeneratedField;

                    if (field != null)
                    {
                        field.HeaderStyle.CssClass = "text left";

                        switch (field.DataType.FullName)
                        {
                        case "System.String":
                            field.HtmlEncode = this.htmlEncode;
                            break;

                        case "System.Decimal":
                        case "System.Double":
                        case "System.Single":
                            cell.CssClass = "text right";
                            field.HeaderStyle.CssClass = "text right";

                            if (e.Row.RowType == DataControlRowType.DataRow)
                            {
                                decimal value = Conversion.TryCastDecimal(cell.Text);

                                if (!value.Equals(0))
                                {
                                    CultureInfo culture = CultureManager.GetCurrent();
                                    cell.Text = value.ToString("C", culture).Replace(culture.NumberFormat.CurrencySymbol, "");
                                }
                            }
                            break;

                        case "System.DateTime":
                            if (e.Row.RowType == DataControlRowType.DataRow)
                            {
                                DateTime date = Conversion.TryCastDate(cell.Text);

                                if (date.Date == date)
                                {
                                    cell.Text = Conversion.TryCastDate(cell.Text).ToString("D", CultureManager.GetCurrent());
                                }
                                else
                                {
                                    cell.Text = Conversion.TryCastDate(cell.Text).ToString("F", CultureManager.GetCurrent());
                                }
                            }

                            break;
                        }
                    }
                }
            }

            base.OnRowDataBound(e);
        }
Example #9
0
        public static void AddFilters <T>(ref Sql sql, T poco, List <Filter> filters)
        {
            if (filters == null ||
                filters.Count.Equals(0))
            {
                return;
            }

            foreach (var filter in filters)
            {
                if (string.IsNullOrWhiteSpace(filter.ColumnName))
                {
                    if (!string.IsNullOrWhiteSpace(filter.PropertyName))
                    {
                        filter.ColumnName = filter.PropertyName.ToUnderscoreCase();
                    }
                }

                string column = Sanitizer.SanitizeIdentifierName(filter.ColumnName);

                if (string.IsNullOrWhiteSpace(column))
                {
                    continue;
                }

                string statement = filter.FilterStatement;

                if (statement == null ||
                    statement.ToUpperInvariant() != "OR")
                {
                    statement = "AND";
                }

                statement += " ";

                switch ((FilterCondition)filter.FilterCondition)
                {
                case FilterCondition.IsEqualTo:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " = @0", filter.FilterValue);
                    break;

                case FilterCondition.IsNotEqualTo:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " != @0", filter.FilterValue);
                    break;

                case FilterCondition.IsLessThan:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " < @0", filter.FilterValue);
                    break;

                case FilterCondition.IsLessThanEqualTo:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " <= @0", filter.FilterValue);
                    break;

                case FilterCondition.IsGreaterThan:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " > @0", filter.FilterValue);
                    break;

                case FilterCondition.IsGreaterThanEqualTo:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " >= @0", filter.FilterValue);
                    break;

                case FilterCondition.IsBetween:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " BETWEEN @0 AND @1", filter.FilterValue, filter.FilterAndValue);
                    break;

                case FilterCondition.IsNotBetween:
                    sql.Append(statement + Sanitizer.SanitizeIdentifierName(column) + " NOT BETWEEN @0 AND @1", filter.FilterValue, filter.FilterAndValue);
                    break;

                case FilterCondition.IsLike:
                    sql.Append(statement + " lower(" + Sanitizer.SanitizeIdentifierName(column) + ") LIKE @0", "%" + filter.FilterValue.ToLower(CultureManager.GetCurrent()) + "%");
                    break;

                case FilterCondition.IsNotLike:
                    sql.Append(statement + " lower(" + Sanitizer.SanitizeIdentifierName(column) + ") NOT LIKE @0", "%" + filter.FilterValue.ToLower(CultureManager.GetCurrent()) + "%");
                    break;
                }
            }
        }
Example #10
0
 /// <summary>
 /// Validates the entity data.
 /// </summary>
 private void ValidateEntity()
 {
     if (txtNombre.Text == string.Empty)
     {
         throw new Exception(string.Format(CultureManager.GetError("MUST_ENTER_VALUE"), CultureManager.GetLabel("FULLNAME")));
     }
 }
        public IUController Initialize(ExchangeInfo exchangeInfo)
        {
            // ExchangeInfo with Destinations
            mExchangeInfoConditional = exchangeInfo as ExchangeInfoConditionalNavigation;

            if (mExchangeInfoConditional != null)
            {
                this.SuspendLayout();

                Text             = CultureManager.TranslateString(LanguageConstantKeys.L_QUESTION, LanguageConstantValues.L_QUESTION, Text);
                lblQuestion.Text = mExchangeInfoConditional.ConditionalNavigationInfo.Question;

                int lCount = 0;
                int lnexty = 0;
                int lseedy = 19;
                int lgrBox = 0;
                foreach (DestinationInfo lDestinationInfo in mExchangeInfoConditional.ConditionalNavigationInfo)
                {
                    #region radioButton01
                    if (lCount == 0)
                    {
                        radioButton01.AutoSize = true;
                        radioButton01.Size     = new System.Drawing.Size(14, 13);
                        radioButton01.Location = new System.Drawing.Point(12, lseedy);
                        radioButton01.TabIndex = lCount;
                        radioButton01.TabStop  = true;
                        radioButton01.UseVisualStyleBackColor = true;
                        radioButton01.Text = lDestinationInfo.AssociatedText;
                        radioButton01.Tag  = lCount;

                        lnexty = radioButton01.Location.Y;
                    }
                    #endregion radioButton01
                    else
                    {
                        lnexty += lseedy;
                        //
                        // radioButton
                        //
                        RadioButton rb = new RadioButton();
                        rb.AutoSize = true;
                        rb.Location = new System.Drawing.Point(12, lnexty);
                        rb.Size     = new System.Drawing.Size(14, 13);
                        rb.Location = new System.Drawing.Point(12, lnexty);
                        rb.Name     = "radioButton" + lCount.ToString();
                        rb.TabIndex = lCount;
                        rb.TabStop  = true;
                        rb.UseVisualStyleBackColor = true;
                        rb.Text = lDestinationInfo.AssociatedText;
                        rb.Tag  = lCount;

                        grpBoxDestinations.Controls.Add(rb);


                        lgrBox += (lnexty + 10);
                    }
                    lCount++;
                }

                // Adjust the form size
                this.Size = new Size(this.Size.Width, grpBoxDestinations.Top + panel2.Height + (lCount + 2) * lseedy);
                // Select the first option
                radioButton01.Checked = true;
                this.ResumeLayout();
            }
            return(null);
        }
Example #12
0
        protected override void SelectedIndexChanged()
        {
            Session["id"] = Grid.SelectedRow.Cells[IndexIdTicket + DesplazamientoPorColumnasFijas].Text;

            OpenWin("../../CicloLogistico/AltaTicket.aspx", CultureManager.GetMenu("ALTA_TICKET"));
        }
Example #13
0
        public override IEnumerable <SerializedObject> GetSerializedObjects(IRequestHandler requestHandler, SerializedObject serializedPage, params KeyValuePair <string, string>[] args)
        {
            if (!this.HasArgument(args, "OrderBy") || !this.HasArgument(args, "Direction"))
            {
                if (this.HasArgument(args, "MemberId"))
                {
                    return(requestHandler.Storage.GetRepository <ISerializedObjectRepository>().Foreign(CultureManager.GetCurrentCulture(requestHandler.Storage).Id, this.GetIntArgument(args, "MemberId"), serializedPage.ObjectId));
                }

                return(requestHandler.Storage.GetRepository <ISerializedObjectRepository>().Foreign(CultureManager.GetCurrentCulture(requestHandler.Storage).Id, serializedPage.ObjectId));
            }

            int      orderBy   = this.GetIntArgument(args, "OrderBy");
            string   direction = this.GetStringArgument(args, "Direction");
            Member   member    = requestHandler.Storage.GetRepository <IMemberRepository>().WithKey(orderBy);
            DataType dataType  = requestHandler.Storage.GetRepository <IDataTypeRepository>().WithKey((int)member.PropertyDataTypeId);

            if (this.HasArgument(args, "MemberId"))
            {
                return(requestHandler.Storage.GetRepository <ISerializedObjectRepository>().Foreign(CultureManager.GetCurrentCulture(requestHandler.Storage).Id, this.GetIntArgument(args, "MemberId"), serializedPage.ObjectId, dataType.StorageDataType, orderBy, direction));
            }

            return(requestHandler.Storage.GetRepository <ISerializedObjectRepository>().Foreign(CultureManager.GetCurrentCulture(requestHandler.Storage).Id, serializedPage.ObjectId, dataType.StorageDataType, orderBy, direction));
        }
Example #14
0
 protected void ThrowInvalidValue(string resource, string variable)
 {
     throw new ApplicationException(string.Format(CultureManager.GetError("INVALID_VALUE"), CultureManager.GetString(resource, variable)));
 }
Example #15
0
        /// <summary>
        /// Validates current edited object.
        /// </summary>
        protected override void ValidateSave()
        {
            if (cbSubSistema.SelectedIndex == -1)
            {
                throw new Exception(string.Format(CultureManager.GetError("NO_SELECTED"), CultureManager.GetEntity("SISTEMA")));
            }

            if (txtReferencia.Text.Contains(","))
            {
                throw new Exception(CultureManager.GetError("FUNC_REF_WRONG_CHARS"));
            }
        }
Example #16
0
 protected List <EntregaAControlar> GetEntregasAControlar(ViajeDistribucion viaje)
 {
     return(viaje.GetEntregasOrdenadas().Select(e => new EntregaAControlar
     {
         Id = e.Id,
         Entrega = e.Descripcion,
         Tipo = e.TipoServicio != null ? e.TipoServicio.Descripcion : e.Linea != null ? CultureManager.GetEntity("PARENTI02") : string.Empty,
         Programado = e.Programado,
         Entrada = e.Entrada,
         Manual = e.Manual,
         Salida = e.Salida,
         KmGps = e.KmGps,
         KmCalculado = e.KmCalculado,
         KmControlado = e.KmControlado,
         Estado = e.Estado,
         Base = e.Linea != null
     }).ToList());
 }
Example #17
0
        /// <summary>
        /// Load report from the XML configuration file.
        /// </summary>
        /// <param name="configurationFile">Reports configuration file name.</param>
        public void LoadFromFile(string configurationFile)
        {
            Reports.Clear();

            // Verify the path and file specified in MainMenuReports Settings.
            string lFilePath = configurationFile;

            if (!System.IO.File.Exists(lFilePath))
            {
                lFilePath = System.Windows.Forms.Application.StartupPath + "\\" + lFilePath;
                if (!System.IO.File.Exists(lFilePath))
                {
                    return;
                }
            }

            try
            {
                XmlDocument lXMLDoc = new XmlDocument();
                lXMLDoc.Load(lFilePath);

                XmlNodeList lNodeList = lXMLDoc.GetElementsByTagName("Report");

                int    lCode       = 1;
                char[] lSeparators = new char[] { ',' };
                foreach (XmlNode lNode in lNodeList)
                {
                    string lAgentsWithoutBlanks = UtilFunctions.GetProtectedXmlNodeValue(configurationFile, lNode, "agents");
                    lAgentsWithoutBlanks = lAgentsWithoutBlanks.Replace(" ", string.Empty);
                    string[] lAgents = lAgentsWithoutBlanks.Split(lSeparators, StringSplitOptions.RemoveEmptyEntries);
                    // If connected agent is not in the list, skip that report.
                    if (lAgents.Length > 0 && !Logics.Logic.Agent.IsActiveFacet(lAgents))
                    {
                        continue;
                    }

                    // Get report info.
                    string lClass            = UtilFunctions.GetProtectedXmlNodeValue(configurationFile, lNode, "class");
                    string lReportTypeString = UtilFunctions.GetProtectedXmlNodeValue(configurationFile, lNode, "reporttype");

                    // If type is not supported, skip it.
                    ReportTypes lReportType = ReportTypes.Unknown;
                    switch (lReportTypeString.ToUpper())
                    {
                    case "WORD":
                        lReportType = ReportTypes.Word;
                        break;

                    case "EXCEL":
                        lReportType = ReportTypes.Excel;
                        break;

                    case "CRYSTAL":
                        lReportType = ReportTypes.CrystalReports;
                        break;

                    case "RDLC":
                        lReportType = ReportTypes.RDLC;
                        break;
                    }
                    if (lReportType == ReportTypes.Unknown)
                    {
                        continue;
                    }

                    string lDataSetFileName = UtilFunctions.GetProtectedXmlNodeValue(configurationFile, lNode, "datasetfile");

                    // Get complete filename.
                    if (File.Exists(lDataSetFileName))
                    {
                        FileInfo lDataSetFile = new FileInfo(lDataSetFileName);
                        lDataSetFileName = lDataSetFile.FullName;
                    }

                    // Get language information.
                    XmlNodeList lLanguageNodeList = lNode.SelectNodes("Language");
                    bool        lExistLanguage    = false;
                    string      lAlias            = "";
                    string      lReportFileName   = "";
                    foreach (XmlNode lNodeLanguage in lLanguageNodeList)
                    {
                        string lLanguageKey = UtilFunctions.GetProtectedXmlNodeValue(configurationFile, lNodeLanguage, "key");
                        if (lLanguageKey.Length == 0 ||
                            lLanguageKey.Equals(CultureManager.Culture.Name, StringComparison.InvariantCultureIgnoreCase))
                        {
                            lAlias          = UtilFunctions.GetProtectedXmlNodeValue(configurationFile, lNodeLanguage, "alias");
                            lReportFileName = UtilFunctions.GetProtectedXmlNodeValue(configurationFile, lNodeLanguage, "reportfilepath");
                            lExistLanguage  = true;
                            break;
                        }
                    }

                    // If report is not for current language, skip it.
                    if (!lExistLanguage)
                    {
                        continue;
                    }

                    if (File.Exists(lReportFileName))
                    {
                        FileInfo lReportFile = new FileInfo(lReportFileName);
                        lReportFileName = lReportFile.FullName;
                    }

                    // Add instance report info to the list.
                    ReportConfiguration lReport = new ReportConfiguration(lCode.ToString(), lAlias, lClass, lReportFileName, lReportType, lDataSetFileName);
                    Reports.Add(lReport);
                    lCode++;
                }
            }
            catch (Exception e)
            {
                Exception excProcessingFile = new Exception(CultureManager.TranslateString(LanguageConstantKeys.L_ERROR_LOADING_REPORTSCONFIG, LanguageConstantValues.L_ERROR_LOADING_REPORTSCONFIG), e);
                Presentation.ScenarioManager.LaunchErrorScenario(excProcessingFile);
            }
        }
Example #18
0
        protected void BoundItem(RepeaterItemPedido item)
        {
            const string cell = "<td class=\"number\">{0}</td>";

            var tickets = DAOFactory.TicketDAO.GetByPedido(new[] { cbEmpresa.Selected },
                                                           new[] { cbLinea.Selected },
                                                           new[] { item.Pedido.Id })
                          .OrderBy(p => p.Vehiculo);

            Carga = Convert.ToDouble(tickets.First().CantidadCarga);
            var cantidad = item.Pedido.Cantidad + item.Pedido.CantidadAjuste;

            CantidadMixers = 0;
            var ultimoVehiculo = 0;

            foreach (var ticket in tickets)
            {
                if (ticket.Vehiculo != null && ticket.Vehiculo.Id != ultimoVehiculo)
                {
                    CantidadMixers++;
                    ultimoVehiculo = ticket.Vehiculo.Id;
                }
            }

            var movilesNecesarios = Math.Ceiling(Math.Min(cantidad / Carga, item.Pedido.TiempoCiclo * 1.0 / item.Pedido.Frecuencia));

            item.lblPedido.Text = item.Pedido.Codigo;
            item.lblPedido.Attributes.Add("id", item.Pedido.Id.ToString("#0"));
            item.lblHoraCarga.Text = item.Pedido.HoraCarga.ToDisplayDateTime().ToString("HH:mm");
            item.lblEnObra.Text    = item.Pedido.FechaEnObra.ToDisplayDateTime().ToString("HH:mm");
            item.lblEnObra.Attributes.Add("estado", item.Pedido.Estado == Pedido.Estados.Pendiente ? "0" : "1");
            item.lblCliente.Text           = item.Pedido.Cliente.Descripcion;
            item.lblPuntoEntrega.Text      = item.Pedido.PuntoEntrega.Descripcion;
            item.LblContacto.Text          = item.Pedido.Contacto;
            item.LblObservacion.Text       = item.Pedido.Observacion;
            item.lblProducto.Text          = item.Pedido.Producto != null ? item.Pedido.Producto.Descripcion : "";
            item.lblCantidad.Text          = cantidad.ToString("0.00");
            item.lblBomba.Text             = item.Pedido.NumeroBomba;
            item.LblEsMinimixer.Text       = item.Pedido.EsMinimixer ? CultureManager.GetLabel("SI") : CultureManager.GetLabel("NO");
            item.lblTiempoCiclo.Text       = FormatTimeSpan(TimeSpan.FromMinutes(item.Pedido.TiempoCiclo));
            item.lblFrecuencia.Text        = FormatTimeSpan(TimeSpan.FromMinutes(item.Pedido.Frecuencia));
            item.lblMovilesNecesarios.Text = movilesNecesarios.ToString("0");
            item.hidId.Value   = item.Pedido.Id.ToString("#0");
            item.litStyle.Text = item.Pedido.Estado == Pedido.Estados.Pendiente ? "pendiente" : "generado";

            var cargaPorHora = GetCargaPorHora(item);

            foreach (var cargaHora in cargaPorHora)
            {
                var val = cargaHora.Value;
                item.litHoras.Text += string.Format(cell, val == 0 ? string.Empty : val.ToString());

                if (val > 0)
                {
                    var hora = cargaHora.Key;

                    if (_volumenPorHora.ContainsKey(hora))
                    {
                        _volumenPorHora[hora] += val;
                    }
                    else
                    {
                        _volumenPorHora.Add(hora, val);
                    }
                }
            }

            _tiempoCiclos.Add(cantidad * item.Pedido.TiempoCiclo);
            CantidadTotal += cantidad;
        }
Example #19
0
        /// <summary>
        /// Binds tarifas.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RepeaterTarifas_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var param = e.Item.DataItem as TarifaTransportista;

            var txtCorto         = e.Item.FindControl("txtTarifaCorto") as TextBox;
            var txtLargo         = e.Item.FindControl("txtTarifaLargo") as TextBox;
            var txtCostoBulto    = e.Item.FindControl("txtCostoBulto") as TextBox;
            var txtCostoHora     = e.Item.FindControl("txtCostoHora") as TextBox;
            var txtCostoKm       = e.Item.FindControl("txtCostoKm") as TextBox;
            var cbCliente        = e.Item.FindControl("cbCliente") as DropDownList;
            var btEliminarTarifa = e.Item.FindControl("btEliminarTarifa") as LinkButton;

            if (btEliminarTarifa != null)
            {
                btEliminarTarifa.OnClientClick = "return confirm('" + CultureManager.GetSystemMessage("CONFIRM_OPERATION") + "');";
            }

            BindClientes(cbCliente);

            if (param == null)
            {
                return;
            }

            if (txtCorto != null)
            {
                txtCorto.Text = param.TarifaTramoCorto.ToString();
            }
            if (txtLargo != null)
            {
                txtLargo.Text = param.TarifaTramoLargo.ToString();
            }
            if (txtCostoBulto != null)
            {
                txtCostoBulto.Text = param.CostoPorBulto.ToString();
            }
            if (txtCostoHora != null)
            {
                txtCostoHora.Text = param.CostoPorHora.ToString();
            }
            if (txtCostoKm != null)
            {
                txtCostoKm.Text = param.CostoPorKm.ToString();
            }

            if (param.Cliente == null)
            {
                return;
            }

            if (cbCliente == null)
            {
                return;
            }

            var li = cbCliente.Items.FindByValue(param.Cliente.Id.ToString());

            if (li != null)
            {
                li.Selected = true;
            }
        }
Example #20
0
 protected void SetCsvSessionVars(string csv)
 {
     Session["CSV_EXPORT"]    = csv;
     Session["CSV_FILE_NAME"] = CultureManager.GetMenu(Module.Name);
 }
 public static string GetLocalizationValue(this IRequestHandler requestHandler, int dictionaryId)
 {
     return(requestHandler.GetLocalizationValue(dictionaryId, CultureManager.GetCurrentCulture(requestHandler.Storage).Id));
 }
Example #22
0
        public static long Add(string catalog, DateTime valueDate, DateTime bookDate, int officeId, int userId,
                               long loginId, int costCenterId, string referenceNumber, Collection <JournalDetail> details,
                               Collection <Attachment> attachments)
        {
            if (details == null)
            {
                throw new InvalidOperationException(Errors.NoTransactionToPost);
            }

            if (details.Count.Equals(0))
            {
                throw new InvalidOperationException(Errors.NoTransactionToPost);
            }

            decimal debitTotal  = (from detail in details select detail.LocalCurrencyDebit).Sum();
            decimal creditTotal = (from detail in details select detail.LocalCurrencyCredit).Sum();

            if (debitTotal != creditTotal)
            {
                throw new InvalidOperationException(Errors.ReferencingSidesNotEqual);
            }

            int decimalPlaces = CultureManager.GetCurrencyDecimalPlaces();

            if ((from detail in details
                 where
                 decimal.Round(detail.Credit * detail.ExchangeRate, decimalPlaces) !=
                 decimal.Round(detail.LocalCurrencyCredit, decimalPlaces) ||
                 decimal.Round(detail.Debit * detail.ExchangeRate, decimalPlaces) !=
                 decimal.Round(detail.LocalCurrencyDebit, decimalPlaces)
                 select detail).Any())
            {
                throw new InvalidOperationException(Errors.ReferencingSidesNotEqual);
            }

            using (NpgsqlConnection connection = new NpgsqlConnection(DbConnection.GetConnectionString(catalog)))
            {
                connection.Open();

                using (NpgsqlTransaction transaction = connection.BeginTransaction())
                {
                    try
                    {
                        string sql =
                            "INSERT INTO transactions.transaction_master(transaction_master_id, transaction_counter, transaction_code, book, value_date, book_date, user_id, login_id, office_id, cost_center_id, reference_number) SELECT nextval(pg_get_serial_sequence('transactions.transaction_master', 'transaction_master_id')), transactions.get_new_transaction_counter(@ValueDate), transactions.get_transaction_code(@ValueDate, @OfficeId, @UserId, @LoginId), @Book, @ValueDate, @BookDate, @UserId, @LoginId, @OfficeId, @CostCenterId, @ReferenceNumber;SELECT currval(pg_get_serial_sequence('transactions.transaction_master', 'transaction_master_id'));";
                        long transactionMasterId;
                        using (NpgsqlCommand master = new NpgsqlCommand(sql, connection))
                        {
                            master.Parameters.AddWithValue("@ValueDate", valueDate);
                            master.Parameters.AddWithValue("@BookDate", bookDate);
                            master.Parameters.AddWithValue("@OfficeId", officeId);
                            master.Parameters.AddWithValue("@UserId", userId);
                            master.Parameters.AddWithValue("@LoginId", loginId);
                            master.Parameters.AddWithValue("@Book", "Journal");
                            master.Parameters.AddWithValue("@CostCenterId", costCenterId);
                            master.Parameters.AddWithValue("@ReferenceNumber", referenceNumber);

                            transactionMasterId = Conversion.TryCastLong(master.ExecuteScalar());
                        }

                        foreach (JournalDetail model in details)
                        {
                            sql =
                                "INSERT INTO transactions.transaction_details(value_date, transaction_master_id, tran_type, account_id, statement_reference, cash_repository_id, currency_code, amount_in_currency, local_currency_code, er, amount_in_local_currency) " +
                                "SELECT @ValueDate, @TransactionMasterId, @TranType, core.get_account_id_by_account_number(@AccountNumber::text), @StatementReference, office.get_cash_repository_id_by_cash_repository_code(@CashRepositoryCode), @CurrencyCode, @AmountInCurrency, transactions.get_default_currency_code_by_office_id(@OfficeId), @Er, @AmountInLocalCurrency;";

                            if (model.Credit > 0 && model.Debit > 0)
                            {
                                throw new InvalidOperationException(Errors.BothSidesCannotHaveValue);
                            }

                            if (model.LocalCurrencyCredit > 0 && model.LocalCurrencyDebit > 0)
                            {
                                throw new InvalidOperationException(Errors.BothSidesCannotHaveValue);
                            }

                            decimal amountInCurrency;
                            decimal amountInLocalCurrency;

                            string tranType;

                            if (model.Credit.Equals(0) && model.Debit > 0)
                            {
                                tranType              = "Dr";
                                amountInCurrency      = model.Debit;
                                amountInLocalCurrency = model.LocalCurrencyDebit;
                            }
                            else
                            {
                                tranType              = "Cr";
                                amountInCurrency      = model.Credit;
                                amountInLocalCurrency = model.LocalCurrencyCredit;
                            }

                            using (NpgsqlCommand transactionDetail = new NpgsqlCommand(sql, connection))
                            {
                                transactionDetail.Parameters.AddWithValue("@ValueDate", valueDate);
                                transactionDetail.Parameters.AddWithValue("@TransactionMasterId", transactionMasterId);
                                transactionDetail.Parameters.AddWithValue("@TranType", tranType);
                                transactionDetail.Parameters.AddWithValue("@AccountNumber", model.AccountNumber);
                                transactionDetail.Parameters.AddWithValue("@StatementReference",
                                                                          model.StatementReference);
                                transactionDetail.Parameters.AddWithValue("@CashRepositoryCode",
                                                                          model.CashRepositoryCode);
                                transactionDetail.Parameters.AddWithValue("@CurrencyCode", model.CurrencyCode);
                                transactionDetail.Parameters.AddWithValue("@AmountInCurrency", amountInCurrency);
                                transactionDetail.Parameters.AddWithValue("@OfficeId", officeId);
                                transactionDetail.Parameters.AddWithValue("@Er", model.ExchangeRate);
                                transactionDetail.Parameters.AddWithValue("@AmountInLocalCurrency",
                                                                          amountInLocalCurrency);
                                transactionDetail.ExecuteNonQuery();
                            }
                        }

                        #region Attachment

                        if (attachments != null && attachments.Count > 0)
                        {
                            foreach (Attachment attachment in attachments)
                            {
                                sql =
                                    "INSERT INTO core.attachments(user_id, resource, resource_key, resource_id, original_file_name, file_extension, file_path, comment) SELECT @UserId, @Resource, @ResourceKey, @ResourceId, @OriginalFileName, @FileExtension, @FilePath, @Comment;";
                                using (NpgsqlCommand attachmentCommand = new NpgsqlCommand(sql, connection))
                                {
                                    attachmentCommand.Parameters.AddWithValue("@UserId", userId);
                                    attachmentCommand.Parameters.AddWithValue("@Resource",
                                                                              "transactions.transaction_master");
                                    attachmentCommand.Parameters.AddWithValue("@ResourceKey", "transaction_master_id");
                                    attachmentCommand.Parameters.AddWithValue("@ResourceId", transactionMasterId);
                                    attachmentCommand.Parameters.AddWithValue("@OriginalFileName",
                                                                              attachment.OriginalFileName);
                                    attachmentCommand.Parameters.AddWithValue("@FileExtension",
                                                                              Path.GetExtension(attachment.OriginalFileName));
                                    attachmentCommand.Parameters.AddWithValue("@FilePath", attachment.FilePath);
                                    attachmentCommand.Parameters.AddWithValue("@Comment", attachment.Comment);

                                    attachmentCommand.ExecuteNonQuery();
                                }
                            }
                        }

                        #endregion Attachment

                        #region Auto Verification

                        sql = "SELECT * FROM transactions.auto_verify(@TranId::bigint, @OfficeId::integer);";
                        using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
                        {
                            command.Parameters.AddWithValue("@TranId", transactionMasterId);
                            command.Parameters.AddWithValue("@OfficeId", officeId);

                            command.ExecuteNonQuery();
                        }

                        #endregion

                        transaction.Commit();
                        return(transactionMasterId);
                    }
                    catch (NpgsqlException ex)
                    {
                        Log.Warning(
                            @"Could not post transaction. ValueDate: {ValueDate}, OfficeId: {OfficeId}, UserId: {UserId}, LoginId: {LoginId}, CostCenterId:{CostCenterId}, ReferenceNumber: {ReferenceNumber}, Details: {Details}, Attachments: {Attachments}. {Exception}.",
                            valueDate, officeId, userId, loginId, costCenterId, referenceNumber, details, attachments,
                            ex);
                        transaction.Rollback();
                        throw;
                    }
                    catch (InvalidOperationException ex)
                    {
                        Log.Warning(
                            @"Could not post transaction. ValueDate: {ValueDate}, OfficeId: {OfficeId}, UserId: {UserId}, LoginId: {LoginId}, CostCenterId:{CostCenterId}, ReferenceNumber: {ReferenceNumber}, Details: {Details}, Attachments: {Attachments}. {Exception}.",
                            valueDate, officeId, userId, loginId, costCenterId, referenceNumber, details, attachments,
                            ex);
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }
Example #23
0
        protected override void OnRowDataBound(C1GridView grid, C1GridViewRowEventArgs e, RankingVehiculosVo dataItem)
        {
            e.Row.Attributes.Remove("onclick");
            e.Row.Attributes.Add("cursor", "arrow");

            if (dataItem == null)
            {
                return;
            }

            GridUtils.GetCell(e.Row, RankingVehiculosVo.IndexPuntaje).BackColor    = GetColor(Convert.ToDouble(GridUtils.GetCell(e.Row, RankingVehiculosVo.IndexPuntaje).Text));
            GridUtils.GetCell(e.Row, RankingVehiculosVo.IndexKilometros).Text      = String.Format("{0:0.00}", dataItem.Kilometros);
            GridUtils.GetCell(e.Row, RankingVehiculosVo.IndexHorasMovimiento).Text = string.Format(CultureManager.GetLabel("MOVIMIENTO_SIN_EVENTOS"),
                                                                                                   dataItem.HorasMovimiento.Days,
                                                                                                   dataItem.HorasMovimiento.Hours,
                                                                                                   dataItem.HorasMovimiento.Minutes,
                                                                                                   dataItem.HorasMovimiento.Seconds);
        }
Example #24
0
        public static string GetFormattedValue(object value, string formatExpression = "")
        {
            string cellValue = value.ToString();

            if (value is DateTime)
            {
                var date = value.To <DateTime>();

                if (date.Date == date)
                {
                    return(date.ToString(formatExpression.Or("d")));
                }

                cellValue = date.ToLocalTime().ToString(formatExpression.Or("g"));
            }

            if (value is DateTimeOffset)
            {
                var date = value.To <DateTimeOffset>();

                if (date.Date == date)
                {
                    return(date.ToString(formatExpression.Or("d")));
                }

                cellValue = date.ToLocalTime().ToString(formatExpression.Or("g"));
            }

            if (value is decimal || value is double || value is float)
            {
                decimal amount = value.To <decimal>();

                cellValue = amount.ToString(formatExpression.Or("C"), CultureManager.GetCurrentUiCulture()).Replace(CultureManager.GetCurrentUiCulture().NumberFormat.CurrencySymbol, "");
            }

            return(HttpUtility.HtmlEncode(cellValue));
        }
Example #25
0
 protected TaskZeroSettings()
 {
     CultureManager = CultureManager.Empty();
 }
        protected override void CreateRowTemplate(C1GridViewRow row)
        {
            var lblEstado   = row.Cells[ViajeDistribucionVo.IndexEstado].FindControl("lblEstado") as ResourceLabel;
            var lnkIniciar  = row.Cells[ViajeDistribucionVo.IndexEstado].FindControl("lnkIniciar") as ResourceLinkButton;
            var lnkCerrar   = row.Cells[ViajeDistribucionVo.IndexEstado].FindControl("lnkCerrar") as ResourceLinkButton;
            var lnkReenviar = row.Cells[ViajeDistribucionVo.IndexEstado].FindControl("lnkReenviar") as ResourceLinkButton;
            var lnkAsociar  = row.Cells[ViajeDistribucionVo.IndexEstado].FindControl("lnkAsociar") as ResourceLinkButton;
            var lnkCombinar = row.Cells[ViajeDistribucionVo.IndexEstado].FindControl("lnkCombinar") as ResourceLinkButton;
            var cbVehiculo  = row.Cells[ViajeDistribucionVo.IndexVehiculo].FindControl("cbVehiculo") as DropDownList;

            if (lblEstado == null)
            {
                lblEstado = new ResourceLabel {
                    ResourceName = "Labels", ID = "lblEstado", Visible = false
                };
                row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(lblEstado);
            }

            if (lnkIniciar == null)
            {
                lnkIniciar = new ResourceLinkButton
                {
                    ResourceName    = "Labels",
                    ID              = "lnkIniciar",
                    CommandName     = "Start",
                    CommandArgument = row.RowIndex.ToString("#0"),
                    VariableName    = "DISTRIBUCION_INICIAR",
                    Visible         = false
                };
                row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(lnkIniciar);
            }

            row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(new Literal {
                Text = @"<br/>"
            });

            if (lnkAsociar == null)
            {
                lnkAsociar = new ResourceLinkButton
                {
                    ResourceName    = "Labels",
                    ID              = "lnkAsociar",
                    CommandName     = "Asociar",
                    CommandArgument = row.RowIndex.ToString("#0"),
                    VariableName    = "ASOCIAR_VEHICULO",
                    Visible         = false,
                    OnClientClick   = string.Concat("return confirm('", CultureManager.GetString("SystemMessages", "CONFIRM_OPERATION"), "');")
                };

                row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(lnkAsociar);
            }

            if (lnkCombinar == null)
            {
                lnkCombinar = new ResourceLinkButton
                {
                    ResourceName    = "Labels",
                    ID              = "lnkCombinar",
                    CommandName     = "Combinar",
                    CommandArgument = row.RowIndex.ToString("#0"),
                    VariableName    = "DISTRIBUCION_COMBINAR",
                    Visible         = false,
                    OnClientClick   = string.Concat("return confirm('", CultureManager.GetString("SystemMessages", "CONFIRM_OPERATION"), "');")
                };

                row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(lnkCombinar);
            }

            if (lnkCerrar == null)
            {
                lnkCerrar = new ResourceLinkButton
                {
                    ResourceName    = "Labels",
                    ID              = "lnkCerrar",
                    CommandName     = "Close",
                    CommandArgument = row.RowIndex.ToString("#0"),
                    VariableName    = "DISTRIBUCION_CERRAR",
                    Visible         = false,
                    OnClientClick   = string.Concat("return confirm('", CultureManager.GetString("SystemMessages", "CONFIRM_OPERATION"), "');")
                };

                row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(lnkCerrar);
            }

            if (lnkReenviar == null)
            {
                lnkReenviar = new ResourceLinkButton
                {
                    ResourceName    = "Labels",
                    ID              = "lnkReenviar",
                    CommandName     = "Reenviar",
                    CommandArgument = row.RowIndex.ToString("#0"),
                    VariableName    = "DISTRIBUCION_REENVIAR",
                    Visible         = false,
                    OnClientClick   = string.Concat("return confirm('", CultureManager.GetString("SystemMessages", "CONFIRM_OPERATION"), "');")
                };

                row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(new Literal {
                    Text = @"<br/>"
                });
                row.Cells[ViajeDistribucionVo.IndexEstado].Controls.Add(lnkReenviar);
            }

            if (cbVehiculo == null)
            {
                cbVehiculo = new DropDownList
                {
                    ID      = "cbVehiculo",
                    Visible = true
                };

                row.Cells[ViajeDistribucionVo.IndexVehiculo].Controls.Add(cbVehiculo);
            }

            cbVehiculo.SelectedIndexChanged += ComboOnSelectedIndexChanged;
            lnkIniciar.Command  += LnkbtnEstadoCommand;
            lnkCerrar.Command   += LnkbtnEstadoCommand;
            lnkReenviar.Command += LnkbtnEstadoCommand;
            lnkAsociar.Command  += LnkbtnEstadoCommand;
            lnkCombinar.Command += LnkbtnEstadoCommand;
        }
Example #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id;
                if (Request.QueryString["id"] == null || !int.TryParse(Request.QueryString["id"], out id))
                {
                    LblInfo.Text = CultureManager.GetError("NO_ENTREGA_INFO");
                    return;
                }

                var entrega = DAOFactory.EntregaDistribucionDAO.FindById(id);
                if (entrega != null)
                {
                    lblEntrega.Text  = entrega.Descripcion;
                    lblViaje.Text    = entrega.Viaje.Codigo;
                    lblVehiculo.Text = entrega.Viaje.Vehiculo != null ? entrega.Viaje.Vehiculo.Interno : CultureManager.GetError("NO_VEHICLE_ASSIGNED");
                    lblEstado.Text   = CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado));
                    if (entrega.PuntoEntrega.Nomenclado)
                    {
                        lblDireccion.Text = entrega.PuntoEntrega.DireccionNomenclada;
                    }
                    else if (entrega.ReferenciaGeografica != null)
                    {
                        lblDireccion.Text = GeocoderHelper.GetDescripcionEsquinaMasCercana(entrega.ReferenciaGeografica.Latitude, entrega.ReferenciaGeografica.Longitude);
                    }
                    lblEntrada.Text = (entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("yyyy/MM/dd HH:mm") : string.Empty);
                    lblManual.Text  = (entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("yyyy/MM/dd HH:mm") : string.Empty);
                    lblSalida.Text  = (entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("yyyy/MM/dd HH:mm") : string.Empty);
                    lnkMonitorCiclo.Attributes.Add("id", entrega.Viaje.Id.ToString("#0"));
                }
            }
        }
Example #28
0
        public override IEnumerable <Object> GetObjects(IRequestHandler requestHandler, Object page, params KeyValuePair <string, string>[] args)
        {
            if (!this.HasArgument(args, "ClassId"))
            {
                return new Object[] { }
            }
            ;

            if (!this.HasArgument(args, "OrderBy") || !this.HasArgument(args, "Direction"))
            {
                return(requestHandler.Storage.GetRepository <IObjectRepository>().FilteredByClassId(this.GetIntArgument(args, "ClassId")));
            }

            int      orderBy   = this.GetIntArgument(args, "OrderBy");
            string   direction = this.GetStringArgument(args, "Direction");
            Member   member    = requestHandler.Storage.GetRepository <IMemberRepository>().WithKey(orderBy);
            DataType dataType  = requestHandler.Storage.GetRepository <IDataTypeRepository>().WithKey((int)member.PropertyDataTypeId);

            return(requestHandler.Storage.GetRepository <IObjectRepository>().FilteredByClassId(this.GetIntArgument(args, "ClassId"), dataType.StorageDataType, orderBy, direction, CultureManager.GetCurrentCulture(requestHandler.Storage).Id));
        }
    }
Example #29
0
        private void SetView(int view)
        {
            switch (view)
            {
            case Views.Vehiculos:
                ListControl.Set(null);
                gridVehiculos.DataSource = VehiculosPendientes;
                gridVehiculos.DataBind();
                IndexControl.Set(0);
                break;

            case Views.Control:
                if (!VehiculosSeleccionados.Any())
                {
                    ShowError(string.Format(CultureManager.GetError("MUST_SELECT_VALUE"), CultureManager.GetEntity("PARENTI03")));
                    SetView(Views.Vehiculos);
                    return;
                }
                if (ListControl.Get() == null)
                {
                    var viajes = GetDistribuciones(VehiculosSeleccionados).Where(x => !x.Controlado).Select(v => v.Id).ToList();
                    ListControl.Set(viajes);
                    CountControl.Set(viajes.Count);
                }
                var index = IndexControl.Get();
                var count = CountControl.Get();

                var viaje = GetDistribucionAControlar(index);
                BindViaje(viaje);

                txtIndexControl.Text = (index + 1).ToString("#0");
                lblCountControl.Text = count.ToString("#0");
                btSiguiente.Visible  = index < count - 1;
                btAnterior.Visible   = index > 0;

                break;

            case Views.Resumen:
                var distribuciones = GetDistribuciones(new[] { -1 });
                var controladas    = distribuciones.Where(d => d.Controlado).Select(d => new ViajeDistribucionVo(d)).ToList();
                //var noControladas = distribuciones.Where(d => !d.Controlado).ToList();

                gridResumen.GroupedColumns.Clear();
                gridResumen.GroupedColumns.Add(gridResumen.Columns[0] as C1Field);
                gridResumen.DataSource = controladas;
                gridResumen.DataBind();
                break;
            }

            tab.ActiveTabIndex  = view;
            updCompleto.Visible = true;
            updCompleto.Update();
        }
Example #30
0
        private void OnDownloadProgress(object sender, DownloadProgressChangedEventArgs e)
        {
            string message = string.Format(CultureManager.GetCurrent(), Labels.PercentCompleted, e.ProgressPercentage);

            this.OnProgress(new ProgressInfo(this.Description, message));
        }
        internal static void ScheduleGames(ref List<Matchup> matchups, DateTime dts, TimeSpan timeWindowStart, int gamesPerDay, Guid orgId, int openDaysBitMask)
        {
            int numberOfGamesCounter = 1;
            int minutesPerGame = 15;
            CultureManager cultureManager = new CultureManager(orgId, openDaysBitMask);
            IEnumerator<DateTime> dayEnumerator = cultureManager.GetNextBusinessDay(dts).GetEnumerator();
            DateTime dt;
            int currentRound = 0;
            foreach (Matchup mu in matchups)
            {
                if (numberOfGamesCounter == gamesPerDay || mu.Round != currentRound)
                {
                    dayEnumerator.MoveNext();
                    dts = dayEnumerator.Current;
                    dts = new DateTime(dts.Year, dts.Month, dts.Day);
                    dts = dts.Add(timeWindowStart);
                    numberOfGamesCounter = 0;
                }

                mu.Start = dts;
                numberOfGamesCounter++;
                dts = dts.AddMinutes(minutesPerGame);
                mu.End = dts;
                currentRound = mu.Round;
            }
        }