Thursday, June 12, 2014

MSSQL - Communicating one database to another using opendatasource

Communicating one database to another using opendatasource.

Example;

select UserId , Username , EmployeeId

from OPENDATASOURCE('SQLOLEDB', 'Data Source=172.166.10.116; User ID=sa;Password=12345678').hrms.dbo.employee_list  

Wednesday, June 11, 2014

C#.NET - Check decimal value in DataGridView Cell

Where to use?




Step 1: Add DataGridViewTextBoxColumn column in DataGridView.
Step 2: Add EditingControlShowing events in DataGridView

Code:

private void dgvClientBilling_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
            System.Windows.Forms.TextBox txt = (System.Windows.Forms.TextBox)e.Control;
            txt.KeyPress += new KeyPressEventHandler(txt_KeyPress);
}


public void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '\b') && (e.KeyChar != '.'))
                {
                    e.Handled = true;
                }
                else
                {
                    e.Handled = false;
                }
                if (Char.IsControl(e.KeyChar))
                {
                    e.Handled = false;
                }
                else if (Char.IsNumber(e.KeyChar) || e.KeyChar == '.')
                {
                    TextBox tb = sender as TextBox;
                    int cursorPosLeft = tb.SelectionStart;
                    int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
                    string result = tb.Text.Substring(0, cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight);
                    string[] parts = result.Split('.');
                    if (parts.Length > 1)
                    {
                        if (parts[1].Length > 2 || parts.Length > 2)
                        {
                            e.Handled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex.ToString());
            }
        }


C#.NET - ContextMenuStrip Enable / Disable while opening

Where to use?

When there is a need to enable/disable particular menu we can use this code.

Control: ContextMenuStrip ( Name : cmsQA)

Event: ( Opening)



Code :

private void cmsQA_Opening(object sender, CancelEventArgs e)
{
            try
            {
                e.Cancel = !(lsvFiles.SelectedItems.Count > 0);
                if (lsvFiles.SelectedItems.Count == 1)
                {
                    cmsAllocation.Items["tsmAssignFile"].Enabled = false;
                    cmsAllocation.Items["tsmUpload"].Enabled = false;
                    cmsAllocation.Items["tsmChangeTemplate"].Enabled = false;
                    cmsAllocation.Items["tsmDelete"].Enabled = false;

                    int iIndex = 5;

                    int[] iAssigneFileStatus = new int[] { 1, 5, 9 };
                    if (iAssigneFileStatus.Contains(iIndex))
                    {
                        cmsAllocation.Items["tsmAssignFile"].Enabled = true;
                    }


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

        }




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)
            {
            }
}