/// <summary>
        /// 生成对象操作
        /// </summary>
        public ActionResult BuilderDAL(E_PageParameter ePageParameter)
        {
            BuilderDALCode    builderDAL = new BuilderDALCode();
            DbObject          db         = new DbObject(ePageParameter.connstring);
            E_DALCode         eDalCode   = new E_DALCode();
            string            tname      = ePageParameter.tablename.Replace(ePageParameter.prefix, "");
            List <ColumnInfo> list       = db.GetColumnInfoList(ePageParameter.dbname, ePageParameter.tablename);

            eDalCode.Fieldlist = list;
            eDalCode.TableName = ePageParameter.tablename;
            eDalCode.ModelName = "E_" + tname.Substring(0, 1).ToUpper() + tname.Substring(1, tname.Length - 1);
            eDalCode.Modelpath = "Model";
            eDalCode.DbObject  = db;
            eDalCode.Keys      = list.Where(a => a.IsPrimaryKey).ToList();
            eDalCode.DALpath   = "DAL";
            eDalCode.DALName   = "D_" + tname.Substring(0, 1).ToUpper() + tname.Substring(1, tname.Length - 1);
            DataRow tableDescRow = db.GetTablesExProperty(ePageParameter.dbname).Select("objname='" + ePageParameter.tablename + "'").FirstOrDefault();

            if (tableDescRow != null)
            {
                eDalCode.TableDescription = tableDescRow["value"]?.ToString();
            }
            builderDAL.eDALCode = eDalCode;
            string modelStr = builderDAL.CreatDAL();

            ViewBag.CodeHtml = modelStr;
            return(PartialView("~/Views/Code/BuilderDAL.cshtml"));
        }
Beispiel #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSession();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });

            using (var scope = app.ApplicationServices.CreateScope())
            {
                AppDbContent content = scope.ServiceProvider.GetRequiredService <AppDbContent>();
                DbObject.Initial(content);
            }
        }
Beispiel #3
0
        public override IEnumerable <string> SqlCommands(IDbConnection connection)
        {
            foreach (var cmd in base.SqlCommands(connection))
            {
                yield return(cmd);
            }

            DbObject obj = DbObject.FromType(_propertyInfo.DeclaringType);

            obj.SquareBraces = false;
            yield return($"EXEC sp_rename '{obj}.{_attr.OldName}', '{_propertyInfo.SqlColumnName()}', 'COLUMN'");

            ForeignKeyAttribute fkAttr = _propertyInfo.GetAttribute <ForeignKeyAttribute>();

            if (fkAttr != null)
            {
                yield return($"ALTER TABLE [{obj.Schema}].[{obj.Name}] DROP CONSTRAINT [FK_{obj.ConstraintName()}_{_attr.OldName}]");

                if (fkAttr.CreateIndex)
                {
                    yield return($"DROP INDEX [IX_{DbObject.ConstraintName(_propertyInfo.DeclaringType)}_{_attr.OldName}] ON [{obj.Schema}].[{obj.Name}]");
                }

                CreateForeignKey fk = new CreateForeignKey(_propertyInfo);
                foreach (var cmd in fk.SqlCommands(connection))
                {
                    yield return(cmd);
                }
            }
        }
Beispiel #4
0
 public void Setup()
 {
     this.filler  = new TemplateFiller();
     obj          = new DbObject("test", DateTime.Now);
     obj["prop1"] = "value1";
     obj["prop2"] = "value2 value2 value2";
     obj.AddTableRow("table1", new (string, string)[] { ("col1", "r1c1"), ("col2", "col2"), ("col3", "r1c3") });
Beispiel #5
0
        public DataSet SelectPagedList(string procedureName, string[] paramters, string[] paramtersVal)
        {
            var parameters = new SqlParameter[paramtersVal.Length + 1];

            // build stored procedure paramters.
            for (int i = 0; i < paramtersVal.Length; i++)
            {
                if (paramtersVal[i] == null || paramtersVal[i].Equals(""))
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], DBNull.Value);
                }
                else
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], paramtersVal[i]);
                }
            }

            // add output paramter
            var outParm = new SqlParameter("@PageCount", SqlDbType.Int);

            outParm.Direction = ParameterDirection.Output;
            parameters[paramtersVal.Length] = outParm;

            // get dataset from db.
            var ds = new DbObject().RunProcedureOutParam(procedureName, parameters, "list");

            return(ds);
        }
Beispiel #6
0
        private string GetPermissions(DbObject Ob)
        {
            string ret = "";

            string sql = "SELECT 'GRANT ' + p.permission_name collate latin1_general_cs_as \r\n" +
                         " + ' ON [' + s.name + '].[' + o.name + '] TO [' + pr.name + ']' as Line  \r\n" +
                         "FROM sys.database_permissions AS p \r\n" +
                         "INNER JOIN sys.objects AS o ON p.major_id=o.object_id \r\n" +
                         "INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id \r\n" +
                         "INNER JOIN sys.database_principals AS pr ON p.grantee_principal_id=pr.principal_id \r\n" +
                         "WHERE o.Name = '" + Ob.ObjectName + "'";

            SQLServer db = new SQLServer(Ob.Server, Ob.Database, "", "");

            try {
                SqlDataReader dr = db.FetchDataReader(sql);

                while (dr.Read())
                {
                    ret += dr["Line"].ToString() + "\r\n";
                }
                dr.Close();
            } finally {
                db.Close();
            }

            return(ret);
        }
Beispiel #7
0
        private void SetObjectProperties(DbObject obj)
        {
            if (!(Connection.GetConnection() is SqlConnection))
            {
                throw new InvalidCastException();
            }
            using (SqlConnection connection = (SqlConnection)Connection.GetConnection())
            {
                connection.Open();

                string     query   = _provider.GetPropertiesScript(obj);
                SqlCommand command = new SqlCommand(query, connection);

                foreach (var param in _provider.GetLoadPropertiesParameters(obj))
                {
                    command.Parameters.Add(param);
                }

                SqlDataReader reader = command.ExecuteReader();

                reader.Read();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    if (reader.HasRows)
                    {
                        obj.Properties.Add(reader.GetName(i), reader.GetValue(i));
                    }
                }
            }

            obj.IsPropertyLoaded = true;
        }
Beispiel #8
0
        private void SetChildrens(DbObject target, DbEntityEnum childrenType)
        {
            if (!(Connection.GetConnection() is SqlConnection))
            {
                throw new InvalidCastException();
            }


            using (SqlConnection connection = (SqlConnection)Connection.GetConnection())
            {
                connection.Open();

                List <DbObject> childs = new List <DbObject>();

                string query = _provider.GetLoadNameScript(target.Type, childrenType);

                SqlCommand command = new SqlCommand(query, connection);

                foreach (var param in _provider.GetChildrenLoadParameters(target, childrenType))
                {
                    command.Parameters.Add(param);
                }

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        DbObject child = (DbEntityFactory.ObjectCreator.Create(reader, childrenType));
                        if (!target.AddChild(child))
                        {
                            throw new ArgumentException();
                        }
                        childs.Add(child);
                    }
                }

                foreach (var child in childs)
                {
                    if (child.CanHaveDefinition)
                    {
                        query = _provider.GetDefinitionScript();
                        SqlCommand descCommand = new SqlCommand(query, connection);
                        foreach (var param in _provider.GetDefinitionParamteters(child))
                        {
                            descCommand.Parameters.Add(param);
                        }
                        using (SqlDataReader descReader = descCommand.ExecuteReader())
                        {
                            StringBuilder defText = new StringBuilder();
                            while (descReader.Read())
                            {
                                defText.Append(descReader.GetString(0));
                            }

                            child.Definition = defText.ToString();
                        }
                    }
                }
            }
        }
Beispiel #9
0
        protected List <DbObject> LoadColumns(string dbName, string tableName)
        {
            var columns = new List <DbObject>();
            var sql     = String.Format(@"
                                                    USE [{0}]
                                                    SELECT  (name+' ('+TYPE_NAME(xtype)+ (CASE TYPE_NAME(xtype) WHEN 'varchar' THEN '('+CAST([length] AS VARCHAR)+')' ELSE '' END) +', '+ CASE(isnullable) WHEN 0 THEN 'not null' WHEN 1 THEN 'null' END +')') AS name
                                                    FROM    SysColumns
                                                    WHERE   id = OBJECT_ID('{1}')
                                                    ORDER BY colorder ASC", dbName, tableName);

            using (var dr = SqlHelper.ExecuteReader(this._connectionString, CommandType.Text, sql))
            {
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        var name  = dr["name"] as String;
                        var dbObj = new DbObject
                        {
                            Name = name,
                            Type = DbObjectType.Column
                        };
                        columns.Add(dbObj);
                    }
                }
            }
            return(columns);
        }
        public JsonResult GetTreeNodeList(E_PageParameter ePageParameter)
        {
            DbObject db = new DbObject(ePageParameter.connstring);

            List <E_TreeNode> NodeList = new List <E_TreeNode>();
            var tables = db.GetTableViews(ePageParameter.dbname);

            foreach (var item in tables)
            {
                E_TreeNode nodetable = new E_TreeNode();
                nodetable.id       = 0;
                nodetable.name     = item;
                nodetable.nodetype = 1;
                List <ColumnInfo> ColumnList     = db.GetColumnInfoList(ePageParameter.dbname, item);
                List <E_TreeNode> columnnodelist = new List <E_TreeNode>();
                foreach (var columnitem in ColumnList)
                {
                    E_TreeNode nodecolumn = new E_TreeNode();
                    nodecolumn.id       = 0;
                    nodecolumn.name     = columnitem.ColumnName + "(" + columnitem.TypeName + ")" + columnitem.Description;
                    nodecolumn.children = null;
                    nodecolumn.nodetype = 2;
                    columnnodelist.Add(nodecolumn);
                }
                nodetable.children = columnnodelist;
                NodeList.Add(nodetable);
            }
            return(Json(NodeList, JsonRequestBehavior.AllowGet));
        }
Beispiel #11
0
        protected List <DbObject> LoadDatabases()
        {
            var databases = new List <DbObject>();
            var sql       = @"SELECT  *
                               FROM    Master..SysDatabases
                               ORDER BY Name";

            using (var dr = SqlHelper.ExecuteReader(this._connectionString, CommandType.Text, sql))
            {
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        var name = dr["name"] as String;
                        if (this.sysDatabases.Contains(name))
                        {
                            continue;
                        }
                        var dbObj = new DbObject
                        {
                            Name = name,
                            Type = DbObjectType.Database
                        };
                        databases.Add(dbObj);
                    }
                }
            }
            return(databases);
        }
Beispiel #12
0
        protected List <DbObject> LoadTables(string dbName)
        {
            var tables = new List <DbObject>();
            var sql    = String.Format(@"
                                                    SELECT  Name
                                                    FROM    [{0}]..SysObjects
                                                    WHERE   XType = 'U'
                                                    ORDER BY Name ", dbName);

            using (var dr = SqlHelper.ExecuteReader(this._connectionString, CommandType.Text, sql))
            {
                if (dr != null)
                {
                    while (dr.Read())
                    {
                        var name  = dr["name"] as String;
                        var dbObj = new DbObject
                        {
                            Name = name,
                            Type = DbObjectType.Table
                        };
                        tables.Add(dbObj);
                    }
                }
            }
            return(tables);
        }
Beispiel #13
0
        public async Task LoadPropertiesAsync(DbObject obj, CancellationToken token)
        {
            using (var connection = _connection.GetConnection())
            {
                await connection.OpenAsync(token);

                string query = _component.ScriptProvider.ProvidePropertiesScript(obj);

                var command = _component.CreateCommand();
                command.Connection  = connection;
                command.CommandText = query;

                using (var reader = await command.ExecuteReaderAsync(token))
                {
                    reader.Read();
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        if (reader.HasRows)
                        {
                            obj.Properties.Add(reader.GetName(i), reader.GetValue(i));
                        }
                    }
                }
            }
        }
Beispiel #14
0
        private void BindData(DbObject dbobj)
        {
            DataSet dsobj = new DataSet();

            SqlParameter[] parameters2 =
            {
                new SqlParameter("@OrgId", SqlDbType.Int, 4, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, OrgId),
            };
            dsobj = dbobj.dsRunProcedure("sp_SelectEquipAltLists", parameters2, "Lists");

            ddStatusId.DataSource     = dsobj;
            ddStatusId.DataMember     = "Lists";
            ddStatusId.DataValueField = "id";
            ddStatusId.DataTextField  = "vchName";
            ddStatusId.DataBind();

            ddPMScheduleId.DataSource     = dsobj;
            ddPMScheduleId.DataMember     = "Lists1";
            ddPMScheduleId.DataValueField = "id";
            ddPMScheduleId.DataTextField  = "vchName";
            ddPMScheduleId.DataBind();
            ddPMScheduleId.Items.Insert(0, "");

            ddInspectionId.DataSource     = dsobj;
            ddInspectionId.DataMember     = "Lists2";
            ddInspectionId.DataValueField = "id";
            ddInspectionId.DataTextField  = "vchName";
            ddInspectionId.DataBind();
            ddInspectionId.Items.Insert(0, "");
        }
Beispiel #15
0
        static DbObject MakeDbObject(string table, string column)
        {
            DbObject dbObject = new DbObject(new Identifier(table));

            dbObject.Add(new DbObject(new Identifier(column)));
            return(dbObject);
        }
Beispiel #16
0
        public DatabaseGrant(
            long id,
            long databaseId,
            DbObject resource,
            string[] privileges,
            long userId,
            string[] columnNames = null)
        {
            Ensure.IsValidId(id);
            Ensure.IsValidId(databaseId, nameof(databaseId));
            Ensure.IsValidId(userId, nameof(userId));
            Ensure.NotNull(privileges, nameof(privileges));

            #region Preconditions

            if (privileges.Length == 0)
            {
                throw new ArgumentException("Must not be empty", nameof(privileges));
            }

            #endregion

            Id          = id;
            DatabaseId  = databaseId;
            UserId      = userId;
            SchemaName  = resource.SchemaName;
            ObjectType  = resource.Type;
            ObjectName  = resource.ObjectName;
            Actions     = privileges;
            ColumnNames = columnNames;
        }
 public TreeRootViewModel(DbObject model, Loader loader) : base(null, true)
 {
     DbLoader          = loader;
     Model             = model;
     IsDefaultDatabase = string.IsNullOrWhiteSpace(DbLoader.Connection.InitialCatalog);
     IsConnected       = false;
 }
        public static async Task <int> ImportCustomers()
        {
            var imp = new QuickBookImportCustomers();
            await Task.Run(() => imp.Start());

            var list = imp.Customers;

            if (list.Count == 0)
            {
                return(0);
            }

            var dt = new DataTable();

            dt.Columns.Add("Name", typeof(string));
            foreach (var name in list)
            {
                dt.Rows.Add(name);
            }

            DbObject.ExecStoredProc("ImportAdvertisersFromQb", (cmd) =>
            {
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@advertisers", SqlDbType.Structured)
                {
                    Value = dt
                });
            });

            Advertizer.ReloadAllFromDb();

            return(list.Count);
        }
        public override object ResolveDbValue(DbObject db)
        {
            List <SelectOption> v = null;
            var d       = db.Get <int[]>(this.Name, null);
            var reldata = db.Get <string[]>(this.Name + "__data", null);

            if (d != null)
            {
                v = new List <SelectOption>();
                for (int i = 0; i < d.Length; i++)
                {
                    var option = new SelectOption();
                    option.Add("Value", d[i]);
                    option.Add("Text", reldata[i]);
                    v.Add(option);
                }
            }
            // var relData = db.Get<IEnumerable<DbObject>>(this.DBName + "__data", null);

            // if (relData != null)
            // {
            //     v = new List<SelectOption>();
            //     foreach(DbObject obj in relData)
            //     {
            //         var option = new SelectOption();
            //         option.Add("Value", obj.Get("ID", 0));
            //         option.Add("Text", obj.Get("NAME", ""));
            //         v.Add(option);
            //     }
            // }

            return(v);
        }
        public string GetProfilePathServer(bool DoForTAS)
        {
            string strProfPath = "";

            using (NoRightsCheck())
            {
                if (String.IsNullOrEmpty(DbObject["Ident_DomainRD"].New.String))
                {
                    throw new ViException(881146, ExceptionRelevance.EndUser, "Ident_DomainRD");
                }

                ISingleDbObject dbDomain = DbObject.GetFK("Ident_DomainRD").Create();

                if (DoForTAS)
                {
                    string strTAS = (string)dbDomain.Custom.CallMethod("GetTASName");

                    if (String.IsNullOrEmpty(strTAS))
                    {
                        return(String.Empty);
                    }

                    strProfPath = String.Concat(@"\\", strTAS, @"\", dbDomain["ServerPartShareOnTAS"].New.String, @"\", DbObject["SubPath"].New.String);
                }
                else
                {
                    strProfPath = String.Concat(dbDomain["ServerPartShareOnServers"].New.String, @"\", DbObject["SubPath"].New.String);
                }
            }

            return(strProfPath);
        }
        public string GetProfilePathClient(bool DoForTAS)
        {
            string          strProfPath = "";
            ISingleDbObject oDomain;

            using (NoRightsCheck())
            {
                if (String.IsNullOrEmpty(DbObject["Ident_DomainRD"].New.String))
                {
                    throw new ViException(881146, ExceptionRelevance.EndUser, "Ident_DomainRD");
                }

                oDomain = DbObject.GetFK("Ident_DomainRD").Create();

                if (null == oDomain.Custom)
                {
                    throw new ViException(881150, ExceptionRelevance.EndUser, "Domain");
                }

                strProfPath = (string)oDomain.Custom.CallMethod("GetNetPath", DoForTAS);

                if (!String.IsNullOrEmpty(strProfPath))
                {
                    strProfPath += String.Concat(@"\", oDomain["ClientPartApps"].New.String, @"\", DbObject["SubPath"].New.String);
                }
            }

            return(strProfPath);
        }
Beispiel #22
0
        public override object ResolveDbValue(DbObject db)
        {
            List <SelectOption> v = null;
            var d       = db.Get <int[]>(this.DBName, null);
            var reldata = db.Get <string[]>(this.DBName + "__data", null);

            if (d != null)
            {
                v = new List <SelectOption>();
                for (int i = 0; i < d.Length; i++)
                {
                    var option = new SelectOption();
                    if (this.ControlInfo.CollectionInfo.SourceType == DataSourceType.Enum)
                    {
                        option = GetEnumValue(d[i]);
                    }
                    else
                    {
                        option.Add("Value", d[i]);
                        option.Add("Text", reldata[i]);
                    }
                    v.Add(option);
                }
            }

            return(v);
        }
Beispiel #23
0
        public void SaveCharacterProperties(DbObject dbObject, DatabaseTransaction transaction)
        {
            // known issue: properties that were removed from the bucket will not updated.  this is a problem if we
            // ever need to straight up "delete" a property.

            foreach (var prop in dbObject.PropertiesBool)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesBoolInsert, dbObject.Id, (ushort)prop.Key, prop.Value);
            }

            foreach (var prop in dbObject.PropertiesInt)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesIntInsert, dbObject.Id, (ushort)prop.Key, prop.Value);
            }

            foreach (var prop in dbObject.PropertiesInt64)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesBigIntInsert, dbObject.Id, (ushort)prop.Key, prop.Value);
            }

            foreach (var prop in dbObject.PropertiesDouble)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesDoubleInsert, dbObject.Id, (ushort)prop.Key, prop.Value);
            }

            foreach (var prop in dbObject.PropertiesString)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesStringInsert, dbObject.Id, (ushort)prop.Key, prop.Value);
            }
        }
Beispiel #24
0
        public void UpdateCharacterProperties(DbObject dbObject, DatabaseTransaction transaction)
        {
            foreach (var prop in dbObject.PropertiesBool)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesBoolUpdate, prop.Value, (ushort)prop.Key, dbObject.Id);
            }

            foreach (var prop in dbObject.PropertiesInt)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesIntUpdate, prop.Value, (ushort)prop.Key, dbObject.Id);
            }

            foreach (var prop in dbObject.PropertiesInt64)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesBigIntUpdate, prop.Value, (ushort)prop.Key, dbObject.Id);
            }

            foreach (var prop in dbObject.PropertiesDouble)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesDoubleUpdate, prop.Value, (ushort)prop.Key, dbObject.Id);
            }

            foreach (var prop in dbObject.PropertiesString)
            {
                transaction.AddPreparedStatement(CharacterPreparedStatement.CharacterPropertiesStringUpdate, prop.Value, (ushort)prop.Key, dbObject.Id);
            }
        }
Beispiel #25
0
        public int SaveRow(string procedureName, string[] paramters, string[] paramtersVal)
        {
            var parameters = new SqlParameter[paramtersVal.Length];

            // build stored procedure paramters.
            for (int i = 0; i < paramtersVal.Length; i++)
            {
                if (string.IsNullOrEmpty(paramtersVal[i]))
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], DBNull.Value);
                }
                else if (paramters[i].ToLower().Contains("password"))
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], EncryptDecryptString.Encrypt(paramtersVal[i], "Taj$$Key"));
                }
                else if (paramtersVal[i].Length >= 50)
                {
                    parameters[i]       = new SqlParameter("@" + paramters[i], System.Data.SqlDbType.NVarChar, paramtersVal[i].Length * 2);
                    parameters[i].Value = paramtersVal[i];
                }
                else
                {
                    parameters[i] = new SqlParameter("@" + paramters[i], paramtersVal[i]);
                }
            }

            // start save to db.
            int RowsAffected = 0;
            int Result       = new DbObject().RunProcedure(procedureName, parameters, out RowsAffected);

            return(Result);
        }
Beispiel #26
0
        public object RunSQLString(string sqlString)
        {
            // run sql string in to db.
            var Result = new DbObject().RunQuery(sqlString, "Table1");

            return(Result);
        }
Beispiel #27
0
        private void Process(object arg)
        {
            MemoryStream stream;
            Socket       client = (Socket)arg;

            try {
                byte[] buffer = new byte[bufferSize];
                while (true)
                {
                    stream = new MemoryStream();
                    int totalBytes = 0;
                    Console.Write("took ");
                    do
                    {
                        short bytes = (short)client.Receive(buffer);
                        stream.Write(buffer, 0, bytes);
                        Console.Write(bytes + ", ");
                        totalBytes += bytes;
                    }while (client.Available > 0);
                    Console.WriteLine();
                    Console.WriteLine("Сообщение получено от " + client.RemoteEndPoint.ToString() + "в размере " + totalBytes);
                    dbRequest request = (dbRequest)DbObject.Deserialize(stream);
                    stream.Close();
                    dbResult result = ProcessDbObject(request);
                    SendDbResult(client, result);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine("Разъединение " + client.RemoteEndPoint.ToString());
                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
        }
Beispiel #28
0
        public JsonResult SaveRole(EditRuoliView model)
        {
            DbObject obj = new DbObject();

            try
            {
                foreach (var x in model.ruoli)
                {
                    if (userManager.IsInRole(model.Id, x.Name))
                    {
                        userManager.RemoveFromRole(model.Id, x.Name);
                    }

                    if (x.check)
                    {
                        userManager.AddToRole(model.Id, x.Name);
                    }
                }
                obj.db_obj_ack = "OK";
            }
            catch (ArgumentException ex)
            {
                obj.db_obj_ack     = "KO";
                obj.db_obj_message = ex.Message;
            }

            return(Json(obj, JsonRequestBehavior.AllowGet));
        }
Beispiel #29
0
        public async Task <JsonResult> ResetPasswordUser(UtentiView model)
        {
            DbObject obj  = new DbObject();
            var      user = await userManager.FindByIdAsync(model.Id);

            if (user != null)
            {
                string password = UtilsHelper.RandomString(8);
                await userManager.RemovePasswordAsync(model.Id);

                await userManager.AddPasswordAsync(model.Id, password);

                string GetCurrentUrl = Request.Url.GetLeftPart(UriPartial.Authority);

                string destinatario      = model.UserName;
                string emaildestinatario = model.UserName;
                string oggetto           = "Reset account NewAge Finanze";
                string corpo             = "<p>La richiesta per il reset della password è stata effettuata.<br/>" +
                                           "Potrai accedere usando le nuove credenziali:</p>" +
                                           "<p>password: "******"</p>";
                string firma = "<strong>-- NewAge Finanze Team</strong>";

                UtilsHelper.InviaLaMail(destinatario, emaildestinatario, null, oggetto, corpo, firma);
                obj.db_obj_ack = "OK";
            }
            else
            {
                obj.db_obj_ack     = "KO";
                obj.db_obj_message = "Non è stato possibile effettuare il reset della password per l'utente selezionato";
            }
            return(Json(obj, JsonRequestBehavior.AllowGet));
        }
Beispiel #30
0
 public async Task LoadChildrenAsync(DbObject obj, CancellationToken token)
 {
     foreach (var child in _component.Hierarchy.Structure[obj.Type].ChildrenTypes)
     {
         await LoadChildrenAsync(obj, child, token);
     }
 }
 /// <summary>
 /// Shows the form as a dialog with the specified object.
 /// </summary>
 /// <param name="owner">The owner window.</param>
 /// <param name="obj">The database object to display.</param>
 /// <returns>The dialog result.</returns>
 public DialogResult ShowDialog(IWin32Window owner, DbObject obj)
 {
     // Select the server an table.
     this.control.Object = obj;
     // Set the dialog name.
     this.Text = "{0} Object Properties".FormatWith(obj.GetName());
     // Open the dialog.
     return base.ShowDialog(owner);
 }
        // Protected methods.
        /// <summary>
        /// An event handler called when a new object has been set.
        /// </summary>
        /// <param name="oldObject">The old object.</param>
        /// <param name="newObject">The new object.</param>
        protected virtual void OnObjectSet(DbObject oldObject, DbObject newObject)
        {
            // If the object has not changed, do nothing.
            if (oldObject == newObject) return;

            if (null == newObject)
            {
                this.labelTitle.Text = "No object selected";
                this.tabControl.Visible = false;
            }
            else
            {
                this.labelTitle.Text = newObject.GetName();
                this.propertyGrid.SelectedObject = newObject;
                this.tabControl.Visible = true;
            }
            this.tabControl.SelectedTab = this.tabPageProperties;
            if (this.Focused)
            {
                this.propertyGrid.Select();
            }
        }
Beispiel #33
0
        /// <summary>
        /// Liefert das spezifizierte DB-Objekt aus der internen Collection zurück. Wenn es nicht enthalten ist,
        /// wird das Objekt neu erzeugt, in die Collection eingefügt, und die neue Referenz zurückgegeben.
        /// </summary>
        /// <param name="objectType">Objekttyp-Bezeichnung</param>
        /// <param name="objectOwner">Owner des DB-Objektes</param>
        /// <param name="objectName">Name des DB-Objektes</param>
        /// <returns></returns>
        public DbObject GetDbObject(string objectType, string objectOwner, string objectName)
        {
            var dbObject = DbObjects
                .FirstOrDefault(
                    o =>
                        o.OwnerName == objectOwner &&
                        o.TypeName == objectType &&
                        o.ObjectName == objectName);

            if (null == dbObject)
            {
                DbObjects.Add(
                    dbObject =
                        new DbObject
                        {
                            OwnerName = objectOwner,
                            TypeName = objectType,
                            ObjectName = objectName
                        });
            }

            return dbObject;
        }
 public static DbQuerySql CreateInsertAll(ITable table, DbObject value, DbObjectDatabase database, object userState = null)
 {
     // If the table is not configured, throw an exception.
     if (!table.IsConfigured) throw new DbException("Cannot create a database query for the table \'{0}\'. The table is not configured.".FormatWith(table.LocalName));
     // If the table  requires a database, check that a database is configured for this server.
     if (table.DefaultDatabase && (database == null)) throw new DbException("Cannot create a database query for the table \'{0}\'. The table requires a database but the server does not have a database configured.".FormatWith(table.LocalName));
     // Check the table type matches the database object type.
     if (table.Type != value.GetType()) throw new DbException("Cannot create a database insert query for table \'{0}\', because object type \'{1}\' does not match the table type \'{2}\'.".FormatWith(table.LocalName, table.Type.Name, value.GetType().Name));
     // Get the table name.
     string tableName = DbQuerySql.GetTableName(table, database);
     // Create the query.
     DbQuerySql query = new DbQuerySql(
         "INSERT INTO {0} ({1}) VALUES ({2})".FormatWith(
             DbQuerySql.GetFieldNames(table, tableName),
             DbQuerySql.GetFieldIndices(table, 0)
         ),
         table, userState);
     // Add the parameters.
     foreach (DbField field in table.Fields)
     {
         query.parameters.Add(value.GetValue(field.LocalName));
     }
     // Return the query.
     return query;
 }
Beispiel #35
0
        /// <summary>
        /// Erzeugt und liefert die Liste der Datenbank-Objekte in der reihenfolge der Berücksichtigung von Abhängigkeiten.
        /// </summary>
        /// <returns></returns>
        private IEnumerable<DbObject> GetSortedDependencies()
        {
            _sortedDependencies = null;

            foreach (var dbObject in DbObjects)
            {
                _currentObject = dbObject;
                AddObjectToSortedDependencies(dbObject);
            }

            return _sortedDependencies;
        }
        public static DbQuerySql CreateUpdateAllOn(ITable table, DbObject value, string fieldOn, object valueOn, DbObjectDatabase database, object userState = null)
        {
            // If the table is not configured, throw an exception.
            if (!table.IsConfigured) throw new DbException("Cannot create a database query for the table \'{0}\'. The table is not configured.".FormatWith(table.LocalName));
            // If the table  requires a database, check that a database is configured for this server.
            if (table.DefaultDatabase && (database == null)) throw new DbException("Cannot create a database query for the table \'{0}\'. The table requires a database but the server does not have a database configured.".FormatWith(table.LocalName));
            // Check the table type matches the database object type.
            if (table.Type != value.GetType()) throw new DbException("Cannot create a database update query for table \'{0}\', because object type \'{1}\' does not match the table type \'{2}\'.".FormatWith(table.LocalName, table.Type.Name, value.GetType().Name));

            // Get the table name.
            string tableName = DbQuerySql.GetTableName(table, database);

            // Get the on field.
            DbField field = table[fieldOn];
            // Check the on field exists.
            if(null == field) throw new DbException("Cannot create a database query on matching field \'{0}\' for the table \'{1}\', because the field does not exist.".FormatWith(fieldOn, table.LocalName));

            // Get the fields to update, excluding the on field.
            int fieldIndex = 0;
            string fields = DbQuerySql.GetFieldsSetExcluding(table, fieldOn, database, ref fieldIndex);

            // Create the query.
            DbQuerySql query = new DbQuerySql(
                "UPDATE {0} SET {1} WHERE {2}={{{3}}}".FormatWith(
                    tableName,
                    fields,
                    field.GetDatabaseName(),
                    fieldIndex++
                ),
                table,
                userState);
            // Return the query.
            return query;
        }
Beispiel #37
0
        /// <summary>
        /// Rekursive Funktion zum Hinzufügen von Abhängigkeiten zur sortierten Datenbankobjekt-Liste _sortedDependencies.
        /// Bevor das angegebene Datenbank-Objekt an die Liste angefügt wird, wird sichergestellt, dass alle Datenbank-Objekte,
        /// von denen das aktuelle DB-Objekt abhängt, bereits in der Liste enthalten sind. Diese Funktion wird rekursiv
        /// aufgerufen, um ebenfalls die Abhängigkeiten der referenzierten Objekte zu berücksichtigen.
        /// </summary>
        /// <param name="dbObject">Aktuelles Datenbank-Objekt</param>
        private void AddObjectToSortedDependencies(DbObject dbObject)
        {
            if (_sortedDependencies == null)
            {
                _sortedDependencies = new List<DbObject>();
            }

            foreach (var refObject in dbObject.DependsOn.Where(o => !_sortedDependencies.Contains(o) && _currentObject != o))
            {
                AddObjectToSortedDependencies(refObject);
            }

            if (!_sortedDependencies.Contains(dbObject))
            {
                _sortedDependencies.Add(dbObject);
            }
        }
 /// <summary>
 /// Creates a new event instance.
 /// </summary>
 /// <param name="selectedResult">The selected result.</param>
 /// <param name="allResults">All results.</param>
 public DatabaseObjectSelectedEventArgs(DbObject selectedResult, DbDataObject allResults)
 {
     this.SelectedResult = selectedResult;
     this.AllResults = allResults;
 }
 // Public methods.
 /// <summary>
 /// Opens the modal dialog to select database objects from the specified database server and table.
 /// </summary>
 /// <typeparam name="T">The database object type.</typeparam>
 /// <param name="owner">The window owner.</param>
 /// <param name="server">The database server.</param>
 /// <param name="table">The database table.</param>
 /// <param name="result">The result to display when the dialog opens.</param>
 /// <returns>The dialog result.</returns>
 public DialogResult ShowDialog(IWin32Window owner, DbServerSql server, ITable table, DbDataObject result)
 {
     // Reset the result.
     this.SelectedResult = null;
     this.AllResults = result;
     // Initialize the control.
     this.control.Select(server, table, result);
     // Show the dialog.
     return base.ShowDialog(owner);
 }
 /// <summary>
 /// An event handler called when the user selects the database object.
 /// </summary>
 /// <param name="sender">The sender object.</param>
 /// <param name="e">The event arguments.</param>
 private void OnSelected(object sender, DatabaseObjectSelectedEventArgs e)
 {
     // Set the result.
     this.SelectedResult = e.SelectedResult;
     this.AllResults = e.AllResults;
     // Set the dialog result.
     this.DialogResult = DialogResult.OK;
     // Close the form.
     this.Close();
 }