• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# NpgsqlCommand类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中NpgsqlCommand的典型用法代码示例。如果您正苦于以下问题:C# NpgsqlCommand类的具体用法?C# NpgsqlCommand怎么用?C# NpgsqlCommand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



NpgsqlCommand类属于命名空间,在下文中一共展示了NpgsqlCommand类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ExecuteNonQuery

    /// <summary>
    /// 执行 Transact-SQL 语句并返回受影响的行数。
    /// </summary>
    public int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText,
        params DbParameter[] cmdParms)
    {
        NpgsqlCommand cmd = new NpgsqlCommand();

        using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }
    }
开发者ID:89sos98,项目名称:LBC,代码行数:16,代码来源:PostgreHelper.cs


示例2: DeriveParametersVarious

        public void DeriveParametersVarious()
        {
            using (var conn = OpenConnection())
            {
                // This function returns record because of the two Out (InOut & Out) parameters
                conn.ExecuteNonQuery(@"
                    CREATE OR REPLACE FUNCTION pg_temp.func(IN param1 INT, OUT param2 text, INOUT param3 INT) RETURNS record AS
                    '
                    BEGIN
                            param2 = ''sometext'';
                            param3 = param1 + param3;
                    END;
                    ' LANGUAGE 'plpgsql';
                ");

                var cmd = new NpgsqlCommand("pg_temp.func", conn) { CommandType = CommandType.StoredProcedure };
                NpgsqlCommandBuilder.DeriveParameters(cmd);
                Assert.That(cmd.Parameters, Has.Count.EqualTo(3));
                Assert.That(cmd.Parameters[0].Direction, Is.EqualTo(ParameterDirection.Input));
                Assert.That(cmd.Parameters[1].Direction, Is.EqualTo(ParameterDirection.Output));
                Assert.That(cmd.Parameters[2].Direction, Is.EqualTo(ParameterDirection.InputOutput));
                cmd.Parameters[0].Value = 5;
                cmd.Parameters[2].Value = 4;
                cmd.ExecuteNonQuery();
                Assert.That(cmd.Parameters[0].Value, Is.EqualTo(5));
                Assert.That(cmd.Parameters[1].Value, Is.EqualTo("sometext"));
                Assert.That(cmd.Parameters[2].Value, Is.EqualTo(9));
            }
        }
开发者ID:ArsenShnurkov,项目名称:npgsql,代码行数:29,代码来源:CommandBuilderTests.cs


示例3: ExecuteQuery

 /// <summary>
 /// 在事务中执行查询,返回DataSet
 /// </summary>
 public DataSet ExecuteQuery(DbTransaction trans, CommandType cmdType, string cmdText,
     params DbParameter[] cmdParms)
 {
     NpgsqlCommand cmd = new NpgsqlCommand();
     PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
     NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
     DataSet ds = new DataSet();
     da.Fill(ds, "ds");
     cmd.Parameters.Clear();
     return ds;
 }
开发者ID:89sos98,项目名称:LBC,代码行数:14,代码来源:PostgreHelper.cs


示例4: RecordWithNonIntField

 public void RecordWithNonIntField()
 {
     using (var conn = OpenConnection())
     using (var cmd = new NpgsqlCommand("SELECT ('one', 2)", conn))
     using (var reader = cmd.ExecuteReader())
     {
         reader.Read();
         var record = reader.GetFieldValue<object[]>(0);
         Assert.That(record[0], Is.EqualTo("one"));
         Assert.That(record[1], Is.EqualTo(2));
     }
 }
开发者ID:npgsql,项目名称:npgsql,代码行数:12,代码来源:BugTests.cs


示例5: Bug1285

        public void Bug1285()
        {
            using (var conn = OpenConnection())
            using (var cmd = new NpgsqlCommand { Connection = conn })
            {
                cmd.CommandText = Bug1285CreateStatement;
                cmd.ExecuteNonQuery();

                cmd.CommandText = Bug1285SelectStatement;
                cmd.Parameters.Add(new NpgsqlParameter("@1", Guid.NewGuid()));
                cmd.ExecuteNonQuery();
            }
        }
开发者ID:npgsql,项目名称:npgsql,代码行数:13,代码来源:BugTests.cs


示例6: AllowDBNull

        public void AllowDBNull()
        {
            using (var conn = OpenConnection())
            {
                conn.ExecuteNonQuery("CREATE TEMP TABLE data (nullable INTEGER, non_nullable INTEGER NOT NULL)");

                using (var cmd = new NpgsqlCommand("SELECT nullable,non_nullable,8 FROM data", conn))
                using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo))
                {
                    var columns = reader.GetColumnSchema();
                    Assert.That(columns[0].AllowDBNull, Is.True);
                    Assert.That(columns[1].AllowDBNull, Is.False);
                    Assert.That(columns[2].AllowDBNull, Is.Null);
                }
            }
        }
开发者ID:npgsql,项目名称:npgsql,代码行数:16,代码来源:ReaderNewSchemaTests.cs


示例7: BaseCatalogName

        public void BaseCatalogName()
        {
            var dbName = new NpgsqlConnectionStringBuilder(ConnectionString).Database;
            using (var conn = OpenConnection())
            {
                conn.ExecuteNonQuery("CREATE TEMP TABLE data (foo INTEGER)");

                using (var cmd = new NpgsqlCommand("SELECT foo,8 FROM data", conn))
                using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
                {
                    var columns = reader.GetColumnSchema();
                    Assert.That(columns[0].BaseCatalogName, Is.EqualTo(dbName));
                    Assert.That(columns[1].BaseCatalogName, Is.EqualTo(dbName));
                }
            }
        }
开发者ID:npgsql,项目名称:npgsql,代码行数:16,代码来源:ReaderNewSchemaTests.cs


示例8: BaseColumnName

        public void BaseColumnName()
        {
            using (var conn = OpenConnection())
            {
                conn.ExecuteNonQuery("CREATE TEMP TABLE data (foo INTEGER)");

                using (var cmd = new NpgsqlCommand("SELECT foo,8 AS bar,8,'8'::VARCHAR(10) FROM data", conn))
                using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
                {
                    var columns = reader.GetColumnSchema();
                    Assert.That(columns[0].BaseColumnName, Is.EqualTo("foo"));
                    Assert.That(columns[1].BaseColumnName, Is.EqualTo("bar"));
                    Assert.That(columns[2].BaseColumnName, Is.Null);
                    Assert.That(columns[3].BaseColumnName, Is.EqualTo("varchar"));
                }
            }
        }
开发者ID:npgsql,项目名称:npgsql,代码行数:17,代码来源:ReaderNewSchemaTests.cs


示例9: PrimaryKeyFieldMetadataSupport

 public void PrimaryKeyFieldMetadataSupport()
 {
     using (var conn = OpenConnection())
     {
         conn.ExecuteNonQuery("CREATE TEMP TABLE data (id SERIAL PRIMARY KEY, serial SERIAL)");
         using (var command = new NpgsqlCommand("SELECT * FROM data", conn))
         {
             using (var dr = command.ExecuteReader(CommandBehavior.KeyInfo))
             {
                 dr.Read();
                 var metadata = dr.GetSchemaTable();
                 var key = metadata.Rows.Cast<DataRow>().Single(r => (bool)r["IsKey"]);
                 Assert.That(key["ColumnName"], Is.EqualTo("id"));
             }
         }
     }
 }
开发者ID:ArsenShnurkov,项目名称:npgsql,代码行数:17,代码来源:ReaderOldSchemaTests.cs


示例10: ExecuteReader

    /// <summary>
    /// 执行查询,返回DataReader
    /// </summary>
    public DbDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText,
        params DbParameter[] cmdParms)
    {
        NpgsqlCommand cmd = new NpgsqlCommand();
        NpgsqlConnection conn = new NpgsqlConnection(connectionString);

        try
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            NpgsqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            return rdr;
        }
        catch
        {
            conn.Close();
            throw;
        }
    }
开发者ID:89sos98,项目名称:LBC,代码行数:22,代码来源:PostgreHelper.cs


示例11: ManyParametersWithMixedFormatCode

        public void ManyParametersWithMixedFormatCode()
        {
            using (var conn = OpenConnection())
            using (var cmd = new NpgsqlCommand())
            {
                cmd.Connection = conn;
                var sb = new StringBuilder("SELECT @text_param");
                cmd.Parameters.AddWithValue("@text_param", "some_text");
                for (var i = 0; i < conn.BufferSize; i++)
                {
                    var paramName = $"@binary_param{i}";
                    sb.Append(",");
                    sb.Append(paramName);
                    cmd.Parameters.AddWithValue(paramName, 8);
                }
                cmd.CommandText = sb.ToString();

                Assert.That(() => cmd.ExecuteNonQuery(), Throws.Exception
                    .TypeOf<PostgresException>()
                    .With.Property(nameof(PostgresException.SqlState)).EqualTo("54000")
                );
            }
        }
开发者ID:npgsql,项目名称:npgsql,代码行数:23,代码来源:BugTests.cs


示例12: PrimaryKeyFieldsMetadataSupport

        public void PrimaryKeyFieldsMetadataSupport()
        {
            using (var conn = OpenConnection())
            {
                conn.ExecuteNonQuery("DROP TABLE IF EXISTS DATA2 CASCADE");
                conn.ExecuteNonQuery(@"CREATE TEMP TABLE DATA2 (
                                field_pk1                      INT2 NOT NULL,
                                field_pk2                      INT2 NOT NULL,
                                field_serial                   SERIAL,
                                CONSTRAINT data2_pkey PRIMARY KEY (field_pk1, field_pk2)
                                ) WITH OIDS");

                using (var command = new NpgsqlCommand("SELECT * FROM DATA2", conn))
                using (var dr = command.ExecuteReader(CommandBehavior.KeyInfo))
                {
                    dr.Read();
                    var keyColumns =
                        dr.GetSchemaTable().Rows.Cast<DataRow>().Where(r => (bool)r["IsKey"]).ToArray();
                    Assert.That(keyColumns, Has.Length.EqualTo(2));
                    Assert.That(keyColumns.Count(c => (string)c["ColumnName"] == "field_pk1"), Is.EqualTo(1));
                    Assert.That(keyColumns.Count(c => (string)c["ColumnName"] == "field_pk2"), Is.EqualTo(1));
                }
            }
        }
开发者ID:ArsenShnurkov,项目名称:npgsql,代码行数:24,代码来源:ReaderOldSchemaTests.cs


示例13: DeriveParametersInOnly

        public void DeriveParametersInOnly()
        {
            using (var conn = OpenConnection())
            {
                // This function returns record because of the two Out (InOut & Out) parameters
                conn.ExecuteNonQuery(@"
                    CREATE OR REPLACE FUNCTION pg_temp.func(IN param1 INT, IN param2 INT) RETURNS int AS
                    '
                    BEGIN
                    RETURN param1 + param2;
                    END;
                    ' LANGUAGE 'plpgsql';
                ");

                var cmd = new NpgsqlCommand("pg_temp.func", conn) { CommandType = CommandType.StoredProcedure };
                NpgsqlCommandBuilder.DeriveParameters(cmd);
                Assert.That(cmd.Parameters, Has.Count.EqualTo(2));
                Assert.That(cmd.Parameters[0].Direction, Is.EqualTo(ParameterDirection.Input));
                Assert.That(cmd.Parameters[1].Direction, Is.EqualTo(ParameterDirection.Input));
                cmd.Parameters[0].Value = 5;
                cmd.Parameters[1].Value = 4;
                Assert.That(cmd.ExecuteScalar(), Is.EqualTo(9));
            }
        }
开发者ID:ArsenShnurkov,项目名称:npgsql,代码行数:24,代码来源:CommandBuilderTests.cs


示例14: DeleteUser

		//
		// MembershipProvider.DeleteUser
		//

		public override bool DeleteUser(string username, bool deleteAllRelatedData)
		{
			NpgsqlConnection conn = new NpgsqlConnection(connectionString);
			NpgsqlCommand cmd =
				new NpgsqlCommand(
					string.Format("DELETE FROM {0} WHERE user_name = @user_name AND application_name = @application_name", tableName), conn);

			cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
			cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;

			int rowsAffected = 0;

			try
			{
				conn.Open();

				rowsAffected = cmd.ExecuteNonQuery();

				if (deleteAllRelatedData)
				{
					// Process commands to delete all data for the user in the database.
				}
			}
			catch (NpgsqlException e)
			{
				if (WriteExceptionsToEventLog)
				{
					WriteToEventLog(e, "DeleteUser");

                    // use fully qualified name so as not to conflict with System.Data.ProviderException
                    // in System.Data.Entity assembly
					throw new System.Configuration.Provider.ProviderException(exceptionMessage);
				}
				else
				{
					throw;//e;
				}
			}
			finally
			{
				cmd.Dispose();
				conn.Close();
			}

			return (rowsAffected > 0);		}
开发者ID:seeseekey,项目名称:CSCL,代码行数:49,代码来源:NpgsqlMembershipProvider.cs


示例15: CreateUser

		//
		// MembershipProvider.CreateUser
		//

		public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion,
		                                          string passwordAnswer, bool isApproved, object providerUserKey,
		                                          out MembershipCreateStatus status)
		{
			ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);

			OnValidatingPassword(args);

			if (args.Cancel)
			{
				status = MembershipCreateStatus.InvalidPassword;
				return null;
			}


			if (RequiresUniqueEmail && !string.IsNullOrEmpty(GetUserNameByEmail(email)))
			{
				status = MembershipCreateStatus.DuplicateEmail;
				return null;
			}

			MembershipUser u = GetUser(username, false);

			if (u == null)
			{
				DateTime createDate = DateTime.Now;

				if (providerUserKey == null)
				{
					providerUserKey = Guid.NewGuid();
				}
				else
				{
					if (!(providerUserKey is Guid))
					{
						status = MembershipCreateStatus.InvalidProviderUserKey;
						return null;
					}
				}

				NpgsqlConnection conn = new NpgsqlConnection(connectionString);
				NpgsqlCommand cmd =
					new NpgsqlCommand(
						string.Format("INSERT INTO {0} (UserId, user_name, Password, Email, password_question,  password_answer, is_approved, Comment, creation_date, last_password_changed_date, last_activity_date, application_name, is_locked_out, last_locked_out_date, failed_password_attempt_count, failed_password_attempt_window_start,  failed_password_answer_attempt_count, failed_password_answer_attempt_window_start) Values(@UserId, @user_name, @Password, @Email, @password_question,  @password_answer, @is_approved, @Comment, @creation_date, @last_password_changed_date,  @last_activity_date, @application_name, @is_locked_out, @last_locked_out_date,  @failed_password_attempt_count, @failed_password_attempt_window_start,  @failed_password_answer_attempt_count, @failed_password_answer_attempt_window_start)", tableName), conn);

				cmd.Parameters.Add("@UserId", NpgsqlDbType.Text).Value = providerUserKey.ToString();
				cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
				cmd.Parameters.Add("@Password", NpgsqlDbType.Text, 255).Value = EncodePassword(password);
				cmd.Parameters.Add("@Email", NpgsqlDbType.Text, 128).Value = email;
				cmd.Parameters.Add("@password_question", NpgsqlDbType.Text, 255).Value = passwordQuestion;
				cmd.Parameters.Add("@password_answer", NpgsqlDbType.Text, 255).Value = passwordAnswer == null
				                                                                       	? null
				                                                                       	: EncodePassword(passwordAnswer);
				cmd.Parameters.Add("@is_approved", NpgsqlDbType.Boolean).Value = isApproved;
				cmd.Parameters.Add("@Comment", NpgsqlDbType.Text, 255).Value = "";
				cmd.Parameters.Add("@creation_date", NpgsqlDbType.Timestamp).Value = createDate;
				cmd.Parameters.Add("@last_password_changed_date", NpgsqlDbType.Timestamp).Value = createDate;
				cmd.Parameters.Add("@last_activity_date", NpgsqlDbType.Timestamp).Value = createDate;
				cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;
				cmd.Parameters.Add("@is_locked_out", NpgsqlDbType.Boolean).Value = false; //false
				cmd.Parameters.Add("@last_locked_out_date", NpgsqlDbType.Timestamp).Value = createDate;
				cmd.Parameters.Add("@failed_password_attempt_count", NpgsqlDbType.Integer).Value = 0;
				cmd.Parameters.Add("@failed_password_attempt_window_start", NpgsqlDbType.Timestamp).Value = createDate;
				cmd.Parameters.Add("@failed_password_answer_attempt_count", NpgsqlDbType.Integer).Value = 0;
				cmd.Parameters.Add("@failed_password_answer_attempt_window_start", NpgsqlDbType.Timestamp).Value = createDate;

				try
				{
					conn.Open();

					int recAdded = cmd.ExecuteNonQuery();

					if (recAdded > 0)
					{
						status = MembershipCreateStatus.Success;
					}
					else
					{
						status = MembershipCreateStatus.UserRejected;
					}
				}
				catch (NpgsqlException e)
				{
					if (WriteExceptionsToEventLog)
					{
						WriteToEventLog(e, "CreateUser");
					}

					status = MembershipCreateStatus.ProviderError;
				}
				finally
				{
					cmd.Dispose();
					conn.Close();
				}

//.........这里部分代码省略.........
开发者ID:seeseekey,项目名称:CSCL,代码行数:101,代码来源:NpgsqlMembershipProvider.cs


示例16: ChangePasswordQuestionAndAnswer

		//
		// MembershipProvider.ChangePasswordQuestionAndAnswer
		//

		public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPwdQuestion,
		                                                     string newPwdAnswer)
		{
			if (!ValidateUser(username, password))
			{
				return false;
			}

			NpgsqlConnection conn = new NpgsqlConnection(connectionString);
			NpgsqlCommand cmd =
				new NpgsqlCommand(
					string.Format("UPDATE {0} SET password_question = @Question, password_answer = @Answer WHERE user_name = @user_name AND application_name = @application_name", tableName), conn);

			cmd.Parameters.Add("@Question", NpgsqlDbType.Text, 255).Value = newPwdQuestion;
			cmd.Parameters.Add("@Answer", NpgsqlDbType.Text, 255).Value = EncodePassword(newPwdAnswer);
			cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
			cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;


			int rowsAffected = 0;

			try
			{
				conn.Open();

				rowsAffected = cmd.ExecuteNonQuery();
			}
			catch (NpgsqlException e)
			{
				if (WriteExceptionsToEventLog)
				{
					WriteToEventLog(e, "ChangePasswordQuestionAndAnswer");

                    // use fully qualified name so as not to conflict with System.Data.ProviderException
                    // in System.Data.Entity assembly
					throw new System.Configuration.Provider.ProviderException(exceptionMessage);
				}
				else
				{
					throw;// e;
				}
			}
			finally
			{
				cmd.Dispose();
				conn.Close();
			}

			return (rowsAffected > 0);
		}
开发者ID:seeseekey,项目名称:CSCL,代码行数:54,代码来源:NpgsqlMembershipProvider.cs


示例17: ChangePassword

		//
		// System.Web.Security.MembershipProvider methods.
		//

		//
		// MembershipProvider.ChangePassword
		//

		public override bool ChangePassword(string username, string oldPwd, string newPwd)
		{
			if (!ValidateUser(username, oldPwd))
			{
				return false;
			}


			ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPwd, true);

			OnValidatingPassword(args);

			if (args.Cancel)
			{
				if (args.FailureInformation != null)
				{
					throw args.FailureInformation;
				}
				else
				{
					throw new MembershipPasswordException("Change password canceled due to new password validation failure.");
				}
			}


			NpgsqlConnection conn = new NpgsqlConnection(connectionString);
			NpgsqlCommand cmd =
				new NpgsqlCommand(
					string.Format("UPDATE {0} SET Password = @Password, last_password_changed_date = @last_password_changed_date  WHERE user_name = @user_name AND application_name = @application_name", tableName), conn);

			cmd.Parameters.Add("@Password", NpgsqlDbType.Text, 255).Value = EncodePassword(newPwd);
			cmd.Parameters.Add("@last_password_changed_date", NpgsqlDbType.Timestamp).Value = DateTime.Now;
			cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
			cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;


			int rowsAffected = 0;

			try
			{
				conn.Open();

				rowsAffected = cmd.ExecuteNonQuery();
			}
			catch (NpgsqlException e)
			{
				if (WriteExceptionsToEventLog)
				{
					WriteToEventLog(e, "ChangePassword");

                    // use fully qualified name so as not to conflict with System.Data.ProviderException
                    // in System.Data.Entity assembly
					throw new System.Configuration.Provider.ProviderException(exceptionMessage);
				}
				else
				{
					throw;// e;
				}
			}
			finally
			{
				cmd.Dispose();
				conn.Close();
			}

			return (rowsAffected > 0);		}
开发者ID:seeseekey,项目名称:CSCL,代码行数:74,代码来源:NpgsqlMembershipProvider.cs


示例18: UpdateFailureCount

		//
		// UpdateFailureCount
		//   A helper method that performs the checks and updates associated with
		// password failure tracking.
		//

		private void UpdateFailureCount(string username, string failureType)
		{
			NpgsqlConnection conn = new NpgsqlConnection(connectionString);
			NpgsqlCommand cmd =
				new NpgsqlCommand(
					string.Format("SELECT failed_password_attempt_count,   failed_password_attempt_window_start,   failed_password_answer_attempt_count,   failed_password_answer_attempt_window_start   FROM {0}   WHERE user_name = @user_name AND application_name = @application_name", tableName), conn);

			cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
			cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;

			NpgsqlDataReader reader = null;
			DateTime windowStart = new DateTime();
			int failureCount = 0;

			try
			{
				conn.Open();

				using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
				{
					if (reader.HasRows)
					{
						reader.Read();

						if (failureType == "password")
						{
							failureCount = reader.GetInt32(0);
							windowStart = reader.GetDateTime(1);
						}

						if (failureType == "passwordAnswer")
						{
							failureCount = reader.GetInt32(2);
							windowStart = reader.GetDateTime(3);
						}
					}
					reader.Close();
				}

				DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);

				if (failureCount == 0 || DateTime.Now > windowEnd)
				{
					// First password failure or outside of PasswordAttemptWindow. 
					// Start a new password failure count from 1 and a new window starting now.

					if (failureType == "password")
					{
						cmd.CommandText = string.Format("UPDATE {0}   SET failed_password_attempt_count = @Count,       failed_password_attempt_window_start = @WindowStart   WHERE user_name = @user_name AND application_name = @application_name", tableName);
					}

					if (failureType == "passwordAnswer")
					{
						cmd.CommandText = string.Format("UPDATE {0}   SET failed_password_answer_attempt_count = @Count,       failed_password_answer_attempt_window_start = @WindowStart   WHERE user_name = @user_name AND application_name = @application_name", tableName);
					}

					cmd.Parameters.Clear();

					cmd.Parameters.Add("@Count", NpgsqlDbType.Integer).Value = 1;
					cmd.Parameters.Add("@WindowStart", NpgsqlDbType.Timestamp).Value = DateTime.Now;
					cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
					cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;

					if (cmd.ExecuteNonQuery() < 0)
                    {
                        // use fully qualified name so as not to conflict with System.Data.ProviderException
                        // in System.Data.Entity assembly
						throw new System.Configuration.Provider.ProviderException("Unable to update failure count and window start.");
					}
				}
				else
				{
					if (failureCount++ >= MaxInvalidPasswordAttempts)
					{
						// Password attempts have exceeded the failure threshold. Lock out
						// the user.

						cmd.CommandText = string.Format("UPDATE {0}   SET is_locked_out = @is_locked_out, last_locked_out_date = @last_locked_out_date   WHERE user_name = @user_name AND application_name = @application_name", tableName);

						cmd.Parameters.Clear();

						cmd.Parameters.Add("@is_locked_out", NpgsqlDbType.Boolean).Value = true;
						cmd.Parameters.Add("@last_locked_out_date", NpgsqlDbType.Timestamp).Value = DateTime.Now;
						cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
						cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;

						if (cmd.ExecuteNonQuery() < 0)
                        {
                            // use fully qualified name so as not to conflict with System.Data.ProviderException
                            // in System.Data.Entity assembly
							throw new System.Configuration.Provider.ProviderException("Unable to lock out user.");
						}
					}
					else
//.........这里部分代码省略.........
开发者ID:seeseekey,项目名称:CSCL,代码行数:101,代码来源:NpgsqlMembershipProvider.cs


示例19: ValidateUser

		//
		// MembershipProvider.ValidateUser
		//

		public override bool ValidateUser(string username, string password)
		{
			bool isValid = false;

			NpgsqlConnection conn = new NpgsqlConnection(connectionString);
			NpgsqlCommand cmd =
				new NpgsqlCommand(
					"SELECT Password, is_approved FROM " + tableName + "" +
					" WHERE user_name = @user_name AND application_name = @application_name AND is_locked_out = false", conn);

			cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
			cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;

			NpgsqlDataReader reader = null;
			bool isApproved = false;
			string pwd = "";

			try
			{
				conn.Open();

				using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
				{
					if (reader.HasRows)
					{
						reader.Read();
						pwd = reader.GetString(0);
						isApproved = reader.GetBoolean(1);
					}
					else
					{
						return false;
					}
					reader.Close();
				}

				if (CheckPassword(password, pwd))
				{
					if (isApproved)
					{
						isValid = true;

						NpgsqlCommand updateCmd =
							new NpgsqlCommand(
								"UPDATE " + tableName + " SET last_login_date = @last_login_date, last_activity_date = @last_activity_date" +
								" WHERE user_name = @user_name AND application_name = @application_name", conn);

						updateCmd.Parameters.Add("@last_login_date", NpgsqlDbType.Timestamp).Value = DateTime.Now;
						updateCmd.Parameters.Add("@last_activity_date", NpgsqlDbType.Timestamp).Value = DateTime.Now;
							// fixed by Alex .ToString("yyyy/MM/dd HH:mm:ss");
						updateCmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
						updateCmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;

						updateCmd.ExecuteBlind();
					}
				}
				else
				{
					cmd.Dispose();
					conn.Close();

					UpdateFailureCount(username, "password");
				}
			}
			catch (NpgsqlException e)
			{
				if (WriteExceptionsToEventLog)
				{
					WriteToEventLog(e, "ValidateUser");

                    // use fully qualified name so as not to conflict with System.Data.ProviderException
                    // in System.Data.Entity assembly
					throw new System.Configuration.Provider.ProviderException(exceptionMessage);
				}
				else
				{
					throw e;
				}
			}
			finally
			{
				if (reader != null)
				{
					reader.Close();
				}
				cmd.Dispose();
				conn.Close();
			}

			return isValid;
		}
开发者ID:seeseekey,项目名称:CSCL,代码行数:95,代码来源:NpgsqlMembershipProvider.cs


示例20: GetPassword

		//
		// MembershipProvider.GetPassword
		//

		public override string GetPassword(string username, string answer)
		{
			if (!EnablePasswordRetrieval)
            {
                // use fully qualified name so as not to conflict with System.Data.ProviderException
                // in System.Data.Entity assembly
				throw new System.Configuration.Provider.ProviderException("Password Retrieval Not Enabled.");
			}

			if (PasswordFormat == MembershipPasswordFormat.Hashed)
            {
                // use fully qualified name so as not to conflict with System.Data.ProviderException
                // in System.Data.Entity assembly
				throw new System.Configuration.Provider.ProviderException("Cannot retrieve Hashed passwords.");
			}

			NpgsqlConnection conn = new NpgsqlConnection(connectionString);
			NpgsqlCommand cmd =
				new NpgsqlCommand(
					string.Format("SELECT Password, password_answer, is_locked_out FROM {0} WHERE user_name = @user_name AND application_name = @application_name", tableName), conn);

			cmd.Parameters.Add("@user_name", NpgsqlDbType.Text, 255).Value = username;
			cmd.Parameters.Add("@application_name", NpgsqlDbType.Text, 255).Value = pApplicationName;

			string password = "";
			string passwordAnswer = "";
			NpgsqlDataReader reader = null;

			try
			{
				conn.Open();

				using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
				{
					if (reader.HasRows)
					{
						reader.Read();

						if (reader.GetBoolean(2))
						{
							throw new MembershipPasswordException("The supplied user is locked out.");
						}

						password = reader.GetString(0);
						passwordAnswer = reader.GetString(1);
					}
					else
					{
						throw new MembershipPasswordException("The supplied user name is not found.");
					}
					reader.Close();
				}
			}
			catch (NpgsqlException e)
			{
				if (WriteExceptionsToEventLog)
				{
                    WriteToEventLog(e, "GetPassword");
                    // use fully qualified name so as not to conflict with System.Data.ProviderException
                    // in System.Data.Entity assembly
					throw new System.Configuration.Provider.ProviderException(exceptionMessage);
				}
				else
				{
					throw e;
				}
			}
			finally
			{
				if (reader != null)
				{
					reader.Close();
				}
				cmd.Dispose();
				conn.Close();
			}


			if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
			{
				UpdateFailureCount(username, "passwordAnswer");

				throw new MembershipPasswordException("Incorrect password answer.");
			}


			if (PasswordFormat == MembershipPasswordFormat.Encrypted)
			{
				password = UnEncodePassword(password);
			}

			return password;
		}
开发者ID:seeseekey,项目名称:CSCL,代码行数:97,代码来源:NpgsqlMembershipProvider.cs



注:本文中的NpgsqlCommand类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# NpgsqlConnection类代码示例发布时间:2022-05-24
下一篇:
C# NpcScript类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap