Thursday 19 March 2020

SQL Check if table exists

Check if table exists

Before creating a new table or before dropping a table you need to check if table exists in the database. To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID().
The INFORMATION_SCHEMA.TABLES returns one row for each table in the current database. The OBJECT_ID() function returns the database object id number if the object exists in the database. ::SYNTAX :: Check if table exists


IF (EXISTS (SELECT *
   FROM INFORMATION_SCHEMA.TABLES
   WHERE TABLE_SCHEMA = 'dbo'
   AND TABLE_NAME = 'Certifications'))
   BEGIN
      PRINT 'Database Table Exists'
   END;
ELSE
   BEGIN
      PRINT 'No Table in database'
   END;


Result: Database Table Exists

Using OBJECT_ID() function

IF OBJECT_ID('dbo.Certifications') IS NOT NULL
   BEGIN
      PRINT 'Database Table Exists'
   END;
ELSE
   BEGIN
      PRINT 'No Table in database'
   END;


Result: Database Table Exists

Friday 9 August 2019

Get Difference between two dates as Minutes, Seconds, Hours in SQL Server

I am using the below query to get difference between two dates in Minutes, Seconds and Hours

DECLARE @mintime DATETIME = '2019-08-09 08:29:43.517'
DECLARE @maxtime DATETIME = getdate()
declare @minute int, @second int, @hour int
set @minute = datediff([minute], @minTime, @maxtime);
set @second = datediff([second], @minTime, @maxtime);
set @hour = datediff([hour], @minTime, @maxtime);
select @minute as [minute],@second as [second],@hour as [hour]

Saturday 27 July 2019

System.InvalidCastException: Object cannot be cast from DBNull to other types

System.InvalidCastException: Object cannot be cast from DBNull to other types. at System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider) at WreckerTowAPI.Controllers.SomeController.Save(List`1 obj)
if (!Convert.IsDBNull(StatusIdOUT.Value))
{
  regResp.Id = Convert.ToInt32(StatusIdOUT.Value);
}
else
{
  regResp.Id = 0;
}

Tuesday 12 September 2017

How to write Exceptions to Event Viewer in C#

1 - First Create Static Method (LogError)
public static class Log
{
  public static void LogError(Exception ex)
  {
     EventLog.WriteEntry("Application", ex.Message + " Trace" + ex.StackTrace, EventLogEntryType.Error, 121, short.MaxValue);
  }
}
2 - Then Call this Static Method inside Catch Block.
try
{
               
}
catch (Exception ex)
{
  Log.LogError(ex);
}

How to Calculate Days difference Between two Dates in C#

DateTime fromdt = dtpFromDate.Value.Date;

DateTime todt = dtpToDt.Value.Date;

int fday = fromdt.Day;

int fmonth = fromdt.Month;

int fyear = fromdt.Year;

DateTime oldDate = new DateTime(fyear, fmonth, fday);

TimeSpan ts = todt - oldDate;

int differenceInDays = ts.Days;

MessageBox.Show(differenceInDays.ToString());

Thursday 25 August 2016

How to Enable and Disable all Validations Controls in a single page in Asp.net C#

For Disable validation controls in a page
public void DisableAllValidations(ControlCollection cntrls)
{
     foreach (Control ctrl in cntrls)
     {
        if (ctrl is CompareValidator)
            ((CompareValidator)ctrl).Enabled = false;
        if (ctrl is CustomValidator)
            ((CustomValidator)ctrl).Enabled = false;
        if (ctrl is RangeValidator)
            ((RangeValidator)ctrl).Enabled = false;
        if (ctrl is RegularExpressionValidator)
            ((RegularExpressionValidator)ctrl).Enabled = false;
        if (ctrl is RequiredFieldValidator)
            ((RequiredFieldValidator)ctrl).Enabled = false;
        DisableForm(ctrl.Controls);
     }
}
For Enable validation controls in a page
public void DisableAllValidations(ControlCollection cntrls)
{
     foreach (Control ctrl in cntrls)
     {
        if (ctrl is CompareValidator)
            ((CompareValidator)ctrl).Enabled = true;
        if (ctrl is CustomValidator)
            ((CustomValidator)ctrl).Enabled = true;
        if (ctrl is RangeValidator)
            ((RangeValidator)ctrl).Enabled = true;
        if (ctrl is RegularExpressionValidator)
            ((RegularExpressionValidator)ctrl).Enabled = true;
        if (ctrl is RequiredFieldValidator)
            ((RequiredFieldValidator)ctrl).Enabled = true;
        DisableForm(ctrl.Controls);
     }
}

Calculate the duration of the visit based on the Start and End Date. The duration will only count regular business days (does not count weekends or holidays)

private double GetBusinessDays(DateTime startD, DateTime endD)
{
   double calcBusinessDays =
           1 + ((endD - startD).TotalDays * 5 -
               (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;

   if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
   if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;
   return calcBusinessDays;
}