Friday, November 18, 2011

Export GridView in ASP.NET to excel

protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=ExportFile.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
gvReport.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

Error in IIS (‘\\?\C:\Windows\system32\inetsrv\config\applicationHost.config’, line number ’0′. The error message is: ‘Configuration file is not well-formed XML’)

Copy the applicationHost.config file from C:\inetpub\history\ in to C:\Windows\System32\inetsrv\config\

This solves the IIS issue.

Formatting Dates, Times and Numbers in ASP.NET

Click here

Monday, October 31, 2011

Get week number from a given date

public static int GetWeekNumber(string date)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime dt = DateTime.ParseExact(date,"dd-MM-yyyy",null);
System.Globalization.Calendar cal = dfi.Calendar;
return cal.GetWeekOfYear(dt, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
}

Thursday, October 27, 2011

Get the first day of week from the week number

public string GetFirstDayOfWeek(int weekNum)
{
DateTime dt = new DateTime(DateTime.Now.Year, 1, 1);
int days = (weekNum) * 7;
DateTime dt1 = dt.AddDays(days);
DayOfWeek dow = dt1.DayOfWeek;
DateTime startDateOfWeek = dt1.AddDays(-(int)dow);
return startDateOfWeek.ToString("dd MMM");
}
public static string GetFirstDayOfWeek(DateTime dayInWeek)
{
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
DateTime firstDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
firstDayInWeek = firstDayInWeek.AddDays(-1);
return firstDayInWeek;
}

SQL Pivoting weekdays


DECLARE @COLUMNS VARCHAR(8000)
SELECT
@COLUMNS =
COALESCE
(
@COLUMNS + ',[' + CAST(DATEPART(WW, TR_DATE) as varchar) + ']',
'[' + CAST(DATEPART(WW, TR_DATE) as varchar)+ ']'
)
FROM
TRANSACTIONS
GROUP BY
DATEPART(WW, TR_DATE)
ORDER BY DATEPART(WW,TR_DATE)
select @COLUMNS
DECLARE @QUERY VARCHAR(8000)
SET @QUERY = 'SELECT *
FROM
(
SELECT
TR_PR_NO,
DATEPART(ww, TR_DATE) as weekdate,
ISNULL(TR_AMOUNT,0) as amount
FROM
TRANSACTIONS
) PIV
PIVOT
(
SUM(amount) FOR weekdate in (' + @columns + ')
) AS chld'
EXECUTE (@query)
GO

Tuesday, October 25, 2011

Get all monday of a month

DateTime date = DateTime.Today;
var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
var weekends = from d in dates
where d.DayOfWeek == DayOfWeek.Monday
select d;
Response.Write(weekends.ToList());