Windows Forms: Create Login Window with User Authentication in C#

This article introduces you to How to Create login Window with User Authentication in C# Windows Forms Application.

I will present the basic idea for role based authentication in c# desktop application programming using DevExpress Control, Entity Framework. The source code in this article is incomplete, to get the full source code you need to purchase.

C# Login form with User Authentication with SQL Server

c# login window with user authentication

Information

- SQL Server

- DevExpress Control v20

- Entity Framework

- Generic Repository, UnitOfWork, Singleton pattern

- Price: 10$

Feature:

- Manage and add new users

- Manage and add new functions

- Manage and add new roles

- Encrypt connection string, password

- Login system based on role

- Easily configure your database connection

- Easily build your dynamic application

I can give you a Devexpress Patch for Visual Studio 2017 when purchasing the source code. It will help you to easily learn and develop your application.

Creating a new Windows Forms Application project, then create an Entities folder

Next, Open your Microsoft SQL Server Management Studio, then run the sql script below to create your database

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FunctionRoles](
	[FunctionId] [int] NOT NULL,
	[RoleId] [int] NOT NULL,
 CONSTRAINT [PK_FunctionRoles] PRIMARY KEY CLUSTERED 
(
	[FunctionId] ASC,
	[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Functions]    Script Date: 9/3/2020 9:19:22 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Functions](
	[FunctionId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[ParentId] [int] NULL,
	[BeginGroup] [bit] NULL,
	[FormName] [nvarchar](255) NULL,
	[FormStyle] [nvarchar](255) NULL,
	[FunctionName] [nvarchar](255) NULL,
	[Image] [varbinary](max) NULL,
	[Menu] [bit] NULL,
	[MethodName] [nvarchar](255) NULL,
	[Order] [int] NULL,
	[Parameter] [nvarchar](255) NULL,
	[RibbonStyle] [bit] NULL,
	[Status] [bit] NULL,
	[Type] [nvarchar](255) NULL,
 CONSTRAINT [PK_Functions] PRIMARY KEY CLUSTERED 
(
	[FunctionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Roles]    Script Date: 9/3/2020 9:19:22 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Roles](
	[RoleId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[RoleName] [nvarchar](255) NULL,
 CONSTRAINT [PK_Roles] PRIMARY KEY CLUSTERED 
(
	[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[UserRoles]    Script Date: 9/3/2020 9:19:22 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserRoles](
	[UserId] [int] NOT NULL,
	[RoleId] [int] NOT NULL,
 CONSTRAINT [PK_UserRoles] PRIMARY KEY CLUSTERED 
(
	[UserId] ASC,
	[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Users]    Script Date: 9/3/2020 9:19:22 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
	[UserId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[FullName] [nvarchar](255) NULL,
	[UserName] [nvarchar](50) NOT NULL,
	[Password] [nvarchar](255) NULL,
	[Status] [bit] NULL,
	[DateCreate] [datetime] NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
	[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_Users]    Script Date: 9/3/2020 9:19:22 AM ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_Users] ON [dbo].[Users]
(
	[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE [dbo].[FunctionRoles]  WITH CHECK ADD  CONSTRAINT [FK_FunctionRoles_Functions] FOREIGN KEY([FunctionId])
REFERENCES [dbo].[Functions] ([FunctionId])
GO
ALTER TABLE [dbo].[FunctionRoles] CHECK CONSTRAINT [FK_FunctionRoles_Functions]
GO
ALTER TABLE [dbo].[FunctionRoles]  WITH CHECK ADD  CONSTRAINT [FK_FunctionRoles_Roles] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Roles] ([RoleId])
GO
ALTER TABLE [dbo].[FunctionRoles] CHECK CONSTRAINT [FK_FunctionRoles_Roles]
GO
ALTER TABLE [dbo].[UserRoles]  WITH CHECK ADD  CONSTRAINT [FK_UserRoles_Roles] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Roles] ([RoleId])
GO
ALTER TABLE [dbo].[UserRoles] CHECK CONSTRAINT [FK_UserRoles_Roles]
GO
ALTER TABLE [dbo].[UserRoles]  WITH CHECK ADD  CONSTRAINT [FK_UserRoles_Users] FOREIGN KEY([UserId])
REFERENCES [dbo].[Users] ([UserId])
GO
ALTER TABLE [dbo].[UserRoles] CHECK CONSTRAINT [FK_UserRoles_Users]

The Users table will contain account credentials.

The Roles table will contain the permissions group name.

The Functions table will contain functional information.

Right-Clicking on your Entities folder, then select Add=>New Items...=>ADO.NET Entity Data Model=> Entity Framework code first from database to create your entity class, then enter your model name is ApplicationDbContext.

I'm using the Generic RepositoryUnitOfWork pattern with Entity Framework to create the DataAccess layer, which helps me handle the CRUD.

The Repository Pattern is the middle layer between the Business Logic layer and the Data Access layer, making data access more strict and secure.

The Unit of Work is the concept related to the effective implementation of the Repository Pattern. It allows us to execute a single database transaction that involves multiple operations of insert, update, delete.

Creating an IRepository interface allows you to access your sql data.

public interface IRepository<T> where T : class
{
    T GetById(object id);
    IList<T> GetList();
    Task<IList<T>> GetListAsync();
    T Find(Expression<Func<T, bool>> expression);
    Task<T> FindAsync(Expression<Func<T, bool>> expression);
    IList<T> GetList(Expression<Func<T, bool>> expression);
    Task<IList<T>> GetListAsync(Expression<Func<T, bool>> expression);
    void Insert(T entity);
    void Update(T entity);
    void Delete(T entity);
    Task SaveChangesAsync();
}

Creating a BaseRepository implement IRepository as shown below.

public abstract class BaseRepository<T> : IRepository<T> where T : class
{
    private readonly ApplicationDbContext _dataContext;

    public BaseRepository(ApplicationDbContext dataContext)
    {
        _dataContext = dataContext;
    }

    public void Delete(T entity)
    {
        _dataContext.Set<T>().Remove(entity);
    }

    public T GetById(object id)
    {
        return _dataContext.Set<T>().Find(id);
    }

    public void Insert(T entity)
    {
        _dataContext.Set<T>().Add(entity);
    }

    public IList<T> GetList()
    {
        return _dataContext.Set<T>().ToList();
    }

    public async Task<IList<T>> GetListAsync()
    {
        return await _dataContext.Set<T>().ToListAsync();
    }

    public IList<T> GetList(Expression<Func<T, bool>> expression)
    {
        return _dataContext.Set<T>().Where(expression).ToList();
    }

    public T Find(Expression<Func<T, bool>> expression)
    {
        return _dataContext.Set<T>().Where(expression).SingleOrDefault();
    }

    public async Task<T> FindAsync(Expression<Func<T, bool>> expression)
    {
        return await _dataContext.Set<T>().Where(expression).SingleOrDefaultAsync();
    }

    public async Task<IList<T>> GetListAsync(Expression<Func<T, bool>> expression)
    {
        return await _dataContext.Set<T>().Where(expression).ToListAsync();
    }

    public void Update(T entity)
    {
        _dataContext.Entry<T>(entity).State = EntityState.Modified;
    }

    public Task SaveChangesAsync()
    {
        return _dataContext.SaveChangesAsync();
    }
}

Creating an IUserRepository allows you to access data from user table.

public interface IUserRepository : IRepository<User>
{
}

Creating a UserRepository implement BaseRepository<User>, IUserRepository

public class UserRepository : BaseRepository<User>, IUserRepository
{
    public UserRepository(ApplicationDbContext dataContext)
        : base(dataContext)
    {
    }
}

Finally, Create an IUnitOfWork allows you to handle data with transaction.

public class UnitOfWork : IUnitOfWork
{
    private bool _disposed;
    private readonly ApplicationDbContext _dataContext;
    private IUserRepository _userRepository;

    public UnitOfWork()
    {
        _dataContext = new ApplicationDbContext();
    }

    public IDatabaseTransaction BeginTransaction()
    {
        return new DatabaseTransaction(_dataContext);
    }

    public IUserRepository User => _userRepository ?? (_userRepository = new UserRepository(_dataContext));

    public void SaveChanges()
    {
        _dataContext.SaveChanges();
    }

    protected void Dispose(bool disposing)
    {
        if (!this._disposed)
        {
            if (disposing)
                _dataContext.Dispose();
        }
        this._disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

Creating a RibbonForm as a Main Form.

public partial class frmMain : RibbonForm
{
    private static frmMain _instance = null;

    public static frmMain Instance
    {
        get
        {
            if (_instance == null)
                _instance = new frmMain();
            return _instance;
        }
        set { _instance = value; }
    }

    public frmMain()
    {
        InitializeComponent();
    }

    private void frmMain_Load(object sender, EventArgs e)
    {
        frmLoginInformation frm = new frmLoginInformation() { MdiParent = this };
        frm.Show();
        //Init Plugin
        try
        {
            AppPlugin.InitPlugin();
            //Init Component
            _instance = this;
        }
        catch (Exception ex)
        {
            XtraMessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ItemLogOut_Click(object sender, EventArgs e)
    {
        Cursor.Current = Cursors.WaitCursor;
        ClearAllItems();
        this.Hide();
        frmLogin.Instance.Show();
        //Init Form Login
        Logout.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        Cursor.Current = Cursors.Default;
    }

    private void ClearAllItems()
    {
        //Remove Forms
        for (int k = tabbedView.Documents.Count - 1; k >= 0; k--)
            (tabbedView.Documents[k].Control as Form).Close();

        //Remove all item in ribbon control.
        for (int i = ribbon.Pages.Count - 1; i >= 0; i--)
        {
            for (int j = ribbon.Pages[i].Groups.Count - 1; j >= 0; j--)
                ribbon.Pages[i].Groups[j].ItemLinks.Clear();//Clear item
                                                            //Clear group
            ribbon.Pages[i].Groups.Clear();
        }
        //Clear pages
        ribbon.Pages.Clear();
    }

    private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
    {
        ClearAllItems();
        Application.Exit();
    }
}

Login form in c# windows application with database

Creating a login form allows you to login with user authentication as shown below.

We will create a default user for c# login system, then store in the app.config file with encrypt. Everytime you login to the system, you need to check user is system default or application user.

After successful login you can create an admin account and user login in c#.

How to validate username and password in c#

The default user helps you create your application with the feature that you define.

public partial class frmLogin : DevExpress.XtraEditors.XtraForm
{
    private static frmLogin _instance = null;
    private readonly IUnitOfWork _unitOfWork;

    public frmLogin()
    {
        InitializeComponent();
    }

    public static frmLogin Instance => _instance ?? (_instance = new frmLogin());

    //how to validate login form in c# windows application
    private void Login()
    {
        if (string.IsNullOrEmpty(txtUserName.Text))
        {
            XtraMessageBox.Show("Please enter your user name.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtUserName.Focus();
            return;
        }
        try
        {
            _unitOfWork = new UnitOfWork();
            User user = _unitOfWork.User.Find(u => u.UserName == txtUserName.Text);
            if (user != null)
            {
                if (user.Status == true)
                {
                    XtraMessageBox.Show("Your account is currently locked.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtUserName.Focus();
                    return;
                }
                if (user.Password != AppHelper.Encrypt(txtPassword.Text))
                {
                    XtraMessageBox.Show("Your Username and password do not match.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPassword.Focus();
                    return;
                }
                frmMain.Instance = null;
                UserInfo.FullName = user.FullName;
                UserInfo.UserName = txtUserName.Text;
                UserInfo.UserId = user.UserId;
                UserInfo.LoginType = UserType.None;
                AppSystem appSystem = new AppSystem(_unitOfWork);
                appSystem.InitControl();
                Hide();
                frmMain.Instance.ShowDialog();
            }
            else
            {
                if (UserInfo.IsUserSystem(txtUserName.Text))
                {
                    if (UserInfo.IsUserSystemLogin(txtUserName.Text, AppHelper.Encrypt(txtPassword.Text)))
                    {
                        frmMain.Instance = null;
                        UserInfo.FullName = "System";
                        UserInfo.UserName = txtUserName.Text;
                        UserInfo.LoginType = UserType.System;
                        AppSystem appSystem = new AppSystem(_unitOfWork);
                        appSystem.InitSystem();
                        Hide();
                        frmMain.Instance.ShowDialog();
                    }
                    else
                    {
                        XtraMessageBox.Show("Your Username and password do not match.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtPassword.Focus();
                    }
                }
                else
                {
                    XtraMessageBox.Show("Your username cannot be found in the system.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtUserName.Focus();
                }
            }
        }
        catch (Exception ex)
        {
            XtraMessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

Creating a login information form allows you to display user credentials as show below.

c# login info

You can initialize your data at the Form_Load event.

private void frmLoginInformation_Load(object sender, EventArgs e)
{
    lblFullName.Text = UserInfo.FullName;
    lblUser.Text = UserInfo.UserName;
    lblDateLogin.Text = DateTime.Now.ToString();
    frmMain.Instance.ItemLogOut.Caption = UserInfo.UserName;
    if (UserInfo.LoginType == UserType.None)
        frmMain.Instance.Logout.Width = 40 + UserInfo.UserName.Length * 3;
    else
        frmMain.Instance.Logout.Width = 80;
    frmMain.Instance.Logout.Hint = UserInfo.UserName;
    frmMain.Instance.Logout.Visibility = BarItemVisibility.Always;
}

Creating a Role form allows you to create new role.

c# roles

Multi user login form in c#

Do the same way for User, Function form.

Creating a user role form allows you to set roles for specific users.

namespace FoxApp.UI.Forms.Systems
{
    public partial class frmUserRoles : DevExpress.XtraEditors.XtraForm
    {
        private readonly IUnitOfWork _unitOfWork;
        private User _user;
        public frmUserRoles(User user, IUnitOfWork unitOfWork)
        {
            InitializeComponent();
            _user = user;
            _unitOfWork = unitOfWork;
        }

        private async void frmUserRoles_Load(object sender, EventArgs e)
        {
            gridControl.DataSource = await _unitOfWork.Role.GetListAsync();
            for (int i = 0; i < gridView.DataRowCount; i++)
            {
                Role role = gridView.GetRow(i) as Role;
                if (role != null)
                {
                    if (_user.Roles.Where(r => r.RoleId == role.RoleId).Count() > 0)
                        gridView.SelectRow(i);
                }
            }
        }

        private async void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                WaitFormHelper.ShowWaitForm(this);
                gridView.FocusedRowHandle = -1;
                for (int i = 0; i < gridView.DataRowCount; i++)
                {
                    if (gridView.IsRowSelected(i))
                    {
                        Role role = gridView.GetRow(i) as Role;
                        if (role != null)
                        {
                            if (!role.Users.Contains(_user))
                                role.Users.Add(_user);
                        }
                    }
                    else
                    {
                        Role role = gridView.GetRow(i) as Role;
                        if (role != null)
                        {
                            if (role.Users.Contains(_user))
                                role.Users.Remove(_user);
                        }
                    }
                }
                await _unitOfWork.Role.SaveChangesAsync();
                WaitFormHelper.SetWaitFormCaption(this, "Your data has been saved successfully.");
            }
            catch (Exception ex)
            {
                WaitFormHelper.CloseWaitForm(this);
                XtraMessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                WaitFormHelper.CloseWaitForm(this);
            }
            Cursor.Current = Cursors.Default;
        }
    }
}

Creating a change password form allows user change the password as shown below.

private void Save()
{
    if (txtNewPassword.Text != txtConfirm.Text)
    {
        XtraMessageBox.Show("Your new password and confirmation password are incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtConfirm.Focus();
        return;
    }
    if (UserInfo.LoginType == UserType.None)
    {
        User user = _unitOfWork.User.Find(u => u.UserName == UserInfo.UserName);
        if (user != null)
        {
            if (user.Password != AppHelper.Encrypt(txtOldPassword.Text))
            {
                XtraMessageBox.Show("Your Username and password do not match.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtOldPassword.Focus();
                return;
            }
            user.Password = AppHelper.Encrypt(txtNewPassword.Text);
            _unitOfWork.User.Update(user);
            _unitOfWork.User.SaveChanges();
            XtraMessageBox.Show("You have successfully changed your password.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Close();
        }
        else
        {
            XtraMessageBox.Show("Your old password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtOldPassword.Focus();
        }
    }
    else
    {
        if (UserInfo.IsUserSystemLogin(UserInfo.SysUser, AppHelper.Encrypt(txtOldPassword.Text)))
        {
            UserInfo.ChangeSystemPassword(AppHelper.Encrypt(txtNewPassword.Text));
            XtraMessageBox.Show("You have successfully changed your password.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Close();
        }
        else
        {
            XtraMessageBox.Show("Your old password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtOldPassword.Focus();
        }
    }
}

Authentication and authorization in windows application c#

Creating an authorization form allows you to set functions to role.

private async void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    Role role = cboRoleName.GetSelectedDataRow() as Role;
    if (role != null)
    {
        try
        {
            WaitFormHelper.ShowWaitForm(this);
            List<Function> functions = treeListFunction.DataSource as List<Function>;
            if (functions != null)
            {
                foreach (Function f in functions)
                {
                    TreeListNode node = treeListFunction.FindNodeByFieldValue("FunctionId", f.FunctionId);
                    if ((node.CheckState == CheckState.Checked) || (node.CheckState == CheckState.Indeterminate))
                    {
                        if (!f.Roles.Contains(role))
                            f.Roles.Add(role);
                    }
                    else
                    {
                        if (f.Roles.Contains(role))
                            f.Roles.Remove(role);
                    }
                }
                await _unitOfWork.Function.SaveChangesAsync();
            }
            WaitFormHelper.SetWaitFormCaption(this, "Your data has been saved successfully.");
        }
        catch (Exception ex)
        {
            WaitFormHelper.CloseWaitForm(this);
            XtraMessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            WaitFormHelper.CloseWaitForm(this);
        }
    }
    else
    {
        XtraMessageBox.Show("Please select your role name.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        cboRoleName.Focus();
    }
    Cursor.Current = Cursors.Default;
}

How to encrypt password in app.config file c#

Creating a configuration form allows you to connect to your sql server, then save your connection string to the app.config file with encrypt connection string data.

private void SaveConfig()
{
    SqlHelper helper;
    string ConnectionString = String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", cboServer.Text.Trim(), txtCatalog.Text, txtUserName.Text.Trim(), txtPassword.Text.Trim());
    if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Text))
    {
        ConnectionString = String.Format("Data Source={0};Initial Catalog={1}; Integrated Security=true;", cboServer.Text.Trim(), txtCatalog.Text);
        helper = new SqlHelper(ConnectionString);
        if (helper.CheckConnection())
        {
            XtraMessageBox.Show("You have successfully configured the connection to the Server.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            AppConnection.ConnectionString = AppHelper.Encrypt(ConnectionString);
            Close();
        }
        else
            XtraMessageBox.Show("An error occurred while connecting to the Server.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
    else
    {
        helper = new SqlHelper(ConnectionString);
        if (helper.CheckConnection())
        {
            XtraMessageBox.Show("You have successfully configured the connection to the Server.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            AppConnection.ConnectionString = AppHelper.Encrypt(ConnectionString);
            Close();
        }
        else
            XtraMessageBox.Show("An error occurred while connecting to the Server.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}

We will decrypt connection string c#, then check connection to the sql database server. If the connection is successful, we will update the encrypted connection string to the app.config file. Using encrypt and decypt allows you to hide connection string in app.config c#.

Finally, I'll create an AppSystem class that allows you initialize the application.

public void InitControl()
{
    int lIndex = 0, sIndex = 0;
    //Init ComponentModel
    ((System.ComponentModel.ISupportInitialize)(frmMain.Instance.ribbon)).BeginInit();
    //Init Image
    frmMain.Instance.ribbon.LargeImages = frmMain.Instance.LimageCollection;
    //Clear image collection
    frmMain.Instance.LimageCollection.Images.Clear();
    frmMain.Instance.SimageCollection.Images.Clear();
    //Init

    User user = _unitOfWork.User.GetApplyEagerLoading(u => u.UserId == UserInfo.UserId, r => r.Roles, r => r.Roles.Select(f => f.Functions)).SingleOrDefault();
    if (user != null)
    {
        //Init Function
        List<Function> list = new List<Function>();
        foreach (Role role in user.Roles)
        {
            var functions = role.Functions.Where(f => f.Status == true).ToList();
            foreach (Function f in functions)
            {
                if (!list.Contains(f))
                    list.Add(f);
            }
        }
        //
        var tabs = list.Where(f => f.Type == "Tab").OrderBy(f => f.Order).ToList();
        foreach (Function tab in tabs)
        {
            //Add Page
            RibbonPage rPage = new RibbonPage(tab.FunctionName) { Name = $"ribbonPage{tab.FunctionId}" };
            frmMain.Instance.ribbon.Pages.Add(rPage);

            var groups = list.Where(f => f.Type == "Group" && f.ParentId == tab.FunctionId).OrderBy(f => f.Order).ToList();
            foreach (Function group in groups)
            {
                //Add PageGroup
                RibbonPageGroup rGroup = new RibbonPageGroup(group.FunctionName) { Name = $"ribbonPageGroup{group.FunctionId}", AllowTextClipping = false };
                rPage.Groups.Add(rGroup);

                var items = list.Where(f => f.Type == "Item" && f.ParentId == group.FunctionId).OrderBy(f => f.Order).ToList();
                foreach (Function item in items)
                {
                    if (item.Menu == true)
                    {
                        //Add main menu
                        BarSubItem mainMenu = new BarSubItem(frmMain.Instance.ribbon.Manager, item.FunctionName) { Name = $"barButtonItem{item.FunctionId}", Tag = new AppModule() { Id = item.FunctionId, ModuleId = item.FormName, Caption = item.FunctionName, Type = item.FormStyle, MethodName = item.MethodName, Parameter = item.Parameter }, Hint = item.FunctionName, Description = item.FunctionName };
                        frmMain.Instance.ribbon.Items.Add(mainMenu);
                        if (item.Image != null)
                        {
                            if (item.RibbonStyle == true)
                                frmMain.Instance.SimageCollection.AddImage(DataConvert.ByteArrayToImage(item.Image));
                            else
                                frmMain.Instance.LimageCollection.AddImage(DataConvert.ByteArrayToImage(item.Image));
                            if (frmMain.Instance.SimageCollection.Images.Count > 0 && item.RibbonStyle == true)
                            {
                                mainMenu.ImageIndex = sIndex;
                                sIndex++;
                                mainMenu.RibbonStyle = RibbonItemStyles.SmallWithoutText | RibbonItemStyles.SmallWithText;
                            }
                            else
                            {
                                mainMenu.LargeImageIndex = lIndex;
                                lIndex++;
                                mainMenu.RibbonStyle = RibbonItemStyles.All;
                            }
                        }
                        //Add item into menu
                        var menus = list.Where(f => f.Type == "Item" && f.ParentId == item.FunctionId).OrderBy(f => f.Order).ToList();
                        foreach (Function menu in menus)
                        {
                            if (menu.Menu == true)
                            {
                                //Add sub menu
                                BarSubItem subMenu = new BarSubItem(frmMain.Instance.ribbon.Manager, menu.FunctionName) { Name = $"barButtonItem{menu.FunctionId}", Tag = new AppModule() { Id = menu.FunctionId, ModuleId = menu.FormName, Caption = menu.FunctionName, Type = menu.FormStyle, MethodName = menu.MethodName, Parameter = menu.Parameter }, Hint = menu.FunctionName, Description = menu.FunctionName };
                                frmMain.Instance.ribbon.Items.Add(subMenu);
                                var subMenus = list.Where(f => f.Type == "Item" && f.ParentId == menu.FunctionId).OrderBy(f => f.Order).ToList();
                                foreach (Function sMenu in subMenus)
                                {
                                    //Add image
                                    if (sMenu.Image != null)
                                        frmMain.Instance.SimageCollection.AddImage(DataConvert.ByteArrayToImage(sMenu.Image));
                                    BarButtonItem bItem = new BarButtonItem() { Caption = sMenu.FunctionName, Name = $"barButtonItem{sMenu.FunctionId}", Tag = new AppModule() { Id = sMenu.FunctionId, ModuleId = sMenu.FormName, Caption = sMenu.FunctionName, Type = sMenu.FormStyle, MethodName = sMenu.MethodName, Parameter = sMenu.Parameter }, Hint = sMenu.FunctionName, Description = sMenu.FunctionName };
                                    if (frmMain.Instance.SimageCollection.Images.Count > 0 && sMenu.Image != null)
                                    {
                                        bItem.ImageIndex = sIndex;
                                        sIndex++;
                                    }
                                    bItem.ItemClick += ItemClick;
                                    bItem.RibbonStyle = RibbonItemStyles.All;
                                    subMenu.LinksPersistInfo.Add(new LinkPersistInfo(bItem, sMenu.BeginGroup ?? false));
                                    frmMain.Instance.ribbon.Items.Add(bItem);
                                }
                                mainMenu.ItemLinks.Add(subMenu, menu.BeginGroup ?? false);
                            }
                            else
                            {
                                //Add image
                                if (menu.Image != null)
                                    frmMain.Instance.SimageCollection.AddImage(DataConvert.ByteArrayToImage(menu.Image));
                                BarButtonItem bItem = new BarButtonItem() { Caption = menu.FunctionName, Name = $"barButtonItem{menu.FunctionId}", Tag = new AppModule() { Id = menu.FunctionId, ModuleId = menu.FormName, Caption = menu.FunctionName, Type = menu.FormStyle, MethodName = menu.MethodName, Parameter = menu.Parameter }, Hint = menu.FunctionName, Description = menu.FunctionName };
                                bItem.ItemClick += ItemClick;
                                bItem.RibbonStyle = RibbonItemStyles.All;
                                if (frmMain.Instance.SimageCollection.Images.Count > 0 && menu.Image != null)
                                {
                                    bItem.ImageIndex = sIndex;
                                    sIndex++;
                                }
                                mainMenu.LinksPersistInfo.Add(new LinkPersistInfo(bItem, menu.BeginGroup ?? false));
                                frmMain.Instance.ribbon.Items.Add(bItem);
                            }
                        }
                        rGroup.ItemLinks.Add(mainMenu, true);
                    }
                    else
                    {
                        if (item.Image != null)
                        {
                            if (item.RibbonStyle == true)
                                frmMain.Instance.SimageCollection.AddImage(DataConvert.ByteArrayToImage(item.Image));
                            else
                                frmMain.Instance.LimageCollection.AddImage(DataConvert.ByteArrayToImage(item.Image));
                        }
                        BarButtonItem bItem = new BarButtonItem(frmMain.Instance.ribbon.Manager, item.FunctionName) { Name = $"barButtonItem{item.FunctionId}", Tag = new AppModule() { Id = item.FunctionId, ModuleId = item.FormName, Caption = item.FunctionName, Type = item.FormStyle, MethodName = item.MethodName, Parameter = item.Parameter }, Hint = item.FunctionName, Description = item.FunctionName };
                        bItem.ItemClick += ItemClick;
                        if (item.Image != null)
                        {
                            if (frmMain.Instance.SimageCollection.Images.Count > 0 && item.RibbonStyle == true)
                            {
                                bItem.ImageIndex = sIndex;
                                sIndex++;
                                bItem.RibbonStyle = RibbonItemStyles.SmallWithoutText | RibbonItemStyles.SmallWithText;
                                rGroup.ItemLinks.Add(bItem, item.BeginGroup ?? false);
                            }
                            else
                            {
                                bItem.LargeImageIndex = lIndex;
                                lIndex++;
                                bItem.RibbonStyle = RibbonItemStyles.All;
                                rGroup.ItemLinks.Add(bItem, item.BeginGroup ?? false);
                            }
                        }
                        else
                        {
                            bItem.RibbonStyle = RibbonItemStyles.All;
                            rGroup.ItemLinks.Add(bItem, item.BeginGroup ?? false);
                        }
                        frmMain.Instance.ribbon.Items.Add(bItem);
                    }
                }
            }
        }
    }

    //Add more 
    //
    ((System.ComponentModel.ISupportInitialize)(frmMain.Instance.ribbon)).EndInit();
}

We will read the functionality from the database, then initialize the application based on the specified roles.