Wednesday, June 11, 2014

C#.NET - Loading combo box in DataGridView

DataGridview:

Loading combo box in DataGridView.


Code:

private void LoadCapcityUtilizationReport()
{
try
{
int iClientId = 0;
            DataTable dtCapcity = clsCommon.oAdmin.dtGetCapcityUtilizationReport(dtpCapacityFromDate.Value, iClientId);
                if (dtCapcity != null)
                {

DataTable dtClient = clsCommon.oAdmin.GetActiveClientNames();
                    if (dtClient != null)
                    {
                        DataRow dr = dtClient.NewRow();
                        dr["ClientId"] = "0";
                        dr["ClientName"] = "--Select--";
                        dtClient.Rows.InsertAt(dr, 0);

                        dgvColClient.DataPropertyName = "ClientName";
                        dgvColClient.HeaderText = "Client";

                        dgvColClient.ValueMember = "ClientId";
                        dgvColClient.DisplayMember = "ClientName";
                        dgvColClient.DataSource = dtClient.DefaultView;
                        dgvColClient.DefaultCellStyle.NullValue = dtClient.Rows[0]["ClientName"].ToString();

                    }
                    dGvCapacity.DataSource = dtCapcity.DefaultView;
                    dGvCapacity.Refresh();

                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex.ToString());
            }

        }

Tuesday, June 10, 2014

MSSQL - Optional parameter for procedure

ALTER PROCEDURE [dbo].[MyProcName]
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS
begin
      select @Parameter1,@Parameter2,@Parameter3
end


C#.NET - Check whether file closed

if (!IsFileClosed(sLocalCurrentDocumentPath))
{
MessageBox.Show("Document opened already..!", clsCommon.sProjectName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}

public static bool IsFileClosed(string filename)
{
try
{
using (var inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
                    return true;
            }
}
catch (IOException)
{
return false;
      }
}

C#.NET - Accessing Share folder files with Network Authentication

Purpose :

Accessing Share folder files with Network Authentication

Step 1 : Create a class named SoddingNetworkAuth

Class Name : SoddingNetworkAuth.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class NetworkAuth : IDisposable
{
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
    [DllImport("kernel32", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hObject);
    private IntPtr userHandle = IntPtr.Zero;
    private WindowsImpersonationContext impersonationContext;
    public NetworkAuth(string user, string domain, string password)
    {
        try
        {
            if (!string.IsNullOrEmpty(user))
            {
                // Call LogonUser to get a token for the user 
                bool loggedOn = LogonUser(user, domain, password,
                 9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
                 3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
                out userHandle);
                if (!loggedOn)
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                // Begin impersonating the user 
                impersonationContext = WindowsIdentity.Impersonate(userHandle);
            }
        }
        catch (Exception ex)
        {
            ExceptionHandler.HandleException(ex.ToString());
        }
    }
    public void Dispose()
    {
        try
        {
            if (userHandle != IntPtr.Zero)
                CloseHandle(userHandle);
            if (impersonationContext != null)
                impersonationContext.Undo();
        }
        catch (Exception ex)
        {
            ExceptionHandler.HandleException(ex.ToString());
        }
    }
}


Step 2 : Place it anywhere inside the form and use this below code to copy file

#region "File copying with NetworkAuth "
using (new NetworkAuth("sShareFolder_Username","sShareFolderName", "sShareFolder_Password"))
{
      try
            {
                /* This is for checking voice file details */
                if (!File.Exists("GiveFilePath"))
                {
                    File.Copy("SourcePath", "DestinationPath", true);
                }
            }
            catch (Exception ex)
            {
            }
}   


C#.NET - Calculation user idle time using windows application

Controls Needed :

BackgroundWorker

Explanation :

This is to help you to calculate user idle time using windows application. When user idle for some it will start calculating their idle time , when user again user their system it will end idle time.


Code :

#region "Idle Time"

// This is to specify minutes to calculate idle time. Suppose if you want to calculate for above 10 minutes of user idle time .
private int iTimePeriod = 10;

bool bCalculateIdleTime = false;
DateTime dtIdleStartTime = DateTime.Now;
       

// Unmanaged function from user32.dll
 [DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

// Struct we'll need to pass to the function
internal struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}

#endregion "Idle Time"

private void bgWorkerIdleUser_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                while (true)
                {
                    // Get the system uptime
                    int systemUptime = Environment.TickCount;
                    // The tick at which the last input was recorded
                    int LastInputTicks = 0;
                    // The number of ticks that passed since last input
                    int IdleTicks = 0;

                    // Set the struct
                    LASTINPUTINFO LastInputInfo = new LASTINPUTINFO();
                    LastInputInfo.cbSize = (uint)Marshal.SizeOf(LastInputInfo);
                    LastInputInfo.dwTime = 0;

                    // If we have a value from the function
                    if (GetLastInputInfo(ref LastInputInfo))
                    {
                        // Get the number of ticks at the point when the last activity was seen
                        LastInputTicks = (int)LastInputInfo.dwTime;
                        // Number of idle ticks = system uptime ticks - number of ticks at last input
                        IdleTicks = systemUptime - LastInputTicks;
                    }

                    TimeSpan t = TimeSpan.FromSeconds(IdleTicks / 1000);

                    if (t.Hours == 0 && t.Minutes == 0 && t.Seconds == 0)
                    {
                       
                        int iTotalSeconds = (int)Math.Round((DateTime.Now - dtIdleStartTime).TotalSeconds);

                        if (iTotalSeconds >= (iTimePeriod * 60) && iTotalSeconds > 0)
                        {
                            IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
                           
                        }
                       
                        bCalculateIdleTime = false;
                    }
                    else if (t.Seconds > 0)
                    {
                        if (!bCalculateIdleTime)
                        {
                            bCalculateIdleTime = true;
                            dtIdleStartTime = DateTime.Now;
                        }
                    }


                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex.ToString());
            }
        }

C#.Net - Displaying Sno in DataGridView

private void dGvCapacity_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                string strRowNumber = (e.RowIndex + 1).ToString();
                SizeF size = e.Graphics.MeasureString(strRowNumber, this.Font);
                if (dGvCapacity.RowHeadersWidth < (int)(size.Width + 20))
                {
                    dGvCapacity.RowHeadersWidth = (int)(size.Width + 20);
                }
                Brush b = SystemBrushes.ControlText;
                e.Graphics.DrawString(strRowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2));
            }
            catch (Exception ex)
            {

            }
        }


C#.NET - Load Month names and Year in Combo Box


private delegate void del_LoadMonth();
private delegate void del_LoadYear();

private void LoadMonth()
{
if (cboMonth.InvokeRequired)
cboMonth.Invoke(new del_ LoadMonth(LoadMonth),null);
            else
            {
                for (int i = 0; i < 12; i++)
                {
                    cboMonth.Items.Insert(i, CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i]);
                }
                cboMonth.SelectedIndex = DateTime.Now.Month - 1;
            }
}
private void LoadYear()
{
            try
            {
                if (cboYear.InvokeRequired)
                    cboYear.Invoke(new del_ LoadYear(LoadYear), null);
                else
                {
                    int iCurrentYear = DateTime.Now.Year;
                    for (int i = 2014; i <= iCurrentYear; i++)
                    {
                        cboYear.Items.Add(i.ToString());
                    }

                    cboYear.SelectedIndex = (cboYear.Items.Count - 1);
                }
            }
            catch (Exception ex)
            {

            }

}