Пример #1
0
 public NuevoInsumo(CommonUtils.Insumo insumoAModificar)
 {
     InitializeComponent();
     insumo = insumoAModificar;
     CargarDatosInsumo();
     CargarListaInsumos();            
 }
Пример #2
0
 public PnlNuevaReceta(CommonUtils.Receta recetaAModificar)
 {
     InitializeComponent();
     InitConexionDB();            
     this.receta = recetaAModificar;
     CargarDatosDeReceta();
     CargarDataGridControlListaRecetas();
 }
Пример #3
0
        public NuevaDosificacion( CommonUtils.Dosificacion dosificacion )
        {
            InitializeComponent( );
            log4net.Config.XmlConfigurator.Configure( );
            InitConexionDB( );

            isUpdating = true;
            DosificacionID = dosificacion.DosificacionID;
            txtLlave.Text = dosificacion.Llave;
            txtAutorizacion.Text = dosificacion.Autorizacion;
            txtFactura.Text = dosificacion.NroFactura;
            dateFechaLimite.Text = Convert.ToDateTime( dosificacion.FechaLimite ).ToShortDateString( );
            checkBoxActiva.Checked = dosificacion.Activa == 1 ? true : false;
        }
Пример #4
0
        public DatosEmpresa( CommonUtils.Empresa empresa )
        {
            InitializeComponent( );
            log4net.Config.XmlConfigurator.Configure( );
            InitConexionDB( );

            isUpdating = true;
            txtDireccion.Text = empresa.Direccion;
            txtNIT.Text = empresa.NIT;
            txtNomEmpresa.Text = empresa.NombreEmpresa;
            txtRazonSocial.Text = empresa.RazonSocial;
            spinEdit.Text = empresa.SucursalNro.ToString( );
            txtTelefono.Text = empresa.Telefono;
            txtRubro.Text = empresa.Rubro;
        }
Пример #5
0
        private void EstimatePitch()
        {
            var    gotPitch = false;
            double?f0       = null;

            while (true)
            {
                const int pitchWindowLength = 2048;

                var rms = 0.0;

                var ok = this._sampleBuffer.Read(pitchWindowLength, segment =>
                {
                    foreach (var x in segment)
                    {
                        rms += x * x;
                    }
                    rms = Math.Sqrt(rms / pitchWindowLength);

                    f0 = McLeodPitchMethod.EstimateFundamentalFrequency(this._waveIn.WaveFormat.SampleRate, segment);
                });

                if (!ok)
                {
                    break;      // バッファーをすべて読み終わった
                }
                gotPitch = true;

                if (f0.HasValue && this._store.IsKeyEstimationRunning)
                {
                    // クロマベクトルに反映
                    var m = CommonUtils.ToChromaIndex(CommonUtils.HzToMidiNote(f0.Value));
                    this._chromaVector[m] += rms;
                }
            }

            if (gotPitch)
            {
                this._store.EstimatedPitch = f0;
            }

            if (gotPitch && this._store.IsKeyEstimationRunning)
            {
                // キー推定
                this._store.EstimatedKey = KeyFinding.FindKey(this._chromaVector);
            }

            if (f0.HasValue && (this._store.IsUpperHarmonyEnabled || this._store.IsLowerHarmonyEnabled))
            {
                var key = this._store.EstimatedKey;
                if (key.HasValue)
                {
                    var baseScale = key.Value.Mode == KeyMode.Major ? s_majorScale : s_minorScale;
                    var scale     = new bool[12];
                    for (var i = 0; i < scale.Length; i++)
                    {
                        scale[i] = baseScale[(key.Value.Tonic + i) % 12];
                    }

                    var noteNum = CommonUtils.HzToMidiNote(f0.Value);
                    var m       = CommonUtils.ToChromaIndex(noteNum);

                    if (scale[m])
                    {
                        // スケール内の音なら、ハモる音高を求める

                        if (this._store.IsUpperHarmonyEnabled)
                        {
                            // スケール内で3度上の音を探す
                            var harmonyNoteNum = noteNum + 1;
                            for (var i = 0; i < 2; harmonyNoteNum++)
                            {
                                if (scale[CommonUtils.ToChromaIndex(harmonyNoteNum)])
                                {
                                    i++;
                                }
                            }

                            var freq = CommonUtils.MidiNoteToHz(harmonyNoteNum);
                            this._upperHarmonyPlayer.SetPitchFactor((float)(freq / f0.Value));
                        }

                        if (this._store.IsLowerHarmonyEnabled)
                        {
                            // スケール内で3度下の音を探す
                            var harmonyNoteNum = noteNum - 1;
                            for (var i = 0; i < 2; harmonyNoteNum--)
                            {
                                if (scale[CommonUtils.ToChromaIndex(harmonyNoteNum)])
                                {
                                    i++;
                                }
                            }

                            var freq = CommonUtils.MidiNoteToHz(harmonyNoteNum);
                            this._upperHarmonyPlayer.SetPitchFactor((float)(freq / f0.Value));
                        }
                    }
                }
            }
        }
Пример #6
0
 public SqlServerInsertOrUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression)
     : base(orm, commonUtils, commonExpression)
 {
 }
        /// <summary>
        /// Updates the expiration date and time for an existing ticket.  If the ticket does not exist in the ticket store, just return (do not throw an exception).
        /// </summary>
        /// <param name="casAuthenticationTicket">The CasAuthenticationTicket to insert</param>
        /// <param name="newExpiration">The new expiration date and time</param>
        /// <exception cref="ArgumentNullException">casAuthenticationTicket is null</exception>
        public void UpdateTicketExpiration(CasAuthenticationTicket casAuthenticationTicket, DateTime newExpiration)
        {
            CommonUtils.AssertNotNull(casAuthenticationTicket, "casAuthenticationTicket parameter cannot be null.");

            InsertTicket(casAuthenticationTicket, newExpiration);
        }
Пример #8
0
 public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere)
 {
 }
Пример #9
0
        public async Task <AuthenticateResponse> Authenticate(string token)
        {
            // Internal auth does not support token auth
            if (_appSettings.ExternalAuthUrl == null)
            {
                return(null);
            }

            var res = await _loginManager.CheckAccess(token);

            if (!res.Success)
            {
                return(null);
            }

            // Create user if not exists because login manager has greenlighed us
            var user = await _userManager.FindByNameAsync(res.UserName) ??
                       await CreateUserInternal(new User { UserName = res.UserName }, CommonUtils.RandomString(16));

            if (!user.Metadata.IsSameAs(res.Metadata))
            {
                user.Metadata = res.Metadata;
                await _applicationDbContext.SaveChangesAsync();
            }

            await SyncRoles(user);

            // authentication successful so generate jwt token
            var tokenDescriptor = await GenerateJwtToken(user);

            return(new AuthenticateResponse(user, tokenDescriptor.Token, tokenDescriptor.ExpiresOn));
        }
Пример #10
0
        internal static string ToSqlStatic(CommonUtils _commonUtils, CommonExpression _commonExpression, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List <SelectTableInfo> _tables, List <Dictionary <Type, string> > tbUnions, Func <Type, string, string> _aliasRule, string _tosqlAppendContent, List <GlobalFilter.Item> _whereGlobalFilter, IFreeSql _orm)
        {
            if (_orm.CodeFirst.IsAutoSyncStructure)
            {
                _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray());
            }

            if (_whereGlobalFilter.Any())
            {
                foreach (var tb in _tables.Where(a => a.Type != SelectTableInfoType.Parent))
                {
                    tb.Cascade = _commonExpression.GetWhereCascadeSql(tb, _whereGlobalFilter, true);
                }
            }

            var sb          = new StringBuilder();
            var tbUnionsGt0 = tbUnions.Count > 1;

            for (var tbUnionsIdx = 0; tbUnionsIdx < tbUnions.Count; tbUnionsIdx++)
            {
                if (tbUnionsIdx > 0)
                {
                    sb.Append("\r\n \r\nUNION ALL\r\n \r\n");
                }
                if (tbUnionsGt0)
                {
                    sb.Append(_select).Append(" * from (");
                }
                var tbUnion = tbUnions[tbUnionsIdx];

                var sbnav = new StringBuilder();
                sb.Append(_select);
                if (_distinct)
                {
                    sb.Append("DISTINCT ");
                }
                sb.Append(field);
                if (string.IsNullOrEmpty(_orderby) && _skip > 0)
                {
                    sb.Append(", ROWNUM AS \"__rownum__\"");
                }
                sb.Append(" \r\nFROM ");
                var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray();
                var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray();
                for (var a = 0; a < tbsfrom.Length; a++)
                {
                    sb.Append(_commonUtils.QuoteSqlName(tbUnion[tbsfrom[a].Table.Type])).Append(" ").Append(_aliasRule?.Invoke(tbsfrom[a].Table.Type, tbsfrom[a].Alias) ?? tbsfrom[a].Alias);
                    if (tbsjoin.Length > 0)
                    {
                        //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1
                        for (var b = 1; b < tbsfrom.Length; b++)
                        {
                            sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tbUnion[tbsfrom[b].Table.Type])).Append(" ").Append(_aliasRule?.Invoke(tbsfrom[b].Table.Type, tbsfrom[b].Alias) ?? tbsfrom[b].Alias);

                            if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On) && string.IsNullOrEmpty(tbsfrom[b].Cascade))
                            {
                                sb.Append(" ON 1 = 1");
                            }
                            else
                            {
                                var onSql = tbsfrom[b].NavigateCondition ?? tbsfrom[b].On;
                                sb.Append(" ON ").Append(onSql);
                                if (string.IsNullOrEmpty(tbsfrom[b].Cascade) == false)
                                {
                                    if (string.IsNullOrEmpty(onSql))
                                    {
                                        sb.Append(tbsfrom[b].Cascade);
                                    }
                                    else
                                    {
                                        sb.Append(" AND ").Append(tbsfrom[b].Cascade);
                                    }
                                }
                            }
                        }
                        break;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition))
                        {
                            sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")");
                        }
                        if (!string.IsNullOrEmpty(tbsfrom[a].On))
                        {
                            sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")");
                        }
                        if (a > 0 && !string.IsNullOrEmpty(tbsfrom[a].Cascade))
                        {
                            sbnav.Append(" AND ").Append(tbsfrom[a].Cascade);
                        }
                    }
                    if (a < tbsfrom.Length - 1)
                    {
                        sb.Append(", ");
                    }
                }
                foreach (var tb in tbsjoin)
                {
                    if (tb.Type == SelectTableInfoType.Parent)
                    {
                        continue;
                    }
                    switch (tb.Type)
                    {
                    case SelectTableInfoType.LeftJoin:
                        sb.Append(" \r\nLEFT JOIN ");
                        break;

                    case SelectTableInfoType.InnerJoin:
                        sb.Append(" \r\nINNER JOIN ");
                        break;

                    case SelectTableInfoType.RightJoin:
                        sb.Append(" \r\nRIGHT JOIN ");
                        break;
                    }
                    sb.Append(_commonUtils.QuoteSqlName(tbUnion[tb.Table.Type])).Append(" ").Append(_aliasRule?.Invoke(tb.Table.Type, tb.Alias) ?? tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition);
                    if (!string.IsNullOrEmpty(tb.Cascade))
                    {
                        sb.Append(" AND ").Append(tb.Cascade);
                    }
                    if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition))
                    {
                        sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")");
                    }
                }
                if (_join.Length > 0)
                {
                    sb.Append(_join);
                }

                sbnav.Append(_where);
                if (!string.IsNullOrEmpty(_tables[0].Cascade))
                {
                    sbnav.Append(" AND ").Append(_tables[0].Cascade);
                }

                if (string.IsNullOrEmpty(_orderby) && (_skip > 0 || _limit > 0))
                {
                    sbnav.Append(" AND ROWNUM < ").Append(_skip + _limit + 1);
                }
                if (sbnav.Length > 0)
                {
                    sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5));
                }
                if (string.IsNullOrEmpty(_groupby) == false)
                {
                    sb.Append(_groupby);
                    if (string.IsNullOrEmpty(_having) == false)
                    {
                        sb.Append(" \r\nHAVING ").Append(_having.Substring(5));
                    }
                }
                sb.Append(_orderby);

                if (string.IsNullOrEmpty(_orderby))
                {
                    if (_skip > 0)
                    {
                        sb.Insert(0, $"{_select} t.* FROM (").Append(") t WHERE t.\"__rownum__\" > ").Append(_skip);
                    }
                }
                else
                {
                    if (_skip > 0 && _limit > 0)
                    {
                        sb.Insert(0, $"{_select} t.* FROM (SELECT rt.*, ROWNUM AS \"__rownum__\" FROM (").Append(") rt WHERE ROWNUM < ").Append(_skip + _limit + 1).Append(") t WHERE t.\"__rownum__\" > ").Append(_skip);
                    }
                    else if (_skip > 0)
                    {
                        sb.Insert(0, $"{_select} t.* FROM (").Append(") t WHERE ROWNUM > ").Append(_skip);
                    }
                    else if (_limit > 0)
                    {
                        sb.Insert(0, $"{_select} t.* FROM (").Append(") t WHERE ROWNUM < ").Append(_limit + 1);
                    }
                }

                sbnav.Clear();
                if (tbUnionsGt0)
                {
                    sb.Append(") ftb");
                }
            }
            return(sb.Append(_tosqlAppendContent).ToString());
        }
Пример #11
0
        //categoria 5 es para combo
        private bool esPosibleBorrarReceta(CommonUtils.Receta recipe)
        {
            //string sqlQuery="select RecetaId from Producto where ProductoId in (Select ProductoId from Producto_Producto where ComboId=12) "
            string sqlQuery="select RecetaId from Receta where RecetaId="+recipe.idReceta+" and RecetaId in (select RecetaId from Producto where CategoriaId!=5)";
            if (CommonUtils.ConexionBD.EjecutarConsulta(sqlQuery).Rows.Count > 0)
            {
                return false;
            }
            sqlQuery = "Select RecetaId from Producto where RecetaId="+recipe.idReceta+" and ProductoId in( Select ProductoId from Producto_Producto where ComboId in (Select ProductoId from Producto where CategoriaId=5))";

            if (CommonUtils.ConexionBD.EjecutarConsulta(sqlQuery).Rows.Count > 0)
            {
                return false;
            }
            return true;
        }
        public void Test()
        {
            var expectedMetrics = new List <Assertions.ExpectedMetric>
            {
                //transactions
                new Assertions.ExpectedMetric {
                    metricName = @"WebTransaction/MVC/Home/Index", callCount = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"WebTransaction/Custom/MyCustomChangeMetricName", callCount = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"WebTransaction/Custom/MyCustomRenamedMetricName", callCount = 1
                },

                // Unscoped
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/HomeController/Index", callCount = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"Custom/MyCustomChangeMetricName", callCount = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"Custom/MyCustomRenamedMetricName", callCount = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/RejitController/GetChangeAttributeValue", callCount = 2
                },

                // Scoped
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/HomeController/Index", metricScope = "WebTransaction/MVC/Home/Index", callCount = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"Custom/MyCustomChangeMetricName", metricScope = "WebTransaction/Custom/MyCustomChangeMetricName", callCount = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"Custom/MyCustomRenamedMetricName", metricScope = "WebTransaction/Custom/MyCustomRenamedMetricName", callCount = 1
                }
            };

            var notExpectedMetrics = new List <Assertions.ExpectedMetric>
            {
                //transactions
                new Assertions.ExpectedMetric {
                    metricName = @"WebTransaction/MVC/Rejit/GetChangeAttributeValue"
                },

                // Scoped
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/RejitController/GetChangeAttributeValue", metricScope = "WebTransaction/MVC/Rejit/GetChangeAttributeValue"
                }
            };

            var metrics = CommonUtils.GetMetrics(_fixture.AgentLog);

            _fixture.TestLogger?.WriteLine(_fixture.AgentLog.GetFullLogAsString());

            NrAssert.Multiple(
                () => Assertions.MetricsExist(expectedMetrics, metrics),
                () => Assertions.MetricsDoNotExist(notExpectedMetrics, metrics)
                );
        }
Пример #13
0
        // cli argument processor
        private static void ProcessArguments()
        {
            if (IsHelpUsagePatternMode)
            {
                Console.WriteLine(UsagePatterns.Replace("\t", "    "));
            }

            else if (IsVersionMode)
            {
                PyRevitCLIAppCmds.PrintVersion(checkUpdates: true);
            }

            else if (all("wiki"))
            {
                CommonUtils.OpenUrl(PyRevitLabsConsts.WikiUrl);
            }

            else if (all("blog"))
            {
                CommonUtils.OpenUrl(PyRevitLabsConsts.BlogsUrl);
            }

            else if (all("docs"))
            {
                CommonUtils.OpenUrl(PyRevitLabsConsts.DocsUrl);
            }

            else if (all("source"))
            {
                CommonUtils.OpenUrl(PyRevitLabsConsts.SourceRepoUrl);
            }

            else if (all("youtube"))
            {
                CommonUtils.OpenUrl(PyRevitLabsConsts.YoutubeUrl);
            }

            else if (all("support"))
            {
                CommonUtils.OpenUrl(PyRevitLabsConsts.SupportUrl);
            }

            else if (all("env"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Env);
                }
                else
                {
                    PyRevitCLIAppCmds.MakeEnvReport(json: arguments["--json"].IsTrue);
                }
            }

            else if (all("update") && !any("clones", "extensions"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Update);
                }
                else
                {
                    PyRevitCLIAppCmds.UpdateRemoteDataSources();
                }
            }

            else if (all("clone"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Clone);
                }
                else
                {
                    PyRevitCLICloneCmds.CreateClone(
                        cloneName: TryGetValue("<clone_name>"),
                        deployName: TryGetValue("<deployment_name>"),
                        branchName: TryGetValue("--branch"),
                        repoUrl: TryGetValue("--source"),
                        imagePath: TryGetValue("--image"),
                        destPath: TryGetValue("--dest"),
                        credentials: TryGetCredentials()
                        );
                }
            }

            else if (all("clones"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Clones);
                }

                else if (all("info"))
                {
                    PyRevitCLICloneCmds.PrintCloneInfo(TryGetValue("<clone_name>"));
                }

                else if (all("open"))
                {
                    PyRevitCLICloneCmds.OpenClone(TryGetValue("<clone_name>"));
                }

                else if (all("add"))
                {
                    if (all("this"))
                    {
                        PyRevitCLICloneCmds.RegisterClone(
                            TryGetValue("<clone_name>"),
                            Path.GetDirectoryName(CLIPath),
                            force: arguments["--force"].IsTrue
                            );
                    }
                    else
                    {
                        PyRevitCLICloneCmds.RegisterClone(
                            TryGetValue("<clone_name>"),
                            TryGetValue("<clone_path>"),
                            force: arguments["--force"].IsTrue
                            );
                    }
                }

                else if (all("forget"))
                {
                    PyRevitCLICloneCmds.ForgetClone(
                        allClones: arguments["--all"].IsTrue,
                        cloneName: TryGetValue("<clone_name>")
                        );
                }

                else if (all("rename"))
                {
                    PyRevitCLICloneCmds.RenameClone(
                        cloneName: TryGetValue("<clone_name>"),
                        cloneNewName: TryGetValue("<clone_new_name>")
                        );
                }

                else if (all("delete"))
                {
                    PyRevitCLICloneCmds.DeleteClone(
                        allClones: arguments["--all"].IsTrue,
                        cloneName: TryGetValue("<clone_name>"),
                        clearConfigs: arguments["--clearconfigs"].IsTrue
                        );
                }

                else if (all("branch"))
                {
                    PyRevitCLICloneCmds.GetSetCloneBranch(
                        cloneName: TryGetValue("<clone_name>"),
                        branchName: TryGetValue("<branch_name>")
                        );
                }

                else if (all("version"))
                {
                    PyRevitCLICloneCmds.GetSetCloneTag(
                        cloneName: TryGetValue("<clone_name>"),
                        tagName: TryGetValue("<tag_name>")
                        );
                }

                else if (all("commit"))
                {
                    PyRevitCLICloneCmds.GetSetCloneCommit(
                        cloneName: TryGetValue("<clone_name>"),
                        commitHash: TryGetValue("<commit_hash>")
                        );
                }

                else if (all("origin"))
                {
                    PyRevitCLICloneCmds.GetSetCloneOrigin(
                        cloneName: TryGetValue("<clone_name>"),
                        originUrl: TryGetValue("<origin_url>"),
                        reset: arguments["--reset"].IsTrue
                        );
                }

                else if (all("deployments"))
                {
                    PyRevitCLICloneCmds.PrintCloneDeployments(TryGetValue("<clone_name>"));
                }

                else if (all("engines"))
                {
                    PyRevitCLICloneCmds.PrintCloneEngines(TryGetValue("<clone_name>"));
                }

                else if (all("update"))
                {
                    PyRevitCLICloneCmds.UpdateClone(
                        allClones: arguments["--all"].IsTrue,
                        cloneName: TryGetValue("<clone_name>"),
                        credentials: TryGetCredentials()
                        );
                }

                else
                {
                    PyRevitCLICloneCmds.PrintClones();
                }
            }

            else if (all("attach"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Attach);
                }
                else
                {
                    // get clone
                    var clone = PyRevitClones.GetRegisteredClone(TryGetValue("<clone_name>"));

                    // determine version
                    var engStrVer = TryGetValue("<engine_version>");
                    PyRevitEngineVersion engineVersion = null;
                    if (arguments["default"].IsTrue)
                    {
                        engineVersion = PyRevitEngineVersion.Default;
                    }
                    else
                    {
                        // try parse the engine version as an integer e.g. 277 for 2.7.7
                        if (int.TryParse(engStrVer, out var engIntVer))
                        {
                            engineVersion = (PyRevitEngineVersion)engIntVer;
                        }
                    }

                    if (engineVersion is null)
                    {
                        // then engine must be an engine id
                        PyRevitCLICloneCmds.AttachClone(
                            clone: clone,
                            engineId: engStrVer,
                            revitYear: TryGetValue("<revit_year>"),
                            installed: arguments["--installed"].IsTrue,
                            attached: arguments["--attached"].IsTrue,
                            allUsers: arguments["--allusers"].IsTrue
                            );
                    }
                    else
                    {
                        PyRevitCLICloneCmds.AttachClone(
                            clone: clone,
                            engineVersion: engineVersion,
                            revitYear: TryGetValue("<revit_year>"),
                            installed: arguments["--installed"].IsTrue,
                            attached: arguments["--attached"].IsTrue,
                            allUsers: arguments["--allusers"].IsTrue
                            );
                    }
                }
            }

            else if (all("detach"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Detach);
                }
                else
                {
                    PyRevitCLICloneCmds.DetachClone(
                        revitYear: TryGetValue("<revit_year>"),
                        all: arguments["--all"].IsTrue,
                        currentAndAllUsers: true
                        );
                }
            }

            else if (all("attached"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Attached);
                }
                else
                {
                    PyRevitCLICloneCmds.ListAttachments(revitYear: TryGetValue("<revit_year>"));
                }
            }

            else if (all("switch"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Switch);
                }
                else
                {
                    PyRevitCLICloneCmds.SwitchAttachment(
                        cloneName: TryGetValue("<clone_name>"),
                        revitYear: TryGetValue("<revit_year>")
                        );
                }
            }

            else if (all("extend"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Extend);
                }

                else if (any("ui", "lib"))
                {
                    PyRevitCLIExtensionCmds.Extend(
                        ui: arguments["ui"].IsTrue,
                        lib: arguments["lib"].IsTrue,
                        extName: TryGetValue("<extension_name>"),
                        destPath: TryGetValue("--dest"),
                        repoUrl: TryGetValue("<repo_url>"),
                        branchName: TryGetValue("--branch"),
                        credentials: TryGetCredentials()
                        );
                }

                else
                {
                    PyRevitCLIExtensionCmds.Extend(
                        extName: TryGetValue("<extension_name>"),
                        destPath: TryGetValue("--dest"),
                        branchName: TryGetValue("--branch")
                        );
                }
            }

            else if (all("extensions"))
            {
                if (all("search"))
                {
                    PyRevitCLIExtensionCmds.PrintExtensionDefinitions(
                        searchPattern: TryGetValue("<search_pattern>"),
                        headerPrefix: "Matched"
                        );
                }

                else if (any("info", "help"))
                {
                    PyRevitCLIExtensionCmds.ProcessExtensionInfoCommands(
                        extName: TryGetValue("<extension_name>"),
                        info: arguments["info"].IsTrue,
                        help: arguments["help"].IsTrue
                        );
                }

                else if (all("open"))
                {
                    PyRevitCLIExtensionCmds.ProcessExtensionOpenCommand(
                        cloneName: TryGetValue("<clone_name>"),
                        extName: TryGetValue("<extension_name>")
                        );
                }

                else if (all("delete"))
                {
                    PyRevitCLIExtensionCmds.DeleteExtension(TryGetValue("<extension_name>"));
                }

                else if (all("origin"))
                {
                    PyRevitCLIExtensionCmds.GetSetExtensionOrigin(
                        extName: TryGetValue("<extension_name>"),
                        originUrl: TryGetValue("<origin_url>"),
                        reset: arguments["--reset"].IsTrue
                        );
                }

                else if (all("paths"))
                {
                    if (IsHelpMode)
                    {
                        PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.ExtensionsPaths);
                    }

                    else if (all("add"))
                    {
                        PyRevitCLIExtensionCmds.AddExtensionPath(
                            searchPath: TryGetValue("<extensions_path>")
                            );
                    }

                    else if (all("forget"))
                    {
                        PyRevitCLIExtensionCmds.ForgetAllExtensionPaths(
                            all: arguments["--all"].IsTrue,
                            searchPath: TryGetValue("<extensions_path>")
                            );
                    }

                    else
                    {
                        PyRevitCLIExtensionCmds.PrintExtensionSearchPaths();
                    }
                }

                else if (any("enable", "disable"))
                {
                    PyRevitCLIExtensionCmds.ToggleExtension(
                        enable: arguments["enable"].IsTrue,
                        cloneName: TryGetValue("<clone_name>"),
                        extName: TryGetValue("<extension_name>")
                        );
                }

                else if (all("sources"))
                {
                    if (IsHelpMode)
                    {
                        PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.ExtensionsSources);
                    }

                    else if (all("add"))
                    {
                        PyRevitCLIExtensionCmds.AddExtensionLookupSource(
                            lookupPath: TryGetValue("<source_json_or_url>")
                            );
                    }

                    else if (all("forget"))
                    {
                        PyRevitCLIExtensionCmds.ForgetExtensionLookupSources(
                            all: arguments["--all"].IsTrue,
                            lookupPath: TryGetValue("<source_json_or_url>")
                            );
                    }

                    else
                    {
                        PyRevitCLIExtensionCmds.PrintExtensionLookupSources();
                    }
                }

                else if (all("update"))
                {
                    PyRevitCLIExtensionCmds.UpdateExtension(
                        all: arguments["--all"].IsTrue,
                        extName: TryGetValue("<extension_name>"),
                        credentials: TryGetCredentials()
                        );
                }

                else if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Extensions);
                }

                else
                {
                    PyRevitCLIExtensionCmds.PrintExtensions();
                }
            }

            else if (all("releases"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Releases);
                }

                else if (all("open"))
                {
                    PyRevitCLIReleaseCmds.OpenReleasePage(
                        searchPattern: TryGetValue("<search_pattern>"),
                        latest: arguments["latest"].IsTrue,
                        listPreReleases: arguments["--pre"].IsTrue
                        );
                }

                else if (all("download"))
                {
                    PyRevitCLIReleaseCmds.DownloadReleaseAsset(
                        arguments["archive"].IsTrue ? GithubReleaseAssetType.Archive : GithubReleaseAssetType.Installer,
                        destPath: TryGetValue("--dest"),
                        searchPattern: TryGetValue("<search_pattern>"),
                        latest: arguments["latest"].IsTrue,
                        listPreReleases: arguments["--pre"].IsTrue
                        );
                }

                else
                {
                    PyRevitCLIReleaseCmds.PrintReleases(
                        searchPattern: TryGetValue("<search_pattern>"),
                        latest: arguments["latest"].IsTrue,
                        printReleaseNotes: arguments["--notes"].IsTrue,
                        listPreReleases: arguments["--pre"].IsTrue
                        );
                }
            }

            else if (all("revits"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Revits);
                }

                else if (all("killall"))
                {
                    PyRevitCLIRevitCmds.KillAllRevits(
                        revitYear: TryGetValue("<revit_year>")
                        );
                }

                else if (all("fileinfo"))
                {
                    PyRevitCLIRevitCmds.ProcessFileInfo(
                        targetPath: TryGetValue("<file_or_dir_path>"),
                        outputCSV: TryGetValue("--csv"),
                        IncludeRVT: arguments["--rvt"].IsTrue,
                        includeRTE: arguments["--rte"].IsTrue,
                        includeRFA: arguments["--rfa"].IsTrue,
                        includeRFT: arguments["--rft"].IsTrue
                        );
                }

                else if (arguments["--supported"].IsTrue)
                {
                    PyRevitCLIRevitCmds.ProcessBuildInfo(
                        outputCSV: TryGetValue("--csv")
                        );
                }

                else
                {
                    PyRevitCLIRevitCmds.PrintLocalRevits(running: arguments["--installed"].IsFalse);
                }
            }

            else if (all("run"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Run);
                }
                else if (all("commands"))
                {
                    PyRevitCLIRevitCmds.ListAvailableCommands();
                }
                else
                {
                    var modelList = TryGetValue("--models");
                    if (modelList != null)
                    {
                        PyRevitCLIRevitCmds.RunExtensionCommand(
                            commandName: TryGetValue("<script_or_command_name>"),
                            targetFile: modelList,
                            revitYear: TryGetValue("--revit"),
                            runOptions: new PyRevitRunnerOptions()
                        {
                            PurgeTempFiles = arguments["--purge"].IsTrue,
                            ImportPath     = TryGetValue("--import", null),
                            AllowDialogs   = arguments["--allowdialogs"].IsTrue
                        },
                            targetIsFileList: true
                            );
                    }
                    else
                    {
                        PyRevitCLIRevitCmds.RunExtensionCommand(
                            commandName: TryGetValue("<script_or_command_name>"),
                            targetFile: TryGetValue("<model_file>"),
                            revitYear: TryGetValue("--revit"),
                            runOptions: new PyRevitRunnerOptions()
                        {
                            PurgeTempFiles = arguments["--purge"].IsTrue,
                            ImportPath     = TryGetValue("--import", null),
                            AllowDialogs   = arguments["--allowdialogs"].IsTrue
                        }
                            );
                    }
                }
            }

            else if (all("caches"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Caches);
                }

                else if (all("bim360", "clear"))
                {
                    PyRevitCLIAppCmds.ClearCaches(
                        allCaches: arguments["--all"].IsTrue,
                        revitYear: TryGetValue("<revit_year>"),
                        cachetype: TargetCacheType.BIM360Cache
                        );
                }

                else if (all("clear"))
                {
                    PyRevitCLIAppCmds.ClearCaches(
                        allCaches: arguments["--all"].IsTrue,
                        revitYear: TryGetValue("<revit_year>"),
                        cachetype: TargetCacheType.PyRevitCache
                        );
                }
            }

            else if (all("config"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Config);
                }
                else
                {
                    PyRevitCLIConfigCmds.SeedConfigs(
                        templateConfigFilePath: TryGetValue("--from")
                        );
                }
            }

            else if (all("configs"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Configs);
                }

                else if (all("bincache"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetBinaryCaches(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Binary cache is {0}",
                                                        PyRevitConfigs.GetBinaryCaches() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("checkupdates"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetCheckUpdates(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Check Updates is {0}",
                                                        PyRevitConfigs.GetCheckUpdates() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("autoupdate"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetAutoUpdate(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Auto Update is {0}",
                                                        PyRevitConfigs.GetAutoUpdate() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("rocketmode"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetRocketMode(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Rocket Mode is {0}",
                                                        PyRevitConfigs.GetRocketMode() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("logs"))
                {
                    if (all("none"))
                    {
                        PyRevitConfigs.SetLoggingLevel(PyRevitLogLevels.Quiet);
                    }

                    else if (all("verbose"))
                    {
                        PyRevitConfigs.SetLoggingLevel(PyRevitLogLevels.Verbose);
                    }

                    else if (all("debug"))
                    {
                        PyRevitConfigs.SetLoggingLevel(PyRevitLogLevels.Debug);
                    }

                    else
                    {
                        Console.WriteLine(string.Format("Logging Level is {0}", PyRevitConfigs.GetLoggingLevel().ToString()));
                    }
                }

                else if (all("filelogging"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetFileLogging(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("File Logging is {0}",
                                                        PyRevitConfigs.GetFileLogging() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("startuptimeout"))
                {
                    if (arguments["<timeout>"] is null)
                    {
                        Console.WriteLine(string.Format("Startup log timeout is set to: {0}",
                                                        PyRevitConfigs.GetStartupLogTimeout()));
                    }
                    else
                    {
                        PyRevitConfigs.SetStartupLogTimeout(int.Parse(TryGetValue("<timeout>")));
                    }
                }

                else if (all("loadbeta"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetLoadBetaTools(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Load Beta is {0}",
                                                        PyRevitConfigs.GetLoadBetaTools() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("cpyversion"))
                {
                    if (arguments["<cpy_version>"] is null)
                    {
                        Console.WriteLine(string.Format("CPython version is set to: {0}",
                                                        PyRevitConfigs.GetCpythonEngineVersion()));
                    }
                    else
                    {
                        PyRevitConfigs.SetCpythonEngineVersion(int.Parse(TryGetValue("<cpy_version>")));
                    }
                }

                else if (all("usercanupdate"))
                {
                    if (any("yes", "no"))
                    {
                        PyRevitConfigs.SetUserCanUpdate(arguments["yes"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("User {0} update",
                                                        PyRevitConfigs.GetUserCanUpdate() ? "CAN" : "CAN NOT"));
                    }
                }

                else if (all("usercanextend"))
                {
                    if (any("yes", "no"))
                    {
                        PyRevitConfigs.SetUserCanExtend(arguments["yes"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("User {0} extend",
                                                        PyRevitConfigs.GetUserCanExtend() ? "CAN" : "CAN NOT"));
                    }
                }

                else if (all("usercanconfig"))
                {
                    if (any("yes", "no"))
                    {
                        PyRevitConfigs.SetUserCanConfig(arguments["yes"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("User {0} config",
                                                        PyRevitConfigs.GetUserCanConfig() ? "CAN" : "CAN NOT"));
                    }
                }

                else if (all("colordocs"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetColorizeDocs(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Doc Colorizer is {0}",
                                                        PyRevitConfigs.GetColorizeDocs() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("tooltipdebuginfo"))
                {
                    if (any("enable", "disable"))
                    {
                        PyRevitConfigs.SetAppendTooltipEx(arguments["enable"].IsTrue);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Doc Colorizer is {0}",
                                                        PyRevitConfigs.GetAppendTooltipEx() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("routes"))
                {
                    if (all("port"))
                    {
                        var portNumber = TryGetValue("<port_number>");
                        if (portNumber is null)
                        {
                            Console.WriteLine(string.Format("Routes Port: {0}", PyRevitConfigs.GetRoutesServerPort()));
                        }
                        else
                        {
                            PyRevitConfigs.SetRoutesServerPort(int.Parse(portNumber));
                        }
                    }

                    else if (all("coreapi"))
                    {
                        if (all("enable"))
                        {
                            PyRevitConfigs.SetRoutesLoadCoreAPIStatus(true);
                        }
                        else if (all("disable"))
                        {
                            PyRevitConfigs.SetRoutesLoadCoreAPIStatus(false);
                        }
                        else
                        {
                            Console.WriteLine(string.Format("Routes Core API is {0}",
                                                            PyRevitConfigs.GetRoutesLoadCoreAPIStatus() ? "Enabled" : "Disabled"));
                        }
                    }

                    else if (all("enable"))
                    {
                        PyRevitConfigs.EnableRoutesServer();
                    }

                    else if (all("disable"))
                    {
                        PyRevitConfigs.DisableRoutesServer();
                    }

                    else
                    {
                        Console.WriteLine(string.Format("Routes Server is {0}",
                                                        PyRevitConfigs.GetRoutesServerStatus() ? "Enabled" : "Disabled"));
                    }
                }

                else if (all("telemetry"))
                {
                    if (all("utc"))
                    {
                        if (any("yes", "no"))
                        {
                            PyRevitConfigs.SetUTCStamps(arguments["yes"].IsTrue);
                        }
                        else
                        {
                            Console.WriteLine(PyRevitConfigs.GetUTCStamps() ? "Using UTC timestamps" : "Using Local timestamps");
                        }
                    }

                    else if (all("file"))
                    {
                        var destPath = TryGetValue("<dest_path>");
                        if (destPath is null)
                        {
                            Console.WriteLine(string.Format("Telemetry File Path: {0}", PyRevitConfigs.GetAppTelemetryFlags()));
                        }
                        else
                        {
                            PyRevitConfigs.EnableTelemetry(telemetryFileDir: destPath);
                        }
                    }

                    else if (all("server"))
                    {
                        var serverUrl = TryGetValue("<dest_path>");
                        if (serverUrl is null)
                        {
                            Console.WriteLine(string.Format("Telemetry Server Url: {0}", PyRevitConfigs.GetAppTelemetryFlags()));
                        }
                        else
                        {
                            PyRevitConfigs.EnableTelemetry(telemetryServerUrl: serverUrl);
                        }
                    }

                    else if (all("hooks"))
                    {
                        if (any("yes", "no"))
                        {
                            PyRevitConfigs.SetTelemetryIncludeHooks(arguments["yes"].IsTrue);
                        }
                        else
                        {
                            Console.WriteLine(PyRevitConfigs.GetTelemetryIncludeHooks() ? "Sending telemetry for hooks" : "Not sending telemetry for hooks");
                        }
                    }

                    else if (all("enable"))
                    {
                        PyRevitConfigs.EnableTelemetry();
                    }

                    else if (all("disable"))
                    {
                        PyRevitConfigs.DisableTelemetry();
                    }

                    else
                    {
                        Console.WriteLine(string.Format("Telemetry is {0}",
                                                        PyRevitConfigs.GetTelemetryStatus() ? "Enabled" : "Disabled"));
                        Console.WriteLine(string.Format("File Path: {0}", PyRevitConfigs.GetTelemetryFilePath()));
                        Console.WriteLine(string.Format("Server Url: {0}", PyRevitConfigs.GetTelemetryServerUrl()));
                    }
                }

                else if (all("apptelemetry"))
                {
                    if (all("flags"))
                    {
                        var flagsValue = TryGetValue("<flags>");
                        if (flagsValue is null)
                        {
                            Console.WriteLine(string.Format("App Telemetry Flags: {0}", PyRevitConfigs.GetAppTelemetryFlags()));
                        }
                        else
                        {
                            PyRevitConfigs.SetAppTelemetryFlags(flags: flagsValue);
                        }
                    }

                    else if (all("server"))
                    {
                        var serverPath = TryGetValue("<server_path>");
                        if (serverPath is null)
                        {
                            Console.WriteLine(string.Format("App Telemetry Server: {0}", PyRevitConfigs.GetAppTelemetryServerUrl()));
                        }
                        else
                        {
                            PyRevitConfigs.EnableAppTelemetry(apptelemetryServerUrl: serverPath);
                        }
                    }

                    else if (all("enable"))
                    {
                        PyRevitConfigs.EnableAppTelemetry();
                    }

                    else if (all("disable"))
                    {
                        PyRevitConfigs.DisableAppTelemetry();
                    }

                    else
                    {
                        Console.WriteLine(string.Format("App Telemetry is {0}",
                                                        PyRevitConfigs.GetAppTelemetryStatus() ? "Enabled" : "Disabled"));
                        Console.WriteLine(string.Format("Server Url: {0}", PyRevitConfigs.GetAppTelemetryServerUrl()));
                        Console.WriteLine(string.Format("App Telemetry flag is {0}",
                                                        PyRevitConfigs.GetAppTelemetryFlags()));
                    }
                }

                else if (all("outputcss"))
                {
                    if (arguments["<css_path>"] is null)
                    {
                        Console.WriteLine(string.Format("Output Style Sheet is set to: {0}",
                                                        PyRevitConfigs.GetOutputStyleSheet()));
                    }
                    else
                    {
                        PyRevitConfigs.SetOutputStyleSheet(TryGetValue("<css_path>"));
                    }
                }

                else if (all("seed"))
                {
                    PyRevitConfigs.SeedConfig(makeCurrentUserAsOwner: arguments["--lock"].IsTrue);
                }

                else if (any("enable", "disable"))
                {
                    if (arguments["<option_path>"] != null)
                    {
                        // extract section and option names
                        string orignalOptionValue = TryGetValue("<option_path>");
                        if (orignalOptionValue.Split(':').Count() == 2)
                        {
                            string configSection = orignalOptionValue.Split(':')[0];
                            string configOption  = orignalOptionValue.Split(':')[1];

                            var cfg = PyRevitConfigs.GetConfigFile();
                            cfg.SetValue(configSection, configOption, arguments["enable"].IsTrue);
                        }
                        else
                        {
                            PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Main);
                        }
                    }
                }

                else
                {
                    if (arguments["<option_path>"] != null)
                    {
                        // extract section and option names
                        string orignalOptionValue = TryGetValue("<option_path>");
                        if (orignalOptionValue.Split(':').Count() == 2)
                        {
                            string configSection = orignalOptionValue.Split(':')[0];
                            string configOption  = orignalOptionValue.Split(':')[1];

                            var cfg = PyRevitConfigs.GetConfigFile();

                            // if no value provided, read the value
                            var optValue = TryGetValue("<option_value>");
                            if (optValue != null)
                            {
                                cfg.SetValue(configSection, configOption, optValue);
                            }
                            else if (optValue is null)
                            {
                                var existingVal = cfg.GetValue(configSection, configOption);
                                if (existingVal != null)
                                {
                                    Console.WriteLine(string.Format("{0} = {1}", configOption, existingVal));
                                }
                                else
                                {
                                    Console.WriteLine(string.Format("Configuration key \"{0}\" is not set", configOption));
                                }
                            }
                        }
                        else
                        {
                            PyRevitCLIAppHelps.PrintHelp(PyRevitCLICommandType.Main);
                        }
                    }
                }
            }

            else if (all("doctor"))
            {
                if (IsHelpMode)
                {
                    PyRevitCLIAppCmds.RunDoctor("--wrappedhelp");
                }

                else if (TryGetValue("<doctor_command>") is var doctorCommand && doctorCommand != null)
                {
                    PyRevitCLIAppCmds.RunDoctor(doctorCommand, dryRun: arguments["--dryrun"].IsTrue);
                }

                else if (all("doctor", "--list"))
                {
                    PyRevitCLIAppCmds.RunDoctor("--list");
                }

                else
                {
                    PyRevitCLIAppCmds.RunDoctor("");
                }
            }
Пример #14
0
        internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List <SelectTableInfo> _tables, IFreeSql _orm)
        {
            if (_orm.CodeFirst.IsAutoSyncStructure)
            {
                _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray());
            }

            var sb = new StringBuilder();

            sb.Append(_select).Append(field).Append(" \r\nFROM ");
            var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray();
            var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray();

            for (var a = 0; a < tbsfrom.Length; a++)
            {
                sb.Append(_commonUtils.QuoteSqlName(tbsfrom[a].Table.DbName)).Append(" ").Append(tbsfrom[a].Alias);
                if (tbsjoin.Length > 0)
                {
                    //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1
                    for (var b = 1; b < tbsfrom.Length; b++)
                    {
                        sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tbsfrom[b].Table.DbName)).Append(" ").Append(tbsfrom[b].Alias).Append(" ON 1 = 1");
                    }
                    break;
                }
                if (a < tbsfrom.Length - 1)
                {
                    sb.Append(", ");
                }
            }
            foreach (var tb in tbsjoin)
            {
                if (tb.Type == SelectTableInfoType.Parent)
                {
                    continue;
                }
                switch (tb.Type)
                {
                case SelectTableInfoType.LeftJoin:
                    sb.Append(" \r\nLEFT JOIN ");
                    break;

                case SelectTableInfoType.InnerJoin:
                    sb.Append(" \r\nINNER JOIN ");
                    break;

                case SelectTableInfoType.RightJoin:
                    sb.Append(" \r\nRIGHT JOIN ");
                    break;
                }
                sb.Append(_commonUtils.QuoteSqlName(tb.Table.DbName)).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On);
            }
            if (_join.Length > 0)
            {
                sb.Append(_join);
            }

            var sbqf = new StringBuilder();

            foreach (var tb in _tables)
            {
                if (tb.Type == SelectTableInfoType.Parent)
                {
                    continue;
                }
                if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
                {
                    sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
                }
            }
            if (_where.Length > 0)
            {
                sb.Append(" \r\nWHERE ").Append(_where.ToString().Substring(5));
                if (sbqf.Length > 0)
                {
                    sb.Append(sbqf.ToString());
                }
            }
            else
            {
                if (sbqf.Length > 0)
                {
                    sb.Append(" \r\nWHERE ").Append(sbqf.Remove(0, 5));
                }
            }
            if (string.IsNullOrEmpty(_groupby) == false)
            {
                sb.Append(_groupby);
                if (string.IsNullOrEmpty(_having) == false)
                {
                    sb.Append(" \r\nHAVING ").Append(_having.Substring(5));
                }
            }
            sb.Append(_orderby);
            if (_limit > 0)
            {
                sb.Append(" \r\nlimit ").Append(_limit);
            }
            if (_skip > 0)
            {
                sb.Append(" \r\noffset ").Append(_skip);
            }

            return(sb.ToString());
        }
Пример #15
0
 private void manageClient(CommonUtils.Cliente newCliente)
 {
     //string sql = "SELECT ClienteId from Cliente where NIT='" + cliente.NIT + "'";
     Int64 clienteNitTemp = 0;
     Int64.TryParse(newCliente.NIT, out clienteNitTemp);
     if (clienteNitTemp == 0)
     {
         newCliente.IdCliente = -1;
         newCliente.NIT = clienteNitTemp.ToString();
         return;
     }
     string sql = "SELECT ClienteId from Cliente where NIT='" + newCliente.NIT + "'";
     CommonUtils.ConexionBD.AbrirConexion();
     SqlDataReader reader = CommonUtils.ConexionBD.EjecutarConsultaReader(sql);
     int numberOfElements = 0;
     int idClient = 0;
     while (reader.Read())
     {
         numberOfElements++;
         idClient = (int)reader.GetDecimal(0);
     }
     CommonUtils.ConexionBD.CerrarConexion();
     if (numberOfElements == 0)
     {
         sql = "INSERT INTO Cliente (Nombre,NIT,Telefono,Direccion)  VALUES (N'" +
                  newCliente.Nombre + "','" + newCliente.NIT + "','" + CommonUtils.StringUtils.EscapeSQL(newCliente.Telefono) + "','" + CommonUtils.StringUtils.EscapeSQL(newCliente.Direccion) + "')";
         // CommonUtils.ConexionBD.Actualizar(sql);
         decimal value = CommonUtils.ConexionBD.ActualizarRetornandoId(sql);
         newCliente.IdCliente = (int)value;
     }
     else//there is a client with that nit, 
     {
         sql = "UPDATE Cliente set Nombre='" + newCliente.Nombre + "'  where clienteId='" + idClient + "'";
         CommonUtils.ConexionBD.Actualizar(sql);
         newCliente.IdCliente = idClient;
     }
 }
        public override bool Execute()
        {
            var psi = new ProcessStartInfo();

            psi.UseShellExecute = false;

            if (TargetTypeExecutable.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase))
            {
                psi.FileName  = Target;
                psi.Arguments = Arguments;
            }
            else
            {
                // We need the active environment to run these commands.
                var resolver = new ResolveEnvironment(ProjectPath, BuildEngine);
                if (!resolver.Execute())
                {
                    return(false);
                }
                psi.FileName = resolver.InterpreterPath;

                if (TargetTypeModule.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase))
                {
                    psi.Arguments = string.Format("-m {0} {1}", Target, Arguments);
                }
                else if (TargetTypeScript.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase))
                {
                    psi.Arguments = string.Format("\"{0}\" {1}", Target, Arguments);
                }
                else if (TargetTypeCode.Equals(TargetType, StringComparison.InvariantCultureIgnoreCase))
                {
                    psi.Arguments = string.Format("-c \"{0}\"", Target);
                }

                // If no search paths are read, this is set to an empty string
                // to mask any global setting.
                psi.EnvironmentVariables[resolver.PathEnvironmentVariable] = string.Join(";", resolver.SearchPaths);
            }

            psi.WorkingDirectory = WorkingDirectory;

            if (!string.IsNullOrEmpty(Environment))
            {
                foreach (var line in Environment.Split('\r', '\n'))
                {
                    int equals = line.IndexOf('=');
                    if (equals > 0)
                    {
                        psi.EnvironmentVariables[line.Substring(0, equals)] = line.Substring(equals + 1);
                    }
                }
            }

            if (ExecuteInNone.Equals(ExecuteIn, StringComparison.InvariantCultureIgnoreCase))
            {
                psi.CreateNoWindow = true;
                psi.WindowStyle    = ProcessWindowStyle.Hidden;
            }
            else if (ExecuteInConsolePause.Equals(ExecuteIn, StringComparison.InvariantCultureIgnoreCase))
            {
                psi.Arguments = string.Format(
                    "/C \"\"{0}\" {1}\" & pause",
                    psi.FileName,
                    psi.Arguments
                    );
                psi.FileName = CommonUtils.GetAbsoluteFilePath(System.Environment.SystemDirectory, "cmd.exe");
            }

            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError  = true;
            using (var process = Process.Start(psi)) {
                process.OutputDataReceived += Process_OutputDataReceived;
                process.ErrorDataReceived  += Process_ErrorDataReceived;
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();

                return(process.ExitCode == 0);
            }
        }
Пример #17
0
 public OdbcDamengDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression)
 {
     _orm              = orm;
     _commonUtils      = commonUtils;
     _commonExpression = commonExpression;
 }
Пример #18
0
 public Select1Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere)
 {
 }
Пример #19
0
 private void registrarReserva(CommonUtils.Cliente cliente1)
 {                  
     string entregado = "False";
     string tipoPedido = "Reserva";
     string pagado = "False";
     string fechaEntrega = dateEditFechaEntrega.DateTime.ToString();
     double total = double.Parse(columnTotal.SummaryItem.SummaryValue.ToString());
     this.manageClient(cliente1);
     string sqlQuery = "Insert into Pedido(FechaPedidoText,FechaEntregaText,Descuento,TipoPedido,Pagado,FechaEntrega,Entregado,ClienteId,TotalVenta,FechaPedido,NombreCliente,Direccion,Telefono,NIT,NumeroPedido) values('" + DateTime.Now.ToString("yyyy-MM-dd H:mm:ss.fff") + "','" + dateEditFechaEntrega.DateTime.ToString("yyyy-MM-dd H:mm:ss.fff") + "','" + 0 + "','" + tipoPedido + "','" + pagado + "','" + fechaEntrega + "','" + entregado + "','" + cliente1.IdCliente + "','" + total + "','" + DateTime.Now + "','" + cliente1.Nombre + "','" + cliente1.Direccion + "','" + cliente1.Telefono + "','" + cliente1.NIT + "','" + cliente1.NumeroPedido + "')";
         decimal idPedido = CommonUtils.ConexionBD.ActualizarRetornandoId(sqlQuery);
         List<DataRow> listaPedidos = dataTable.AsEnumerable().ToList();
         foreach (DataRow item in listaPedidos)
         {
             string costoReceta = CalculadoraVentas.obtenerCostoReceta(item);//this.obtenerCostoReceta(item);
             sqlQuery = "insert into Pedido_Producto(PedidoId,ProductoId,Cantidad,Total,CostoReceta,PrecioProducto,Descripcion) values('" + idPedido + "','" + item["Id"] + "','" + item["Cantidad"] + "','" + item["Subtotal"] + "','" + costoReceta + "','" + item["Precio"] + "','" + item["Descripcion"] + "')";
             CommonUtils.ConexionBD.Actualizar(sqlQuery);
         }
 }
Пример #20
0
        public JsonResult ExportAdd(EditViewModel model)
        {
            CustomJsonResult r = new CustomJsonResult();

            r.ContentType = "text/html";

            try
            {
                HttpPostedFileBase file_upload = Request.Files[0];

                if (file_upload == null)
                {
                    return(Json("text/html", ResultType.Failure, "找不到上传的对象"));
                }

                if (file_upload.ContentLength == 0)
                {
                    return(Json("text/html", ResultType.Failure, "文件内容为空,请重新选择"));
                }

                System.IO.FileInfo file = new System.IO.FileInfo(file_upload.FileName);
                string             ext  = file.Extension.ToLower();

                if (ext != ".xls")
                {
                    return(Json("text/html", ResultType.Failure, "上传的文件不是excel格式(xls)"));
                }

                HSSFWorkbook workbook = new HSSFWorkbook(file_upload.InputStream);

                ISheet sheet = workbook.GetSheetAt(0);

                ExportCheckErrorPoint exportCheckErrorPoint = new ExportCheckErrorPoint();

                IRow rowTitle = sheet.GetRow(0);

                exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(0), "设备ID");
                exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(1), "机身号");
                exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(2), "终端号");
                exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(3), "版本号");
                exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(4), "押金");
                exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(5), "租金");


                if (exportCheckErrorPoint.TitleHasError)
                {
                    return(Json("text/html", ResultType.Failure, "上传的文件模板错误,请点击下载的文件模板"));
                }


                int rowCount = sheet.LastRowNum + 1;

                if (rowCount == 1)
                {
                    return(Json("text/html", ResultType.Failure, "上传的文件数据为空,请检查后再次上传"));
                }


                List <PosMachine> posMachines = new List <PosMachine>();
                for (int i = 1; i < rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);

                    string deviceId       = row.GetCell(0).ToString();
                    string fuselageNumber = row.GetCell(1) == null ? "" : row.GetCell(1).ToString();
                    string terminalNumber = row.GetCell(2) == null ? "" : row.GetCell(2).ToString();
                    string version        = row.GetCell(3) == null ? "" : row.GetCell(3).ToString();
                    string deposit        = row.GetCell(4) == null ? "" : row.GetCell(4).ToString();
                    string rent           = row.GetCell(5) == null ? "" : row.GetCell(5).ToString();

                    if (string.IsNullOrEmpty(deviceId))
                    {
                        return(Json("text/html", ResultType.Failure, "检查到有为空的设备ID,请完善后再次上传"));
                    }

                    if (string.IsNullOrEmpty(deviceId) || deviceId.Length > 100)
                    {
                        exportCheckErrorPoint.AddPoint(deviceId, "设备ID不能为空,且不能超过100个字符");
                    }

                    if (string.IsNullOrEmpty(fuselageNumber) || fuselageNumber.Length > 100)
                    {
                        exportCheckErrorPoint.AddPoint(deviceId, "机身号不能为空,且不能超过100个字符");
                    }

                    if (string.IsNullOrEmpty(terminalNumber) || terminalNumber.Length > 100)
                    {
                        exportCheckErrorPoint.AddPoint(deviceId, "终端号不能为空,且不能超过100个字符");
                    }

                    if (string.IsNullOrEmpty(version) || version.Length > 100)
                    {
                        exportCheckErrorPoint.AddPoint(deviceId, "版本号不能为空,且不能超过100个字符");
                    }

                    if (CommonUtils.IsDecimal(deposit))
                    {
                        exportCheckErrorPoint.AddPoint(deviceId, "押金必须数字格式,且整数位最多16位,小数位最多2位");
                    }

                    if (CommonUtils.IsDecimal(rent))
                    {
                        exportCheckErrorPoint.AddPoint(deviceId, "租金必须数字格式,且整数位最多16位,小数位最多2位");
                    }

                    PosMachine posMachine = new PosMachine();
                    posMachine.DeviceId       = deviceId;
                    posMachine.FuselageNumber = fuselageNumber;
                    posMachine.TerminalNumber = terminalNumber;
                    posMachine.Version        = version;
                    posMachines.Add(posMachine);
                }


                if (exportCheckErrorPoint.ErrorPoint.Count > 0)
                {
                    return(Json("text/html", ResultType.Failure, exportCheckErrorPoint.ErrorPoint, "更新数据失败,检查到无效的数据"));
                }


                using (TransactionScope ts = new TransactionScope())
                {
                    foreach (var posMachine in posMachines)
                    {
                        var old = CurrentDb.PosMachine.Where(m => m.DeviceId == posMachine.DeviceId).FirstOrDefault();
                        if (old != null)
                        {
                            exportCheckErrorPoint.AddPoint(old.DeviceId, "设备ID号:" + posMachine.DeviceId + ",已经存在");
                        }
                    }


                    if (exportCheckErrorPoint.ErrorPoint.Count > 0)
                    {
                        return(Json("text/html", ResultType.Failure, exportCheckErrorPoint.ErrorPoint, "更新数据失败,检查到无效的数据"));
                    }

                    DateTime dateNow = DateTime.Now;
                    foreach (var posMachine in posMachines)
                    {
                        posMachine.CreateTime = dateNow;
                        posMachine.Creator    = this.CurrentUserId;
                        CurrentDb.PosMachine.Add(posMachine);
                    }

                    CurrentDb.SaveChanges();
                    ts.Complete();
                }


                return(Json("text/html", ResultType.Success, "上传成功"));
            }
            catch (Exception ex)
            {
                Log.Error("导入POS机信息", ex);
                return(Json("text/html", ResultType.Exception, "上传失败,系统出现异常"));
            }
        }
Пример #21
0
 public DamengSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere)
 {
 }
Пример #22
0
 public OracleInsertOrUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression)
     : base(orm, commonUtils, commonExpression)
 {
 }
Пример #23
0
        internal static string ToSqlStatic(CommonUtils _commonUtils, CommonExpression _commonExpression, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List <SelectTableInfo> _tables, Func <Type, string, string> tableRuleInvoke, List <LambdaExpression> _whereCascadeExpression, IFreeSql _orm)
        {
            if (_orm.CodeFirst.IsAutoSyncStructure)
            {
                _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray());
            }

            if (_whereCascadeExpression.Any())
            {
                foreach (var tb in _tables.Where(a => a.Type != SelectTableInfoType.Parent))
                {
                    tb.Cascade = _commonExpression.GetWhereCascadeSql(tb, _whereCascadeExpression);
                }
            }

            var sb    = new StringBuilder();
            var sbnav = new StringBuilder();

            sb.Append(_select);
            if (_distinct)
            {
                sb.Append("DISTINCT ");
            }
            sb.Append(field).Append(" \r\nFROM ");
            var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray();
            var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray();

            for (var a = 0; a < tbsfrom.Length; a++)
            {
                sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias);
                if (tbsjoin.Length > 0)
                {
                    //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1
                    for (var b = 1; b < tbsfrom.Length; b++)
                    {
                        sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias);

                        if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On) && string.IsNullOrEmpty(tbsfrom[b].Cascade))
                        {
                            sb.Append(" ON 1 = 1");
                        }
                        else
                        {
                            sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On);
                            if (string.IsNullOrEmpty(tbsfrom[b].Cascade) == false)
                            {
                                sb.Append(" AND (").Append(tbsfrom[b].Cascade).Append(")");
                            }
                        }
                    }
                    break;
                }
                else
                {
                    if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition))
                    {
                        sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")");
                    }
                    if (!string.IsNullOrEmpty(tbsfrom[a].On))
                    {
                        sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")");
                    }
                    if (a > 0 && !string.IsNullOrEmpty(tbsfrom[a].Cascade))
                    {
                        sbnav.Append(" AND (").Append(tbsfrom[a].Cascade).Append(")");
                    }
                }
                if (a < tbsfrom.Length - 1)
                {
                    sb.Append(", ");
                }
            }
            foreach (var tb in tbsjoin)
            {
                if (tb.Type == SelectTableInfoType.Parent)
                {
                    continue;
                }
                switch (tb.Type)
                {
                case SelectTableInfoType.LeftJoin:
                    sb.Append(" \r\nLEFT JOIN ");
                    break;

                case SelectTableInfoType.InnerJoin:
                    sb.Append(" \r\nINNER JOIN ");
                    break;

                case SelectTableInfoType.RightJoin:
                    sb.Append(" \r\nRIGHT JOIN ");
                    break;
                }
                sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition);
                if (!string.IsNullOrEmpty(tb.Cascade))
                {
                    sb.Append(" AND (").Append(tb.Cascade).Append(")");
                }
                if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition))
                {
                    sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")");
                }
            }
            if (_join.Length > 0)
            {
                sb.Append(_join);
            }

            sbnav.Append(_where);
            if (!string.IsNullOrEmpty(_tables[0].Cascade))
            {
                sbnav.Append(" AND (").Append(_tables[0].Cascade).Append(")");
            }

            foreach (var tb in _tables)
            {
                if (tb.Type == SelectTableInfoType.Parent)
                {
                    continue;
                }
                if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
                {
                    sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
                }
            }
            if (sbnav.Length > 0)
            {
                sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5));
            }
            if (string.IsNullOrEmpty(_groupby) == false)
            {
                sb.Append(_groupby);
                if (string.IsNullOrEmpty(_having) == false)
                {
                    sb.Append(" \r\nHAVING ").Append(_having.Substring(5));
                }
            }
            sb.Append(_orderby);
            if (_limit > 0)
            {
                sb.Append(" \r\nlimit ").Append(_limit);
            }
            if (_skip > 0)
            {
                sb.Append(" \r\noffset ").Append(_skip);
            }

            sbnav.Clear();
            return(sb.ToString());
        }
Пример #24
0
 public OdbcSqlServerExpression(CommonUtils common) : base(common)
 {
 }
Пример #25
0
 public MySqlCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression)
 {
 }
Пример #26
0
        /// <summary>
        /// Saves or Save As the  file
        /// </summary>
        /// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param>
        /// <param name="fileName">The name of the project file.</param>
        private void DoSave(bool isCalledFromSaveAs, string fileName)
        {
            Utilities.ArgumentNotNull("fileName", fileName);

            CheckProjectIsValid();

            using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) {
                Node.ProjectMgr.Site.GetUIThread().Invoke(() => {
                    IntPtr docData = IntPtr.Zero;

                    try {
                        IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
                        if (rdt == null)
                        {
                            throw new InvalidOperationException("Could not get running document table from the services exposed by this project");
                        }

                        // First we see if someone else has opened the requested view of the file.
                        uint itemid;
                        IVsHierarchy ivsHierarchy;
                        uint docCookie;
                        int canceled;
                        string url = this.Node.Url;

                        ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, url, out ivsHierarchy, out itemid, out docData, out docCookie));

                        // If an empty file name is passed in for Save then make the file name the project name.
                        if (!isCalledFromSaveAs && fileName.Length == 0)
                        {
                            ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, url, this.Node.ID, docData, out canceled));
                        }
                        else
                        {
                            Utilities.ValidateFileName(this.Node.ProjectMgr.Site, fileName);

                            // Compute the fullpath from the directory of the existing Url.
                            string fullPath = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(url), fileName);

                            if (!isCalledFromSaveAs)
                            {
                                if (!CommonUtils.IsSamePath(this.Node.Url, fullPath))
                                {
                                    throw new InvalidOperationException();
                                }

                                ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled));
                            }
                            else
                            {
                                ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled));
                            }
                        }

                        if (canceled == 1)
                        {
                            throw new InvalidOperationException();
                        }
                    } catch (COMException e) {
                        throw new InvalidOperationException(e.Message);
                    } finally {
                        if (docData != IntPtr.Zero)
                        {
                            Marshal.Release(docData);
                        }
                    }
                });
            }
        }
        /// <summary>
        /// Converts a CAS Service Ticket to its corresponding key in the
        /// ticket manager store (cache provider).
        /// </summary>
        /// <param name="serviceTicket">
        /// The CAS Service ticket to convert.
        /// </param>
        /// <returns>
        /// The cache key associated with the corresponding
        /// service ticket
        /// </returns>
        /// <exception cref="ArgumentNullException">serviceTicket is null</exception>
        /// <exception cref="ArgumentException">serviceTicket is empty</exception>
        private static string GetTicketKey(string serviceTicket)
        {
            CommonUtils.AssertNotNullOrEmpty(serviceTicket, "serviceTicket parameter cannot be null or empty.");

            return(CACHE_TICKET_KEY_PREFIX + serviceTicket);
        }
Пример #28
0
 public OdbcKingbaseESDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
     : base(orm, commonUtils, commonExpression, dywhere)
 {
 }
Пример #29
0
        // Updates the if then machine based on received message
        public string UpdateIfThenMachine(CanData can, string cartype)
        {
            // setups the can information for string comparison to the XML
            string stringid  = String.Format("{0:X}", can.id);
            string stringmsg = CommonUtils.ConvertMsgtoString(can.msg, can.dlc);

            // Cycles through the dictionary of ifthens
            foreach (KeyValuePair <string, State> pair in IfThenPackets)
            {
                // if in the if state then proceed with message matching
                if (pair.Value == State.If)
                {
                    // MainWindow.ErrorDisplayString("In Update IfThen: dictionary -- " + pair.Key);

                    // compares can message in xml to received can message
                    try
                    {
                        XElement carElement = XElement.Load(ConfigFiles.Settings1.Default.filterURI);

                        // Error Checking -- very clunky; needs revisions
                        if (carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault() == null)
                        {
                            return(null);
                        }
                        var cartypeElement = carElement.Descendants("CarType").Where(e2 => e2.Element("CarName").Value.Equals(cartype)).FirstOrDefault();
                        //MainWindow.ErrorDisplayString("1:" + cartypeElement.ToString());


                        // ************************
                        // Needs to cycle through all of the If thens so that the if and thens can be properly synced together
                        // ************************


                        // Error Checking -- very clunky; needs revisions
                        if (cartypeElement.Elements("IFTHEN").Where(e2 => e2.Element("Name").Value.Equals(pair.Key, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() == null)
                        {
                            return(null);
                        }
                        var ifthenElement = cartypeElement.Elements("IFTHEN").Where(e2 => e2.Element("Name").Value.Equals(pair.Key, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                        //MainWindow.ErrorDisplayString("2:" + ifthenElement.ToString());

                        if (ifthenElement.Elements("If") == null)
                        {
                            return(null);
                        }
                        var packetElement = ifthenElement.Elements("If");
                        //MainWindow.ErrorDisplayString("3:" + packetElement.ToString());

                        if (packetElement.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase) &&
                                                                   e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() != null)
                        {
                            var msgElement = packetElement.Elements("Packet").Where(e3 => e3.Element("Message").Value.Equals(stringmsg, StringComparison.OrdinalIgnoreCase) &&
                                                                                    e3.Element("ID").Value.Equals(stringid, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();


                            if (ifthenElement.Elements("Then") == null)
                            {
                                return(null);
                            }
                            var responseElement = ifthenElement.Elements("Then");

                            if (responseElement.Elements("Packet") == null)
                            {
                                return(null);
                            }
                            //var responsePacketElement = responseElement.Descendants("Packet");
                            var responsePacketElement = responseElement.Elements("Packet").FirstOrDefault();

                            return((string)responsePacketElement.Element("ID") + ";"
                                   + (string)responsePacketElement.Element("DLC") + ";"
                                   + (string)responsePacketElement.Element("Flag") + ";"
                                   + (string)responsePacketElement.Element("Message"));
                        }

                        return(null);
                    }
                    //catch (FileNotFoundException)
                    catch (Exception)
                    {
                        ErrorLog.NewLogEntry("Filter", "URI filename not found");
                        return(null);
                    }
                }
            }

            return(null);
        }
Пример #30
0
 public SqliteUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
     : base(orm, commonUtils, commonExpression, dywhere)
 {
 }
Пример #31
0
        private DataSet GetQueryCondition()
        {
            Hashtable htParams = new Hashtable();

            if (!(teOUTBANDNO.Text == ""))
            {
                htParams.Add("OUTBANDNO", teOUTBANDNO.Text);
            }
            if (!(teVBELN.Text == ""))
            {
                htParams.Add("VBELN", teVBELN.Text);
            }
            if (!(teCREATED_BY.Text == ""))
            {
                htParams.Add("CREATED_BY", teCREATED_BY.Text);
            }
            if (!(teSALESTO.Text == ""))
            {
                htParams.Add("SALESTO", teSALESTO.Text);
            }
            if (!(teXHGG.Text == ""))
            {
                htParams.Add("XHGG", teXHGG.Text);
            }
            if (!(lookUpPLANT.Text == ""))//if (!(lookUpPLANT.Text == ""))
            {
                htParams.Add("PLANT", lookUpPLANT.EditValue.ToString());
            }
            if (!(comboBoxSTATUS.Text == ""))
            {
                htParams.Add("STATUS", comboBoxSTATUS.Text);
            }
            if (!(teBATCHNO.Text == ""))
            {
                htParams.Add("BATCHNO", teBATCHNO.Text);
            }
            if (!(teCabinet_NO.Text == ""))
            {
                htParams.Add("Cabinet_NO", teCabinet_NO.Text);
            }
            if (!(teCI.Text == ""))
            {
                htParams.Add("CI", teCI.Text);
            }
            if (!(teShipmentNo.Text == ""))
            {
                htParams.Add("ShipmentNo", teShipmentNo.Text);
            }
            if (!(dateLFDAT1.Text == ""))
            {
                htParams.Add("LFDAT1", dateLFDAT1.Text);
            }
            if (!(dateLFDAT2.Text == ""))
            {
                htParams.Add("LFDAT2", dateLFDAT2.Text);
            }
            if (!(dateQCDAT1.Text == ""))
            {
                htParams.Add("QCDAT1", dateQCDAT1.Text);
            }
            if (!(dateQCDAT2.Text == ""))
            {
                htParams.Add("QCDAT2", dateQCDAT2.Text);
            }
            DataTable dtParams = CommonUtils.ParseToDataTable(htParams);
            DataSet   dsParams = new DataSet();

            dtParams.TableName = TRANS_TABLES.TABLE_MAIN_DATA;
            dsParams.Tables.Add(dtParams);
            return(dsParams);
        }
Пример #32
0
 public override string ToString()
 {
     return(string.Format("ICS: Conversation={0}, {1}", this.Conversation, CommonUtils.ConcatEntries <int>(this.CoveringPropertyTags, (int ptag) => ptag.ToString("X"))));
 }
Пример #33
0
 public SqlServerDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
     : base(orm, commonUtils, commonExpression, dywhere)
 {
 }
Пример #34
0
 public MySqlExpression(CommonUtils common) : base(common)
 {
 }
Пример #35
0
 public SqliteExpression(CommonUtils common) : base(common)
 {
 }
Пример #36
0
 public MySqlCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression)
 {
     _orm              = orm;
     _commonUtils      = commonUtils;
     _commonExpression = commonExpression;
 }
Пример #37
0
        public CalculadoraVentas(CommonUtils.ActualizarGrids IUpdateGrids,DataTable table,Form parentForm,double totalDinero,bool reserva,bool sePago,CommonUtils.Cliente _client)
        {
            InitializeComponent();
            InitializePrintSettings( );
            dbLog = new CommonUtils.DataBaseLog();
            log4net.Config.XmlConfigurator.Configure( );
            dataTable = table;
            total = totalDinero;
            txtCuenta.Text = total.ToString();
            txtTotal.Text = total.ToString();
            pagado = sePago;
            esReserva = reserva;
            cliente = _client;
           // ventasPanel = ventasPnl;
            UpdateGrids = IUpdateGrids;

            InitConexionDB();
            

            if (parentForm != null)
            {
                Left = parentForm.Left + (parentForm.Width - Width) / 2;
                Top = parentForm.Top + (parentForm.Height - Height) / 2;
            }
        }
Пример #38
0
        /// <summary>
        /// Pastes SyncItem into the database.
        ///
        /// </summary>
        /// <param name="syncItem">The sync item.</param>
        /// <param name="ignoreMissingTemplateFields">Whether to ignore fields in the serialized item that do not exist on the Sitecore template</param>
        /// <returns>
        /// The pasted item.
        /// </returns>
        /// <exception cref="T:Sitecore.Data.Serialization.Exceptions.ParentItemNotFoundException"><c>ParentItemNotFoundException</c>.</exception><exception cref="T:System.Exception"><c>Exception</c>.</exception><exception cref="T:Sitecore.Data.Serialization.Exceptions.ParentForMovedItemNotFoundException"><c>ParentForMovedItemNotFoundException</c>.</exception>
        public override ISourceItem Deserialize(ISerializedItem serializedItem, bool ignoreMissingTemplateFields)
        {
            Assert.ArgumentNotNull(serializedItem, "serializedItem");

            var typed = serializedItem as SitecoreSerializedItem;

            if (typed == null)
            {
                throw new ArgumentException("Serialized item must be a SitecoreSerializedItem", "serializedItem");
            }

            var syncItem = typed.InnerItem;

            Database database = Factory.GetDatabase(syncItem.DatabaseName);

            Item destinationParentItem = database.GetItem(syncItem.ParentID);
            ID   itemId            = ID.Parse(syncItem.ID);
            Item targetItem        = database.GetItem(itemId);
            bool newItemWasCreated = false;

            // the target item did not yet exist, so we need to start by creating it
            if (targetItem == null)
            {
                targetItem = CreateTargetItem(syncItem, destinationParentItem);

                _logger.CreatedNewItem(targetItem);

                newItemWasCreated = true;
            }
            else
            {
                // check if the parent of the serialized item does not exist
                // which, since the target item is known to exist, means that
                // the serialized item was moved but its new parent item does
                // not exist to paste it under
                if (destinationParentItem == null)
                {
                    throw new ParentForMovedItemNotFoundException
                          {
                              ParentID = syncItem.ParentID,
                              Item     = targetItem
                          };
                }

                // if the parent IDs mismatch that means we need to move the existing
                // target item to its new parent from the serialized item
                if (destinationParentItem.ID != targetItem.ParentID)
                {
                    var oldParent = targetItem.Parent;
                    targetItem.MoveTo(destinationParentItem);
                    _logger.MovedItemToNewParent(destinationParentItem, oldParent, targetItem);
                }
            }
            try
            {
                ChangeTemplateIfNeeded(syncItem, targetItem);
                RenameIfNeeded(syncItem, targetItem);
                ResetTemplateEngineIfItemIsTemplate(targetItem);

                using (new EditContext(targetItem))
                {
                    targetItem.RuntimeSettings.ReadOnlyStatistics = true;
                    targetItem.RuntimeSettings.SaveAll            = true;

                    foreach (Field field in targetItem.Fields)
                    {
                        if (field.Shared && syncItem.SharedFields.All(x => x.FieldID != field.ID.ToString()))
                        {
                            _logger.ResetFieldThatDidNotExistInSerialized(field);
                            field.Reset();
                        }
                    }

                    foreach (SyncField field in syncItem.SharedFields)
                    {
                        PasteSyncField(targetItem, field, ignoreMissingTemplateFields, newItemWasCreated);
                    }
                }

                ClearCaches(database, itemId);
                targetItem.Reload();
                ResetTemplateEngineIfItemIsTemplate(targetItem);

                Hashtable versionTable = CommonUtils.CreateCIHashtable();

                // this version table allows us to detect and remove orphaned versions that are not in the
                // serialized version, but are in the database version
                foreach (Item version in targetItem.Versions.GetVersions(true))
                {
                    versionTable[version.Uri] = null;
                }

                foreach (SyncVersion syncVersion in syncItem.Versions)
                {
                    var version = PasteSyncVersion(targetItem, syncVersion, ignoreMissingTemplateFields, newItemWasCreated);
                    if (versionTable.ContainsKey(version.Uri))
                    {
                        versionTable.Remove(version.Uri);
                    }
                }

                foreach (ItemUri uri in versionTable.Keys)
                {
                    var versionToRemove = Database.GetItem(uri);

                    _logger.RemovingOrphanedVersion(versionToRemove);

                    versionToRemove.Versions.RemoveVersion();
                }

                ClearCaches(targetItem.Database, targetItem.ID);

                return(new SitecoreSourceItem(targetItem));
            }
            catch (ParentForMovedItemNotFoundException)
            {
                throw;
            }
            catch (ParentItemNotFoundException)
            {
                throw;
            }
#if SITECORE_7
            catch (FieldIsMissingFromTemplateException)
            {
                throw;
            }
#endif
            catch (Exception ex)
            {
                if (newItemWasCreated)
                {
                    targetItem.Delete();
                    ClearCaches(database, itemId);
                }
                throw new Exception("Failed to paste item: " + syncItem.ItemPath, ex);
            }
        }