I'm a little confuse with regards to database and how it's used.

I want to store my window application's data into microsoft access.
Example.
I have 3TB
TBCurrentpassword
TBNewpassword
TBConfirmpassword

how do i write a program:
1. Store data in Microsoft access.
2. Compare the data stored etc.

and what connection shld i use cause I'm not even sure about to do they connect=/ can someone give some advice. thank youu

serkan sendur commented: Bad thread name -2
kvprajapati commented: N.A -3

Recommended Answers

All 10 Replies

1. Store data in Microsoft access.
>> You can use System.Data.OleDb namespace. Check this example: http://www.c-sharpcorner.com/UploadFile/mimrantaj/Database102102008130743PM/Database1.aspx

2. Compare the data stored etc.
>> Did you mean validation? if so may be a select query like - SELECT blah from tblTable WHERE password='yourpassword' will help

i think so? An example would be.

You have to key in ur current password inorder to change into newpassword.
so when u key current password it will take the data from window application and compare with the stored data in M.access and after confirm the password data would be stored in the M.access.
so i was wondering how to get to it=/

To perform database actions, you must have to learn ADO.NET class library.

commented: Correct +9

Not sure if you are looking for something like this.

Query: UPDATE yourtable SET TBNewpassword = textbox2.Text WHERE TBCurrentpassword = textbox1.Text

Watch some data access video tutorials on windowsclient.net
when opened with windows media play, hit shift+ctrl+N and it will take half as it would in normal speed.

I posted a code snippet of a login screen:
http://www.daniweb.com/code/snippet217409.html

That code will address retrieving and comparing passwords.

thanks. i'm trying to figure out though cause I've nv seen most of it before and what i know is actually really really really basic.

solved?

they have solve the question but i just don't understand how it is being used etc..

Try this application (attached as zip). You should be able to run the project with making any changes.

I plumbed a data access layer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace daniweb.users
{
  public static class DataAccess
  {
    const string filePath = @"..\..\mydb.mdb";
    internal static readonly string ConnectionString = BuildAccessConnectionString(filePath, string.Empty, string.Empty, string.Empty);


    internal static string BuildAccessConnectionString(string Filename, string Username, string Password, string DatabasePassword)
    {
      return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';User Id={1};Password={2};Jet OLEDB:Database Password={3};",
                                   Filename.Replace("'", "''"),
                                   Username,
                                   Password,
                                   DatabasePassword);
    }

    private static OleDbConnection GetConnection()
    {
      return new OleDbConnection(ConnectionString);
    }

    private static OleDbCommand GetCommand(OleDbConnection conn)
    {
      OleDbCommand cmd = new OleDbCommand();
      cmd.Connection = conn;
      return cmd;
    }


    public static int Execute(string query)
    {
      return Execute(query, default(OleDbParameter[]));
    }
    public static int Execute(string query, OleDbParameter parm)
    {
      return Execute(query, new OleDbParameter[] { parm });
    }
    public static int Execute(string query, List<OleDbParameter> parms)
    {
      OleDbParameter[] pList = null;
      if (parms != null)
        pList = parms.ToArray();
      return Execute(query, pList);
    }
    public static int Execute(string query, OleDbParameter[] parms)
    {
      using (OleDbConnection conn = GetConnection())
      {
        conn.Open();
        using (OleDbCommand cmd = GetCommand(conn))
        {
          cmd.CommandText = query;
          if (parms != null)
            cmd.Parameters.AddRange(parms);
          return cmd.ExecuteNonQuery();
        }
      }
    }


    public static DataTable QueryDataTable(string query)
    {
      return QueryDataTable(query, default(OleDbParameter[]));
    }
    public static DataTable QueryDataTable(string query, OleDbParameter parm)
    {
      return QueryDataTable(query, new OleDbParameter[] { parm });
    }
    public static DataTable QueryDataTable(string query, List<OleDbParameter> parms)
    {
      OleDbParameter[] pList = null;
      if (parms != null)
        pList = parms.ToArray();
      return QueryDataTable(query, pList);
    }
    public static DataTable QueryDataTable(string query, OleDbParameter[] parms)
    {
      DataTable result;

      using (OleDbConnection conn = GetConnection())
      {
        conn.Open();
        using (OleDbCommand cmd = GetCommand(conn))
        {
          cmd.CommandText = query;
          if (parms != null)
            cmd.Parameters.AddRange(parms);
          using (OleDbDataReader dr = cmd.ExecuteReader())
          {
            result = new DataTable();
            result.Load(dr);
            return result;
          }
        }
      }
    }

  }
}

Then your crypto unit:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace daniweb.users
{
  public static class Crypto
  {
    /// <summary>
    /// Key for the crypto provider
    /// </summary>
    private static readonly byte[] _key = { 0xA1, 0xF1, 0xA6, 0xBB, 0xA2, 0x5A, 0x37, 0x6F, 0x81, 0x2E, 0x17, 0x41, 0x72, 0x2C, 0x43, 0x27 };
    /// <summary>
    /// Initialization vector for the crypto provider
    /// </summary>
    private static readonly byte[] _initVector = { 0xE1, 0xF1, 0xA6, 0xBB, 0xA9, 0x5B, 0x31, 0x2F, 0x81, 0x2E, 0x17, 0x4C, 0xA2, 0x81, 0x53, 0x61 };

#if (DEBUG) //Only compile this method for local debugging.
    /// <summary>
    /// Decrypt a string
    /// </summary>
    /// <param name="Value"></param>
    /// <returns></returns>
    private static string Decrypt(string Value)
    {
      SymmetricAlgorithm mCSP;
      ICryptoTransform ct = null;
      MemoryStream ms = null;
      CryptoStream cs = null;
      byte[] byt;
      byte[] _result;

      mCSP = new RijndaelManaged();

      try
      {
        mCSP.Key = _key;
        mCSP.IV = _initVector;
        ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);


        byt = Convert.FromBase64String(Value);

        ms = new MemoryStream();
        cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
        cs.Write(byt, 0, byt.Length);
        cs.FlushFinalBlock();

        cs.Close();
        _result = ms.ToArray();
      }
      catch
      {
        _result = new byte[0];
      }
      finally
      {
        if (ct != null)
          ct.Dispose();
        if (ms != null)
          ms.Dispose();
        if (cs != null)
          cs.Dispose();
      }

      return ASCIIEncoding.UTF8.GetString(_result);
    }
#endif


    /// <summary>
    /// Encrypt a string
    /// </summary>
    /// <param name="Password"></param>
    /// <returns></returns>
    internal static string Encrypt(string Password)
    {
      if (string.IsNullOrEmpty(Password))
        return string.Empty;

      byte[] Value = Encoding.UTF8.GetBytes(Password);
      SymmetricAlgorithm mCSP = new RijndaelManaged();
      mCSP.Key = _key;
      mCSP.IV = _initVector;
      using (ICryptoTransform ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV))
      {
        using (MemoryStream ms = new MemoryStream())
        {
          using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
          {
            cs.Write(Value, 0, Value.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
          }
        }
      }
    }

  }
}

Then a "User Entity". This should implement all sort of interfaces if you decide to use entities:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace daniweb.users
{
  public class User
  {
    private int _userId;
    private string _userName;
    private string _passwordHash;
    private bool _admin;
    private bool _disabled;

    public int UserId
    {
      get { return _userId; }
    }
    public string UserName 
    { 
      get { return _userName; }
      set { _userName = value; }
    }
    public bool Admin 
    { 
      get { return _admin; }
      set { _admin = value; }
    }
    public bool Disabled
    {
      get { return _disabled; }
      set { _disabled = value; }
    }    

    //ctor
    public User()
    {
      _userId = default(int);
      _userName = string.Empty;
      _passwordHash = string.Empty;
      _admin = default(bool);
      _disabled = default(bool);
    }
    public User(string UserName, bool Admin)
      : this()
    {
    }

    public void Save()
    {
      string query;
      if (_userId == 0) //new record
        query = "Insert Into UserTable ([UserName], [Password], [Admin], [Disabled]) Values (?,?,?,?)";
      else
        query = "Update UserTable Set [UserName] = ?, [Password] = ?, [Admin] = ?, [Disabled] = ? Where [ID] = ?";

      List<OleDbParameter> lst = new List<OleDbParameter>();
      lst.Add(new OleDbParameter("UserName", this.UserName));
      lst.Add(new OleDbParameter("Password", this._passwordHash));
      lst.Add(new OleDbParameter("Admin", this.Admin));
      lst.Add(new OleDbParameter("Disabled", this.Disabled));
      if (_userId > 0)
        lst.Add(new OleDbParameter("ID", this.UserId));

      int rowCnt = DataAccess.Execute(query, lst);

      if (rowCnt == 0)
        throw new InvalidOperationException("Failed to locate user for updating");
      else
      {
        //Fetch values from the database after saving, since the DB could change them
        using (DataTable dt = LookupUserRecord(UserName))
        {
          if (dt.Rows.Count == 0)
            throw new InvalidOperationException("Unable to locate user record!");
          Deserialize(dt.Rows[0]);
        }
      }
    }

    public void SetPassword(string Password)
    {
      _passwordHash = Crypto.Encrypt(Password);
    }

    /// <summary>
    /// Validates the password is correct for the user
    /// </summary>
    /// <param name="Password">Password to validate</param>
    public bool PasswordMatches(string Password)
    {
      return (string.Compare(_passwordHash, Crypto.Encrypt(Password), false) == 0);
    }

    internal static User LookupUser(string UserName)
    {
      User result;

      using (DataTable dt = LookupUserRecord(UserName))
      {
        if (dt.Rows.Count == 0)
          return null;
        else
          result = new User();
        
        DataRow row = dt.Rows[0];
        result.Deserialize(row);
        return result;
      }
    }

    private static DataTable LookupUserRecord(string UserName)
    {
      const string query = "Select * From UserTable Where UserName = ?";
      OleDbParameter dp = new OleDbParameter("UserName", UserName);
      return DataAccess.QueryDataTable(query, dp);
    }

    private void Deserialize(DataRow row)
    {
      this._userId = Convert.ToInt32(row["ID"]); //cant be null
      this._userName = Convert.ToString(row["UserName"]); //nulls convert to string
      this._passwordHash = Convert.ToString(row["Password"]); //nulls convert to string
      this._passwordHash = Convert.ToString(row["Password"]); //nulls convert to string
      this._admin = (row["Admin"] is DBNull ? false : Convert.ToBoolean(row["Admin"]));
      this._disabled = (row["Disabled"] is DBNull ? false : Convert.ToBoolean(row["Disabled"]));
    }

    /// <summary>
    /// Deletes a user
    /// </summary>
    /// <param name="UserId"></param>
    /// <returns>True if the user was deleted</returns>
    public static bool Delete(int UserId)
    {
      const string query = "Delete From UserTable Where UserId = ?";
      OleDbParameter dp = new OleDbParameter("ID", UserId);
      return (DataAccess.Execute(query, dp) == 1);
    }

    /// <summary>
    /// Deletes a user
    /// </summary>
    /// <param name="UserId"></param>
    /// <returns>True if the user was deleted</returns>
    public static bool Delete(string UserName)
    {
      const string query = "Delete From UserTable Where UserName = ?";
      OleDbParameter dp = new OleDbParameter("UserName", UserName);
      return (DataAccess.Execute(query, dp) == 1);
    }

  }
}

You have a login screen, user search screen, user edit screen and a set password screen.

commented: Excellent help +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.