NpgsqlDbColumn LoadColumnDefinition(NpgsqlDataReader reader)
        {
            var columnName = reader.GetString(reader.GetOrdinal("attname"));
            var column = new NpgsqlDbColumn
            {
                AllowDBNull = !reader.GetBoolean(reader.GetOrdinal("attnotnull")),
                BaseCatalogName = _connection.Database,
                BaseColumnName = columnName,
                BaseSchemaName = reader.GetString(reader.GetOrdinal("nspname")),
                BaseServerName = _connection.Host,
                BaseTableName = reader.GetString(reader.GetOrdinal("relname")),
                ColumnName = columnName,
                ColumnOrdinal = reader.GetInt32(reader.GetOrdinal("attnum")) - 1,
                ColumnAttributeNumber = (short)(reader.GetInt16(reader.GetOrdinal("attnum")) - 1),
                IsKey = reader.GetBoolean(reader.GetOrdinal("isprimarykey")),
                IsReadOnly = !reader.GetBoolean(reader.GetOrdinal("is_updatable")),
                IsUnique = reader.GetBoolean(reader.GetOrdinal("isunique")),
                DataTypeName = reader.GetString(reader.GetOrdinal("typname")),

                TableOID = reader.GetFieldValue<uint>(reader.GetOrdinal("attrelid")),
                TypeOID = reader.GetFieldValue<uint>(reader.GetOrdinal("typoid"))
            };

            var defaultValueOrdinal = reader.GetOrdinal("default");
            column.DefaultValue = reader.IsDBNull(defaultValueOrdinal) ? null : reader.GetString(defaultValueOrdinal);

            column.IsAutoIncrement = column.DefaultValue != null && column.DefaultValue.StartsWith("nextval(");

            ColumnPostConfig(column, reader.GetInt32(reader.GetOrdinal("atttypmod")));

            return column;
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            tainted_2 = args[1];

            tainted_3 = tainted_2;

            do
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();

                break;
            }while((1 == 0));

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string           connectionString = "Server=localhost;port=1337;User Id=postgre_user;Password=postgre_password;Database=dbname";
            NpgsqlConnection dbConnection     = null;

            try{
                dbConnection = new NpgsqlConnection(connectionString);
                dbConnection.Open();
                NpgsqlCommand    cmd = new NpgsqlCommand(query, dbConnection);
                NpgsqlDataReader dr  = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Console.Write("{0}\n", dr[0]);
                }
                dbConnection.Close();
            }catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
 public PostgreSqlDataReaderHelper(NpgsqlDataReader dataReader) => this._dataReader = dataReader;
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((Math.Pow(4, 2) <= 42))
            {
                StringBuilder escape = new StringBuilder();
                for (int i = 0; i < tainted_2.Length; ++i)
                {
                    char current = tainted_2[i];
                    switch (current)
                    {
                    case '\\':
                        escape.Append(@"\5c");
                        break;

                    case '*':
                        escape.Append(@"\2a");
                        break;

                    case '(':
                        escape.Append(@"\28");
                        break;

                    case ')':
                        escape.Append(@"\29");
                        break;

                    case '\u0000':
                        escape.Append(@"\00");
                        break;

                    case '/':
                        escape.Append(@"\2f");
                        break;

                    default:
                        escape.Append(current);
                        break;
                    }
                }
                tainted_3 = escape.ToString();
            }
            else if (!(Math.Pow(4, 2) <= 42))
            {
                {}
            }

            //flaw

            string query = "SELECT * FROM Articles WHERE id=" + tainted_3;


            string           connectionString = "Server=localhost;port=1337;User Id=postgre_user;Password=postgre_password;Database=dbname";
            NpgsqlConnection dbConnection     = null;

            try{
                dbConnection = new NpgsqlConnection(connectionString);
                dbConnection.Open();
                NpgsqlCommand    cmd = new NpgsqlCommand(query, dbConnection);
                NpgsqlDataReader dr  = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Console.Write("{0}\n", dr[0]);
                }
                dbConnection.Close();
            }catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 5
0
 public static DateTime GetDateTimeSafe(this NpgsqlDataReader reader, int idColum) =>
 reader.IsDBNull(idColum) ? new DateTime() : reader.GetDateTime(idColum);
Exemplo n.º 6
0
        public bool GetAvatarProperties(ref UserProfileProperties props, ref string result)
        {
            string query = string.Empty;

            query += "SELECT * FROM userprofile WHERE ";
            query += "useruuid = :Id";

            try
            {
                using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("Id", props.UserId.ToString());

                        using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if (reader.HasRows)
                            {
                                m_log.DebugFormat("[PROFILES_DATA]" +
                                                  ": Getting data for {0}.", props.UserId);
                                reader.Read();
                                props.WebUrl = (string)reader["profileURL"];
                                UUID.TryParse((string)reader["profileImage"], out props.ImageId);
                                props.AboutText = (string)reader["profileAboutText"];
                                UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId);
                                props.FirstLifeText = (string)reader["profileFirstText"];
                                UUID.TryParse((string)reader["profilePartner"], out props.PartnerId);
                                props.WantToMask = (int)reader["profileWantToMask"];
                                props.WantToText = (string)reader["profileWantToText"];
                                props.SkillsMask = (int)reader["profileSkillsMask"];
                                props.SkillsText = (string)reader["profileSkillsText"];
                                props.Language   = (string)reader["profileLanguages"];
                            }
                            else
                            {
                                m_log.DebugFormat("[PROFILES_DATA]" +
                                                  ": No data for {0}", props.UserId);

                                props.WebUrl           = string.Empty;
                                props.ImageId          = UUID.Zero;
                                props.AboutText        = string.Empty;
                                props.FirstLifeImageId = UUID.Zero;
                                props.FirstLifeText    = string.Empty;
                                props.PartnerId        = UUID.Zero;
                                props.WantToMask       = 0;
                                props.WantToText       = string.Empty;
                                props.SkillsMask       = 0;
                                props.SkillsText       = string.Empty;
                                props.Language         = string.Empty;
                                props.PublishProfile   = false;
                                props.PublishMature    = false;

                                query  = "INSERT INTO userprofile (";
                                query += "useruuid, ";
                                query += "profilePartner, ";
                                query += "profileAllowPublish, ";
                                query += "profileMaturePublish, ";
                                query += "profileURL, ";
                                query += "profileWantToMask, ";
                                query += "profileWantToText, ";
                                query += "profileSkillsMask, ";
                                query += "profileSkillsText, ";
                                query += "profileLanguages, ";
                                query += "profileImage, ";
                                query += "profileAboutText, ";
                                query += "profileFirstImage, ";
                                query += "profileFirstText) VALUES (";
                                query += ":userId, ";
                                query += ":profilePartner, ";
                                query += ":profileAllowPublish, ";
                                query += ":profileMaturePublish, ";
                                query += ":profileURL, ";
                                query += ":profileWantToMask, ";
                                query += ":profileWantToText, ";
                                query += ":profileSkillsMask, ";
                                query += ":profileSkillsText, ";
                                query += ":profileLanguages, ";
                                query += ":profileImage, ";
                                query += ":profileAboutText, ";
                                query += ":profileFirstImage, ";
                                query += ":profileFirstText)";

                                dbcon.Close();
                                dbcon.Open();

                                using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon))
                                {
                                    put.Parameters.AddWithValue("userId", props.UserId.ToString());
                                    put.Parameters.AddWithValue("profilePartner", props.PartnerId.ToString());
                                    put.Parameters.AddWithValue("profileAllowPublish", props.PublishProfile);
                                    put.Parameters.AddWithValue("profileMaturePublish", props.PublishMature);
                                    put.Parameters.AddWithValue("profileURL", props.WebUrl);
                                    put.Parameters.AddWithValue("profileWantToMask", props.WantToMask);
                                    put.Parameters.AddWithValue("profileWantToText", props.WantToText);
                                    put.Parameters.AddWithValue("profileSkillsMask", props.SkillsMask);
                                    put.Parameters.AddWithValue("profileSkillsText", props.SkillsText);
                                    put.Parameters.AddWithValue("profileLanguages", props.Language);
                                    put.Parameters.AddWithValue("profileImage", props.ImageId.ToString());
                                    put.Parameters.AddWithValue("profileAboutText", props.AboutText);
                                    put.Parameters.AddWithValue("profileFirstImage", props.FirstLifeImageId.ToString());
                                    put.Parameters.AddWithValue("profileFirstText", props.FirstLifeText);

                                    put.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[PROFILES_DATA]" +
                                  ": Requst properties exception {0}", e.Message);
                result = e.Message;
                return(false);
            }
            return(true);
        }
Exemplo n.º 7
0
        private void button1_Click(object sender, EventArgs e)
        {
            String a = comboBox1.Text;

            if (a == "Kraji")
            {
                using (NpgsqlConnection conn = new NpgsqlConnection("Server = ec2-54-78-127-245.eu-west-1.compute.amazonaws.com; Port = 5432; Database = dbqabpjav305q8; User Id = lofhqfjluzqqyf; Password = 0f97f004987c14fa398b21069e1d5ecacc20742baa4c9265ad383d987721990e; sslmode=Require; Trust Server Certificate=true;"))
                {
                    listBox1.Items.Clear();

                    using (var cmd = new NpgsqlCommand("SELECT * FROM kraji; ", conn))
                    {
                        conn.Open();

                        NpgsqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            listBox1.Items.Add(reader["ID"].ToString());
                            listBox1.Items.Add(string.Format("{0} | {1} | {2} ",
                                                             reader["ime"].ToString(),
                                                             reader["postna_stevilka"].ToString(),
                                                             reader["opis"].ToString()));
                        }
                        conn.Close();
                    }
                }
            }

            if (a == "Dejavnosti")
            {
                using (NpgsqlConnection conn = new NpgsqlConnection("Server = ec2-54-78-127-245.eu-west-1.compute.amazonaws.com; Port = 5432; Database = dbqabpjav305q8; User Id = lofhqfjluzqqyf; Password = 0f97f004987c14fa398b21069e1d5ecacc20742baa4c9265ad383d987721990e; sslmode=Require; Trust Server Certificate=true;"))
                {
                    listBox1.Items.Clear();

                    using (var cmd = new NpgsqlCommand("SELECT * FROM dejavnosti; ", conn))
                    {
                        conn.Open();

                        NpgsqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            listBox1.Items.Add(reader["ID"].ToString());
                            listBox1.Items.Add(string.Format("{0} | {1} | {2} | {3} | {4} ",
                                                             reader["ime"].ToString(),
                                                             reader["datum_zacetek"].ToString(),
                                                             reader["opis"].ToString(),
                                                             reader["sprememba"].ToString(),
                                                             reader["datum_konec"].ToString()));
                        }
                        conn.Close();
                    }
                }
            }
            if (a == "Dijaki")
            {
                using (NpgsqlConnection conn = new NpgsqlConnection("Server = ec2-54-78-127-245.eu-west-1.compute.amazonaws.com; Port = 5432; Database = dbqabpjav305q8; User Id = lofhqfjluzqqyf; Password = 0f97f004987c14fa398b21069e1d5ecacc20742baa4c9265ad383d987721990e; sslmode=Require; Trust Server Certificate=true;"))
                {
                    listBox1.Items.Clear();
                    using (var cmd = new NpgsqlCommand("SELECT * FROM dijaki; ", conn))
                    {
                        conn.Open();

                        NpgsqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            listBox1.Items.Add(reader["ID"].ToString());
                            listBox1.Items.Add(string.Format("{0} | {1} | {2} | {3} | {4} | {5} | {6}  ",
                                                             reader["ime"].ToString(),
                                                             reader["priimek"].ToString(),
                                                             reader["telefon"].ToString(),
                                                             reader["email"].ToString(),
                                                             reader["opis"].ToString(),
                                                             reader["kraj_id"].ToString(),
                                                             reader["datum_roj"].ToString()));
                        }
                        conn.Close();
                    }
                }
            }
            if (a == "Naloge")
            {
                using (NpgsqlConnection conn = new NpgsqlConnection("Server = ec2-54-78-127-245.eu-west-1.compute.amazonaws.com; Port = 5432; Database = dbqabpjav305q8; User Id = lofhqfjluzqqyf; Password = 0f97f004987c14fa398b21069e1d5ecacc20742baa4c9265ad383d987721990e; sslmode=Require; Trust Server Certificate=true;"))
                {
                    listBox1.Items.Clear();
                    using (var cmd = new NpgsqlCommand("SELECT * FROM naloge; ", conn))
                    {
                        conn.Open();

                        NpgsqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            listBox1.Items.Add(reader["ID"].ToString());
                            listBox1.Items.Add(string.Format("{0} | {1} | {2} |",
                                                             reader["ime"].ToString(),
                                                             reader["opravil"].ToString(),
                                                             reader["opis"].ToString()));
                        }
                        conn.Close();
                    }
                }
            }
            if (a == "Uporabniki")
            {
                using (NpgsqlConnection conn = new NpgsqlConnection("Server = ec2-54-78-127-245.eu-west-1.compute.amazonaws.com; Port = 5432; Database = dbqabpjav305q8; User Id = lofhqfjluzqqyf; Password = 0f97f004987c14fa398b21069e1d5ecacc20742baa4c9265ad383d987721990e; sslmode=Require; Trust Server Certificate=true;"))
                {
                }
            }
        }
        /// <summary>
        /// The mapping from a database record to data transfer object.
        /// </summary>
        /// <param name="reader">
        /// An instance of the SQL reader.
        /// </param>
        /// <returns>
        /// A deserialized instance of <see cref="CDP4Common.DTO.OrdinalScale"/>.
        /// </returns>
        public virtual CDP4Common.DTO.OrdinalScale MapToDto(NpgsqlDataReader reader)
        {
            string tempModifiedOn;
            string tempName;
            string tempShortName;
            string tempNumberSet;
            string tempMinimumPermissibleValue;
            string tempIsMinimumInclusive;
            string tempMaximumPermissibleValue;
            string tempIsMaximumInclusive;
            string tempPositiveValueConnotation;
            string tempNegativeValueConnotation;
            string tempIsDeprecated;
            string tempUseShortNameValues;

            var valueDict      = (Dictionary <string, string>)reader["ValueTypeSet"];
            var iid            = Guid.Parse(reader["Iid"].ToString());
            var revisionNumber = int.Parse(valueDict["RevisionNumber"]);

            var dto = new CDP4Common.DTO.OrdinalScale(iid, revisionNumber);

            dto.ExcludedPerson.AddRange(Array.ConvertAll((string[])reader["ExcludedPerson"], Guid.Parse));
            dto.ExcludedDomain.AddRange(Array.ConvertAll((string[])reader["ExcludedDomain"], Guid.Parse));
            dto.Alias.AddRange(Array.ConvertAll((string[])reader["Alias"], Guid.Parse));
            dto.Definition.AddRange(Array.ConvertAll((string[])reader["Definition"], Guid.Parse));
            dto.HyperLink.AddRange(Array.ConvertAll((string[])reader["HyperLink"], Guid.Parse));
            dto.Unit = Guid.Parse(reader["Unit"].ToString());
            dto.ValueDefinition.AddRange(Array.ConvertAll((string[])reader["ValueDefinition"], Guid.Parse));
            dto.MappingToReferenceScale.AddRange(Array.ConvertAll((string[])reader["MappingToReferenceScale"], Guid.Parse));

            if (valueDict.TryGetValue("ModifiedOn", out tempModifiedOn))
            {
                dto.ModifiedOn = Utils.ParseUtcDate(tempModifiedOn);
            }

            if (valueDict.TryGetValue("Name", out tempName))
            {
                dto.Name = tempName.UnEscape();
            }

            if (valueDict.TryGetValue("ShortName", out tempShortName))
            {
                dto.ShortName = tempShortName.UnEscape();
            }

            if (valueDict.TryGetValue("NumberSet", out tempNumberSet))
            {
                dto.NumberSet = Utils.ParseEnum <CDP4Common.SiteDirectoryData.NumberSetKind>(tempNumberSet);
            }

            if (valueDict.TryGetValue("MinimumPermissibleValue", out tempMinimumPermissibleValue) && tempMinimumPermissibleValue != null)
            {
                dto.MinimumPermissibleValue = tempMinimumPermissibleValue.UnEscape();
            }

            if (valueDict.TryGetValue("IsMinimumInclusive", out tempIsMinimumInclusive))
            {
                dto.IsMinimumInclusive = bool.Parse(tempIsMinimumInclusive);
            }

            if (valueDict.TryGetValue("MaximumPermissibleValue", out tempMaximumPermissibleValue) && tempMaximumPermissibleValue != null)
            {
                dto.MaximumPermissibleValue = tempMaximumPermissibleValue.UnEscape();
            }

            if (valueDict.TryGetValue("IsMaximumInclusive", out tempIsMaximumInclusive))
            {
                dto.IsMaximumInclusive = bool.Parse(tempIsMaximumInclusive);
            }

            if (valueDict.TryGetValue("PositiveValueConnotation", out tempPositiveValueConnotation) && tempPositiveValueConnotation != null)
            {
                dto.PositiveValueConnotation = tempPositiveValueConnotation.UnEscape();
            }

            if (valueDict.TryGetValue("NegativeValueConnotation", out tempNegativeValueConnotation) && tempNegativeValueConnotation != null)
            {
                dto.NegativeValueConnotation = tempNegativeValueConnotation.UnEscape();
            }

            if (valueDict.TryGetValue("IsDeprecated", out tempIsDeprecated))
            {
                dto.IsDeprecated = bool.Parse(tempIsDeprecated);
            }

            if (valueDict.TryGetValue("UseShortNameValues", out tempUseShortNameValues))
            {
                dto.UseShortNameValues = bool.Parse(tempUseShortNameValues);
            }

            return(dto);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Loads the estate settings.
        /// </summary>
        /// <param name="regionID">region ID.</param>
        /// <returns></returns>
        public EstateSettings LoadEstateSettings(UUID regionID, bool create)
        {
            EstateSettings es = new EstateSettings();

            string sql = "select estate_settings.\"" + String.Join("\",estate_settings.\"", FieldList) +
                         "\" from estate_map left join estate_settings on estate_map.\"EstateID\" = estate_settings.\"EstateID\" " +
                         " where estate_settings.\"EstateID\" is not null and \"RegionID\" = :RegionID";

            bool insertEstate = false;

            using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
                {
                    cmd.Parameters.Add(_Database.CreateParameter("RegionID", regionID));
                    conn.Open();
                    using (NpgsqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            foreach (string name in FieldList)
                            {
                                FieldInfo f = _FieldMap[name];
                                object    v = reader[name];
                                if (f.FieldType == typeof(bool))
                                {
                                    f.SetValue(es, v);
                                }
                                else if (f.FieldType == typeof(UUID))
                                {
                                    UUID estUUID = UUID.Zero;

                                    UUID.TryParse(v.ToString(), out estUUID);

                                    f.SetValue(es, estUUID);
                                }
                                else if (f.FieldType == typeof(string))
                                {
                                    f.SetValue(es, v.ToString());
                                }
                                else if (f.FieldType == typeof(UInt32))
                                {
                                    f.SetValue(es, Convert.ToUInt32(v));
                                }
                                else if (f.FieldType == typeof(Single))
                                {
                                    f.SetValue(es, Convert.ToSingle(v));
                                }
                                else
                                {
                                    f.SetValue(es, v);
                                }
                            }
                        }
                        else
                        {
                            insertEstate = true;
                        }
                    }
                }

            if (insertEstate && create)
            {
                DoCreate(es);
                LinkRegion(regionID, (int)es.EstateID);
            }

            LoadBanList(es);

            es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
            es.EstateAccess   = LoadUUIDList(es.EstateID, "estate_users");
            es.EstateGroups   = LoadUUIDList(es.EstateID, "estate_groups");

            //Set event
            es.OnSave += StoreEstateSettings;
            return(es);
        }
Exemplo n.º 10
0
        public override IEnumerable <FieldActivity> Get(IEnumerable <CompoundIdentity> ids)
        {
            if (ids != null && this.CanGet())
            {
                Dictionary <Guid, HashSet <Guid> > systemIds = new Dictionary <Guid, HashSet <Guid> >();
                HashSet <Guid> oids;
                foreach (CompoundIdentity cur in ids)
                {
                    if (!cur.IsNullOrEmpty())
                    {
                        if (systemIds.ContainsKey(cur.DataStoreIdentity))
                        {
                            oids = systemIds[cur.DataStoreIdentity];
                        }
                        else
                        {
                            oids = new HashSet <Guid>();
                            systemIds[cur.DataStoreIdentity] = oids;
                        }
                        oids.Add(cur.Identity);
                    }
                }

                if (systemIds.Count > 0)
                {
                    StringBuilder where = new StringBuilder(" WHERE ");
                    foreach (KeyValuePair <Guid, HashSet <Guid> > cur in systemIds)
                    {
                        oids = cur.Value;
                        if (oids.Count > 0)
                        {
                            if (systemIds.Count > 1)
                            {
                                where.Append('(');
                            }
                            where.Append("\"SystemId\"='");
                            where.Append(cur.Key.ToString());
                            where.Append("' AND \"Id\" IN (");
                            foreach (Guid cid in oids)
                            {
                                where.Append('\'');
                                where.Append(cid.ToString());
                                where.Append("',");
                            }
                            where[where.Length - 1] = ')';
                            if (systemIds.Count > 1)
                            {
                                where.Append(") OR (");
                            }
                        }
                    }
                    if (where[where.Length - 1] == '(') //need to lop off the " OR ("
                    {
                        where.Length = where.Length - 5;
                    }

                    NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
                    cmd.CommandText = Db.SelectActivities + where.ToString();
                    NpgsqlDataReader     rdr         = Db.ExecuteReader(cmd);
                    List <FieldActivity> permissions = new List <FieldActivity>();
                    try
                    {
                        FieldActivity o;
                        while (rdr.Read())
                        {
                            o = FieldActivityBuilder.Instance.Build(rdr);
                            if (o != null)
                            {
                                permissions.Add(o);
                            }
                        }
                        if (cmd.Connection.State == System.Data.ConnectionState.Open)
                        {
                            cmd.Connection.Close();
                        }
                    }
                    catch
                    { }
                    finally
                    {
                        cmd.Dispose();
                    }

                    return(permissions);
                }
                else
                {
                    return(new FieldActivity[0]); //empty set
                }
            }
            return(null);
        }
Exemplo n.º 11
0
 public Kategorija(NpgsqlDataReader dr)
 {
     IdKategorija    = int.Parse(dr ["id_kategorija"].ToString());
     NazivKategorija = dr["naziv"].ToString();
     Opis            = dr ["opis"].ToString();
 }
        //Query SYS use Ajax
        public ActionResult Query_sys(string query)
        {
            var    Row    = "";
            string column = "";
            string row    = "";

            TEST        test        = db.TEST.Where(m => m.ID_TEST == ID_TEST).FirstOrDefault();
            BAZA_DANYCH bAZA_DANYCH = db.BAZA_DANYCH.Where(m => m.ID_BAZA == test.ID_BAZA).FirstOrDefault();



            //PostreSQL Query
            if (bAZA_DANYCH.TYP == "POSTGRESQL          ")
            {
                string connetionString = "Host=" + bAZA_DANYCH.SCIEZKA + ";Username="******";Password="******";Database=" + bAZA_DANYCH.NAZWA + ";";

                try
                {
                    NpgsqlConnection cnn = new NpgsqlConnection(connetionString);

                    cnn.Open();
                    NpgsqlCommand    command = new NpgsqlCommand(query, cnn);
                    NpgsqlDataReader dr      = command.ExecuteReader();


                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        column += "<th style=\"background-color:#808080\"> " + dr.GetName(i) + "</th>";
                    }
                    var Column = "<tr>" + column + "</tr>";



                    while (dr.Read())
                    {
                        for (int i = 0; i < dr.FieldCount; i++)
                        {
                            row += "<th>" + dr[i].ToString() + "</th>";
                        }
                        Row += "<tr>" + row + "</tr>";
                        row  = "";
                    }
                    var Table = Column + Row;
                    cnn.Close();
                    return(Json(Table));
                }
                catch (Exception exp)
                {
                    return(Json(exp.Message));
                }
            }
            else
            {
                //Oracle Query

                string connetionString = "Data Source=" + bAZA_DANYCH.SCIEZKA + ";User Id=" + bAZA_DANYCH.LOGIN + ";Password="******";DBA Privilege=SYSDBA;";

                try
                {
                    OracleConnection cnn = new OracleConnection(connetionString);
                    cnn.Open();
                    OracleCommand    command = new OracleCommand(query, cnn);
                    OracleDataReader dr      = command.ExecuteReader();


                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        column += "<th style=\"background-color:#808080\"> " + dr.GetName(i) + "</th>";
                    }
                    var Column = "<tr>" + column + "</tr>";



                    while (dr.Read())
                    {
                        for (int i = 0; i < dr.FieldCount; i++)
                        {
                            row += "<th>" + dr[i].ToString() + "</th>";
                        }
                        Row += "<tr>" + row + "</tr>";
                        row  = "";
                    }
                    var Table = Column + Row;
                    cnn.Close();
                    return(Json(Table));
                }
                catch (Exception exp)
                {
                    return(Json(exp.Message));
                }
            }
        }
Exemplo n.º 13
0
 public NpgsqlReaderEnumerator(NpgsqlDataReader _rdr)
 {
     rdr = _rdr;
 }
Exemplo n.º 14
0
 public NpgsqlReaderEnumerable(NpgsqlDataReader _rdr)
 {
     en = new NpgsqlReaderEnumerator(_rdr);
 }
Exemplo n.º 15
0
        protected void search_queries_btn_Click(object sender, EventArgs e)
        {
            using (var conn = new NpgsqlConnection("Host=127.0.0.1;Username=postgres;Password=root1;Database=NMBP_1_projekt"))
            {
                conn.Open();
                using (NpgsqlCommand cmd = new NpgsqlCommand())
                {
                    cmd.Connection = conn;

                    string dateToString   = date_to.Value;
                    string dateFromString = date_from.Value;

                    string selectedValue = RadioButtonChooseQueriesSearch.SelectedValue.ToString();

                    string dateFrom = dateFromString;
                    string dateTo   = dateToString;

                    //cmd.Parameters.Add("dateFrom", NpgsqlDbType.Date).Value= dateFrom;
                    //cmd.Parameters.Add("dateTo", NpgsqlDbType.Date).Value = dateTo;
                    cmd.Parameters.AddWithValue(":dateFrom", dateFrom);
                    cmd.Parameters.AddWithValue(":dateTo", dateTo);

                    cmd.CommandType = CommandType.Text;
                    String query   = "";
                    bool   isDays  = selectedValue.Equals("days");
                    bool   isHours = selectedValue.Equals("hours");
                    if (isDays)
                    {
                        query = @getQuerySqlByDays(dateFrom, dateTo);
                    }
                    else if (isHours)
                    {
                        query = getQuerySqlByTime(dateFrom, dateTo);
                    }

                    if (!string.IsNullOrEmpty(query))
                    {
                        cmd.CommandText = query;
                        using (NpgsqlDataReader reader = cmd.ExecuteReader())
                        {
                            TableRow columnRow = new TableRow();
                            tablePrikaz.Rows.Add(columnRow);
                            if (isDays)
                            {
                                TableCell columnCell = new TableCell();
                                columnCell.Text = "query";
                                columnRow.Cells.Add(columnCell);

                                for (int i = 1; i < 32; i++)
                                {
                                    columnCell      = new TableCell();
                                    columnCell.Text = "d" + i;
                                    columnRow.Cells.Add(columnCell);
                                }
                            }
                            else
                            {
                                String columnNames = "\t\t";
                                columnNames += "query";
                                TableCell columnCell = new TableCell();
                                columnCell.Text = columnNames;
                                columnRow.Cells.Add(columnCell);
                                for (int i = 1; i < 25; i++)
                                {
                                    columnCell      = new TableCell();
                                    columnCell.Text = "h" + i;
                                    columnRow.Cells.Add(columnCell);
                                }
                            }


                            while (reader.Read())
                            {
                                if (isDays)
                                {
                                    TableCell dataCell = new TableCell();
                                    TableRow  dataRow  = new TableRow();
                                    tablePrikaz.Rows.Add(dataRow);

                                    for (int i = 0; i < 32; i++)
                                    {
                                        String column = "";
                                        if (reader.IsDBNull(i))
                                        {
                                            column += "0";
                                        }
                                        else
                                        {
                                            column += reader.GetString(i);
                                        }
                                        dataCell      = new TableCell();
                                        dataCell.Text = column;
                                        dataRow.Cells.Add(dataCell);
                                    }
                                }
                                else
                                {
                                    TableCell dataCell = new TableCell();
                                    TableRow  dataRow  = new TableRow();
                                    tablePrikaz.Rows.Add(dataRow);

                                    for (int i = 0; i < 25; i++)
                                    {
                                        String column = "";
                                        if (reader.IsDBNull(i))
                                        {
                                            column += "0";
                                        }
                                        else
                                        {
                                            column += reader.GetString(i);
                                        }
                                        dataCell      = new TableCell();
                                        dataCell.Text = column;
                                        dataRow.Cells.Add(dataCell);
                                    }
                                }
                            }

                            reader.Close();
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
        public static MergeModel GetMergeModel(Collection <long> ids, TranBook tranBook, SubTranBook subTranBook)
        {
            int rowIndex = 0;

            if (ids == null)
            {
                return(new MergeModel());
            }

            if (ids.Count.Equals(0))
            {
                return(new MergeModel());
            }

            MergeModel model = new MergeModel();

            foreach (long tranId in ids)
            {
                model.AddTransactionIdToCollection(tranId);
            }

            model.Book    = tranBook;
            model.SubBook = subTranBook;

            using (NpgsqlConnection connection = new NpgsqlConnection(DbConnection.GetConnectionString()))
            {
                using (NpgsqlCommand command = GetViewCommand(tranBook, subTranBook, ids))
                {
                    command.Connection = connection;
                    command.Connection.Open();
                    NpgsqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

                    if (!reader.HasRows)
                    {
                        return(new MergeModel());
                    }

                    while (reader.Read())
                    {
                        if (rowIndex.Equals(0))
                        {
                            model.ValueDate           = Conversion.TryCastDate(reader["value_date"]);
                            model.PartyCode           = Conversion.TryCastString(reader["party_code"]);
                            model.PriceTypeId         = Conversion.TryCastInteger(reader["price_type_id"]);
                            model.ReferenceNumber     = Conversion.TryCastString(reader["reference_number"]);
                            model.NonTaxableSales     = Conversion.TryCastBoolean(reader["non_taxable"]);
                            model.ShippingCompanyId   = Conversion.TryCastInteger(reader["shipper_id"]);
                            model.SalesPersonId       = Conversion.TryCastInteger(reader["salesperson_id"]);
                            model.StoreId             = Conversion.TryCastInteger(reader["store_id"]);
                            model.ShippingAddressCode = Conversion.TryCastString(reader["shipping_address_code"]);
                            model.StatementReference  = Conversion.TryCastString(reader["statement_reference"]);
                        }

                        ProductDetail product = new ProductDetail();

                        product.ItemCode = Conversion.TryCastString(reader["item_code"]);
                        product.ItemName = Conversion.TryCastString(reader["item_name"]);
                        product.Unit     = Conversion.TryCastString(reader["unit_name"]);

                        product.Quantity = Conversion.TryCastInteger(reader["quantity"]);
                        product.Price    = Conversion.TryCastDecimal(reader["price"]);
                        product.Amount   = product.Quantity * product.Price;

                        product.Discount       = Conversion.TryCastDecimal(reader["discount"]);
                        product.ShippingCharge = Conversion.TryCastDecimal(reader["shipping_charge"]);
                        product.Subtotal       = product.Amount - product.Discount - product.ShippingCharge;

                        product.TaxCode = Conversion.TryCastString(reader["tax_code"]);
                        product.Tax     = Conversion.TryCastDecimal(reader["tax"]);
                        product.Total   = product.Subtotal + product.Tax;

                        model.AddViewToCollection(product);

                        rowIndex++;
                    }
                }
            }

            if (ids.Count > 0)
            {
                if (!string.IsNullOrWhiteSpace(model.StatementReference))
                {
                    model.StatementReference += Environment.NewLine;
                }

                model.StatementReference += "(" + Entities.Helpers.TransactionBookHelper.GetBookAcronym(tranBook, subTranBook) + "# " + string.Join(",", ids) + ")";
            }

            return(model);
        }
Exemplo n.º 17
0
        //Load All items from list into DataGridView1
        public List <Grocery_Item> Load_Data_Grid(string selected)
        {
            try
            {
                //NHibernate Grocery_Store Query error

                /*using (ISession session = NHibernateHelper.OpenSession()){
                 *      List<Grocery_Store> grocereriesStore = session.Query<Grocery_Store>().ToList();
                 *      List<Grocery_Store> listsForGrid = new List<Grocery_Store>();
                 *
                 *  for (int i = 0; i < grocereriesStore.Count; i++){
                 *      for (int i = 0; i < groceriesStore.Count; i++){
                 *           if (groceriesStore[i].id_grocery_list_fk.ToString() == selected){
                 *              listsForId.Add(groceriesStore[i]);
                 *           }
                 *      }
                 *  }
                 * }*/

                //NpgSqlCommand used
                List <Grocery_Store> groceriesStore = new List <Grocery_Store>();
                List <Grocery_Store> listsForId     = new List <Grocery_Store>();

                NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1 ; Port=5432 ; User Id=postgres; Password=root; Database=GroceryListStoringDB;");
                conn.Open();
                NpgsqlCommand    command    = new NpgsqlCommand(" SELECT * FROM \"Grocery_Store\"", conn);
                NpgsqlDataReader dataReader = command.ExecuteReader();

                //Filling grocereriesStore list from DB
                for (int i = 0; dataReader.Read(); i++)
                {
                    Grocery_Store grocery = new Grocery_Store {
                        id_grocery_list_fk = Int32.Parse(dataReader[0].ToString()), id_grocery_item_fk = Int32.Parse(dataReader[1].ToString())
                    };
                    groceriesStore.Add(grocery);
                }

                //Finding selected list items
                for (int i = 0; i < groceriesStore.Count; i++)
                {
                    if (groceriesStore[i].id_grocery_list_fk.ToString() == selected)
                    {
                        listsForId.Add(groceriesStore[i]);
                    }
                }
                conn.Close();

                using (ISession session = NHibernateHelper.OpenSession())
                {
                    List <Grocery_Item> grocereriesItemsAll = session.Query <Grocery_Item>().ToList();
                    List <Grocery_Item> groceriesList       = new List <Grocery_Item>();

                    //Find grocery items description
                    for (int i = 0; i < listsForId.Count; i++)
                    {
                        for (int j = 0; j < grocereriesItemsAll.Count; j++)
                        {
                            if (listsForId[i].id_grocery_item_fk == grocereriesItemsAll[j].id_grocery_item)
                            {
                                groceriesList.Add(grocereriesItemsAll[j]);
                            }
                        }
                    }
                    return(groceriesList);
                }
            }
            catch (Exception msg) {
                MessageBox.Show(msg.ToString());
                throw;
            }
        }
Exemplo n.º 18
0
        public static int CheckLogIn(string i_name, string i_pwd)
        {
            try
            {
                int count_username = 0;
                var con            = new NpgsqlConnection(DBManagment.cs);
                con.Open();

                var sql = "SELECT count (*) from game_user where username = @username";
                var cmd = new NpgsqlCommand(sql, con);

                cmd.Parameters.AddWithValue("username", i_name);
                cmd.Prepare();

                NpgsqlDataReader rdr = cmd.ExecuteReader();

                rdr.Read();
                count_username = rdr.GetInt32(0);

                rdr.Close();

                if (count_username != 0)
                {
                    //Check if User already has a Session / is logged in
                    sql = "Select count(*) from session where username = @username";
                    var cmd2 = new NpgsqlCommand(sql, con);
                    cmd2.Parameters.AddWithValue("username", i_name);
                    cmd2.Prepare();

                    NpgsqlDataReader rdr2 = cmd2.ExecuteReader();
                    rdr2.Read();
                    int count_session = rdr2.GetInt32(0);
                    rdr2.Close();

                    if (count_session > 0)
                    {
                        //throw new Exception("Error: User already logged in");
                        return(1);
                    }
                    ///////////////////////


                    //Check if pwd is correct
                    sql = "SELECT pwd from game_user where username = @username";
                    var cmd3 = new NpgsqlCommand(sql, con);

                    cmd3.Parameters.AddWithValue("username", i_name);
                    cmd3.Prepare();

                    NpgsqlDataReader rdr3 = cmd3.ExecuteReader();
                    rdr3.Read();
                    string pwd = rdr3.GetString(0);
                    rdr3.Close();

                    if (pwd == i_pwd)
                    {
                        //creating a session by inserting into session table
                        var sql_insert = "Insert into session (username) values (@username)";
                        var cmd4       = new NpgsqlCommand(sql_insert, con);
                        //prepared statment
                        cmd4.Parameters.AddWithValue("username", i_name);
                        cmd4.Prepare();
                        //
                        cmd4.ExecuteNonQuery();
                        con.Close();
                        return(0);
                    }
                    else
                    {
                        con.Close();
                        //throw new Exception("Error -> wrong Password!");
                        return(2);
                    }
                }
                else
                {
                    con.Close();
                    //throw new Exception("Error -> Username doesn't exist!");
                    return(3);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);

                return(4);
            }
        }
Exemplo n.º 19
0
        public OSDArray GetUserImageAssets(UUID avatarId)
        {
            OSDArray data  = new OSDArray();
            string   query = "SELECT \"snapshotuuid\" FROM {0} WHERE \"creatoruuid\" = :Id";

            // Get classified image assets

            try
            {
                using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString))
                {
                    dbcon.Open();

                    using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"classifieds\""), dbcon))
                    {
                        cmd.Parameters.AddWithValue("Id", avatarId.ToString());

                        using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    data.Add(new OSDString((string)reader["snapshotuuid"].ToString()));
                                }
                            }
                        }
                    }

                    dbcon.Close();
                    dbcon.Open();

                    using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"userpicks\""), dbcon))
                    {
                        cmd.Parameters.AddWithValue("Id", avatarId.ToString());

                        using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    data.Add(new OSDString((string)reader["snapshotuuid"].ToString()));
                                }
                            }
                        }
                    }

                    dbcon.Close();
                    dbcon.Open();

                    query = "SELECT \"profileImage\", \"profileFirstImage\" FROM \"userprofile\" WHERE \"useruuid\" = :Id";

                    using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"userpicks\""), dbcon))
                    {
                        cmd.Parameters.AddWithValue("Id", avatarId.ToString());

                        using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    data.Add(new OSDString((string)reader["profileImage"].ToString()));
                                    data.Add(new OSDString((string)reader["profileFirstImage"].ToString()));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[PROFILES_DATA]" +
                                  ": GetAvatarNotes exception {0}", e.Message);
            }
            return(data);
        }
Exemplo n.º 20
0
        public List <Caixa> BuscarEntreDatas(DateTime inicio, DateTime fim)
        {
            List <Caixa> res = null;

            if (inicio > fim)
            {
                DateTime aux;
                aux    = fim;
                fim    = inicio;
                inicio = aux;
            }
            try
            {
                NpgsqlConnection conexao = Util.ConexaoBanco.GetConnection();
                Util.ConexaoBanco.AbrirConexao();

                if (Util.ConexaoBanco.SetDefaultSchema() != 0)
                {
                    throw new Exception("Erro de acesso ao banco, erro na definição definição do esquema do banco de dados");
                }

                using (NpgsqlCommand com = conexao.CreateCommand())
                {
                    com.CommandType = CommandType.Text;
                    com.CommandText = $@"
select codigo, valor_em_caixa, data
  from caixa
 where data <@ daterange('[{inicio.ToString("yyyy-MM-dd")}, { fim.ToString("yyyy-MM-dd")}]')
 order by data asc;";

                    using (NpgsqlDataReader reader = com.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            res = new List <Caixa>();

                            while (reader.Read())
                            {
                                Caixa linha = new Caixa
                                {
                                    Codigo       = Convert.ToUInt64(reader["codigo"].ToString()),
                                    ValorEmCaixa = Convert.ToSingle(reader["valor_em_caixa"].ToString()),
                                    Data         = Convert.ToDateTime(reader["data"].ToString())
                                };
                                res.Add(linha);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                res = null;

                LogSistema.AdicionarEvento($"Erro ao pesquisar por Caixas: {ex.Message}");
            }
            finally
            {
                Util.ConexaoBanco.FecharConexao();
            }
            return(res);
        }
Exemplo n.º 21
0
        private void GetSettingsValue(int snoozeOptionsId, CacheObject cacheObjectType, out object cacheValue)
        {
            using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
            {
                using (NpgsqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM \"SnoozeOptions\" WHERE id=:id";
                    cmd.Parameters.Add("id", snoozeOptionsId);

                    NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
                    reader.Read();

                    int?        sid           = DbValueConverter.Convert <int>(reader["id"]);
                    bool?       cardsEnabled  = DbValueConverter.Convert <bool>(reader["cards_enabled"]);
                    bool?       rightsEnabled = DbValueConverter.Convert <bool>(reader["rights_enabled"]);
                    bool?       timeEnabled   = DbValueConverter.Convert <bool>(reader["time_enabled"]);
                    int?        snoozeCards   = DbValueConverter.Convert <int>(reader["snooze_cards"]);
                    int?        snoozeHigh    = DbValueConverter.Convert <int>(reader["snooze_high"]);
                    int?        snoozeLow     = DbValueConverter.Convert <int>(reader["snooze_low"]);
                    ESnoozeMode?snoozeMode    = DbValueConverter.Convert <ESnoozeMode>(reader["snooze_mode"]);
                    int?        snoozeRights  = DbValueConverter.Convert <int>(reader["snooze_rights"]);
                    int?        snoozeTime    = DbValueConverter.Convert <int>(reader["snooze_time"]);

                    //cache values
                    DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime);
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeCardsEnabled, snoozeOptionsId, expires)]  = cardsEnabled;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeRightsEnabled, snoozeOptionsId, expires)] = rightsEnabled;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeTimeEnabled, snoozeOptionsId, expires)]   = timeEnabled;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeCards, snoozeOptionsId, expires)]         = snoozeCards;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeHigh, snoozeOptionsId, expires)]          = snoozeHigh;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeLow, snoozeOptionsId, expires)]           = snoozeLow;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeMode, snoozeOptionsId, expires)]          = snoozeMode;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeRights, snoozeOptionsId, expires)]        = snoozeRights;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeTime, snoozeOptionsId, expires)]          = snoozeTime;
                    Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsSnoozeOptionsId, snoozeOptionsId, expires)]     = sid;

                    //set output value
                    switch (cacheObjectType)
                    {
                    case CacheObject.SettingsSnoozeCardsEnabled: cacheValue = cardsEnabled; break;

                    case CacheObject.SettingsSnoozeRightsEnabled: cacheValue = rightsEnabled; break;

                    case CacheObject.SettingsSnoozeTimeEnabled: cacheValue = timeEnabled; break;

                    case CacheObject.SettingsSnoozeCards: cacheValue = snoozeCards; break;

                    case CacheObject.SettingsSnoozeHigh: cacheValue = snoozeHigh; break;

                    case CacheObject.SettingsSnoozeLow: cacheValue = snoozeLow; break;

                    case CacheObject.SettingsSnoozeMode: cacheValue = snoozeMode; break;

                    case CacheObject.SettingsSnoozeRights: cacheValue = snoozeRights; break;

                    case CacheObject.SettingsSnoozeTime: cacheValue = snoozeTime; break;

                    case CacheObject.SettingsSnoozeOptionsId: cacheValue = sid; break;

                    default: cacheValue = null; break;
                    }
                }
            }
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((1 == 0))
            {
                {}
            }
            else if (!(1 == 0))
            {
                StringBuilder text = new StringBuilder(tainted_2);
                text.Replace("&", "&amp;");
                text.Replace("'", "&apos;");
                text.Replace(@"""", "&quot;");
                text.Replace("<", "&lt;");
                text.Replace(">", "&gt;");
                tainted_3 = text.ToString();
            }
            else
            {
                {}
            }

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string           connectionString = "Server=localhost;port=1337;User Id=postgre_user;Password=postgre_password;Database=dbname";
            NpgsqlConnection dbConnection     = null;

            try{
                dbConnection = new NpgsqlConnection(connectionString);
                dbConnection.Open();
                NpgsqlCommand    cmd = new NpgsqlCommand(query, dbConnection);
                NpgsqlDataReader dr  = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Console.Write("{0}\n", dr[0]);
                }
                dbConnection.Close();
            }catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 23
0
 public static string GetStringSafe(this NpgsqlDataReader reader, int idColum) =>
 reader.IsDBNull(idColum) ? null : reader.GetString(idColum);
Exemplo n.º 24
0
 public PostgresDatabaseReader(NpgsqlDataReader dataReader)
 {
     this.DataReader = dataReader;
 }
Exemplo n.º 25
0
        //verifica se o usuario digitado no autenticacao está correto, se estiver ele aplica o jogo a bilioteca do usuario
        private void btnLogin_Click(object sender, EventArgs e)
        {
            Loja loja = new Loja();
            
            
            //instanceia o Form Loja para receber a lista dos jogos no btnLogin_Click
            Loja lista = new Loja();
            
            
            
            //instanceia a classe LoginCadastro para receber as variaveis login e senha para a verificação
            Conexoes.LoginCadastro objusuario = new Conexoes.LoginCadastro();
            objusuario.login = txtLogin.Text;
            objusuario.senha = txtSenha.Text;

            //abre a conexão com o banco instanciando o ConexaoDB para o objconexao e executando o  comando pgsqlConnection
            NpgsqlConnection pgsqlConnection = null;
            ConexaoDB objconexao = new ConexaoDB();
            pgsqlConnection = objconexao.getConexao();

            pgsqlConnection.Open();

            
            //forçando qual deve ser o jogo
            string naruto = "Naruto Shippuden Ultimate ninja Storm 4";

            /*if (objusuario.logar(objusuario.login, objusuario.senha) == true)
            {
                //if()
                string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + naruto+ "');";
                NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                NpgsqlDataReader dr1 = cmd.ExecuteReader();
                dr1.Close();

                MessageBox.Show("Jogo Inserido na  Biblioteca ");

                Close();



            }
            else
            {

                MessageBox.Show("Usuario incorreto! /n Tente novamente");

            } */

            if (objusuario.logar(objusuario.login, objusuario.senha) == true)
            {


                if (loja.botaoNaruto == true)
                {
                    string nome = "Naruto Shippuden Ultimate ninja Storm 4";

                    string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + nome + "');";
                    NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                    NpgsqlDataReader dr1 = cmd.ExecuteReader();
                    dr1.Close();

                    MessageBox.Show("Jogo Inserido na  Biblioteca ");

                    Close();
                }
                else if (loja.botaoGta == true)
                {
                    string nome = "Grand Theft Auto 5";

                    string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + nome + "');";
                    NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                    NpgsqlDataReader dr1 = cmd.ExecuteReader();
                    dr1.Close();

                    MessageBox.Show("Jogo Inserido na  Biblioteca ");

                    Close();
                }
                else if (loja.botaoPokemon == true)
                {
                    string nome = "Pokémon Fire Red";

                    string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + nome + "');";
                    NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                    NpgsqlDataReader dr1 = cmd.ExecuteReader();
                    dr1.Close();

                    MessageBox.Show("Jogo Inserido na  Biblioteca ");

                    Close();
                }
                else if (loja.botaoFF == true)
                {
                    string nome = "Final Fantasy XV";

                    string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + nome + "');";
                    NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                    NpgsqlDataReader dr1 = cmd.ExecuteReader();
                    dr1.Close();

                    MessageBox.Show("Jogo Inserido na  Biblioteca ");

                    Close();
                }
                else if (loja.botaoGta == true)
                {
                    string nome = "Grand Theft Auto 5";

                    string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + nome + "');";
                    NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                    NpgsqlDataReader dr1 = cmd.ExecuteReader();
                    dr1.Close();

                    MessageBox.Show("Jogo Inserido na  Biblioteca ");

                    Close();
                }
                else if (loja.botaoSonic == true)
                {
                    string nome = "Sonic Rider";

                    string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + nome + "');";
                    NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                    NpgsqlDataReader dr1 = cmd.ExecuteReader();
                    dr1.Close();

                    MessageBox.Show("Jogo Inserido na  Biblioteca ");

                    Close();
                }
                else if (loja.botaoBO4 == true)
                {
                    string nome = "Call of Duty Black Ops ";
                    if (verificaJogoBiblioteca(objusuario.login, nome) == true)
                    {
                        string sql = "INSERT INTO tbl_tem(fk_usuario_login, fk_jogo_nome) VALUES " + "('" + objusuario.login + "', '" + nome + "');";
                        NpgsqlCommand cmd = new NpgsqlCommand(sql, pgsqlConnection);

                        NpgsqlDataReader dr1 = cmd.ExecuteReader();
                        dr1.Close();

                        MessageBox.Show("Jogo Inserido na  Biblioteca ");

                        Close();
                    }
                    else
                    {
                        MessageBox.Show("jogo já inserido na biblioteca.");
                    }
                }

            }
            else
            {
                MessageBox.Show("Usuario não encontrado!");
            }
            
        }
Exemplo n.º 26
0
 public void ExecuteReader(String sql)
 {
     command.CommandText = sql;
     reader = command.ExecuteReader();
 }
Exemplo n.º 27
0
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((4 + 2 >= 42))
            {
                {}
            }
            else if (!(4 + 2 >= 42))
            {
                {}
            }
            else
            {
                string pattern = @"/^[0-9]*$/";
                Regex  r       = new Regex(pattern);
                Match  m       = r.Match(tainted_2);
                if (!m.Success)
                {
                    tainted_3 = "";
                }
                else
                {
                    tainted_3 = tainted_2;
                }
            }

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string           connectionString = "Server=localhost;port=1337;User Id=postgre_user;Password=postgre_password;Database=dbname";
            NpgsqlConnection dbConnection     = null;

            try{
                dbConnection = new NpgsqlConnection(connectionString);
                dbConnection.Open();
                NpgsqlCommand    cmd = new NpgsqlCommand(query, dbConnection);
                NpgsqlDataReader dr  = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Console.Write("{0}\n", dr[0]);
                }
                dbConnection.Close();
            }catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 28
0
 public void ExecuteReader(String sql, Object[] param)
 {
     command.CommandText = Construct(sql, param);
     reader = command.ExecuteReader();
 }
Exemplo n.º 29
0
        private void UpdateInTeam()
        {
            //Create the empty table data
            DataTable dt = new DataTable("Table");

            dt.Columns.Add("golf_id", typeof(string));
            dt.Columns.Add("förnamn", typeof(string));
            dt.Columns.Add("efternamn", typeof(string));

            String           sql     = "SELECT    \"tävling_medlem\".\"tävling_id\",    medlem.golf_id,    medlem.\"förnamn\",    medlem.efternamn FROM    public.\"tävling_medlem\",    public.medlem WHERE    \"tävling_medlem\".golf_id = medlem.golf_id AND   \"tävling_medlem\".\"tävling_id\" = '" + tävling_id.ToString() + "';";
            NpgsqlCommand    command = new NpgsqlCommand(sql, GolfReception.conn);
            NpgsqlDataReader ndr     = command.ExecuteReader();

            while (ndr.Read())
            {
                DataRow row = dt.NewRow();
                row["golf_id"]   = ndr["golf_id"].ToString();
                row["förnamn"]   = ndr["förnamn"].ToString();
                row["efternamn"] = ndr["efternamn"].ToString();
                dt.Rows.Add(row);
            }
            ndr.Close();

            //Lista med de som ska tas bort
            LinkedList <DataRow> removeList = new LinkedList <DataRow>();

            foreach (DataRow row in dt.Rows)
            {
                bool hasTeam = false;
                for (int i = 0; i < tid_dataGridView.RowCount; i++)
                {
                    String s1 = "";
                    if (!System.DBNull.Value.Equals(tid_dataGridView["spelare_1", i].Value))
                    {
                        s1 = (String)tid_dataGridView["spelare_1", i].Value;
                    }

                    String s2 = "";
                    if (!System.DBNull.Value.Equals(tid_dataGridView["spelare_2", i].Value))
                    {
                        s2 = (String)tid_dataGridView["spelare_2", i].Value;
                    }

                    String s3 = "";
                    if (!System.DBNull.Value.Equals(tid_dataGridView["spelare_3", i].Value))
                    {
                        s3 = (String)tid_dataGridView["spelare_3", i].Value;
                    }

                    String s4 = "";
                    if (!System.DBNull.Value.Equals(tid_dataGridView["spelare_4", i].Value))
                    {
                        s4 = (String)tid_dataGridView["spelare_4", i].Value;
                    }

                    if (
                        s1.Equals(row["golf_id"]) ||
                        s2.Equals(row["golf_id"]) ||
                        s3.Equals(row["golf_id"]) ||
                        s4.Equals(row["golf_id"])
                        )
                    {
                        hasTeam = true;
                    }
                }

                if (hasTeam == false)
                {
                    removeList.AddLast(row);
                }
            }

            //Ta bort alla i borttagninslistan från tabellen
            foreach (DataRow row in removeList)
            {
                dt.Rows.Remove(row);
            }

            DataView dv = new DataView(dt);

            //Set the component data
            inTeam_dataGridView.DataSource = dv;

            inTeam_dataGridView.Columns[0].HeaderText = "Golf-ID";
            inTeam_dataGridView.Columns[1].HeaderText = "Förnamn";
            inTeam_dataGridView.Columns[2].HeaderText = "Efternamn";
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {

            string dbserver = System.Configuration.ConfigurationManager.AppSettings["dbserver"];
            string database = System.Configuration.ConfigurationManager.AppSettings["database"];
            string userid = System.Configuration.ConfigurationManager.AppSettings["userid"];
            string password = System.Configuration.ConfigurationManager.AppSettings["password"];
            NpgsqlConnection conn = new NpgsqlConnection("Server=" + dbserver + ";Port=5432"+ ";User Id=" + userid + ";Password=Saturnus1!" + ";Database=" + database + ";");
            const string accessToken = "xxxxxxxxxxxxxxxxxxx";
            const string accessTokenSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            const string consumerKey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
            const string consumerSecret = "xxxxxxxxxxxxxxxxxxxxxx";
            //const string twitterAccountToDisplay = "xxxxxxxxxxxx";
            string message = "";
            string title = "";
            string time = "";
            string call = "";
            string freq = "";
            string band = "";
            string country = "";
            string mode = "";

            var authorizer = new SingleUserAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = consumerKey,
                    ConsumerSecret = consumerSecret,
                    OAuthToken = accessToken,
                    OAuthTokenSecret = accessTokenSecret
                }
            };

            using (StreamWriter w = File.AppendText("log.txt"))
            {
                Log("Started", w);

            }
            while (true)
            {
                try

                {
                     message = "";
                    conn.Open();
                    NpgsqlCommand cmd2 = new NpgsqlCommand("SELECT  distinct title, dxcall, freq, band, country, mode, dx_continent,skimmode FROM cluster.alert_new_country", conn);
                    //cmd2.Parameters.Add(new NpgsqlParameter("value1", NpgsqlTypes.NpgsqlDbType.Text));
                    // cmd2.Parameters[0].Value = callsign;
                    // string dxcountry = (String)cmd2.ExecuteScalar();
                    NpgsqlDataReader dr2 = cmd2.ExecuteReader();

                    //string dx_cont = "";
                    while (dr2.Read())
                    {
                        title = dr2[0].ToString();
                        call = dr2[1].ToString();
                        freq = dr2[2].ToString();
                        band = dr2[3].ToString();
                        country = dr2[4].ToString();
                        mode = dr2[5].ToString();
                        message = "de " + title + " "  + call + " " + freq.Trim() + "KHz" + " " + band + " " + mode + " " + country;
                        Console.WriteLine(message);
                        conn.Close();

                        using (StreamWriter w = File.AppendText("new_countries.txt"))
                        {
                            w.Write("\r\n");
                            w.Write(message);
                        }
                    
                        try
                        {
                            conn.Open();

                            NpgsqlCommand cmd = new NpgsqlCommand("insert into cluster.alarms(call,time,freq,band,mode,country) values ( :value1 ,:value2,:value3,:value4,:value5,:value6)", conn);
                            cmd.Parameters.Add(new NpgsqlParameter("value1", NpgsqlTypes.NpgsqlDbType.Text));
                            cmd.Parameters.Add(new NpgsqlParameter("value2", NpgsqlTypes.NpgsqlDbType.Text));
                            cmd.Parameters.Add(new NpgsqlParameter("value3", NpgsqlTypes.NpgsqlDbType.Text));
                            cmd.Parameters.Add(new NpgsqlParameter("value4", NpgsqlTypes.NpgsqlDbType.Text));
                            cmd.Parameters.Add(new NpgsqlParameter("value5", NpgsqlTypes.NpgsqlDbType.Text));
                            cmd.Parameters.Add(new NpgsqlParameter("value6", NpgsqlTypes.NpgsqlDbType.Text));

                            cmd.Parameters[0].Value = call;
                            cmd.Parameters[1].Value = time;
                            cmd.Parameters[2].Value = freq;
                            cmd.Parameters[3].Value = band;
                            cmd.Parameters[4].Value = mode;
                            cmd.Parameters[5].Value = country;
                            NpgsqlDataReader dr = cmd.ExecuteReader();
                            conn.Close();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            conn.Close();
                        };
                        Console.WriteLine(message);
                    }

                    using (var context = new TwitterContext(authorizer))
                    {
                        if (call != "")
                        {

                           // var tweet = context.TweetAsync(message).Result;
                        }
                    };



                    conn.Close();

                }
                catch (Exception e)
                {
                     Console.WriteLine(e);
                    using (StreamWriter w = File.AppendText("log.txt"))
                    {
                        Log(e, w);
                    }
                    conn.Close();
                }
                //Console.WriteLine(message);

                string smtpAddress = "smtp.gmail.com";
                    int portNumber = 587;
                    bool enableSSL = true;
                    string emailFrom = "xxxxxxxxxxxxxxxxxxxxx";
                    string pass = "******";
                    string emailTo = "xxxxxxxxxxxxxxxxx";
                    string subject = message;
                    string body = message;

                    using (MailMessage mail = new MailMessage())
                    {
                        mail.From = new MailAddress(emailFrom);
                        mail.To.Add(emailTo);
                        mail.Subject = subject;
                        mail.Body = body;
                        mail.IsBodyHtml = false;

                        using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                        {
                            smtp.Credentials = new NetworkCredential(emailFrom, pass);
                            smtp.EnableSsl = enableSSL;
                            smtp.Timeout = 3000;
                            try
                            {
                                if (message != "")
                                {
                                   smtp.Send(mail);
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                               // Console.ReadKey();
                            }
                        }
                    }

            
                    System.Threading.Thread.Sleep(59000);
                

            }


        }
Exemplo n.º 31
0
		//
		// GetUserFromReader
		//    A helper function that takes the current row from the NpgsqlDataReader
		// and hydrates a MembershiUser from the values. Called by the 
		// MembershipUser.GetUser implementation.
		//

		private MembershipUser GetUserFromReader(NpgsqlDataReader reader)
		{
			object providerUserKey = new Guid(reader.GetValue(0).ToString());
			string username = reader.IsDBNull(1) ? "" : reader.GetString(1);
			string email = reader.IsDBNull(2) ? "" : reader.GetString(2);
			string passwordQuestion = reader.IsDBNull(3) ? "" : reader.GetString(3);
			string comment = reader.IsDBNull(4) ? "" : reader.GetString(4);
			bool isApproved = reader.IsDBNull(5) ? false : reader.GetBoolean(5);
			bool isLockedOut = reader.IsDBNull(6) ? false : reader.GetBoolean(6);
			DateTime creationDate = reader.IsDBNull(7) ? DateTime.Now : reader.GetDateTime(7);
			DateTime lastLoginDate = reader.IsDBNull(8) ? DateTime.Now : reader.GetDateTime(8);
			DateTime lastActivityDate = reader.IsDBNull(9) ? DateTime.Now : reader.GetDateTime(9);
			DateTime lastPasswordChangedDate = reader.IsDBNull(10) ? DateTime.Now : reader.GetDateTime(10);
			DateTime lastLockedOutDate = reader.IsDBNull(11) ? DateTime.Now : reader.GetDateTime(11);

			MembershipUser u =
				new MembershipUser(this.Name, username, providerUserKey, email, passwordQuestion, comment, isApproved, isLockedOut,
				                   creationDate, lastLoginDate, lastActivityDate, lastPasswordChangedDate, lastLockedOutDate);

			return u;
		}
Exemplo n.º 32
0
        protected T[] DoQuery(NpgsqlCommand cmd)
        {
            List <T> result = new List <T>();

            if (cmd.Connection == null)
            {
                cmd.Connection = new NpgsqlConnection(m_connectionString);
            }
            if (cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
            using (NpgsqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader == null)
                {
                    return(new T[0]);
                }

                CheckColumnNames(reader);

                while (reader.Read())
                {
                    T row = new T();

                    foreach (string name in m_Fields.Keys)
                    {
                        if (m_Fields[name].GetValue(row) is bool)
                        {
                            int v = Convert.ToInt32(reader[name]);
                            m_Fields[name].SetValue(row, v != 0 ? true : false);
                        }
                        else if (m_Fields[name].GetValue(row) is UUID)
                        {
                            UUID uuid = UUID.Zero;

                            UUID.TryParse(reader[name].ToString(), out uuid);
                            m_Fields[name].SetValue(row, uuid);
                        }
                        else if (m_Fields[name].GetValue(row) is int)
                        {
                            int v = Convert.ToInt32(reader[name]);
                            m_Fields[name].SetValue(row, v);
                        }
                        else
                        {
                            m_Fields[name].SetValue(row, reader[name]);
                        }
                    }

                    if (m_DataField != null)
                    {
                        Dictionary <string, string> data =
                            new Dictionary <string, string>();

                        foreach (string col in m_ColumnNames)
                        {
                            data[col] = reader[col].ToString();

                            if (data[col] == null)
                            {
                                data[col] = String.Empty;
                            }
                        }

                        m_DataField.SetValue(row, data);
                    }

                    result.Add(row);
                }
                return(result.ToArray());
            }
        }