Monday, July 27, 2009

Dynamic load user control with delegate event

Hello Friends,
Here I will explain you how can you load dynamically user control and perform delegate event on it.
Let's see example here.

Usercontrol : Calc.ascx
-------------------------------

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Calc.ascx.cs" Inherits="Calc" %>

<asp:Label ID="lblNum1" runat="server" Text="Enter The Number One"></asp:Label>  
<asp:TextBox ID="txtNum1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblOperation" runat="server" Text="+" runat="server"></asp:Label><br />
<asp:Label ID="lblNum2" runat="server" Text="Enter The Number Two"></asp:Label>  
<asp:TextBox ID="txtNum2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnAnswer" runat="server" Text="Answer" CausesValidation="false" OnClick="btnAnswer_Click" />
<br />

Usercontrol : Calc.ascx.cs
--------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Calc : System.Web.UI.UserControl
{
public delegate void PerformOperationHandler(double num1, double num2);
public event PerformOperationHandler PerformOperation;

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnAnswer_Click(object sender, EventArgs e)
{
if (PerformOperation != null)
{
PerformOperation(double.Parse(txtNum1.Text),double.Parse(txtNum2.Text));
}
}
}


Page Name:Default.aspx
--------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<%@ Reference Control="~/Calc.ascx" %>


<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="placeholder" runat="server"></asp:PlaceHolder>
<br />
<asp:Label ID="lblAnswer" runat="server"></asp:Label>
</div>
</form>

Page Name:Default.aspx.cs
----------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

UserControl Calculation = LoadControl("~/Calc.ascx") as UserControl ;
placeholder.Controls.Clear();
placeholder.Controls.Add(Calculation);
((Calc)Calculation).PerformOperation+=new Calc.PerformOperationHandler(PerformOperation);

}

public void PerformOperation(double num1, double num2)
{
lblAnswer.Text = (num1 + num2).ToString();
}
}

I hopes it will help you.

Regards,
Kinjal Shah

Create Custom Calendar

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Request["date"] == null)
{
RenderCalendar(System.DateTime.Now);
}
else
{
if (Request["date"] != null)
{
RenderCalendar(Convert.ToDateTime(Request["date"]));
}
}
}

private void RenderCalendar(DateTime CurrentDate)
{
tblCalendar.Rows.Clear();
TableRow TitleRow = new TableRow();
TableCell PrevCell = new TableCell();
HyperLink hypPrev = new HyperLink();
hypPrev.Text = "<";
hypPrev.NavigateUrl = "Calendar.aspx?date=" + CurrentDate.AddMonths(-1).ToShortDateString();
TitleRow.Cells.Add(PrevCell);
PrevCell.Controls.Add(hypPrev);


TableCell DateHeaderCell = new TableCell();
DateHeaderCell.ColumnSpan = 5;
Label lblHeader = new Label();

lblHeader.Text = String.Format("{0:MMM}", CurrentDate) + " " + CurrentDate.Year.ToString();
DateHeaderCell.VerticalAlign = VerticalAlign.Middle;
DateHeaderCell.HorizontalAlign = HorizontalAlign.Center;
DateHeaderCell.Font.Bold = true;
TitleRow.Cells.Add(DateHeaderCell);
DateHeaderCell.Controls.Add(lblHeader);

TableCell NextCell = new TableCell();
HyperLink hypNext = new HyperLink();
hypNext.Text = ">";
hypNext.NavigateUrl = "Calendar.aspx?date=" + CurrentDate.AddMonths(1).ToShortDateString();

TitleRow.Cells.Add(NextCell);
NextCell.Controls.Add(hypNext);

tblCalendar.Rows.Add(TitleRow);

TableRow DayRow = new TableRow();
TableCell DayCellSun = new TableCell();
DayCellSun.Text = "Sun";
DayCellSun.Font.Bold = true;
DayRow.Cells.Add(DayCellSun);

TableCell DayCellMon = new TableCell();
DayCellMon.Text = "Mon";
DayCellMon.Font.Bold = true;
DayRow.Cells.Add(DayCellMon);

TableCell DayCellTue = new TableCell();
DayCellTue.Text = "Tue";
DayCellTue.Font.Bold = true;
DayRow.Cells.Add(DayCellTue);

TableCell DayCellWed = new TableCell();
DayCellWed.Text = "Wed";
DayCellWed.Font.Bold = true;
DayRow.Cells.Add(DayCellWed);

TableCell DayCellThu = new TableCell();
DayCellThu.Text = "Thu";
DayCellThu.Font.Bold = true;
DayRow.Cells.Add(DayCellThu);

TableCell DayCellFri = new TableCell();
DayCellFri.Text = "Fri";
DayCellFri.Font.Bold = true;
DayRow.Cells.Add(DayCellFri);

TableCell DayCellSat = new TableCell();
DayCellSat.Text = "Sat";
DayCellSat.Font.Bold = true;
DayRow.Cells.Add(DayCellSat);

tblCalendar.Rows.Add(DayRow);

String nDate = Convert.ToString(CurrentDate.ToShortDateString());

int year = CurrentDate.Year;
int month = CurrentDate.Month;
// int totalDays = DateTime.DaysInMonth(year,month);

String StartDate = month + "/1/" + year;
String FirstDay = Convert.ToDateTime(StartDate).DayOfWeek.ToString();

int currentDay = Convert.ToInt16(Convert.ToDateTime(nDate).Day);
// string CurrentWeekDay = Convert.ToDateTime(nDate).DayOfWeek.ToString();


int count = 0;
DateTime CountDate = Convert.ToDateTime(StartDate);
for (int i = 0; i <= 6; i++)
{
TableRow tr = new TableRow();
for (int j = 1; j <= 7; j++)
{
String CurrDay = GetDay(Convert.ToString(j));
TableCell td = new TableCell();
if (count >= 1 || FirstDay == CurrDay)
{
if (month == Convert.ToDateTime(CountDate).Month)
{
td.Text = Convert.ToDateTime(CountDate).Day.ToString();
count = count + 1;
DateTime dt = Convert.ToDateTime(CountDate).AddDays(1);
CountDate = Convert.ToDateTime(dt.ToShortDateString());

td.Attributes.Add("onClick", "Javascript:alert(" + count + ");");
}
}
else
{
td.Text = " ";
}
tr.Cells.Add(td);
}
tblCalendar.Rows.Add(tr);
}
}
private String GetDay(String Day)
{
switch (Day)
{
case "1":
return "Sunday";
case "2":
return "Monday";
case "3":
return "Tuesday";
case "4":
return "Wednesday";
case "5":
return "Thursday";
case "6":
return "Friday";
case "7":
return "Saturday";

}
return null;
}

Monday, July 20, 2009

Select Box I.E. Width Problem

Hi,
I trouble with IE dropdown cuteoff problem.
Finally I got solution and here I put that url from where I find solutions.
http://www.hedgerwow.com/360/dhtml/ui_select_with_fixed_width/bk/demo.php

Regards,
Kinjal Shah

Thursday, July 16, 2009

Return String value from enum instead of int value

Hello Frnds,
In my recent project,there is a requirement to get enum string value instead of int. As u all know that enum which will return integer value.
Finally I got the solution. Here I place the code of that customize enum. I hopes it will help you.

Class Name: Enums.cs
public enum HotelActivity : int
{
[StringValue("family friendly")]
Family_Friendly=1
,[StringValue("adults only")]
Adults_Only=2
}

Class Name: StringValueAttribute.cs
public class StringValueAttribute : Attribute
{

public string StringValue { get; protected set; }

public StringValueAttribute(string value)
{
this.StringValue = value;
}
}


Class Name: Extensions.cs
public static class Extensions
{
public static string GetStringValue(this Enum value)
{
// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());

// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];

// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}
}

default.aspx.cs
public partial class default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Framework.Enums.HotelActivity.Family_Friendly.GetStringValue());
}
}

Try to implement this code and enjoy :)

Regards,
Kinjal Shah

Tuesday, July 7, 2009

HTTP Handlers for Image resize in ASP.NET

Hello frnds,
Here I put the code of image resize using http handler.

Page:PhotoResizeHandler.ashx

<%@ WebHandler Language="C#" Class="PhotoResizeHandler" %>

using System;
using System.Web;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
public class PhotoResizeHandler : IHttpHandler
{
string _StrImage = string.Empty;
string _StrExt = string.Empty;
int _IntThumbWidth;
int _IntThumbHeight;

public void ProcessRequest(HttpContext context)
{
if (context.Request.Params["Height"] != null)
{
try
{
_IntThumbHeight = int.Parse(context.Request.Params["Height"]);
}
catch
{
_IntThumbHeight = 0;
}
}
if (context.Request.Params["Width"] != null)
{
try
{
_IntThumbWidth = int.Parse(context.Request.Params["Width"]);
}
catch
{
_IntThumbWidth = 0;
}
}
if (context.Request.Params["Image"] != null)
{
try
{
_StrImage = (context.Request.Params["Image"]).ToString();
}
catch
{
_StrImage = string.Empty;
}
}
if (context.Request.Params["Ext"] != null)
{
try
{
_StrExt = (context.Request.Params["Ext"]).ToString();
}
catch
{
_StrExt = string.Empty;
}
}
ResizeImage(_StrImage, _IntThumbWidth, _IntThumbHeight, _StrExt);

}

public bool IsReusable
{
get
{
return false;
}
}


private void ResizeImage(string MainImage, int thumbWidth, int thumbHeight, string ext)
{
try
{
System.Drawing.Image Image = System.Drawing.Image.FromFile(MainImage);
int srcWidth = Image.Width;
int srcHeight = Image.Height;

int w = thumbWidth, h = thumbHeight;
#region "Proposnal Ratio"
// proposnal resize of your image
if (srcHeight > thumbHeight)
{
w = srcWidth * thumbHeight / srcHeight;
}
else
h = srcHeight;

if (srcWidth > thumbWidth)
{
h = srcHeight * thumbWidth / srcWidth;
}
else
if (w > srcWidth)
w = srcWidth;
if (w > thumbWidth)
h = srcHeight * thumbWidth / srcWidth;
if (h > thumbHeight)
w = srcWidth * thumbHeight / srcHeight;

thumbWidth = (thumbWidth > w ? w : thumbWidth);
thumbHeight = (thumbHeight > h ? h : thumbHeight);
thumbWidth = (thumbWidth == 0 ? 1 : thumbWidth);
thumbHeight = (thumbHeight == 0 ? 1 : thumbHeight);

#endregion

Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(Image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);

switch (ext.ToUpper())
{
case ".JPG":
case ".JPEG":
HttpContext.Current.Response.ContentType = "image/Jpeg";
bmp.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".GIF":
HttpContext.Current.Response.ContentType = "image/Gif";
bmp.Save(HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".PNG":
System.IO.MemoryStream MemStream = new System.IO.MemoryStream();
HttpContext.Current.Response.ContentType = "image/Png";
bmp.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);

MemStream.WriteTo(HttpContext.Current.Response.OutputStream);
//bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png );
break;
}
Image.Dispose();
}
catch (Exception Exc)
{
throw Exc;
}

}
}

Now you need to add one aspx page and create one asp:image controls there.

<asp:Image ID="img" runat="server" />

Then in cs file with on page load event, try to put this line
img.ImageUrl = "PhotoResizeHandler.ashx?Image=" + MainImage + "&Width=65&Height=65&Ext=" + ext;

Hopes this will help you.

Regards,
Kinjal Shah

Thursday, July 2, 2009

Some date functions - just date no time, last day of month, first day of month, first day of week and last day of week

Hi,
I found one article which will fulfill my requirement to perform date operation.
Here I post that link. I hopes it will also help you

http://sqlblogcasts.com/blogs/simons/archive/2008/10/28/Some-date-functions---just-date-no-time--last-day-of-month--first-day-of-month--first-day-of-week-and-last-day-of-week.aspx

Perform paging in sql

CREATE TABLE DuplicateRcordTable (Col1 INT, Col2 INT)
INSERT INTO DuplicateRcordTable
SELECT 1, 1
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4

UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4

UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4

UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4

SELECT * FROM DuplicateRcordTable


--Start to perform Paging

DECLARE @PageSize AS INT
SET @PageSize=5
Declare @StartIndex as int
SET @StartIndex=1

SET @StartIndex=((@StartIndex*@PageSize)-@PageSize) + 1
SET @PageSize=(@StartIndex + @PageSize)-1

SELECT Col1,Col2 FROM
(
SELECT *,ROW_NUMBER() over(order by col1) AS RowNumber FROM DuplicateRcordTable
) T WHERE T.RowNumber between @StartIndex and @PageSize


Result:-
Show All Records



Show records based on paging

Remove duplicate records from the table using CTE

Hello everyone,
I need to remove duplicate rows from the table and for that I made one query with CTE which will remove all duplicate rows from the table.
Here I put an example. So you can get better idea of it.

DROP TABLE DuplicateRcordTable
CREATE TABLE DuplicateRcordTable (Col1 INT, Col2 INT)
INSERT INTO DuplicateRcordTable
SELECT 1, 1
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4

SELECT * FROM DuplicateRcordTable


;with DuplicateRows
AS
(
SELECT *,ROW_NUMBER() over(partition by Col1,Col2 order by Col1) DuplicateRow FROM DuplicateRcordTable
)
DELETE FROM DuplicateRows where DuplicateRow>1

SELECT * FROM DuplicateRcordTable

RESULT:-
Before deleted duplicate records:-



After deleted duplicate records

TSQL Challenge 3 to Reverse string without using Reverse() function

I have accept TSQL Challenge 3 from site and try to solve it.
Here is a URL of TSQL Challenge
http://beyondrelational.com/blogs/tc/archive/2009/05/24/tsql-challenge-3.aspx

Solved TSQL Challenge-3

DECLARE @t TABLE( ID INT IDENTITY, data VARCHAR(20))
INSERT INTO @t(data) SELECT 'Jacob'
INSERT INTO @t(data) SELECT 'Sebastian'

SET NOCOUNT ON

;WITH ReverseName AS
(
SELECT T.ID,T.data,CAST('' AS VARCHAR) AS ReverseData ,TotalLength=LEN(T.data),position=0 FROM @t T
UNION ALL
SELECT ReverseName.ID,ReverseName.data , CAST((ReverseName.ReverseData + substring(ReverseName.data,len(ReverseName.data)-position,1)) AS VARCHAR ) as ReverseData ,ReverseName.TotalLength,position=position+1 FROM ReverseName
where ReverseName.TotalLength>=position
)


SELECT ID,ReverseData AS [Reverse String] FROM ReverseName where position>TotalLength order by ID desc

OUTPUT:-