Sunday, November 23, 2008

Machine ip of client machine using asp.net

Firstly, Request.ServerVariables["HTTP_X_FORWARDED_FOR"] is a correct way to retrieve client IP address. The below code is an approach for getting Clinet IP.

if(Context.Request.ServerVariables["HTTP_VIA"]!=null) // using proxy
{
ip=Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP.
}
else// not using proxy or can't get the Client IP
{
ip=Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
}

You can not always get the Client IP through a proxy.

1. Some proxys can not send the client IP to you.
2. Some Clients can prevent from sending IP by "header_access deny".

Wednesday, October 22, 2008

Create download window in asp.net

string filename = MapPath(".") + "\\Document\\Home Business and Questionnaire.pdf";

Response.ContentType = "Application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename='" + filename + "'");

Response.Flush();
Response.WriteFile(filename);

Sunday, September 28, 2008

Creating Pie chart, rectangle chart in asp.net

protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "image/jpeg";

// Create a Bitmap instance that's 468x60, and a Graphics instance

const int width = 300, height = 300;

Bitmap objBitmap = new Bitmap(width, height);
Graphics objGraphics = Graphics.FromImage(objBitmap);

// Create a black background for the border
objGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height);

//DrawPieChart(ref objGraphics);
DrawRectangle(ref objGraphics);

// Save the image to a file
objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

// clean up...
objGraphics.Dispose();
objBitmap.Dispose();

}

private void DrawPieChart(ref Graphics objGraphics)
{
// Create location and size of ellipse.
int x = 50;
int y = 20;
int width = 200;
int height = 200;

// Create start and sweep angles.
int startAngle = 0;
int sweepAngle = 45;
SolidBrush objBrush = new SolidBrush(Color.Aqua);

objGraphics.FillPie(new HatchBrush(HatchStyle.Percent50, objBrush.Color), x,
y , width, height, startAngle, sweepAngle);

objBrush.Color = Color.Red;
objGraphics.FillPie(new HatchBrush(HatchStyle.Percent50, objBrush.Color), x,
y, width, height, startAngle+45, sweepAngle);

}
private void DrawRectangle(ref Graphics objGraphics)
{
SolidBrush objBrush = new SolidBrush(Color.Aqua);

objGraphics.FillRectangle(objBrush, 10, 50, 100, 40);

objBrush.Color = Color.Red;
objGraphics.FillRectangle(objBrush, 10, 100, 100, 40);
}

Thursday, September 25, 2008

ADO.Net with MSDE

This sample will teach you how to install MSDE and conect to msde via ADO.Net

Step 1 : Download MSDE. Click Here to download MSDE.

step 2: open Command prompt. go to the folder where MSDERelA folder resides (generally it will be in C:\MSDERelA).

Step 3: installing MSDE.
type setup SAPWD=[ur password] InstanceName=[InstanceName] SecurityMode=SQL

Step 4: for Getting into MSDE
type osql -E

Step 5: Create database and table

Step 6: Connecting to MSDE via ADO.Net

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=.;uid=sa;database=Books";

conn.Open();
SqlCommand comm = new SqlCommand("select * from MyTable", conn);
SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
textBox1.Text = dr["Name"].ToString();
textBox2.Text = dr["Age"].ToString();
}

Sunday, July 20, 2008

Multiple resource support in Silverlight

if u kow initial steps, then follow from step 27. This will work for silverlight 2.0. I dont sure this technique is required for new versions.


1. Open Visual Studio

2. Click File \ New Project...

3. Select Visual C# \ Silverlight \ Silverlight Application

4. In the name field type TestProj

5. Click ok and ok

6. In the Project Explorer

7. Right click on the TestProj (c# Icon) Project

8. Click Add \ New Folder

9. Name it Resources

10. Right click on Resources folder and click add New Item...

11. Select Resources File

12. Name it MyResource.resx and click ok

13. Open the new created MyResource.resx

14. In the Access Modifier: dropdown select Public

15. In the Name Field type tb1 and value “tb1 in english”

16. Repeat with Name Field type tb2 and value “tb2 in english”

17. In the file MyResource.Designer.cs change “internal MyResource() {“ to “public MyResource() {”

18. Click Save, press F5 and add debugging to web.config

19. IE opens up with a blank page

20. Close IE

21. Open Page.xaml in xaml editor window

22. In the user control add a new xml namespace xmlns:Loc="clr-namespace:TestProj.Resources"

23. Add a locstrings as a resource to your page eg: x:Name="LocStrings" />

24. Inside the grid add a Textblock and bind it to your resource Tb1 eg:

25. The String should appear in the Design view above

26. Wrap the textblock inside a vertical stackpanel and add a second Textkblock




27. In Project Explorer right click on MyResource.resx and copy and paste it into the resources folder

28. Rename “Copy of MyResource.resx” to “MyResource.de.resx” (DE is the two letter language code for Duetch)

29. Open MyResource.de.resx Edit the value to “tb1 auf deutsch” and “tb2 auf deutsch”

30. repeat step 28 for creating resource in fr, nl (you can add any no of copies depends upon ur requirement).

So we have 4 resource files(since i created resource files for de, fr and nl)
1. MyResource.resx
2. MyResource.de.resx
3. MyResource.fr.resx
4. MyResource.nl.resx


30. Click Save, press F5

31. Notice the files \\bin\debug\de\MyResource.resources.dll
\\bin\debug\fr\MyResource.resources.dll
\\bin\debug\nl\MyResource.resources.dll

32. right click on project and select Properties

33. select build events, in post-build event command line, copy paste following
xcopy /SY "$(TargetDir)de" "$(SolutionDir)$(ProjectName)Web\ClientBin\de\"
xcopy /SY "$(TargetDir)fr" "$(SolutionDir)$(ProjectName)Web\ClientBin\fr\"
xcopy /SY "$(TargetDir)nl" "$(SolutionDir)$(ProjectName)Web\ClientBin\nl\"

34. Compile
35. refresh bin/debug folder
36. check wether bellow files are shown

MyResource.resources.de.dll
MyResource.resources.fr.dll
MyResource.resources.nl.dll

if any of the file is missing, suppose if MyResource.resources.nl.dll is not shown, then go to \\bin\debug\nl folder, copy n paste testproj.resources.dll, and rename it MyResource.resources.nl.dll move this file to \\bin\debug folder

37 Compile and execute.

38. open Page.xaml.cs file
write in
page_load()
{
//textbox uses resource of deutch,
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de"); }

39 Compile and execute.

Tuesday, May 27, 2008

Calling server side method through javascript Using Asp.net

this is a small example, it will call a server method without having the expense of postback

//step 1: Inherit ICallbackEventHandler interface in your form

public partial class FormCallServer: System.Web.UI.UserControl, ICallbackEventHandler
string m_callbackEventArgument = "";

//step 2:
protected void Page_Load(object sender, EventArgs e)
{

string callbackEventReference = Page.ClientScript.GetCallbackEventReference(this,
"document.getElementById('TextBox1').value ",
"ClientCallbackScript","null");

TextBox1.Attributes.Add("onChange", "javascript:" + callbackEventReference ); }

//step 3: Interface require to implement 2 monthods RaiseCallbackEvent and
//GetCallbackResult. These are predefined methods RaiseCallbackEvent initialise and
//GetCallbackResult will execute and return the output to called client method.

//below method is automatically called from client method
//notice parameter callbackEventArgument, it is an passed from client method, by this example it will be TextBox1.value (see which is mensioned above)

public void RaiseCallbackEvent(string callbackEventArgument)
{
m_callbackEventArgument = callbackEventArgument;
}

//below the main method for callback server method
public string GetCallbackResult()
{
//Your codes

return [you must return a string value]; //After executing this method it will below
//javascript function ClientCallbackScript
}

----------------------------------------------------------------------------
//step 4: you need some coding in client side also
//Argument result is the return value, after executing above GetCallbackResult

<Script type="text/javascript" >
function ClientCallbackScript(result)
{
//your code here
//a sample code from my side
document.getElementById('txtMyTestbox').value = result;
}

</Script >

Thursday, April 10, 2008

Get the position of web Controls using Javascript event though controls having no position declared

//-------Find top of Textbox --------------------------
var oNode = document.getElementById('TextBox1');
var iTop = 0;

while(oNode.tagName != "BODY") {
iTop += oNode.offsetTop;
oNode = oNode.offsetParent;
}

//Top of Textbox is now in iTop
document.write(iTop);
//--------------------------------------------------------


//--------Find Left of Textbox----------------------------
var iLeft = 0;
oNode = document.getElementById('UcEventType1_TextBox1');
while(oNode.tagName != "BODY") {
iLeft += oNode.offsetLeft;
oNode = oNode.offsetParent;
}

//Left position of textbox is displaying
document.write(iLeft);
//------------------------------------------------------------

Wednesday, March 5, 2008

Send mail using SQL Server

With XP_SendMail:

CREATE PROCEDURE dbo.foo AS
BEGIN
SET NOCOUNT ON
-- do some other actions
DECLARE @body VARCHAR(1024)
SET @body = 'foo was fired '+
CONVERT(VARCHAR, GETDATE())

EXEC master..xp_sendmail
@recipients='you@you.com',
@message = @body,
@subject = 'foo was fired.'
END

-- or you can do it conditionally:

CREATE PROCEDURE dbo.foo AS
BEGIN
SET NOCOUNT ON
-- do some other action
IF @@ROWCOUNT > 0
BEGIN
DECLARE @body VARCHAR(1024)
SET @body = 'foo was fired ' +
CONVERT(VARCHAR, GETDATE()) +
CHAR(13) + CHAR(10) +
CONVERT(VARCHAR, @@ROWCOUNT)

EXEC master..xp_sendmail
@recipients='you@you.com',
@message = @body,
@subject = 'foo was fired.'
END
END

With XP_SMTP_SendMail (which assumes you are running SQL Server 7.0 or higher, have installed XP_SMTP_SendMail, and have a valid and properly configured SMTP Server):

CREATE PROCEDURE dbo.foo AS
BEGIN
SET NOCOUNT ON
-- do some other actions
DECLARE @body VARCHAR(1024)
SET @body = 'foo was fired '+
CONVERT(VARCHAR, GETDATE())

EXEC master..xp_smtp_sendmail
@TO = 'you@you.com',
@from = 'someone@somewhere.com',
@message = @body,
@subject = 'foo was fired.',
@server = 'smtp.yourdomain.com'
END

-- or you can do it conditionally:

CREATE PROCEDURE dbo.foo AS
BEGIN
SET NOCOUNT ON
-- do some other action
IF @@ROWCOUNT > 0
BEGIN
DECLARE @body VARCHAR(1024)
SET @body = 'foo was fired ' +
CONVERT(VARCHAR, GETDATE()) +
CHAR(13) + CHAR(10) +
CONVERT(VARCHAR, @@ROWCOUNT)

EXEC master..xp_smtp_sendmail
@TO = 'you@you.com',
@from = 'someone@somewhere.com',
@message = @body,
@subject = 'foo was fired.',
@server = 'smtp.yourdomain.com'
END
END

If you need to send an attachment, you can simply add the following parameter:

@attachments = 'c:\attachment.txt'


--------------------------------------------------------------------------------
CDO.Message

This sample assumes you are running Windows 2000 or higher, have a user that has access to sp_OA* procedures, and have a valid and properly configured SMTP server:

CREATE PROCEDURE dbo.sendMail_With_CDOMessage
@to VARCHAR(64),
@subject VARCHAR(255),
@body VARCHAR(1024)
AS
BEGIN
SET NOCOUNT ON

DECLARE
@handle INT,
@return INT,
@s VARCHAR(64),
@sc VARCHAR(1024),
@up CHAR(27),
@from VARCHAR(64),
@server VARCHAR(255),
@filename VARCHAR(255)

SET @s = '"http://schemas.microsoft.com/cdo/configuration/'

SELECT
@s = 'Configuration.Fields(' + @s,
@up = 'Configuration.Fields.Update',
@from = 'someone@somewhere.com',
@server = 'smtp.yourdomain.com'
-- or IP address, e.g. '127.0.0.1'

-- if you want an attachment:
,@filename = 'C:\folder\file.ext'


EXEC @return = sp_OACreate 'CDO.Message', @handle OUT
SET @sc = @s + 'sendusing").Value'
EXEC @return = sp_OASetProperty @handle, @sc, '2'
SET @sc = @s + 'smtpserver").Value'
EXEC @return = sp_OASetProperty @handle, @sc, @server
EXEC @return = sp_OAMethod @handle, @up, NULL
EXEC @return = sp_OASetProperty @handle, 'To', @to
EXEC @return = sp_OASetProperty @handle, 'From', @from
EXEC @return = sp_OASetProperty @handle, 'Subject', @subject
EXEC @return = sp_OASetProperty @handle, 'TextBody', @body

IF @filename IS NOT NULL
EXEC @return = sp_OAMethod @handle, 'AddAttachment', NULL, @filename

EXEC @return = sp_OAMethod @handle, 'Send', NULL
IF @return <> 0
BEGIN
PRINT 'Mail failed.'
IF @from IS NULL
PRINT 'From address undefined.'
ELSE
PRINT 'Check that server is valid.'
ELSE
PRINT 'Mail sent.'

EXEC @return = sp_OADestroy @handle
END
GO