Exemplo n.º 1
0
        /*@Autor Alfredo Santiago Alvarado
         *
         *
         *
        */
        static void Main(string[] args)
        {
            SqlConnections sql = new SqlConnections();
             string consulta = "Select empleados.correo AS CORREOUSUARIO,subjefes.correo AS CORREOSUBJEFE,jefes.CORREO AS CORREOJEFE,DIRECTORES.CORREO AS CORREODIRECTOR ,AAAUSER.FIRST_NAME,WORKORDER.WORKORDERID AS Ticket ,WORKORDERStates.StatusID,convert(date,dateadd(s,datediff(s,GETUTCDATE() ,getdate()) + (WORKORDER.CREATEDTIME/1000),'1970-01-01 00:00:00'),110) 'Created Time' " +
                                       "from WORKORDER  (nolock) " +
                                       "INNER JOIN  WORKORDERStates " +
                                       "ON WORKORDER.WORKORDERID = WORKORDERStates.WORKORDERID " +
                                       "Inner JOIN AAAUSER " +
                                       "ON WORKORDER.requesterid = AAAUSER.USER_ID " +
                                       "LEFT JOIN empleados " +
                                       "ON WORKORDER.requesterid = empleados.user_id " +
                                       "LEFT JOIN subjefes " +
                                       "ON empleados.subjefe_id = subjefes.user_id " +
                                       "LEFT JOIN jefes " +
                                       "ON empleados.jefe_id = JEFES.user_id " +
                                       "LEFT JOIN directores " +
                                       "ON empleados.director_id = directores.user_id " +
                                       "WHERE dateadd(s,datediff(s,GETUTCDATE() ,getdate()) + (WORKORDER.CREATEDTIME/1000),'1970-01-01 00:00:00') >= convert(varchar,CONVERT (date, GETDATE()-4),21) " +
                                       "AND WORKORDERStates.statusid = 301 ";
                sql.consulta(consulta);

             //  Console.WriteLine(sql.difDate("select DATEDIFF (day ,'2015-08-26' , CONVERT (date, SYSDATETIME())) AS diferencia"));

            //    email.sendEMailThroughOUTLOOK("*****@*****.**");
        }
Exemplo n.º 2
0
        private bool ValidateExistingUser(ref string username, string password, UserDefinition user)
        {
            username = user.Username;

            if (user.IsActive != 1)
            {
                if (Log.IsInfoEnabled)
                {
                    Log.Error(String.Format("Inactive user login attempt: {0}", username), this.GetType());
                }

                return(false);
            }

            // prevent more than 50 invalid login attempts in 30 minutes
            var throttler = new Throttler("ValidateUser:"******"site" || user.Source == "sign" || directoryService == null)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return(true);
                }

                return(false);
            }

            if (user.Source != "ldap")
            {
                throw new ArgumentOutOfRangeException("userSource");
            }

            if (!string.IsNullOrEmpty(user.PasswordHash) &&
                user.LastDirectoryUpdate != null &&
                user.LastDirectoryUpdate.Value.AddHours(1) >= DateTime.Now)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return(true);
                }

                return(false);
            }

            DirectoryEntry entry;

            try
            {
                entry = directoryService.Validate(username, password);
                if (entry == null)
                {
                    return(false);
                }

                throttler.Reset();
            }
            catch (Exception ex)
            {
                Log.Error("Error on directory access", ex, this.GetType());

                // couldn't access directory. allow user to login with cached password
                if (!user.PasswordHash.IsTrimmedEmpty())
                {
                    if (validatePassword())
                    {
                        throttler.Reset();
                        return(true);
                    }

                    return(false);
                }

                throw;
            }

            try
            {
                string salt        = user.PasswordSalt.TrimToNull();
                var    hash        = UserRepository.GenerateHash(password, ref salt);
                var    displayName = entry.FirstName + " " + entry.LastName;
                var    email       = entry.Email.TrimToNull() ?? user.Email ?? (username + "@yourdefaultdomain.com");

                using (var connection = SqlConnections.NewFor <UserRow>())
                    using (var uow = new UnitOfWork(connection))
                    {
                        var fld = UserRow.Fields;
                        new SqlUpdate(fld.TableName)
                        .Set(fld.DisplayName, displayName)
                        .Set(fld.PasswordHash, hash)
                        .Set(fld.PasswordSalt, salt)
                        .Set(fld.Email, email)
                        .Set(fld.LastDirectoryUpdate, DateTime.Now)
                        .WhereEqual(fld.UserId, user.UserId)
                        .Execute(connection, ExpectedRows.One);

                        uow.Commit();

                        UserRetrieveService.RemoveCachedUser(user.UserId, username);
                    }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error while updating directory user", ex, this.GetType());
                return(true);
            }
        }
Exemplo n.º 3
0
 private IDbConnection GetConnection()
 {
     return(SqlConnections.New(connectionString, providerName));
 }
Exemplo n.º 4
0
        void GridArayuzleriKaydet(Control ctrl)
        {
            DevExpress.XtraGrid.GridControl gc = new GridControl();
            gc = ctrl as DevExpress.XtraGrid.GridControl;
            DevExpress.XtraGrid.Views.Grid.GridView gv = (DevExpress.XtraGrid.Views.Grid.GridView)gc.Views[0];

            string Layout = "";

            using (var ms = new MemoryStream())
            {
                gv.SaveLayoutToStream(ms);
                ms.Position = 0;
                using (var reader = new StreamReader(ms))
                    Layout = reader.ReadToEnd();
            }
            cs.csGridLayout.InsertLayout(Convert.ToInt32(frmKullaniciGiris.KullaniciID), this.Name, gv.Name, Layout, SqlConnections.GetBaglanti(), trGenel);
        }
Exemplo n.º 5
0
        public List <SimpleReportViewModel> Queries(DateTime start, DateTime end, int consumerId, List <int?> meterId, List <int> parameterId)
        {
            var  lstModel   = new List <SimpleReportViewModel>();
            bool isAdmin    = false;
            bool isOperator = false;
            bool isConsumer = false;

            using (var connection = SqlConnections.NewByKey("Default"))
            {
                if (isAdmin)
                {
                    List <MeterRow>       meters       = connection.List <MeterRow>();
                    List <MeterDetailRow> meterDetails = new List <MeterDetailRow>();
                    meterDetails.AddRange(connection.List <MeterDetailRow>().FindAll(md => meterId.Contains(md.MeterId)));

                    foreach (var item in meterDetails)
                    {
                        var x = connection.ById <SchedulingRow>(item.SchedulingId);
                        lstModel.Add(new SimpleReportViewModel
                        {
                            DimensionOne = x.FullDate.ToString(),
                            Quantity     = int.Parse(item.Value)
                        });
                    }
                    return(lstModel);
                }
                if (isOperator)
                {
                    List <MeterRow> meters    = new List <MeterRow>();
                    var             meterRows = connection.List <MeterRow>();
                    meters = meterRows.FindAll(m => m.ConsumerId == consumerId);
                    List <MeterDetailRow> meterDetails = new List <MeterDetailRow>();
                    foreach (var item in meters)
                    {
                        meterDetails.AddRange(connection.List <MeterDetailRow>().FindAll(md => md.MeterId == item.MeterId));
                    }

                    foreach (var item in meterDetails)
                    {
                        var x = connection.ById <SchedulingRow>(item.SchedulingId);
                        lstModel.Add(new SimpleReportViewModel
                        {
                            DimensionOne = x.FullDate.ToString(),
                            Quantity     = int.Parse(item.Value)
                        });
                    }
                    return(lstModel);
                }
                if (isConsumer)
                {
                    List <MeterRow> meters    = new List <MeterRow>();
                    var             meterRows = connection.List <MeterRow>();
                    meters = meterRows.FindAll(m => m.ConsumerId == consumerId);
                    List <MeterDetailRow> meterDetails = new List <MeterDetailRow>();
                    foreach (var item in meters)
                    {
                        meterDetails.AddRange(connection.List <MeterDetailRow>().FindAll(md => md.MeterId == item.MeterId));
                    }

                    foreach (var item in meterDetails)
                    {
                        var x = connection.ById <SchedulingRow>(item.SchedulingId);
                        lstModel.Add(new SimpleReportViewModel
                        {
                            DimensionOne = x.FullDate.ToString(),
                            Quantity     = int.Parse(item.Value)
                        });
                    }
                    return(lstModel);
                }
            }

            return(lstModel);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Automatically creates a database for the template if it doesn't already exists.
        /// You might delete this method to disable auto create functionality.
        /// </summary>
        private static void EnsureDatabase(string databaseKey)
        {
            var cs = SqlConnections.GetConnectionString(databaseKey);

            var  serverType = cs.Dialect.ServerType;
            bool isSql      = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase);
            bool isPostgres = !isSql& serverType.StartsWith("Postgres", StringComparison.OrdinalIgnoreCase);

            bool isMySql  = !isSql && !isPostgres && serverType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase);
            bool isSqlite = !isSql && !isPostgres && !isMySql && serverType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase);

            if (!isSql && !isPostgres && !isMySql && !isSqlite)
            {
                return;
            }

            var cb = cs.ProviderFactory.CreateConnectionStringBuilder();

            cb.ConnectionString = cs.ConnectionString;
            string catalogKey = "?";

            if (isSqlite)
            {
                catalogKey = "Data Source";
                if (!cb.ContainsKey(catalogKey))
                {
                    return;
                }

                var dataFile = cb[catalogKey] as string;
                if (string.IsNullOrEmpty(dataFile))
                {
                    return;
                }

                dataFile = dataFile.Replace("|DataDirectory|", HostingEnvironment.MapPath("~/App_Data/"));
                if (File.Exists(dataFile))
                {
                    return;
                }

                Directory.CreateDirectory(Path.GetDirectoryName(dataFile));
                using (var sqliteConn = SqlConnections.New(cb.ConnectionString, cs.ProviderName))
                {
                    var createFile = ((WrappedConnection)sqliteConn).ActualConnection.GetType().GetMethod("CreateFile", BindingFlags.Static);
                    if (createFile != null)
                    {
                        createFile.Invoke(null, new object[] { dataFile });
                    }
                }

                SqlConnection.ClearAllPools();
                return;
            }

            foreach (var ck in new[] { "Initial Catalog", "Database", "AttachDBFilename" })
            {
                if (cb.ContainsKey(ck))
                {
                    catalogKey = ck;
                    break;
                }
            }

            var catalog = cb[catalogKey] as string;

            cb[catalogKey] = null;

            using (var serverConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName))
            {
                try
                {
                    serverConnection.Open();
                }
                catch (SqlException ex)
                {
                    if (ex.ErrorCode != -2146232060)
                    {
                        throw;
                    }

                    const string oldVer = @"\v11.0";

                    if (cb.ConnectionString.IndexOf(oldVer) >= 0)
                    {
                        throw new Exception(
                                  "You don't seem to have SQL Express LocalDB 2012 installed.\r\n\r\n" +
                                  "If you have Visual Studio 2015 (with SQL LocalDB 2014) " +
                                  "try changing '" + databaseKey + "' connection string in WEB.CONFIG to:\r\n\r\n" +
                                  cs.ConnectionString.Replace(oldVer, @"\MSSqlLocalDB") + "\r\n\r\nor:\r\n\r\n" +
                                  cs.ConnectionString.Replace(oldVer, @"\v12.0") + "';\r\n\r\n" +
                                  "You can also try another SQL server type like .\\SQLExpress.");
                    }

                    throw;
                }

                string databasesQuery      = "SELECT * FROM sys.databases WHERE NAME = @name";
                string createDatabaseQuery = @"CREATE DATABASE [{0}]";

                if (isPostgres)
                {
                    databasesQuery      = "select * from postgres.pg_catalog.pg_database where datname = @name";
                    createDatabaseQuery = "CREATE DATABASE \"{0}\"";
                }
                else if (isMySql)
                {
                    databasesQuery      = "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @name";
                    createDatabaseQuery = "CREATE DATABASE `{0}`";
                }

                if (serverConnection.Query(databasesQuery, new { name = catalog }).Any())
                {
                    return;
                }

                var isLocalServer = isSql &&
                                    serverConnection.ConnectionString.IndexOf(@"(localdb)\", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                    serverConnection.ConnectionString.IndexOf(@".\") >= 0;

                string command;
                if (isLocalServer)
                {
                    var filename = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), catalog);
                    command = String.Format(@"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}.ldf')",
                                            catalog, filename);

                    if (File.Exists(filename + ".mdf"))
                    {
                        command += " FOR ATTACH";
                    }
                }
                else
                {
                    command = String.Format(createDatabaseQuery, catalog);
                }

                serverConnection.Execute(command);
                SqlConnection.ClearAllPools();
            }
        }
Exemplo n.º 7
0
        private static void RunMigrations(string databaseKey)
        {
            var cs         = SqlConnections.GetConnectionString(databaseKey);
            var connection = cs.ConnectionString;

            string serverType  = cs.Dialect.ServerType;
            bool   isSqlServer = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase);
            bool   isOracle    = serverType.StartsWith("Oracle", StringComparison.OrdinalIgnoreCase);
            bool   isFirebird  = serverType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase);

            // safety check to ensure that we are not modifying an arbitrary database.
            // remove these lines if you want MovieTutorial migrations to run on your DB.
            //if (!isOracle && cs.ConnectionString.IndexOf(typeof(DataMigrations).Namespace +
            //        @"_" + databaseKey + "_v1", StringComparison.OrdinalIgnoreCase) < 0)
            //{
            //    SkippedMigrations = true;
            //    return;
            //}

            string databaseType = isOracle ? "OracleManaged" : serverType;

            using (var sw = new StringWriter())
            {
                Announcer announcer = isOracle || isFirebird ?
                                      new TextWriterAnnouncer(sw)
                {
                    ShowSql = true
                } :
                new TextWriterWithGoAnnouncer(sw)
                {
                    ShowSql = true
                };

                var runner = new RunnerContext(announcer)
                {
                    Database   = databaseType,
                    Connection = cs.ConnectionString,
#if COREFX
                    TargetAssemblies = new[] { typeof(DataMigrations).Assembly },
#else
                    Targets = new string[] { typeof(DataMigrations).Assembly.Location },
#endif
                    Task             = "migrate:up",
                    WorkingDirectory = Path.GetDirectoryName(typeof(DataMigrations).Assembly.Location),
                    Namespace        = "MovieTutorial.Migrations." + databaseKey + "DB",
                    Timeout          = 90
                };

                var culture = CultureInfo.CurrentCulture;
                try
                {
                    if (isFirebird)
                    {
                        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
                    }

                    new TaskExecutor(runner)
                    {
#if COREFX
                        ConnectionString = cs.ConnectionString
#endif
                    }.Execute();
                }
                catch (Exception ex)
                {
                    var output = sw.ToString().Trim();

                    if (output.StartsWith("/*"))
                    {
                        var idx = output.IndexOf("*/");
                        output = output.Substring(idx + 2);
                    }

                    throw new Exception("Error executing migration:\r\n" +
                                        output, ex);
                }
                finally
                {
                    if (isFirebird)
                    {
                        Thread.CurrentThread.CurrentCulture = culture;
                    }
                }
            }
        }
        private void cbtnUretildi_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Üretim Emri Durumu 'Üretildi' Olarak Değiştirilecek.\n{Üretim Fişleri oluşturulacak.}\nOnaylıyor musunuz?", "ARES", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
            {
                return;
            }
            int SeciliSatir  = gvUretimEmri.FocusedRowHandle;
            int UretimEmriID = (int)gvUretimEmri.GetFocusedRowCellValue("UretimEmriID");
            int CiktiStokID  = -1;

            #region REÇETEDEKİ ÇIKTI STOK BİLGİSİ ALINIYOR
            using (SqlCommand cmd = new SqlCommand(@"SELECT StokID FROM dbo.ReceteDetail WHERE (SatirTur = 1) AND (ReceteMasterID = @ReceteMasterID)", SqlConnections.GetBaglanti()))
            {
                cmd.Parameters.Add("@ReceteMasterID", SqlDbType.Int).Value = gvUretimEmri.GetFocusedRowCellValue("ReceteMasterID").ToString();
                using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult))
                {
                    if (dr.Read())
                    {
                        CiktiStokID = (int)dr["StokID"];
                    }
                }
            }
            #endregion

            #region ÇIKTI SATIRI UretimFis TABLOSUNA KAYDEDİLİYOR.
            //using (SqlCommand cmd = new SqlCommand(@"Insert Into UretimFis(UretimEmriID, FisTuru, ModulNo, GirisCikis, FisNo, DepoID, StokID, Miktar) Values(@UretimEmriID, @FisTuru, @ModulNo, @GirisCikis, @FisNo, @DepoID, @StokID, @Miktar)", SqlConnections.GetBaglanti()))
            //{
            //  cmd.Parameters.Add("@UretimEmriID", SqlDbType.Int).Value = gvUretimEmri.GetFocusedRowCellValue("UretimEmriID").ToString();
            //  cmd.Parameters.Add("@FisTuru", SqlDbType.Int).Value = "13"; //13:üretimden giriş fişi,
            //  cmd.Parameters.Add("@ModulNo", SqlDbType.Int).Value = "3"; //3: Malzeme yönetimi
            //  cmd.Parameters.Add("@GirisCikis", SqlDbType.Int).Value = "0";
            //  cmd.Parameters.Add("@FisNo", SqlDbType.NVarChar).Value = gvUretimEmri.GetFocusedRowCellValue("PartiNo").ToString();
            //  cmd.Parameters.Add("@DepoID", SqlDbType.Int).Value = gvUretimEmri.GetFocusedRowCellValue("UretimdenGirisAmbarID").ToString();
            //  cmd.Parameters.Add("@StokID", SqlDbType.Int).Value = CiktiStokID;
            //  cmd.Parameters.Add("@Miktar", SqlDbType.Decimal).Value = CiktiMiktariniGetir();

            //  cmd.ExecuteNonQuery();
            //}
            #endregion

            #region STOKFIS VE STOKFISDETAY TABLOLARINA KAYIT EKLENİYOR.
            int StokFisID = 0;
            #region Stok Fiş
            using (SqlCommand cmdMaster = new SqlCommand(
                       @"INSERT INTO StokFis( StokFisNo, FisTarihi, FisTuru, GirisCikis, ModulNo, CikisAmbarID, GirisAmbarID) 
    VALUES(@StokFisNo,@FisTarihi,@FisTuru,@GirisCikis,@ModulNo,@CikisAmbarID,@GirisAmbarID) SET @YeniID = SCOPE_IDENTITY()", SqlConnections.GetBaglanti()))
            {
                cmdMaster.Parameters.Add("@StokFisNo", SqlDbType.NVarChar).Value = gvUretimEmri.GetFocusedRowCellValue("PartiNo").ToString();
                cmdMaster.Parameters.Add("@FisTarihi", SqlDbType.DateTime).Value = gvUretimEmri.GetFocusedRowCellValue("UretimTarihi").ToString();
                cmdMaster.Parameters.Add("@FisTuru", SqlDbType.Int).Value        = 13;        //Üretimden Giriş Fişi
                cmdMaster.Parameters.Add("@GirisCikis", SqlDbType.Int).Value     = 1;
                cmdMaster.Parameters.Add("@ModulNo", SqlDbType.Int).Value        = 3;         //Malzeme Yönetimi
                cmdMaster.Parameters.Add("@CikisAmbarID", SqlDbType.Int).Value   = -1;
                cmdMaster.Parameters.Add("@GirisAmbarID", SqlDbType.Int).Value   = -1;
                cmdMaster.Parameters.Add("@YeniID", SqlDbType.Int).Direction     = ParameterDirection.Output;
                cmdMaster.ExecuteNonQuery();
                StokFisID = Convert.ToInt32(cmdMaster.Parameters["@YeniID"].Value.ToString());
            }
            #endregion

            #region StokFisDetay
            DataTable dtFisDetay = new DataTable();
            using (SqlDataAdapter da = new SqlDataAdapter(@"
SELECT SatirTur, StokID, Miktar, UretimMiktar
FROM   dbo.ReceteDetail WHERE (ReceteMasterID = @ReceteMasterID)", SqlConnections.GetBaglanti()))
            {
                da.SelectCommand.Parameters.Add("@ReceteMasterID", SqlDbType.Int).Value = gvUretimEmri.GetFocusedRowCellValue("ReceteMasterID").ToString();
                dtFisDetay.Clear();
                da.Fill(dtFisDetay);
            }
            int SiraNo = 0;
            foreach (DataRow row in dtFisDetay.AsEnumerable())
            {
                //ReceteDetail.SatirTur -> 1: Çıktı, 2: Hammadde

                #region ÇIKTI SATIRI İŞLEMİ
                using (SqlCommand cmdDetail = new SqlCommand(
                           @"INSERT INTO StokFisDetay(FisTuru, ModulNo, GirisCikis, StokID, StokFisID, SatirNo, Miktar, CikisAmbarID)
VALUES(13,3,@GirisCikis,@StokID,@StokFisID,@SatirNo,@Miktar,@CikisAmbarID)", SqlConnections.GetBaglanti()))
                {
                    SiraNo++;
                    if (row["SatirTur"].ToString() == "1")
                    {
                        cmdDetail.Parameters.Add("@GirisCikis", SqlDbType.Int).Value = 1;
                    }
                    else if (row["SatirTur"].ToString() == "2")
                    {
                        cmdDetail.Parameters.Add("@GirisCikis", SqlDbType.Int).Value = 0;
                    }
                    cmdDetail.Parameters.Add("@StokID", SqlDbType.Int).Value  = row["StokID"].ToString();
                    cmdDetail.Parameters.Add("@SatirNo", SqlDbType.Int).Value = SiraNo;

                    cmdDetail.Parameters.Add("@Miktar", SqlDbType.Decimal).Value = row["Miktar"].ToString();
                    string a = gvUretimEmri.GetFocusedRowCellValue("UretimdenGirisAmbarID").ToString();
                    cmdDetail.Parameters.Add("@CikisAmbarID", SqlDbType.Int).Value = gvUretimEmri.GetFocusedRowCellValue("UretimdenGirisAmbarID").ToString();
                    cmdDetail.Parameters.Add("@StokFisID", SqlDbType.Int).Value    = StokFisID;
                    cmdDetail.ExecuteNonQuery();
                }
                #endregion
            }
            #endregion
            #endregion

            #region UretimEmri Kaydının Durum'u değiştiriliyor.
            using (SqlCommand cmd = new SqlCommand(@"Update UretimEmri Set Durum=1 Where UretimEmriID=@UretimEmriID", SqlConnections.GetBaglanti()))
            {
                cmd.Parameters.Add("@UretimEmriID", SqlDbType.Int).Value = UretimEmriID;
                cmd.ExecuteNonQuery();
            }
            #endregion

            dt.Clear();
            daUretim.Update(dt);
            daUretim.Fill(dt);

            gvUretimEmri.FocusedRowHandle = SeciliSatir;
        }
Exemplo n.º 9
0
        private void ConnectionsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this._tables.Clear();
            GenerateCodeButton.IsEnabled = false;

            if (this.ConnectionsCombo.SelectedItem != null)
            {
                var conn = (GeneratorConfig.Connection) this.ConnectionsCombo.SelectedItem;

                try
                {
                    using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                    {
                        connection.Open();

                        var schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType);
                        foreach (var t in schemaProvider.GetTableNames(connection))
                        {
                            var table = conn != null?conn.Tables.FirstOrDefault(x => x.Tablename == t.Tablename) : null;

                            var identifier = (table == null || table.Identifier.IsEmptyOrNull()) ?
                                             RowGenerator.ClassNameFromTableName(t.Table) : table.Identifier;
                            var permission    = table == null ? "Administration:General" : table.PermissionKey;
                            var connectionKey = (table != null && !table.ConnectionKey.IsEmptyOrNull()) ?
                                                table.ConnectionKey : conn.Key;

                            var module = (table != null && table.Module != null) ? table.Module :
                                         (Inflector.Inflector.Pascalize(connectionKey) ?? "").Replace(" ", "");

                            var tableItem = new TableItem
                            {
                                IsChecked     = false,
                                ConnectionKey = conn.Key,
                                Module        = module,
                                Identifier    = identifier,
                                PermissionKey = permission,
                                FullName      = t.Tablename
                            };

                            _tables.Add(tableItem);
                            tableItem.PropertyChanged += (s, e2) =>
                            {
                                var t2 = conn.Tables.FirstOrDefault(x => x.Tablename == tableItem.FullName);
                                if (t2 == null)
                                {
                                    t2           = new GeneratorConfig.Table();
                                    t2.Tablename = tableItem.FullName;
                                    conn.Tables.Add(t2);
                                }
                                t2.Identifier    = tableItem.Identifier;
                                t2.Module        = tableItem.Module;
                                t2.ConnectionKey = tableItem.ConnectionKey;
                                t2.PermissionKey = tableItem.PermissionKey;
                                this.config.Save();

                                GenerateCodeButton.IsEnabled = _tables.Any(x => x.IsChecked);
                            };
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        private void checkButton_fotoGoster_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (gvStokListesi.RowCount == 0)
                {
                    return;
                }

                if (checkButton_fotoGoster.Checked == true)
                {
                    pictureEdit1.Visible           = true;
                    layoutControlItem43.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    pictureEdit1.EditValue         = StokArama.StokIDverVarsayilanFotoAl(SqlConnections.GetBaglanti(), trGenel, Convert.ToInt32(gvStokListesi.GetFocusedRowCellValue("StokID")));
                }
                else
                {
                    pictureEdit1.Visible           = false;
                    layoutControlItem43.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                }
            }
            catch (Exception)
            {
            }
        }
        string MiktarliBarkod; // buraya açıklama lazım

        void FiltreKriterleriniBindleHamisina()
        {
            //tabbedControlGroup1.TabPages.
            //layoutControlGroup5.


            //layoutControlItem33.Control.DataBindings

            for (int i = 0; i < layoutControlGroup6.Items.Count; i++)
            {
                this.layoutControlGroup6.Items[i].DataBindings.Clear();
            }

            for (int i = 0; i < layoutControlGroup5.Items.Count; i++)
            {
                this.layoutControlGroup5.Items[i].DataBindings.Clear();
            }

            for (int i = 0; i < layoutControlGroup7.Items.Count; i++)
            {
                this.layoutControlGroup7.Items[i].DataBindings.Clear();
            }

            for (int i = 0; i < layoutControlGroup8.Items.Count; i++)
            {
                this.layoutControlGroup8.Items[i].DataBindings.Clear();
            }

            txtStokKodu.DataBindings.Add("EditValue", StokArama, "StokKodu", false, DataSourceUpdateMode.OnPropertyChanged);
            lkpGrup.Properties.DataSource    = Grubu.StokGrupDoldur(SqlConnections.GetBaglanti(), trGenel);
            lkpGrup.Properties.ValueMember   = "StokGrupID";
            lkpGrup.Properties.DisplayMember = "StokGrupAdi";
            txtStokAdi.DataBindings.Add("EditValue", StokArama, "StokAdi", false, DataSourceUpdateMode.OnPropertyChanged);
            txtBarkodu.DataBindings.Add("EditValue", StokArama, "Barkod", false, DataSourceUpdateMode.OnPropertyChanged);
            checkEdit_SadeceSeciliFiyatiOlanlar.DataBindings.Add("EditValue", StokArama, "SadeceFiyatiOlanlar", false, DataSourceUpdateMode.OnPropertyChanged);
            SeciliFiyatTanimlariniAl();


            //checkedComboBoxFiyatTanimlari.DataBindings.Add("EditValue", StokArama, "StokFiyatTanimIDleri", true, DataSourceUpdateMode.OnPropertyChanged);
            //checkedComboBoxFiyatTanimlari.DataBindings.Add("Text", StokArama, "StokFiyatTanimAdlari", true, DataSourceUpdateMode.OnPropertyChanged);

            //checkedComboBoxFiyatTanimlari.

            txtAciklama.DataBindings.Add("EditValue", StokArama, "Aciklama", false, DataSourceUpdateMode.OnPropertyChanged);
            lkpGrup.DataBindings.Add("EditValue", StokArama, "StokGrupID", false, DataSourceUpdateMode.OnPropertyChanged);
            cmbAktifmi.DataBindings.Add("EditValue", StokArama, "Aktif", false, DataSourceUpdateMode.OnPropertyChanged);


            cmbUrunTanitim.DataBindings.Add("SelectedIndex", StokArama, "UrunTanitimdaGoster", false, DataSourceUpdateMode.OnPropertyChanged);
            lkpGrup.EditValueChanged += new EventHandler(lkpGrup_EditValueChanged);
            cmbEMagazaErisimi.DataBindings.Add("SelectedIndex", StokArama, "EMagazaErisimi", false, DataSourceUpdateMode.OnPropertyChanged);
            txtGaranti.DataBindings.Add("EditValue", StokArama, "Garanti", false, DataSourceUpdateMode.OnPropertyChanged);
            txtDesi.DataBindings.Add("EditValue", StokArama, "Desi", false, DataSourceUpdateMode.OnPropertyChanged);
            txtKisaAciklama.DataBindings.Add("EditValue", StokArama, "KisaAciklama", false, DataSourceUpdateMode.OnPropertyChanged);
            txtDetayliAciklama.DataBindings.Add("EditValue", StokArama, "DetayliUrunBilgisi", false, DataSourceUpdateMode.OnPropertyChanged);
            lkpHemenAlKategori.DataBindings.Add("EditValue", StokArama, "HemenAlKategoriID", false, DataSourceUpdateMode.OnPropertyChanged);
            cmbHemenAlKategoriGuncellenmesin.DataBindings.Add("SelectedIndex", StokArama, "HemenAlKategoriGuncellenmesin", false, DataSourceUpdateMode.OnPropertyChanged);
            lkpHemanAlDurum.DataBindings.Add("EditValue", StokArama, "HemenAlDrum", false, DataSourceUpdateMode.OnPropertyChanged);
            txtHemenAlSira.DataBindings.Add("EditValue", StokArama, "HemenAlSira", false, DataSourceUpdateMode.OnPropertyChanged);
            txtHemenAlID.DataBindings.Add("EditValue", StokArama, "HemenAlID", false, DataSourceUpdateMode.OnPropertyChanged);

            lkpAraGrup.DataBindings.Add("EditValue", StokArama, "StokAraGrupID", false, DataSourceUpdateMode.OnPropertyChanged);

            lkpAltGrup.DataBindings.Add("EditValue", StokArama, "StokAltGrupID", false, DataSourceUpdateMode.OnPropertyChanged);
            cmbMiktarGetir.DataBindings.Add("SelectedIndex", StokArama, "MiktariOlanlar", false, DataSourceUpdateMode.OnPropertyChanged);
            checkBox_MinMikAltındaolanlar.DataBindings.Add("Checked", StokArama, "MinMiktarinAltindaOlanlar", false, DataSourceUpdateMode.OnPropertyChanged);
            checkEdit_OlmasiGerekenMiktardanAzOlanlar.DataBindings.Add("Checked", StokArama, "OlmasiGerekenMiktardanAzOlanlar", false, DataSourceUpdateMode.OnPropertyChanged);

            lkpStokSayimGrubu.DataBindings.Add("EditValue", StokArama, "StokSayimGrubuID", false, DataSourceUpdateMode.OnPropertyChanged);

            txtOzelKodu1.DataBindings.Add("EditValue", StokArama, "OzelKod1", false, DataSourceUpdateMode.OnPropertyChanged);
            txtOzelKodu2.DataBindings.Add("EditValue", StokArama, "OzelKod2", false, DataSourceUpdateMode.OnPropertyChanged);
            txtOzelKodu3.DataBindings.Add("EditValue", StokArama, "OzelKod3", false, DataSourceUpdateMode.OnPropertyChanged);

            cmbStokTipi.DataBindings.Add("SelectedIndex", StokArama, "StokTipi", false, DataSourceUpdateMode.OnPropertyChanged);
            ceGruptakilerinHepsi.DataBindings.Add("Checked", StokArama, "StokGrupHepsiniGetir", false, DataSourceUpdateMode.OnPropertyChanged);

            txtStokAdi.Focus();
        }
        private void btnSec_Click(object sender, EventArgs e)
        {
            if (gvStokListesi.RowCount == 0)
            {
                return;
            }

            decimal Miktarr = 1;

            if (ceBarkoddanMiktarAl.Checked == true)
            {
                try
                {
                    trGenel = SqlConnections.GetBaglanti().BeginTransaction();
                    Miktarr = StokArama.BarkdundanMiktarVer(SqlConnections.GetBaglanti(), trGenel, MiktarliBarkod);
                    trGenel.Commit();
                }
                catch (Exception hata)
                {
                    trGenel.Rollback();
                    frmHataBildir frmHataBildir = new frmHataBildir(hata.Message, hata.StackTrace);
                    frmHataBildir.ShowDialog();
                }
            }
            if (ceMiktariElleGir.Checked == true && !gvStokListesi.IsMultiSelect) // eğer çoklu seçim ise aşağıda çağıracak bu satırları
            {
                frmMiktarGirr = new clsTablolar.frmMiktarGir(Miktarr, clsTablolar.frmMiktarGir.SayiCinsi.Ondalikli);
                frmMiktarGirr.labelControl1.Text = gvStokListesi.GetFocusedRowCellValue("StokAdi").ToString() + "\n Eklenecek Miktarı Girin";
                frmMiktarGirr.ShowDialog();
                Miktarr = Convert.ToDecimal(frmMiktarGirr.textEdit1.EditValue);
            }

            if (StokArama.SayimID != -1)
            {
                Miktarr = Convert.ToDecimal(gvStokListesi.GetFocusedRowCellValue("SayimMiktari"));
            }


            // bunu böyle yaptık çünkü birden fazla satır seçilme işlemindede çalışsın ve s
            // ve bşrden fazla satır seçildiğinde ilk önce seçimin ilk satırını versin
            if (ceCokluSecim.CheckState == CheckState.Checked && gvStokListesi.IsMultiSelect)
            {
                for (int i = 0; i < gvStokListesi.GetSelectedRows().Length; i++)
                {
                    if (ceMiktariElleGir.Checked == true)
                    {
                        frmMiktarGirr = new clsTablolar.frmMiktarGir(Miktarr);
                        frmMiktarGirr.labelControl1.Text = gvStokListesi.GetFocusedRowCellValue("StokAdi").ToString() + "\n Eklenecek Miktarı Girin";
                        frmMiktarGirr.ShowDialog();
                        Miktarr = Convert.ToDecimal(frmMiktarGirr.textEdit1.EditValue);
                    }

                    //if ((int)btnEdit_SayimAciklama.EditValue != -1)
                    if (StokArama.SayimID != -1)
                    {
                        Miktarr = Convert.ToDecimal(gvStokListesi.GetRowCellValue(gvStokListesi.GetSelectedRows()[i], "SayimMiktari"));
                    }


                    Stok_Sec((int)(gvStokListesi.GetRowCellValue(gvStokListesi.GetSelectedRows()[i], "StokID")), Miktarr);
                }
            }
            else
            {
                Stok_Sec((int)(gvStokListesi.GetFocusedRowCellValue("StokID")), Miktarr);
            }

            if (secilenKontrol != null)
            {
                secilenKontrol.SelectAll();
            }

            if (ceArdArdaEkle.Checked == false)
            {
                Close();
            }
        }
        private void btnFiltrele_Click(object sender, EventArgs e)
        {
            try
            {
                StokArama.FotoOzellikleri = (clsTablolar.Stok.csStokArama.enumFotoOzellikleri)Convert.ToInt32(lookUpEdit1.EditValue);

                // buraları biraz karışık açıklama lazım
                // stok arama yalada oldukça alakalı

                StokArama.StokFiyatTanimAdlari = "";
                StokArama.StokFiyatTanimIDleri = "";


                for (int i = 0, b = 0; i < checkedListBox_FiyatTanimlari.ItemCount; i++)
                {
                    if (checkedListBox_FiyatTanimlari.GetItemChecked(i) == true)
                    {
                        if (b > 0) // virgülü koyma ile alaklı bişi sanırım
                        {
                            StokArama.StokFiyatTanimAdlari += " ," + checkedListBox_FiyatTanimlari.GetDisplayItemValue(i);
                            StokArama.StokFiyatTanimIDleri += " ," + checkedListBox_FiyatTanimlari.GetItemValue(i);
                        }
                        else
                        {
                            StokArama.StokFiyatTanimAdlari += checkedListBox_FiyatTanimlari.GetDisplayItemValue(i);
                            StokArama.StokFiyatTanimIDleri += checkedListBox_FiyatTanimlari.GetItemValue(i);
                        }
                        b++;
                    }
                }

                switch (cmbN11.SelectedIndex)
                {
                case 0:
                    StokArama.N11Entegrasyonu = clsTablolar.Stok.csStokArama.n11entegrasyon.Hepsi;
                    break;

                case 1:
                    StokArama.N11Entegrasyonu = clsTablolar.Stok.csStokArama.n11entegrasyon.Olan;
                    break;

                case 2:
                    StokArama.N11Entegrasyonu = clsTablolar.Stok.csStokArama.n11entegrasyon.Olmayan;
                    break;

                default:
                    break;
                }


                //= StokArama.dt_StokListesi;

                if (cedit_FotoKatolog.Checked)
                {
                    gcStokListesi.MainView = layoutView1;
                    //layoutView1.OptionsView.ViewMode = DevExpress.XtraGrid.Views.Layout.LayoutViewMode.MultiColumn;
                    StokArama.TumFotograflariYukle = true;
                    //layoutView1.Columns["StokAdi"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    lvcolStokAdi.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    //lvcolStokID.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    layoutView1.OptionsMultiRecordMode.MultiColumnScrollBarOrientation = DevExpress.XtraGrid.Views.Layout.ScrollBarOrientation.Vertical;
                }
                else
                {
                    gcStokListesi.MainView         = gvStokListesi;
                    StokArama.TumFotograflariYukle = false;
                }

                if (ucStokGruplari1.AhandaBuradakiler != null && ucStokGruplari1.AhandaBuradakiler.Count != 0)
                {
                    StokArama.SeciliGruplar = ucStokGruplari1.AhandaBuradakiler.ToArray();

                    //StokArama.SeciliGruplar =
                }
                else
                {
                    StokArama.SeciliGruplar = null;
                }



                gvStokListesi.Columns.Clear();
                //layoutView1.Columns.Clear();
                trGenel = SqlConnections.GetBaglanti().BeginTransaction();
                gcStokListesi.DataSource = StokArama.StokListeGetir(SqlConnections.GetBaglanti(), trGenel);
                trGenel.Commit();


                if (cedit_FotoKatolog.Checked == false)
                {
                    GridArayuzIslemleri(enGridArayuzIslemleri.Get);
                }

                MiktarliBarkod = txtBarkodu.Text; // bunu neden buna eşitlemiştik

                KacSatirVar();
            }
            catch (Exception hata)
            {
                try { trGenel.Rollback(); } catch (Exception) { }

                frmHataBildir frmHataBildir = new frmHataBildir(hata.Message, hata.StackTrace);
                frmHataBildir.ShowDialog();
            }
        }
        void SeciliFiyatTanimlariniAl()
        {
            checkedListBox_FiyatTanimlari.DataSource    = FiyatTanimlari.TumFiyatTanimlariniGetir(SqlConnections.GetBaglanti(), trGenel, false);
            checkedListBox_FiyatTanimlari.DisplayMember = "FiyatTanimAdi";
            checkedListBox_FiyatTanimlari.ValueMember   = "FiyatTanimID";

            //checkedListBox_FiyatTanimlari.SetItemChecked(1, true);

            clsTablolar.Ayarlar.csAyarlar.StokListeFiyatTanimlari.Split(',');

            for (int i = 0; i < checkedListBox_FiyatTanimlari.ItemCount; i++)
            {
                if (clsTablolar.Ayarlar.csAyarlar.StokListeFiyatTanimlari.Split(',').Contains(checkedListBox_FiyatTanimlari.GetItemValue(i).ToString()))
                {
                    checkedListBox_FiyatTanimlari.SetItemChecked(i, true);
                }
            }
        }
 private void StokAltGrupGuncelle()
 {
     lkpAltGrup.Properties.DataSource    = AltGrubu.StokAltGrupDoldur(SqlConnections.GetBaglanti(), trGenel, StokArama.StokAraGrupID);
     lkpAltGrup.Properties.ValueMember   = "StokAltGrupID";
     lkpAltGrup.Properties.DisplayMember = "StokAltGrupAdi";
 }
 void lkpGrup_EditValueChanged(object sender, EventArgs e)
 {
     lkpAraGrup.Properties.DataSource    = AraGrubu.StokAraGrupDoldur(SqlConnections.GetBaglanti(), trGenel, csGenelKodlar.IDBossaEksiBirVer(lkpGrup.EditValue));
     lkpAraGrup.Properties.ValueMember   = "StokAraGrupID";
     lkpAraGrup.Properties.DisplayMember = "StokAraGrupAdi";
 }
Exemplo n.º 17
0
        private void cbtnKaydedildi_Click(object sender, EventArgs e)
        {
            try
            {
                if (XtraMessageBox.Show("Üretim Emri Durumu 'Kaydedildi' Olarak Değiştirilecek.\n{Üretim Fişleri silinecek.}\nOnaylıyor musunuz?", "ARES", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
                int SeciliSatir = gvUretimEmri.FocusedRowHandle;

                #region StokFis ve StokFisDetay Tablolarından  'StokFisNo' su yakalanan satır siliniyor.
                string StokFisID = "-1";
                using (SqlCommand cmd = new SqlCommand("Select StokFisID From StokFis Where StokFisNo=@StokFisNo", SqlConnections.GetBaglanti()))
                {
                    cmd.Parameters.Add("@StokFisNo", SqlDbType.NVarChar).Value = gvUretimEmri.GetFocusedRowCellValue("PartiNo").ToString();
                    using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult))
                        if (dr.Read())
                        {
                            StokFisID = dr["StokFisID"].ToString();
                        }
                }

                trGenel = SqlConnections.GetBaglanti().BeginTransaction();
                using (SqlCommand cmdDelete = new SqlCommand("Delete From StokFis Where StokFisID=@StokFisID", SqlConnections.GetBaglanti()))
                {
                    cmdDelete.Transaction = trGenel;
                    cmdDelete.Parameters.Add("@StokFisID", SqlDbType.Int).Value = StokFisID;
                    cmdDelete.ExecuteNonQuery();
                }

                System.Collections.Generic.List <Int32> hareketler = new System.Collections.Generic.List <int>();
                using (SqlCommand cmdHareketler = new SqlCommand("Select StokFisDetayID From StokFisDetay Where StokFisID=@StokFisID", SqlConnections.GetBaglanti()))
                {
                    cmdHareketler.Transaction = trGenel;

                    cmdHareketler.Parameters.Add("@StokFisID", SqlDbType.Int).Value = StokFisID;
                    using (SqlDataReader dr = cmdHareketler.ExecuteReader())
                        while (dr.Read())
                        {
                            hareketler.Add(Convert.ToInt32(dr["StokFisDetayID"].ToString()));
                        }
                }

                foreach (Int32 ID in hareketler)
                {
                    using (SqlCommand cmdDelete = new SqlCommand("Delete From StokFisDetay Where StokFisDetayID=@StokFisDetayID", SqlConnections.GetBaglanti()))
                    {
                        cmdDelete.Transaction = trGenel;
                        cmdDelete.Parameters.Add("@StokFisDetayID", SqlDbType.Int).Value = ID;
                        cmdDelete.ExecuteNonQuery();
                    }
                }

                trGenel.Commit();
                #endregion

                #region UretimEmri Kaydının Durum'u değiştiriliyor.
                using (SqlCommand cmd = new SqlCommand(@"Update UretimEmri Set Durum=0 Where UretimEmriID=@UretimEmriID", SqlConnections.GetBaglanti()))
                {
                    cmd.Parameters.Add("@UretimEmriID", SqlDbType.Int).Value = gvUretimEmri.GetFocusedRowCellValue("UretimEmriID").ToString();
                    cmd.ExecuteNonQuery();
                }
                #endregion
                dt.Clear();
                daUretim.Update(dt);
                daUretim.Fill(dt);

                gvUretimEmri.FocusedRowHandle = SeciliSatir;
            }
            catch (Exception hata)
            {
                frmHataBildir frmHataBildir = new frmHataBildir(hata.Message, hata.StackTrace);
                frmHataBildir.ShowDialog();
            }
        }
Exemplo n.º 18
0
        private void GenerateCodes_Click(object sender, RoutedEventArgs e)
        {
            var conn = (GeneratorConfig.Connection) this.ConnectionsCombo.SelectedItem;

            if (conn == null)
            {
                MessageBox.Show("A connection must be selected!");
                return;
            }

            var tables = this._tables.Where(x => x.IsChecked == true);

            if (this.ConnectionsCombo.SelectedItem == null)
            {
                MessageBox.Show("Please select at least one table!");
                return;
            }
            ;

            var noIdentifier = tables.FirstOrDefault(x => x.Identifier.IsTrimmedEmpty());

            if (noIdentifier != null)
            {
                MessageBox.Show("Identifier for table " + noIdentifier.FullName + " is empty!");
                return;
            }
            ;

            foreach (var table in tables)
            {
                try
                {
                    EntityModel rowModel;

                    using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                    {
                        connection.Open();
                        var    tableName = table.FullName;
                        string schema    = null;
                        if (tableName.IndexOf('.') > 0)
                        {
                            schema    = tableName.Substring(0, tableName.IndexOf('.'));
                            tableName = tableName.Substring(tableName.IndexOf('.') + 1);
                        }

                        rowModel = RowGenerator.GenerateModel(connection, schema, tableName,
                                                              table.Module, table.ConnectionKey, table.Identifier, table.PermissionKey, config);

                        var kdiff3Paths = new[]
                        {
                            config.KDiff3Path,
                            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "KDiff3\\kdiff3.exe"),
                            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "KDiff3\\kdiff3.exe"),
                        };

                        CodeFileHelper.Kdiff3Path = kdiff3Paths.FirstOrDefault(File.Exists);

                        if (config.TFSIntegration)
                        {
                            CodeFileHelper.SetupTFSIntegration(config.TFPath);
                        }

                        CodeFileHelper.SetupTSCPath(config.TSCPath);
                        var siteWebProj = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, config.WebProjectFile));

                        new EntityCodeGenerator(rowModel, config, siteWebProj).Run();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

            if (config.GenerateService ||
                config.GenerateUI ||
                config.GenerateCustom)
            {
                var siteWebProj = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, config.WebProjectFile));
                var siteWebPath = Path.GetDirectoryName(siteWebProj);
                CodeFileHelper.ExecuteTSC(Path.Combine(siteWebPath, @"Scripts\"), "");
            }

            MessageBox.Show("Code files for the selected table is generated. Please REBUILD SOLUTION before running application, otherwise you may have script errors!");
            GenerateCodeButton.IsEnabled = false;
        }
Exemplo n.º 19
0
        private decimal CiktiMiktariniGetir()
        {
            decimal CiktiMiktari = 0;

            using (SqlCommand cmd = new SqlCommand(@"SELECT     dbo.UretimEmri.UretimMiktari * dbo.ReceteDetail.Miktar AS CiktiMiktari
FROM         dbo.UretimEmri INNER JOIN
                      dbo.ReceteMaster ON dbo.UretimEmri.ReceteMasterID = dbo.ReceteMaster.ReceteMasterID INNER JOIN
                      dbo.ReceteDetail ON dbo.ReceteMaster.ReceteMasterID = dbo.ReceteDetail.ReceteMasterID
WHERE     (dbo.ReceteDetail.SatirTur = 1) AND (dbo.UretimEmri.UretimEmriID = @UretimEmriID)", SqlConnections.GetBaglanti()))
            {
                cmd.Parameters.Add("@UretimEmriID", SqlDbType.Int).Value = gvUretimEmri.GetFocusedRowCellValue("UretimEmriID").ToString();
                using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult))
                {
                    if (dr.Read())
                    {
                        CiktiMiktari = (decimal)dr["CiktiMiktari"];
                    }
                }
            }
            return(CiktiMiktari);
        }
Exemplo n.º 20
0
        public static AuditLogListResponse List(string schema, AuditLogListRequest request)
        {
#if COREFX
            var fld = Dependency.Resolve <IAuditLogRow>();
#else
            var fld = Dependency.Resolve <IAuditLogRow>(schema);
#endif

            Authorization.ValidateLoggedIn();

            var response = new AuditLogListResponse();

            using (var connection = SqlConnections.NewByKey("Default"))
            {
                response.Entities = new List <Row>();

                var row = ((Row)fld).CreateNew();

                if (request.Sort == null ||
                    request.Sort.Length == 0)
                {
                    request.Sort = new SortBy[] { new SortBy(fld.DateField.Name, true) }
                }
                ;

                var query = new SqlQuery().From(row)
                            .Select(
                    (Field)fld.IdField,
                    fld.EntityTypeIdField,
                    fld.EntityIdField,
                    fld.ParentTypeIdField,
                    fld.OldParentIdField,
                    fld.NewParentIdField,
                    fld.DateField,
                    (Field)fld.UserIdField,
                    fld.AuditTypeIdField,
                    fld.OldAuditDataField,
                    fld.NewAuditDataField)
                            .OrderBy(
                    (Field)fld.IdField)
                            .ApplySkipTakeAndCount(request.Skip, request.Take, request.ExcludeTotalCount)
                            .ApplySort(request.Sort);

                if (request.EntityTypeId != null &&
                    request.EntityId != null)
                {
                    var pEntityId     = query.AddParam(request.EntityId);
                    var pEntityTypeId = query.AddParam(request.EntityTypeId);

                    query.Where(~(
                                    ~(
                                        new Criteria(0, fld.EntityTypeIdField) == pEntityTypeId &
                                        new Criteria(0, fld.EntityIdField) == pEntityId) |
                                    ~(
                                        new Criteria(0, fld.ParentTypeIdField) == pEntityTypeId &
                                        ~(
                                            new Criteria(0, fld.OldParentIdField) == pEntityId |
                                            new Criteria(0, fld.NewParentIdField) == pEntityId))));
                }
                else
                {
                    if (request.EntityTypeId != null)
                    {
                        query.WhereEqual(fld.EntityTypeIdField, request.EntityTypeId);//Convert.ToInt32(request.EntityTypeId.Value));
                    }
                    if (request.EntityId != null)
                    {
                        query.WhereEqual(fld.EntityIdField, request.EntityId.Value);
                    }
                }

                response.TotalCount = query.ForEach(connection, delegate()
                {
                    response.Entities.Add(row.Clone());
                });

                response.SetSkipTakeTotal(query);

                response.IdNameLookups      = new Dictionary <EntityType, Dictionary <long, string> >();
                response.FieldTitles        = new Dictionary <EntityType, Dictionary <string, string> >();
                response.ForeignEntityTypes = new Dictionary <EntityType, Dictionary <string, string> >();
                response.EntityTitles       = new Dictionary <EntityType, string>();

                var lookups  = response.IdNameLookups;
                var titles   = response.FieldTitles;
                var foreigns = response.ForeignEntityTypes;
                var entities = response.EntityTitles;

                Action <EntityType, Int64> addLookup = (entityType, id) => {
                    Dictionary <long, string> lookup;
                    if (!lookups.TryGetValue(entityType, out lookup))
                    {
                        lookup = new Dictionary <long, string>();
                        lookups[entityType] = lookup;
                    }

                    if (!lookup.ContainsKey(id))
                    {
                        lookup[id] = null;
                    }
                };

                Action <EntityType, string> addTitle = (entityType, field) =>
                {
                    Dictionary <string, string> lookup;
                    if (!titles.TryGetValue(entityType, out lookup))
                    {
                        lookup             = new Dictionary <string, string>();
                        titles[entityType] = lookup;
                    }

                    if (!lookup.ContainsKey(field))
                    {
                        lookup[field] = null;
                    }
                };

                Action <EntityType> addEntity = (entityType) =>
                {
                    if (!entities.ContainsKey(entityType))
                    {
                        //Row r;
                        String s = null;
                        // TODO: FIX!
                        //if (schema.TypeToTable.TryGetValue(entityType, out r))
                        //    s = LocalText.TryGet(1055, "Db." + r.Table + ".EntitySingular", false);
                        s = s ?? Enum.GetName(typeof(EntityType), entityType);
                        entities[entityType] = s;
                    }
                };

                Action <EntityType, string, EntityType> addForeign = (entityType, field, foreignType) =>
                {
                    Dictionary <string, string> foreign;
                    if (!foreigns.TryGetValue(entityType, out foreign))
                    {
                        foreign = new Dictionary <string, string>();
                        foreigns[entityType] = foreign;
                    }

                    if (!foreign.ContainsKey(field))
                    {
                        foreign[field] = Enum.GetName(typeof(EntityType), foreignType);
                    }
                };

                foreach (var entity in response.Entities)
                {
                    addEntity(fld.EntityTypeIdField[entity]);
                    addLookup(fld.EntityTypeIdField[entity], fld.EntityIdField[entity].Value);
                    if (fld.ParentTypeIdField[entity] != null)
                    {
                        addEntity(fld.ParentTypeIdField[entity]);
                    }

                    //if (entity.UserId != null)
                    //    addLookup(UserRow.TableName, entity.UserId.Value);

                    Row theRow;
                    if (((AuditType?)fld.AuditTypeIdField[entity] == AuditType.Insert ||
                         (AuditType?)fld.AuditTypeIdField[entity] == AuditType.Update) &&
                        (fld.OldAuditDataField[entity] != null || fld.NewAuditDataField[entity] != null))
                    {
                        theRow = RowRegistry.ByConnectionKey(RowRegistry.DefaultConnectionKey)[fld.EntityTypeIdField[entity]].FirstOrDefault();
                        if (theRow == null)
                        {
                            continue;
                        }

                        UpdateAuditDataDictionary ud = new UpdateAuditDataDictionary();
                        if (fld.OldAuditDataField[entity] != null)
                        {
                            ud.Old = JsonConvert.DeserializeObject <Dictionary <string, object> >(fld.OldAuditDataField[entity].TrimToNull() ?? "{}", JsonSettings.Tolerant);
                        }

                        if (fld.NewAuditDataField[entity] != null)
                        {
                            ud.New = JsonConvert.DeserializeObject <Dictionary <string, object> >(fld.OldAuditDataField[entity].TrimToNull() ?? "{}", JsonSettings.Tolerant);
                        }

                        for (var i = 0; i < 2; i++)
                        {
                            var d = (i == 0) ? ud.Old : ud.New;
                            if (d != null)
                            {
                                foreach (var p in d)
                                {
                                    addTitle(fld.EntityTypeIdField[entity], p.Key);

                                    if (p.Value != null &&
                                        p.Value is Int16 ||
                                        p.Value is Int32 ||
                                        p.Value is Int64)
                                    {
                                        var f = theRow.FindField(p.Key);
                                        if (!ReferenceEquals(null, f) &&
                                            f.ForeignTable != null)
                                        {
                                            //EntityType foreignType;
                                            //if (schema.TableToType.TryGetValue(f.ForeignTable, out foreignType))
                                            {
                                                addForeign(fld.EntityTypeIdField[entity], p.Key, f.ForeignTable);
                                                addLookup(f.ForeignTable, Convert.ToInt64(p.Value));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                foreach (var pair in response.IdNameLookups)
                {
                    Row entity = RowRegistry.ByConnectionKey(RowRegistry.DefaultConnectionKey)[pair.Key].FirstOrDefault();
                    if (entity != null)
                    {
                        var idRow     = entity as IIdRow;
                        var nameField = entity.GetNameField() as StringField;
                        if (idRow != null &&
                            !ReferenceEquals(null, nameField))
                        {
                            var lookup = pair.Value;
                            var idName = GetIdNameDictionary(connection, (IIdRow)entity, nameField, lookup.Keys);
                            foreach (var p in idName)
                            {
                                lookup[p.Key] = p.Value;
                            }
                        }
                    }
                }

                foreach (var pair in response.FieldTitles)
                {
                    Row entity = RowRegistry.ByConnectionKey(RowRegistry.DefaultConnectionKey)[pair.Key].FirstOrDefault();
                    if (entity != null)
                    {
                        var lookup = pair.Value;
                        var keys   = new string[lookup.Keys.Count];
                        lookup.Keys.CopyTo(keys, 0);
                        foreach (var key in keys)
                        {
                            Field f;
                            if (key.EndsWith("Id"))
                            {
                                var s = key.Substring(0, key.Length - 2);
                                f = entity.FindField(s);
                                if (!ReferenceEquals(null, f))
                                {
                                    lookup[key] = f.Title;
                                    continue;
                                }
                            }

                            f = entity.FindField(key);
                            if (!ReferenceEquals(null, f))
                            {
                                lookup[key] = f.Title;
                            }
                        }
                    }
                }


                return(response);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Automatically creates a database for the template if it doesn't already exists.
        /// You might delete this method to disable auto create functionality.
        /// </summary>
        private static void EnsureDatabase(string databaseKey)
        {
            var cs = SqlConnections.GetConnectionString(databaseKey);

            var  serverType = cs.Dialect.ServerType;
            bool isSql      = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase);
            bool isPostgres = serverType.StartsWith("Postgres", StringComparison.OrdinalIgnoreCase);
            bool isMySql    = serverType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase);
            bool isSqlite   = serverType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase);
            bool isFirebird = serverType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase);

            if (isSqlite)
            {
                var contentRoot = Serenity.Dependency.Resolve <IWebHostEnvironment>().ContentRootPath;
                Directory.CreateDirectory(Path.Combine(contentRoot, "App_Data"));
                return;
            }

            var cb = cs.ProviderFactory.CreateConnectionStringBuilder();

            cb.ConnectionString = cs.ConnectionString;

            if (isFirebird)
            {
                if (cb.ConnectionString.IndexOf(@"localhost") < 0 &&
                    cb.ConnectionString.IndexOf(@"127.0.0.1") < 0)
                {
                    return;
                }

                var database = cb["Database"] as string;
                if (string.IsNullOrEmpty(database))
                {
                    return;
                }

                database = Path.GetFullPath(database);
                if (File.Exists(database))
                {
                    return;
                }
                Directory.CreateDirectory(Path.GetDirectoryName(database));

                using (var fbConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName))
                {
                    ((WrappedConnection)fbConnection).ActualConnection.GetType()
                    .GetMethod("CreateDatabase", new Type[] { typeof(string), typeof(bool) })
                    .Invoke(null, new object[] { fbConnection.ConnectionString, false });
                }

                return;
            }

            if (!isSql && !isPostgres && !isMySql)
            {
                return;
            }

            string catalogKey = "?";

            foreach (var ck in new[] { "Initial Catalog", "Database", "AttachDBFilename" })
            {
                if (cb.ContainsKey(ck))
                {
                    catalogKey = ck;
                    break;
                }
            }

            var catalog = cb[catalogKey] as string;

            cb[catalogKey] = null;

            using (var serverConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName))
            {
                try
                {
                    serverConnection.Open();
                }
                catch (SqlException ex)
                {
                    if (ex.Number != -2146232060)
                    {
                        throw;
                    }

                    const string oldVer = @"\v11.0";

                    if (cb.ConnectionString.IndexOf(oldVer) >= 0)
                    {
                        throw new Exception(
                                  "You don't seem to have SQL Express LocalDB 2012 installed.\r\n\r\n" +
                                  "If you have Visual Studio 2015 (with SQL LocalDB 2014) " +
                                  "try changing '" + databaseKey + "' connection string in WEB.CONFIG to:\r\n\r\n" +
                                  cs.ConnectionString.Replace(oldVer, @"\MSSqlLocalDB") + "\r\n\r\nor:\r\n\r\n" +
                                  cs.ConnectionString.Replace(oldVer, @"\v12.0") + "';\r\n\r\n" +
                                  "You can also try another SQL server type like .\\SQLExpress.");
                    }

                    throw;
                }

                string databasesQuery      = "SELECT * FROM sys.databases WHERE NAME = @name";
                string createDatabaseQuery = @"CREATE DATABASE [{0}]";

                if (isPostgres)
                {
                    databasesQuery      = "select * from postgres.pg_catalog.pg_database where datname = @name";
                    createDatabaseQuery = "CREATE DATABASE \"{0}\"";
                }
                else if (isMySql)
                {
                    databasesQuery      = "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @name";
                    createDatabaseQuery = "CREATE DATABASE `{0}`";
                }

                if (serverConnection.Query(databasesQuery, new { name = catalog }).Any())
                {
                    return;
                }

                var isLocalServer = isSql && (
                    serverConnection.ConnectionString.IndexOf(@"(localdb)\", StringComparison.OrdinalIgnoreCase) >= 0 ||
                    serverConnection.ConnectionString.IndexOf(@".\") >= 0 ||
                    serverConnection.ConnectionString.IndexOf(@"localhost") >= 0 ||
                    serverConnection.ConnectionString.IndexOf(@"127.0.0.1") >= 0);

                string command;
                if (isLocalServer)
                {
                    string baseDirectory;
                    var    hostingEnvironment = Serenity.Dependency.TryResolve <IWebHostEnvironment>();
                    if (hostingEnvironment != null)
                    {
                        baseDirectory = hostingEnvironment.ContentRootPath;
                    }
                    else
                    {
                        baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    }

                    var filename = Path.Combine(Path.Combine(baseDirectory, "App_Data/".Replace('/', Path.DirectorySeparatorChar)), catalog);
                    Directory.CreateDirectory(Path.GetDirectoryName(filename));

                    command = String.Format(@"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}.ldf')",
                                            catalog, filename);

                    if (File.Exists(filename + ".mdf"))
                    {
                        command += " FOR ATTACH";
                    }
                }
                else
                {
                    command = String.Format(createDatabaseQuery, catalog);
                }

                serverConnection.Execute(command);
                SqlConnection.ClearAllPools();
            }
        }
Exemplo n.º 22
0
        public void SqlLogger_WorksProperly()
        {
            using (new MunqContext())
            {
                var fld = SystemLogRow.Fields;

                var registrar  = Dependency.Resolve <IDependencyRegistrar>();
                var fakeConfig = A.Fake <IConfigurationRepository>();
                A.CallTo(() => fakeConfig.Load(null))
                .WithAnyArguments()
                .ReturnsLazily((Type t) =>
                               JSON.ParseTolerant(JSON.Stringify(new
                {
                    Level         = "Debug",
                    ConnectionKey = "Serenity",
                    InsertCommand = new SqlInsert(fld.TableName)
                                    .SetTo(fld.EventDate, "@date")
                                    .SetTo(fld.LogLevel, "@level")
                                    .SetTo(fld.LogMessage, "@message")
                                    .SetTo(fld.Exception, "@exception")
                                    .SetTo(fld.SourceType, "@source")
                                    .ToString()
                }), t));

                registrar.RegisterInstance <IConfigurationRepository>("Application", fakeConfig);

                using (var context = NewDbTestContext())
                {
                    context.ExpireOverrides();
                    var logger = new SqlLogger();
                    registrar.RegisterInstance <ILogger>(logger);

                    Log.MinimumLevel = LoggingLevel.Debug;
                    Log.Debug("Hello1", new Exception("SomeException1"), this.GetType());
                    Log.Info("Hello2", new Exception("SomeException2"), this.GetType());
                    Log.Warn("Hello3", new Exception("SomeException3"), this.GetType());

                    using (var connection = SqlConnections.NewByKey("Serenity"))
                    {
                        logger.Flush();
                        var items = connection.List <SystemLogRow>(q => q.SelectTableFields().OrderBy(fld.ID, desc: true).Take(3));

                        Assert.Equal(3, items.Count);

                        var item = items[2];
                        Assert.Equal("Hello1", item.LogMessage);
                        Assert.Contains("SomeException1", item.Exception);
                        Assert.Equal("Debug", item.LogLevel);
                        Assert.Equal(this.GetType().FullName, item.SourceType);
                        Assert.True(DateTime.Now.Subtract(item.EventDate.Value).TotalSeconds < 60);

                        item = items[1];
                        Assert.Equal("Hello2", item.LogMessage);
                        Assert.Contains("SomeException2", item.Exception);
                        Assert.Equal("Info", item.LogLevel);
                        Assert.Equal(this.GetType().FullName, item.SourceType);
                        Assert.True(DateTime.Now.Subtract(item.EventDate.Value).TotalSeconds < 60);

                        item = items[0];
                        Assert.Equal("Hello3", item.LogMessage);
                        Assert.Contains("SomeException3", item.Exception);
                        Assert.Equal("Warn", item.LogLevel);
                        Assert.Equal(this.GetType().FullName, item.SourceType);
                        Assert.True(DateTime.Now.Subtract(item.EventDate.Value).TotalSeconds < 60);
                    }
                }
            }
        }
Exemplo n.º 23
0
        public List <SimpleReportViewModel> Bar()
        {
            //list of department
            var lstModel = new List <SimpleReportViewModel>();

            using (var ChartConnection = SqlConnections.NewByKey("Default"))
            {
                //var xx = ChartConnection.List<SchedulingRow>().FindAll(s => s.Month == DateTime.Now.Month.ToString());
                string query = @"select fullDate, Value
                                from MeterDetail inner join Scheduling 
                                on MeterDetail.SchedulingID = Scheduling.SchedulingID
                                where FullDate between @DateStart and @DateEnd
                                --and MeterID = @MeterId
                                and ParameterID in @ParameterId";

                string dateStart   = "2019-03-14 11:43:21";
                string dateEnd     = "2019-08-09 15:43:21";
                int    meterId     = 1;
                int[]  parameterId = { 1, 2, 3, 4, 5 };

                var chartConnection = ChartConnection.Query(query,
                                                            param: new
                {
                    MeterId     = meterId,
                    ParameterId = parameterId,
                    DateStart   = dateStart,
                    DateEnd     = dateEnd
                });

                string queryTwo = @"select * from Meter inner join Consumer on Meter.ConsumerID = Consumer.ConsumerID";
                var    meters   = ChartConnection.Query(queryTwo);

                string queryThree = @"select * from Parameter inner join MeterDetail on MeterDetail.ParameterID = Parameter.ParameterID where MeterID = @MeterId";
                var    parameters = ChartConnection.Query(queryThree,
                                                          param: new
                {
                    MeterId = meterId
                });

                string queryFour    = @"select ParameterID,FullDate, Value
                                     from MeterDetail inner join Scheduling
                                     on MeterDetail.SchedulingID = Scheduling.SchedulingID
                                     where FullDate between @DateStart and @DateEnd and MeterID = @MeterId and ParameterID in @ParameterId
                                     order by ParameterID";
                var    chartDataset = ChartConnection.Query(queryFour,
                                                            param: new
                {
                    MeterId     = meterId,
                    ParameterId = parameterId,
                    DateStart   = dateStart,
                    DateEnd     = dateEnd
                });
                foreach (var item in chartConnection)
                {
                    string date = item.Day + "";
                    int    v    = int.Parse(item.Value);
                    lstModel.Add(new SimpleReportViewModel
                    {
                        DimensionOne = date,
                        Quantity     = v
                    });
                }
                return(lstModel);
            }
        }
Exemplo n.º 24
0
        private void GenerateCodes_Click(object sender, RoutedEventArgs e)
        {
            if (this.ConnectionsCombo.SelectedItem == null ||
                this.TablesCombo.SelectedItem == null)
            {
                MessageBox.Show("A connection string and table name must be selected!");
                return;
            }

            if (EntitySingular.IsTrimmedEmpty())
            {
                MessageBox.Show("Entity class identifier must be entered!");
                return;
            }

            if (Permission.IsTrimmedEmpty())
            {
                MessageBox.Show("Permission key must be entered!");
                return;
            }

            string tableName = (string)this.TablesCombo.SelectedItem;

            try
            {
                EntityCodeGenerationModel rowModel;
                var conn = (GeneratorConfig.Connection) this.ConnectionsCombo.SelectedItem;
                using (var connection = SqlConnections.New(conn.ConnectionString, conn.ProviderName))
                {
                    connection.Open();
                    var    table       = (string)this.TablesCombo.SelectedItem;
                    string tableSchema = null;
                    if (table.IndexOf('.') > 0)
                    {
                        tableSchema = table.Substring(0, table.IndexOf('.'));
                        table       = table.Substring(table.IndexOf('.') + 1);
                    }
                    rowModel = RowGenerator.GenerateModel(connection, tableSchema, table,
                                                          Module, ConnectionKey, EntitySingular, Permission, config);
                    new EntityCodeGenerator(rowModel, config).Run();

                    MessageBox.Show("Code files for the selected table is generated!");

                    GenerateCodeButton.IsEnabled = false;
                }

                var cnn      = this.ConnectionsCombo.SelectedItem as GeneratorConfig.Connection;
                var tableObj = cnn != null?cnn.Tables.FirstOrDefault(x => x.Tablename == tableName) : null;

                if (tableObj == null && cnn != null)
                {
                    tableObj           = new GeneratorConfig.Table();
                    tableObj.Tablename = tableName;
                    cnn.Tables.Add(tableObj);
                }

                if (tableObj != null)
                {
                    tableObj.Identifier    = EntitySingular;
                    tableObj.PermissionKey = Permission;
                    tableObj.Module        = Module;
                    tableObj.ConnectionKey = ConnectionKey;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            config.Save();
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            var assembly = Assembly.GetAssembly(typeof(Serene.Northwind.Entities.CategoryRow));

            var rowClasses = assembly.GetTypes().Where(w => w.GetCustomAttribute <TableNameAttribute>() != null);

            using (var connection = SqlConnections.New(@"Data Source=(LocalDb)\MSSqlLocalDB; Initial Catalog=Serene_Northwind_v1; Integrated Security=True", "System.Data.SqlClient"))
            {
                connection.Open();
                var schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType);

                foreach (var rowClass in rowClasses)
                {
                    Row row = (Row)Activator.CreateInstance(rowClass);
                    Console.WriteLine(row.Table);
                    var    tableName = row.Table;
                    string schema    = null;
                    if (tableName.IndexOf('.') > 0)
                    {
                        schema    = tableName.Substring(0, tableName.IndexOf('.'));
                        tableName = tableName.Substring(tableName.IndexOf('.') + 1);
                    }

                    var rowFields = row.GetFields();
                    var dbFields  = schemaProvider.GetFieldInfos(connection, schema ?? "dbo", tableName);

                    for (int i = 0; i < row.FieldCount; i++)
                    {
                        Field rowfield = rowFields[i];
                        if (EntityFieldExtensions.IsTableField(rowfield))
                        {
                            var    dbField = dbFields.FirstOrDefault(f => f.FieldName == rowfield.Name);
                            string strNull = rowfield.Flags.HasFlag(FieldFlags.NotNull) ? "NOT NULL" : "NULL";

                            if (dbField == null)
                            {
                                Console.WriteLine($"\t{rowfield.Type} {rowfield.Name} {strNull} \t\t no corresponding field in database!");
                            }
                            else
                            {
                                string strTypeMismatch = rowfield.Type.ToString() == SchemaHelper.SqlTypeNameToFieldType(dbField.DataType, dbField.Size) ?
                                                         "" : "datatype mismatch";

                                string strNullableMismatch = rowfield.Flags.HasFlag(FieldFlags.NotNull) == !dbField.IsNullable ?
                                                             "" : "nullable mismatch";


                                Console.WriteLine($"\t{rowfield.Type} {rowfield.Name} {strNull}"
                                                  + $"\t\t {strTypeMismatch}\t{strNullableMismatch}");
                            }
                        }
                    }
                    Console.WriteLine();
                }


                connection.Close();
            }

            Console.ReadKey();
        }
Exemplo n.º 26
0
        public void Run(string csproj, string[] args)
        {
            var projectDir = Path.GetDirectoryName(csproj);

            var outFile       = GetOption(args, "o").TrimToNull();
            var connectionKey = GetOption(args, "c").TrimToNull();
            var table         = GetOption(args, "t").TrimToNull();
            var what          = GetOption(args, "w").TrimToNull();
            var module        = GetOption(args, "m").TrimToNull();
            var identifier    = GetOption(args, "i").TrimToNull();
            var permissionKey = GetOption(args, "p").TrimToNull();

            if (identifier != null)
            {
                CodeFileHelper.Overwrite = true;
            }

            var config = GeneratorConfig.LoadFromFile(Path.Combine(projectDir, "sergen.json"));

            if (!string.IsNullOrEmpty(config.CustomTemplates))
            {
                Templates.TemplatePath = Path.Combine(projectDir, config.CustomTemplates);
            }

            var connectionKeys = config.Connections
                                 .Where(x => !x.ConnectionString.IsEmptyOrNull())
                                 .Select(x => x.Key).ToList();

            var appSettingsFile = Path.Combine(projectDir, "appsettings.json");
            AppSettingsFormat appSettings;

            if (File.Exists(appSettingsFile))
            {
                appSettings = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(appSettingsFile).TrimToNull() ?? "{}");
            }
            else
            {
                appSettings = new AppSettingsFormat();
            }

            connectionKeys.AddRange(appSettings.Data.Keys);

            var appSettingsFile2 = Path.Combine(projectDir, "appsettings.machine.json");

            if (File.Exists(appSettingsFile2))
            {
                var appSettings2 = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(appSettingsFile2).TrimToNull() ?? "{}");
                foreach (var pair in appSettings2.Data)
                {
                    appSettings.Data[pair.Key] = pair.Value;
                }
            }

            connectionKeys.AddRange(appSettings.Data.Keys);

            connectionKeys = connectionKeys.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(x => x).ToList();

            if (connectionKeys.Count == 0)
            {
                Console.Error.WriteLine("No connections in appsettings.json or sergen.json!");
                Environment.Exit(1);
            }

            if (outFile == null && connectionKey == null)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("=== Table Code Generation ===");
                Console.WriteLine("");
                Console.ResetColor();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Connections:");
                Console.ResetColor();
                foreach (var x in connectionKeys)
                {
                    Console.WriteLine(x);
                }
                Console.ResetColor();
                Console.WriteLine();
            }
            else if (connectionKey == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(connectionKeys));
                Environment.Exit(0);
            }

            string userInput = null;

            if (outFile == null && connectionKey == null)
            {
                userInput = connectionKeys.Count == 1 ? connectionKeys[0] : null;
                while (connectionKey == null ||
                       !connectionKeys.Contains(connectionKey, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Connection: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    connectionKey           = Hinter.ReadHintedLine(connectionKeys, userInput: userInput);
                    userInput = connectionKey;

                    if (connectionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput     = connectionKey;
            connectionKey = connectionKeys.Find(x => string.Compare(x, userInput, StringComparison.OrdinalIgnoreCase) == 0);
            if (connectionKey == null)
            {
                Console.Error.WriteLine("Can't find connection with key: " + userInput + "!");
                Environment.Exit(1);
            }

            if (outFile == null)
            {
                Console.ResetColor();
                Console.WriteLine();
            }

            var dataConnection = appSettings.Data.ContainsKey(connectionKey) ?
                                 appSettings.Data[connectionKey] : null;

            var confConnection = config.Connections.FirstOrDefault(x =>
                                                                   string.Compare(x.Key, connectionKey, StringComparison.OrdinalIgnoreCase) == 0);

            var connectionString = dataConnection != null?dataConnection.ConnectionString.TrimToNull() : null;

            if (connectionString == null && confConnection != null)
            {
                connectionString = confConnection.ConnectionString.TrimToNull();
            }

            var providerName = dataConnection != null?dataConnection.ProviderName.TrimToNull() : null;

            if (providerName == null && confConnection != null)
            {
                providerName = confConnection.ProviderName.TrimToNull();
            }
            providerName = providerName ?? "System.Data.SqlClient";

#if !NET45
            DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);
            DbProviderFactories.RegisterFactory("Microsoft.Data.Sqlite", Microsoft.Data.Sqlite.SqliteFactory.Instance);
            DbProviderFactories.RegisterFactory("Npgsql", Npgsql.NpgsqlFactory.Instance);
            DbProviderFactories.RegisterFactory("FirebirdSql.Data.FirebirdClient", FirebirdSql.Data.FirebirdClient.FirebirdClientFactory.Instance);
            DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySql.Data.MySqlClient.MySqlClientFactory.Instance);
#endif

            if (connectionString.IndexOf("../../..") >= 0)
            {
                connectionString = connectionString.Replace("../../..", Path.GetDirectoryName(csproj));
            }
            else if (connectionString.IndexOf(@"..\..\..\") >= 0)
            {
                connectionString = connectionString.Replace(@"..\..\..\", Path.GetDirectoryName(csproj));
            }

            ISchemaProvider  schemaProvider;
            List <TableName> tableNames;
            using (var connection = SqlConnections.New(connectionString, providerName))
            {
                schemaProvider = SchemaHelper.GetSchemaProvider(connection.GetDialect().ServerType);
                tableNames     = schemaProvider.GetTableNames(connection).ToList();
            }

            var tables = tableNames.Select(x => x.Tablename).ToList();

            if (outFile == null && table == null)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Available Tables:");
                Console.ResetColor();

                foreach (var x in tables)
                {
                    Console.WriteLine(x);
                }
            }
            else if (table == null)
            {
                File.WriteAllText(outFile, JSON.Stringify(tableNames.Select(x =>
                {
                    var xct = confConnection == null ? null : confConnection.Tables.FirstOrDefault(z => string.Compare(z.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);
                    return(new
                    {
                        name = x.Tablename,
                        module = xct == null || xct.Module.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(connectionKey) : xct.Module,
                        permission = xct == null || xct.PermissionKey.IsTrimmedEmpty() ? "Administration:General" : xct.PermissionKey,
                        identifier = xct == null || xct.Identifier.IsEmptyOrNull() ? RowGenerator.ClassNameFromTableName(x.Table) : xct.Identifier,
                    });
                })));

                Environment.Exit(0);
            }

            userInput = tables.Count == 1 ? tables[0] : null;
            if (userInput == null && schemaProvider.DefaultSchema != null &&
                tables.Any(x => x.StartsWith(schemaProvider.DefaultSchema + ".")))
            {
                userInput = schemaProvider.DefaultSchema + ".";
            }

            if (outFile == null)
            {
                Console.WriteLine();

                while (table == null ||
                       !tables.Contains(table, StringComparer.OrdinalIgnoreCase))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    table     = Hinter.ReadHintedLine(tables, userInput: userInput);
                    userInput = table;

                    if (table == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            userInput = table;
            var tableName = tableNames.First(x => string.Compare(x.Tablename, userInput, StringComparison.OrdinalIgnoreCase) == 0);
            if (tableName == null)
            {
                Console.Error.WriteLine("Can't find table with name: " + userInput + "!");
                Environment.Exit(1);
            }

            var confTable = confConnection == null ? null : confConnection.Tables.FirstOrDefault(x =>
                                                                                                 string.Compare(x.Tablename, table, StringComparison.OrdinalIgnoreCase) == 0);

            if (module == null)
            {
                userInput = confTable == null || confTable.Module.IsEmptyOrNull() ?
                            RowGenerator.ClassNameFromTableName(connectionKey) : confTable.Module;

                Console.WriteLine();

                while (module.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Module name for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    module    = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = module;

                    if (module == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (identifier == null)
            {
                userInput = confTable == null || confTable.Identifier.IsEmptyOrNull() ?
                            RowGenerator.ClassNameFromTableName(tableName.Table) : confTable.Identifier;

                Console.WriteLine();

                while (identifier.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a class Identifier for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    identifier = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput  = identifier;

                    if (identifier == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            if (permissionKey == null)
            {
                userInput = confTable == null || confTable.PermissionKey.IsTrimmedEmpty() ?
                            "Administration:General" : confTable.PermissionKey;

                Console.WriteLine();

                while (permissionKey.IsTrimmedEmpty())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Enter a Permission Key for table: ('!' to abort)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    permissionKey           = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = permissionKey;

                    if (permissionKey == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }


            if (what == null)
            {
                Console.WriteLine();

                userInput = "RSUC";
                while (what.IsEmptyOrNull())
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Choose What to Generate (R:Row, S:Repo+Svc, U=UI, C=Custom)");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    what      = Hinter.ReadHintedLine(new string[0], userInput: userInput);
                    userInput = what;

                    if (what == "!")
                    {
                        Console.ResetColor();
                        return;
                    }
                }
            }

            config.GenerateRow     = what.IndexOf("R", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateService = what.IndexOf("S", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateUI      = what.IndexOf("U", StringComparison.OrdinalIgnoreCase) >= 0;
            config.GenerateCustom  = what.IndexOf("C", StringComparison.OrdinalIgnoreCase) >= 0;

            Console.ResetColor();
            Console.WriteLine();

            if (confConnection == null)
            {
                confConnection = new GeneratorConfig.Connection
                {
                    Key = connectionKey
                };
                config.Connections.Add(confConnection);
            }

            if (confTable == null)
            {
                confTable = new GeneratorConfig.Table
                {
                    Identifier    = identifier,
                    Module        = module,
                    PermissionKey = permissionKey,
                    Tablename     = tableName.Tablename
                };

                confConnection.Tables.Add(confTable);
            }
            else
            {
                confTable.Identifier    = identifier;
                confTable.Module        = module;
                confTable.PermissionKey = permissionKey;
            }

            File.WriteAllText(Path.Combine(projectDir, "sergen.json"), config.SaveToJson());

            using (var connection = SqlConnections.New(connectionString, providerName))
            {
                connection.Open();

                var rowModel = RowGenerator.GenerateModel(connection, tableName.Schema, tableName.Table,
                                                          module, connectionKey, identifier, permissionKey, config);

                rowModel.AspNetCore = true;

                var kdiff3Paths = new[]
                {
                    config.KDiff3Path
                };

                CodeFileHelper.Kdiff3Path = kdiff3Paths.FirstOrDefault(File.Exists);
                CodeFileHelper.TSCPath    = config.TSCPath ?? "tsc";

                new EntityCodeGenerator(rowModel, config, csproj).Run();
            }
        }
Exemplo n.º 27
0
        void GridArayuzleriYukle(Control ctrl)
        {
            DevExpress.XtraGrid.GridControl gc = new GridControl();
            gc = ctrl as DevExpress.XtraGrid.GridControl;
            DevExpress.XtraGrid.Views.Grid.GridView gv = (DevExpress.XtraGrid.Views.Grid.GridView)gc.Views[0];

            MemoryStream ms = cs.csGridLayout.GetLayout(Convert.ToInt32(frmKullaniciGiris.KullaniciID), this.Name, gv.Name, SqlConnections.GetBaglanti(), trGenel);

            if (ms.Length > 0)
            {
                gv.RestoreLayoutFromStream(ms);
            }
        }
Exemplo n.º 28
0
        public static void sendEMailThroughOUTLOOK(string mail,string persona , string ticket,int dia)
        {
            try
            {
                SqlConnections temp = new SqlConnections(); // Create the Outlook application.
                Random rand = new Random();
               int unique = rand.Next(1,999999999);
                Outlook.Application oApp = new Outlook.Application();

                Outlook.NameSpace ns = oApp.GetNamespace("MAPI");
                Outlook.MAPIFolder f = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                System.Threading.Thread.Sleep(9000); // test

               Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
               oMsg.HTMLBody = "La persona : " + persona + " cuenta aun con una solicitud pendiente de aprobar<br/>"
                   + "Favor de ingresar a la siguiente liga http://192.168.26.160/pendingApproval/?id=" +ticket+"&unique="+unique+" para aprobar o rechazar el ticket " + ticket
                   +"<br/><b>Atencion : Una vez que actualize el ticket la liga dejara de funcionar es una liga unica. <b/>";
             //  string liga = "http://192.168.26.160/pendingApproval/?id="+ticket + "&unique=" + unique;
              //string query = "INSERT INTO ligas (WORKORDERID,link) VALUES ("+ticket+","+unique+")";
               // temp.insertTemp(query);
               oMsg.Subject = "Pending Aproval Ticket: "+ticket;
               Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
               Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(mail);
               oRecip.Resolve();

                string query = "select count (*) FROM ligas WHERE WORKORDERID = "+ticket;
                int valor = temp.consultaDia(query);

                if (valor == 0)
                {
                    query = "INSERT INTO ligas (WORKORDERID,LINK,nombre_status) VALUES (" + ticket + "," + unique + "," + dia + ")";
                    temp.insertTemp(query);
                    oMsg.Send();
                    oRecip = null;
                    oRecips = null;
                    oMsg = null;
                    oApp = null;
                    Console.WriteLine("correo enviado");
                }//SI esl query regresa 0 el ticket no existe en la tabla temporal por lo tannto se crea un nuevo ticket
                else
                {
                    query = "select nombre_status FROM ligas WHERE WORKORDERID = "+ticket;
                    valor = temp.consultaDia(query);

                    if (dia != valor)
                    {

                        query = "UPDATE ligas SET nombre_status = " + dia + " WHERE workorderid = " + ticket;
                        temp.insertTemp(query);
                        oMsg.Send();
                        oRecip = null;
                        oRecips = null;
                        oMsg = null;
                        oApp = null;
                        Console.WriteLine("correo enviado");

                    }
                    else
                    {
                        Console.WriteLine("El usuario ya recibio un correo el dia de hoy");

                    }
                }//si el query regresa diferente de 0 es porque el ticket ya existe en la tabla

            }//end of try block
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }//end of catch
        }
Exemplo n.º 29
0
        private bool ValidateFirstTimeUser(ref string username, string password)
        {
            var throttler = new Throttler("ValidateUser:"******"Error on directory first time authentication", ex, this.GetType());
                return(false);
            }

            try
            {
                string salt        = null;
                var    hash        = UserRepository.GenerateHash(password, ref salt);
                var    displayName = entry.FirstName + " " + entry.LastName;
                var    email       = entry.Email.TrimToNull() ?? (username + "@yourdefaultdomain.com");
                username = entry.Username.TrimToNull() ?? username;

                using (var connection = SqlConnections.NewFor <UserRow>())
                    using (var uow = new UnitOfWork(connection))
                    {
                        var userId = (int)connection.InsertAndGetID(new UserRow
                        {
                            Username            = username,
                            Source              = "ldap",
                            DisplayName         = displayName,
                            Email               = email,
                            PasswordHash        = hash,
                            PasswordSalt        = salt,
                            IsActive            = 1,
                            InsertDate          = DateTime.Now,
                            InsertUserId        = 1,
                            LastDirectoryUpdate = DateTime.Now
                        });

                        uow.Commit();

                        UserRetrieveService.RemoveCachedUser(userId, username);
                    }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error while importing directory user", ex, this.GetType());
                return(false);
            }
        }
Exemplo n.º 30
0
        public Result <ServiceResponse> ResetPassword(ResetPasswordRequest request)
        {
            return(this.InTransaction("Default", uow =>
            {
                request.CheckNotNull();

                if (string.IsNullOrEmpty(request.Token))
                {
                    throw new ArgumentNullException("token");
                }

                var bytes = HttpContext.RequestServices
                            .GetDataProtector("ResetPassword").Unprotect(Convert.FromBase64String(request.Token));

                int userId;
                using (var ms = new MemoryStream(bytes))
                    using (var br = new BinaryReader(ms))
                    {
                        var dt = DateTime.FromBinary(br.ReadInt64());
                        if (dt < DateTime.UtcNow)
                        {
                            throw new ValidationError(Texts.Validation.InvalidResetToken);
                        }

                        userId = br.ReadInt32();
                    }

                UserRow user;
                using (var connection = SqlConnections.NewFor <UserRow>())
                {
                    user = connection.TryById <UserRow>(userId);
                    if (user == null)
                    {
                        throw new ValidationError(Texts.Validation.InvalidResetToken);
                    }
                }

                if (request.ConfirmPassword != request.NewPassword)
                {
                    throw new ValidationError("PasswordConfirmMismatch", LocalText.Get("Validation.PasswordConfirm"));
                }

                request.NewPassword = UserRepository.ValidatePassword(user.Username, request.NewPassword, false);


                string salt = null;
                var hash = UserRepository.GenerateHash(request.NewPassword, ref salt);
                UserRepository.CheckPublicDemo(user.UserId);

                uow.Connection.UpdateById(new UserRow
                {
                    UserId = user.UserId.Value,
                    PasswordSalt = salt,
                    PasswordHash = hash
                });

                BatchGenerationUpdater.OnCommit(uow, UserRow.Fields.GenerationKey);

                return new ServiceResponse();
            }));
        }
Exemplo n.º 31
0
        public JsonResult GetVisitsTasks(string start, string end)
        {
            var user = (UserDefinition)Authorization.UserDefinition;

            var startDate = DateTime.ParseExact(start, "yyyy-MM-dd", new CultureInfo("en-US"),
                                                DateTimeStyles.None);

            var endDate = DateTime.ParseExact(end, "yyyy-MM-dd", new CultureInfo("en-US"),
                                              DateTimeStyles.None);
            var cabinetIdActive = Request.Cookies["CabinetPreference"];

            var model = new DashboardPageModel();

            using (var connection = SqlConnections.NewFor <VisitsRow>())
            {
                var visitFlds = VisitsRow.Fields.As("vis");
                var patient   = PatientsRow.Fields.As("ptn");
                var visitType = VisitTypesRow.Fields.As("vstt");
                var users     = UserRow.Fields.As("assUsr");

                var query = new SqlQuery()
                            .From(visitFlds)
                            .Select("*")
                            .Where(~(
                                       new Criteria(visitFlds.StartDate) >= startDate
                                       & new Criteria(visitFlds.EndDate) <= endDate
                                       & new Criteria(visitFlds.CabinetId) == int.Parse(cabinetIdActive)
                                       ))
                            .LeftJoin(users, visitFlds.AssignedUserId == users.UserId)
                            .Select(users.DisplayName = visitFlds.AssignedUserName)
                            .LeftJoin(patient, visitFlds.PatientId == patient.PatientId)
                            .Select(patient.Name = visitFlds.PatientName, patient.NotifyOnChange = visitFlds.PatientNotifyOnChange)
                            .LeftJoin(visitType, visitFlds.VisitTypeId == visitType.VisitTypeId)
                            .Select(visitType.BackgroundColor = visitFlds.VisitTypeBackgroundColor, visitType.BorderColor = visitFlds.VisitTypeBorderColor)
                ;



                if (!Authorization.HasPermission(PermissionKeys.Tenants))
                {
                    query.Where(visitFlds.TenantId == user.TenantId);
                }

                var result = connection.Query <VisitsRow>(query);

                foreach (VisitsRow visit in result)
                {
                    model.EventsList.Add(new Event
                    {
                        id                     = visit.VisitId ?? 0,
                        patientId              = visit.PatientId ?? 0,
                        assignedToUser         = visit.AssignedUserName,
                        patientAutoEmailActive = visit.PatientNotifyOnChange ?? false,
                        title                  = string.Join("\n",
                                                             string.IsNullOrEmpty(visit.PatientName)?"* " + LocalText.Get("Db.PatientManagement.Visits.FreeForReservation") + " *": visit.PatientName
                                                             , visit.Description),
                        start           = (visit.StartDate ?? DateTime.Now).ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz"),
                        end             = (visit.EndDate ?? DateTime.Now).ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz"),
                        allDay          = false,
                        backgroundColor = visit.VisitTypeBackgroundColor,
                        borderColor     = visit.VisitTypeBorderColor
                    });
                }
            }

            return(Json(model.EventsList));
        }
        private void frmStokListesi_Load(object sender, EventArgs e)
        {
            try
            {
                layoutControlItem43.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;

                trGenel  = SqlConnections.GetBaglanti().BeginTransaction();
                Grubu    = new clsTablolar.Stok.csStokGrup(SqlConnections.GetBaglanti(), trGenel, -1);
                AraGrubu = new clsTablolar.Stok.csStokAraGrup(SqlConnections.GetBaglanti(), trGenel, -1);
                //StokArama = new clsTablolar.Stok.csStokArama();

                FiltreKriterleriniBindleHamisina();

                //barkodoku.BarkoduOku();

                txtStokAdi.Focus();
                trGenel.Commit();
                HemenAlKategoriYukle();

                clsTablolar.HemenAl.csHemenAlUrunDurum HemenAlUrunDurumu = new clsTablolar.HemenAl.csHemenAlUrunDurum();
                lkpHemanAlDurum.Properties.DataSource    = HemenAlUrunDurumu.Dt_UrunDurumlari;
                lkpHemanAlDurum.Properties.DisplayMember = "DurumAdi";
                lkpHemanAlDurum.Properties.ValueMember   = "DurumKodu";



                clsTablolar.csEnumDanDtVer enumdanVerHamisina = new csEnumDanDtVer();

                lookUpEdit1.Properties.DataSource    = enumdanVerHamisina.ToDataTable(typeof(clsTablolar.Stok.csStokArama.enumFotoOzellikleri));
                lookUpEdit1.Properties.DisplayMember = "name";
                lookUpEdit1.Properties.ValueMember   = "value";

                lookUpEdit1.EditValue = 1;
                //lookUpEdit1.Properties.PopulateColumns();

                //lookUpEdit1.Properties.Columns[1].Visible = false;
                clsTablolar.Stok.csStokSayimGrubu SayimGrubu = new clsTablolar.Stok.csStokSayimGrubu();
                lkpStokSayimGrubu.Properties.DataSource = SayimGrubu.SayimGrubuGetir(SqlConnections.GetBaglanti(), trGenel);

                lkpStokSayimGrubu.Properties.DisplayMember = "SayimAdi";
                lkpStokSayimGrubu.Properties.ValueMember   = "StokSayimGrubuID";

                //checkedListBox_FiyatTanimlari.Text = clsTablolar.Ayarlar.csAyarlar.StokListeFiyatTanimlari;

                panelControl1.Select();
                panelControl1.Focus();
                panelControl1.Select();

                //layoutControlGroup5.tabp
                //xtraTabPage1.Focus();
                //xtraTabPage1.Select();

                txtStokAdi.SelectAll();
                txtStokAdi.Focus();
                txtStokAdi.Select();
                secilenKontrol = txtStokAdi;
            }
            catch (Exception hata)
            {
                trGenel.Rollback();
                frmHataBildir frmHataBildir = new frmHataBildir(hata.Message, hata.StackTrace);
                frmHataBildir.ShowDialog();
            }
            //txtStokKodu.FindForm();
            txtStokAdi.Focus();
        }