Tuesday, 21 July 2015

Days difference between two dates duplicate

DateTime's can be subtracted to get a TimeSpan. The TimeSpan has a TotalDays which is the number of days (includes fractional days as well).
int DaysBetween(DateTime d1, DateTime d2) {
    TimeSpan span = d2.Subtract(d1);
    return (int)span.TotalDays;
}
NOTE Time spans are signed. If d1=1/9/11 and d2=1/11/11, then d1.subtract(d2)=timespan of -2 days. So if you want to use a time span to find out if dates are within X days of each other, you need to take the absolute value of the total days...
Math.Abs(span.TotalDays)

Monday, 20 July 2015

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think you are about this:
CONVERT(datetime, date_as_string, 103)
Notice, that datetime hasn't any format. You think about its presentation. To get the data of datetime in in appropriated format you can use
CONVERT(varchar, date_as_datetime, 103)

Friday, 17 July 2015

Convert Time DataType into AM PM Format:

Use following syntax to convert a time to AM PM format.
Replace the field name with the value in following query.
select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),100)

SELECT REPLACE(CONVERT(varchar(15),StartTime,22),':00','') AS StartTime,
     REPLACE(CONVERT(NVARCHAR(15),EndTime,22),':00','') AS EndTime
FROM LMS_tbl_TimeSlotDetails AS dtl

Tuesday, 7 July 2015

How to insert a data table into SQL Server database table?

Create a User-Defined TableType in your database:
CREATE TYPE [dbo].[MyTableType] AS TABLE(
    [Id] int NOT NULL,
    [Name] [nvarchar](128) NULL
)
Create a Table in your database:
CREATE TABLE[dbo].[Records](    [Id] int NOT NULL,
    [Name] [nvarchar](128) NULL
)
and define a parameter in your Stored Ptocedure:
CREATE PROCEDURE [dbo].[InsertTable]
    @myTableType MyTableType readonly
AS
BEGIN
    insert into [dbo].Records 
    select * from @myTableType 
END
and send your DataTable directly to sql server:
protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(getConString());
        using (var command = new SqlCommand("InsertTable") { CommandType = CommandType.StoredProcedure })
        {
            var dt = GetDataTable(); //create your own data table
            command.Parameters.Add(new SqlParameter("@myTableType", dt));            
            command.Connection = con;
            con.Open();
            command.ExecuteNonQuery();
            //SqlHelper.Exec(command);
        }
    }

    private DataTable GetDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Columns.Add("Name");
        dt.Rows.Add("1","Dharmendra");
        dt.Rows.Add("2", "Rakesh" );
        dt.Rows.Add("3", "Mukesh" );
        return dt;
    }

Getting name of Page being requested/was requested

public string GetPageName() 
{ 
    string path = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo info = new System.IO.FileInfo(path); 
    return info.Name; 
}

Thursday, 2 July 2015

Convert DataTable to Generic List in C#

List<Cards> target = dt.AsEnumerable()
    .Select(row => new Cards
    {
        // assuming column 0's type is Nullable<long>
        CardID = row.Field<long?>(0).GetValueOrDefault(),
        CardName = String.IsNullOrEmpty(row.Field<string>(1))
            ? "not found"
            : row.Field<string>(1),
    }).ToList();

Wednesday, 17 June 2015

DownLoad file using C#

private void Download(string filePath, string fileName)
        {
            //string fileExtension = ".txt";
            // Set Response.ContentType
            Response.ContentType = msdnh.util.DownloadFile.GetContentType(fileName);

            // Append header
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);

            // Write the file to the Response
            Response.TransmitFile(Server.MapPath(filePath + Path.GetFileName(fileName)));
            Response.End();

        }

public static class DownloadFile
    {
        public static string GetContentType(string fName)
        {
            if (string.IsNullOrEmpty(fName))
                return string.Empty;

            string contentType = string.Empty;
            if (fName.EndsWith(".txt"))
            {
                contentType = "application/txt";
            }
            else if (fName.EndsWith(".pdf"))
            {
                contentType = "application/pdf";
            }
            else if (fName.EndsWith(".doc"))
            {
                contentType = "application/msword";
            }
            else if (fName.EndsWith(".docx"))
            {
                contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            }
            else if (fName.EndsWith(".xls"))
            {
                contentType = "application/vnd.ms-excel";
            }
            else if (fName.EndsWith(".xlsx"))
            {
                contentType = "application/vnd.xlsx";
            }
            else if (fName.EndsWith(".jpg"))
            {
                contentType = "image/jpg";
            }
            else if (fName.EndsWith(".gif"))
            {
                contentType = "image/GIF"; ;
            }
            else
            {
                contentType = "application/octet-stream";
            }

            return contentType;
            //switch (fileExtension)
            //{
            //    case ".htm":
            //    case ".html":
            //        contentType = "text/HTML";
            //        break;

            //    case ".txt":
            //        contentType = "text/plain";
            //        break;

            //    case ".doc":
            //    case ".rtf":
            //    case ".docx":
            //        contentType = "Application/msword";
            //        break;

            //    case ".xls":
            //    case ".xlsx":
            //        contentType = "Application/x-msexcel";
            //        break;

            //    case ".jpg":
            //    case ".jpeg":
            //        contentType = "image/jpeg";
            //        break;

            //    case ".gif":
            //        contentType = "image/GIF";
            //        break;

            //    case ".pdf":
            //        contentType = "application/pdf";
            //        break;
            //}

           
        }
    }