Thursday, April 30, 2009

HttpHandler for Displaying Resized images.

How to resize image in asp.net with HttpHandler.

Some time we need to generate Images dynamically and display them on webpage.
In asp.net Using GDI+ we can resize images to fit them in area of our interest. after resizing we can either save them on disk.or can directly display them in webpage.when we display them directly. HttpHandler generate image in memory and send them as response to Client. We can Use asp.net's Image control to display this response directly.

Create GenericHttpHandler Named ImageHandler.ashx and put it in you root directory.
This handler take relative path yof Image and Intended size as input. In response send image with propotional Height and Width. we can Use asp:Image to display this Image.

This Is The Handler to Generate Image.

<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO.Compression;
public class ImageHandler : IHttpHandler
{
//Gets a value indicating whether another request can use the this IHttpHandler instance.
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
// Set up the response settings
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
//Gets or sets a value indicating whether to buffer output and send it after the complete page is finished processing.
context.Response.BufferOutput = false;
string PhotoPath = context.Request.QueryString["PhotoPath"] != null ? context.Request.QueryString["PhotoPath"].ToString() : string.Empty;
int Size = context.Request.QueryString["Size"] != null ? Convert.ToInt32(context.Request.QueryString["Size"]) : 0;
if (PhotoPath != string.Empty && Size != 0)
{
PhotoPath = context.Request.QueryString["PhotoPath"];
byte[] b = ResizeImageFile(context.Server.MapPath("~/") + PhotoPath, Size);
context.Response.OutputStream.Write(b, 0, b.Length);
}
else
{
//Throw Exception if Input parameters ar Invalid Or null
throw new Exception("Invalid Parameters");
}
}
public static byte[] ResizeImageFile(string imageFile, int targetSize)
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromFile(imageFile))
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream Imagememory = new MemoryStream();
newImage.Save(Imagememory, ImageFormat.Png);
return Imagememory.GetBuffer();
}
}
}
}
private static Size CalculateDimensions(Size oldSize, int targetSize)
{
Size newSize = new Size();
if (oldSize.Height > oldSize.Width)
{
newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
newSize.Height = targetSize;
}
else
{
newSize.Width = targetSize;
newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
}
return newSize;
}
}



This is How To Use this handler im aspx Page..

<asp:Image ID="imgNew" runat="server" ImageUrl="~/ImageHandler.ashx?PhotoPath=Images/ESNWRedEnvelope.jpg&Size=100" />

Thanks.

Friday, April 24, 2009

How to Load CSS According to browser using javascript.

We can load css dynamically as per browser versions.
here is the very simple function for loading css dynamically in any browser.
this javascript will work in all browsers which supports javascript.

function LoadCss()
{
var cssPath="";
if (navigator.appVersion.indexOf("MSIE 6.0") != -1)
{
cssPath="CssForIE60.css";
}
else if(navigator.appVersion.indexOf("MSIE 7.0") != -1)
{
cssPath="CssForIE70.css";
}
else
{
cssPath="GeneralCss.css";
}
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = cssPath;
cssNode.media = 'screen';
headID.appendChild(cssNode);
}


Above function will Create Dynamic javascript element(link) and appent it with head of DOM.

this function also can be modified for loading css dynamically in DOM using javascript.
hope this will help you.

thanks.

How to Generate MD5 hash of a string In C#.

How to Generate MD5 hash of a string In C#.
we can genetrate Hash of string in C# using various hashing algorithms.
method to generate hashed string is same for all algorithm.
.Net have many hashing algorithms like for Computing hash string.
eg. MD5 ,SHA1 etc.

(1)Create object of particular algorithm.
(2)Call ComputeHash method on your data.

method ComputeHash Takes Byte array as argument so we will Convert input data in byte array and that pass it to Compute Hash.we will use Encoding namespace to convert data in byte array.
we have to include namespaces.

(1)using System.Security.Cryptography;
(2)using System.Text;

here is the method to Generate Hashed String for UserData.this method will take string as input and returns hashed string.



public static string GetMD5HasCode(string UserData)
{
string HashedOutPut = string.Empty;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedBytes;
UTF8Encoding encoder = new UTF8Encoding();
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(UserData));
for (int i = 0; i < hashedBytes.Length; i++)
{
HashedOutPut += hashedBytes[i].ToString("x2").ToLower();
}
return HashedOutPut;
}


above function will return String of input string in Hexadecimal.
we can Use different format modifire to change output in various formats available.
ex.

F=Real Numbers
X=Hexadecimal
C=Currency

Thanks.

Wednesday, April 22, 2009

SessionID changes after each post back or each refresh of page.

SessionID changes after each post back or each refresh of page.

if you have problem of changing sessionID (Session.SessionID) on each post back or refresh.
you can add Global.asax file In your Application.

Once i Got this problem.i dont know why this happning. But i found Solution
by help of my friend.

you can Add Global.asax in your application folder

OR

You can Declare dummy session in Your Page Load event handler.
eg.

Session["Dummy"]="";

if you find and other solution or reason for this problem please leave
a comment.

Thanks.

How to Store ViewState in Cache Memory

How to Store viewState in Cache Memory.
asp.net provides us pluggable mechanism for storing viewstate to custome store.
this custom can be Session,Cache or FileSystem.we can use any of this to store viewsate.
storing viewstate in Cache memory helps us to reduce pagesize.because on each postback we can reduce bandwidth used to send ViewState data back and forth.
asp.net provide events to plug persistent store for ViewState.

(1)SavePageStateToPersistenceMedium
(2)LoadPageStateFromPersistenceMedium

We can override this for stor viewState data in Cache memory.
To see this In Action Override obove methods in Your code behind.
or Copy Below code.


public partial class EventModel : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
Response.Write("In Is Page Load");
}
protected override void SavePageStateToPersistenceMedium(Object viewState)
{
string ChachedViewStateKey;
ChachedViewStateKey = "__VIEWSTATE_" + Session.SessionID;
Cache.Insert(ChachedViewStateKey, viewState, null, System.DateTime.Now.AddMinutes(Session.Timeout), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
ClientScript.RegisterHiddenField("__VIEWSTATE_Key", ChachedViewStateKey);
}
protected override object LoadPageStateFromPersistenceMedium()
{
string ChachedViewStateKey = Request.Form["__VIEWSTATE_Key"];
if (ChachedViewStateKey == null)
{
return null;
}
else
{
return Cache[ChachedViewStateKey];
}
}
}


we can also save viewstate in file system.

Thanks.

Tuesday, April 21, 2009

How to select XML data as SQL table in SQl server 2005

How to select XML data as SQL table in SQl server 2005.

we can query xml datatype in sql server to retrive all nodes as SQL table.
xml datatype is new in SQL Server 2005.

if we have XML data like :

declare @UserXML XML

set @UserXML='<Users><User><ID>1</ID><Name>Haresh,Herry</Name><IsLoggedIn>1</IsLoggedIn>
</User><User><ID>2</ID><Name>Paresh,Pariyo,Perry</Name><IsLoggedIn>1</IsLoggedIn>
</User><User><ID>3</ID><Name>Ajay,Sinh,Bapu</Name><IsLoggedIn>1</IsLoggedIn>
</User><User><ID>4</ID><Name>Abhijit</Name></User></Users>'


We can query them as :

SELECT tableName.columnName.value('ID[1]','int')AS ID, tableName.columnName.value('Name[1]','VARCHAR(100)')AS [Name], tableName.columnName.value('IsLoggedIn[1]','bit')AS IsLoggedIn
FROM @UserXML.nodes('//User') tableName(columnName)


after executing above Query output will be:


Figure-1(Output)







Thanks.



How to store and read Cookies in asp.net/C#.

How to store and read Cookies in asp.net/C#.

We can have requirement to store cookies in client machine for later use. we can use HttpCookie Class to do this task.

How to Store:
this function will save them on client machine.

private void SetCookies()
{
HttpCookie SearchCookies = new HttpCookie("SearchCookies");
SearchCookies.Expires = DateTime.Now.AddMonths(1);
SearchCookies.Values.Add("Range", radComboRange.SelectedIndex.ToString());
Response.Cookies.Add(SearchCookies);
}



How to Read:
this function will read from Request Object(client machine) and Save cookie value in ViewState.


private void GetCookies()
{
HttpCookie SearchCookies = Request.Cookies["SearchCookies"];
if (SearchCookies != null)
{
if (SearchCookies.Values["Range"] != null)
{
ViewState["Range"] = radComboRange.SelectedIndex = int.Parse(SearchCookies.Values["Range"]);
}
}
}


Thanks.

Friday, April 17, 2009

How to remove Invalid character in Sql server string.

How to remove Invalid character in Sql server string.

How to remove Invalid character in Sql server string.
Suppose you have a string in sql sever which contains Invalid charasters lik *&^%$ etc.
you want plain string without this characters. I develop one function for that ..

this function takes two arguments
(1)String which contains Invalid characters
(2)string of characters whic need to be removed.
and resurns plain string.


CREATE Function RemoveInvalid
(
@InputString varchar(8000),
@InvalidChars varchar(20)
)returns varchar(8000)
as
BEGIN
declare @strMain varchar(8000)
declare @charsToReplace varchar(20)
set @charsToReplace =@InvalidChars
set @strMain=@InputString
declare @i int
set @i=len(@charsToReplace)
while(@i>0)
Begin
declare @tmp char
set @tmp= substring(@charsToReplace,@i,len(@charsToReplace))
set @strMain= replace(LTRIM(RTRIM(@strMain)),@tmp,'')
set @i=@i-1
End
Return @strMain
END



Suppose You Have string Like "'haresh#*^ xxyy','*x #^"
and you want to remove "*x #^" . this function will remove *,space,#,^ from given string.and returns only "hareshyy"

Thanks.

How to Perform Update Operation With Join in SQL server.

How to Perform Update Operation With Join in SQL server.

How to Perform Update Operation With Join in SQL server.

we can Update any tables data in conjuction with join operation. In case when you have to Update multiple records without where condition and based on some Critearea you can use join with update statement. I have a XML string and want to update all records whose ID contains in this XML string.

Declare @XML xml
set @XML='11112'
Update User_mst set [Name]='Haresh,Herry' from
(
select ParamValues.[Name].value('.','VARCHAR(200)') as [Name]
FROM @XML.nodes('/Project/Id') as ParamValues([Name])
) as N inner join User_mst usr on usr.Id=N.[Name]


Thanks.

How to list all comma separated values in all columns of a tabele as single.

How to list all comma separated values in all columns of a table as single column.
If you have a table in SQl like:

[Figure-1 Table with RowData]





and if you want this tables select data as table like:

[Figure-2 RESULT]





we can use XML to SQL Using XML datatype of SQl server 2005 and above.XML datatype
is new datatype in sql server 2005. We can user SQL Statements to select data from XML string.this xml datatype helps us great to do many complex operation in less line of code.
here is the example.

--Create tabel and insert data to see this example in action.
CREATE TABLE [dbo].[User_mst](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50)

CONSTRAINT [PK_User_mst] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

--Insert Data
insert into [User_mst1] ([Name]) values('Haresh,Herry')
insert into [User_mst1] ([Name]) values('Paresh,Pariyo,Perry')
insert into [User_mst1] ([Name]) values('Ajay,Sinh,Bapu')
insert into [User_mst1] ([Name]) values('Abhijit')
after completing object creation we can use followint Query to select all comma separated values of each row to a single column..

--Declared for storing Selected XML
declare @ColumnAsXmlString varchar(8000)
--select Comumn as XML
set @ColumnAsXmlString=(select replace([Name],',','') as NM from User_mst for XML path(''))
--replace <with <>
set @ColumnAsXmlString=replace(@ColumnAsXmlString,'<','<') set @ColumnAsXmlString=replace(@ColumnAsXmlString,'>','>')

-- @ColumnXML as XML datatype
declare @ColumnXML as xml
--Cast string to xml
set @ColumnXML= cast(@ColumnAsXmlString as xml)
--fire Query on XMLdatatype(@ColumnXML) to select All values in XML string as Table

select ParamValues.[Name].value('.','VARCHAR(200)') as [Name]
FROM @ColumnXML.nodes('/NM') as ParamValues([Name]) .
After Runnig this you will get result (Fugure-2).
Thanks.

How to split comma separated string in sql server

How to split comma separated string in sql server

this is the function i found after some Googling.
Which Tekes Two Arguments and Returns A table which contains all Values separated by comma in a Column of table.

(1)String Separated With some character.
(2)characted from where to split string.


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[SplitString]
(
@StringToSplit nvarchar(2000),
@SplitFrom nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1

While (Charindex(@SplitFrom,@StringToSplit)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@StringToSplit,1,Charindex(@SplitFrom,@StringToSplit)-1)))

Set @StringToSplit = Substring(@StringToSplit,Charindex(@SplitFrom,@StringToSplit)+1,len(@StringToSplit))
Set @Cnt = @Cnt + 1
End

Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@StringToSplit))

Return
END


How To Call:


After CReating this function We can call it like a table.

select * from [dbo].[SplitString]('a,b,c',',')

you can Find More Details on

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

Thanks.

Thursday, April 16, 2009

Highlighting/Toggle Highlighting words on page using javascript

Highlighting/Toggle Highlighting words on page using javascript..

in many site we found that they are highliting words on their page accourding requirement.
once i need to highlight all words on page as hyperlink.I used JQuery and make a function
for that.
This function accept an array of words and highlight all words from array on the page.
JQuery helps me alot to do this with minimum time and efforts.
Belo function will search your words in div,span and p tag,make it hyperlink by replacing word with html.
you can also use this function to toggle highlighting of words in the array.
In shotr this is the function to highlight words on page using javascript.
or function to toggle highlight words on page using javascript.


<script type="text/javascript" language="javascript">
var flag=true;
var inputArray=["haresh","dhameliya"];
function ToggleHighlight()
{
var wordArray=inputArray;
if(flag)
{
$("p,span,div").each(function()
{
var tmpText=$(this).html();
for(var i=0;i<wordArray.length;i++)
{
var sRegExInput;
sRegExInput = new RegExp(wordArray[i], "gi");
tmpText=tmpText.replace(sRegExInput,'<span class="tmp"><a href="#"><b>'+wordArray[i]+'<\/b><\/a></span>');
}
$(this).html(tmpText);
})
}
else
{
for(var i=0;i<wordArray.length;i++)
{
$(".tmp:contains("+wordArray[i]+")").replaceWith(wordArray[i]);
}
}
flag=!flag;
}
</script>


Thank to JQuery.

Wednesday, April 15, 2009

Fill DropDownlist with javascript and xmlHttp.

Fill DropDownlist/Combobox/Select with javascript and xmlHttp and JQuery.

Reading XML files with JQuery is very easy nowadays. we can use ajax(JQuery) to get Xml file asynchonously on client machine. then We can fill options with nodes in xml file. Suppose we have select/option on my html page.

<select id="drpStudents">
</select>


We have xml file of students which required to fill in select/option list.

<?xml version="1.0" encoding="utf-8" ?>
<students>
<student id="1">
<name>
<lname>
dhameliya
</lname>
<fname>
haresh
</fname>
</name>
</student>
<student id="2">
<name>
<lname>
Patel
</lname>
<fname>
Naresh
</fname>
</name>
</student>
</students>


and we want to fill select/option with JQuery. here is the function to fill dropdown with javascript and xmlHttp using JQuery this.You have to include referance of JQuery on your page to accomplish this task..

JQuery can be downloaded from http://docs.jquery.com/Downloading_jQuery

function FillDropdownList(XmlPath)
{
$(document).ready(function()
{
$.ajax({
type: "GET",
url: XmlPath,
dataType: "xml",
success: FillData
});
});
function FillData(xml)
{
//Search every Student and Extract Name to fillup dropdownlist.
$(xml).find("student").each(function()
{
var drpStudents=document.getElementById("drpStudents");
drpStudents.options[drpStudents.options.length]=new Option($(this).find("fname").text(),$(this).attr("id"));
});
}
}


this function Get path of xml file as input parameter..thats done.

thanks..
happy programming..

Friday, April 10, 2009

Building Efficient & Dynamic Query in SQl server.

Parameterized Dynamic Sql Query.
We often need to create dynamic queries inside Stored procedure in sql server.
for that we concatenate DML statements and input parameter of stored procedure and a string of statements. And than Use Exec statement to execute those statements..

CREATE Procedure GetUsers
@ID int =0,
@UserID int=0
as BEGIN
declare @Query nvarchar(500)
set @Query='select * from Your_TableName where ID>'+cast(@ID as varchar(100))+' and UserID >'+cast(@UserID as varchar(100))
exec (@Query)
END --exec GetUsers 14,45


This is not good practice for some reasons.
(1)it leads possibility of sql injection.
(2)it is not efficient because it is not precompiled.
(3)each time it will consume new memory because it’s caching will not managed.

I have anothere approach to do that that is Parameterized Dynamic sql query.
It almost take same time to create and resolve issue mentiones. To do that we just need to .

(1) Declare a string of sql statements.
(2) string of declaration of parameter you want to pass in this string.

CREATE Procedure GetUsers
@ID int =0,
@UserID int=0
as BEGIN

declare @Query nvarchar(500) --Statements to execure
declare @Parameters nvarchar(500) --Parameters to pass in
set @Query='select * from NHA_mstBuilders where ID>@QID and UserID>@QUserID'
set @Parameters='@QID int,@QUserID int'--parameter declaration
exec sp_executesql @Query,@Parameters,@QID=@ID,@QUserID=@UserID --pass statements,then parameters and then assing values to that parameters.
END --exec GetUsers 14,45


Than use sp_exectesql to execute dynamic query..

Value of output parameter truncates.Why?

why value of output parameter truncated in asp.net?? Here is the possibel reason.....
In database programming with SQL-Server and C# Some time we use output parameters to get value From database to C# variable.
There is one constructor of sql parameter which takes two arguments.
(1)parameter name.(2)Default value.

SqlParameter sp = new SqlParameter("@Name","");

When you provide default value and you are not providing Size of parameter Default size will be the length of default value.
In above case size of parameter will be 1. So sql will return only single character as output.
To avoid this problem you have to provide size of output parameter in C#.

sp.Size = 5;

Thanks.

Wednesday, April 8, 2009

How to call asp.net page method from javascript using scriptmanager

In Asp.Net 3.5 you can call any method of your .aspx page By Javascript Function..
    
    this is possible because new feature ScriptService in asp.net.
    
    To call page method from javascript:
    
    (1)methos should be declared as Public and Static
    (2)[WebMethod] attribute must be attached with methos.   
    (3)At least One ScriptManager Should be on Page.
    (4)Set EnablePageMethods of ScriptManager to "true" 
    
    once you complete this steps.
    Here is the server side methos looks like:
    
    [WebMethod]
    public static string GetName(string Name)
    {
        return "Hello " + Name + "!!!";
    }
    
    now you have to write function in javascript that notify whether method call was successfull or failed.
    
    function onSuccess(data)
    {
        alert(data);
    }
    function onFail(error)
    {
        alert("Failed");
    }
    
    After Writing this You can Call GetName method of your asp.net Page like:    
    
    PageMethods.GetName("http://dhameliya.blogspot.com",onSuccess,onFail,null);    
     
    here  first parameter is argument,second one is Success Callback and third one is Failure Callbak..
    
    Hope this will will help you .
    Thanks..

Java Sonic - ListenUp Secutiry Exception.

Hi Friends.
I Have Used ListenUp Applet for A Voice Recording Web Application..In Some browsers it records voice Without any Exception.But In Older versions due some strange reeason This Applte Throws A Secutrity Exception ..I Dont'Know Why??
The Exception Is:

ListenUp version V1.90 (build 406, Mon Nov 17 00:00:00 IST 2008)Caught: java.lang.SecurityException: access denied (javax.sound.sampled.AudioPermission record)

this applet says this because you did not grant permission when the certificate appeared. In fat no certificate was Appeared.. So What is The solutions of this Issue.. After Some Googling i Found god one..
Solution:
(1)Find out Wherethis java applte Installed on your machine.
in my case system drive is C:\ so applet path is:C:\Program Files\Java\j2re1.4.1_01

(2)Find Java.Policy File (C:\Program Files\Java\j2re1.4.1_01\lib\security\java.policy).

(3)Add Code Below at the End of java Policy file..

grant { permission javax.sound.sampled.AudioPermission "record"; };
(4)Restart Your Browser

.. After Installing this code Java.policy will looks like..

// Standard extensions get all permissions by default grant codeBase "file:${java.home}/lib/ext/*" { permission java.security.AllPermission; }; // default permissions granted to all domains grant { // Allows any thread to stop itself using the java.lang.Thread.stop() // method that takes no argument. // Note that this permission is granted by default only to remain // backwards compatible. // It is strongly recommended that you either remove this permission // from this policy file or further restrict it to code sources // that you specify, because Thread.stop() is potentially unsafe. // See "http://java.sun.com/notes" for more information. permission java.lang.RuntimePermission "stopThread"; // allows anyone to listen on un-privileged ports permission java.net.SocketPermission "localhost:1024-", "listen"; // "standard" properies that can be read by anyone permission java.util.PropertyPermission "java.version", "read"; permission java.util.PropertyPermission "java.vendor", "read"; permission java.util.PropertyPermission "java.vendor.url", "read"; permission java.util.PropertyPermission "java.class.version", "read"; permission java.util.PropertyPermission "os.name", "read"; permission java.util.PropertyPermission "os.version", "read"; permission java.util.PropertyPermission "os.arch", "read"; permission java.util.PropertyPermission "file.separator", "read"; permission java.util.PropertyPermission "path.separator", "read"; permission java.util.PropertyPermission "line.separator", "read"; permission java.util.PropertyPermission "java.specification.version", "read"; permission java.util.PropertyPermission "java.specification.vendor", "read"; permission java.util.PropertyPermission "java.specification.name", "read"; permission java.util.PropertyPermission "java.vm.specification.version", "read"; permission java.util.PropertyPermission "java.vm.specification.vendor", "read"; permission java.util.PropertyPermission "java.vm.specification.name", "read"; permission java.util.PropertyPermission "java.vm.version", "read"; permission java.util.PropertyPermission "java.vm.vendor", "read"; permission java.util.PropertyPermission "java.vm.name", "read"; }; grant { permission javax.sound.sampled.AudioPermission "record"; };

Now you will be able to record voice Successfully..
Hope This will useful to you.
Thanks.

Tuesday, April 7, 2009

How to Print output of single asp.net control.

I Write Code in C# to print output of Single Control..
We Can Use this function for printing Grid,Table,Div etc Controls.
Importent thing here is tmpPage.RenderControl Method of Page object. Which Will Write HTML Exposed by Control in String Variable..Write it to response of Current Context
and then Use Window.print to print Response of the page.

public void PrintThis(Control ctrl)
{
StringWriter tmpStringWriter = new StringWriter();
System.Web.UI.HtmlTextWriter tmphtmlWrite = new System.Web.UI.HtmlTextWriter(tmpStringWriter);
//Declare Form
HtmlForm tmpform = new HtmlForm();
tmpform.Attributes.Add("runat", "server");
//Declare Page
Page tmpPage = new Page();
tmpPage.EnableEventValidation = false;
tmpPage.Controls.Add(tmpform);
//Add Form Control To Page
tmpform.Controls.Add(ctrl);
//Initialize page
tmpPage.DesignerInitialize();
//Render Page OutPut
tmpPage.RenderControl(tmphtmlWrite);
//Get Output string in String Varuable
string tmpstrHTML = tmpStringWriter.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(tmpstrHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>
");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}


Hop this will help You.
Thanks..

How to get output of one aspx page from another aspx page in asp.net using C# Code.

In Your aspx Page you.

(1).Import
using System.IO;
using System.Text;

(2).Use Server.Execute method.

protected void Page_Load(object sender, EventArgs e)
{
StringWriter strWriter = new StringWriter();
Server.Execute("~/Login.aspx", strWriter, false);
string str = strWriter.ToString();
}

variable str will contains Whole Html Output of Login.aspx page.

Thanks..

Monday, April 6, 2009

How to Use New XML Datatype of sql server to pass data in SQL Server Instead Comma Separated values.

Hi Friends..
Working with SQL database we often need to pass comma separated values for many reasons.
eg.Inserting multiple record ,Updating Multiple records or deleting multiple records.
In such conditon we generally think of Comma separated values.which will be separated by looping in SQL server.and used as per our case. Instead of this you can Use XML string .SQL Server 2005 Supports XML Data tyape using read XML file and XML string Using XQuery..
Lets See How??
declare @XMLData as XML

set @XMLData='<Messages><Message><ID>94</ID><RID>1</RID><Message>HI</Message><PostedDate>2009-04-06T01:35:26.437</PostedDate></Message><Message><ID>95</ID><RID>1</RID><Message>HUA</Message><PostedDate>2009-04-06T01:36:26</PostedDate></Message><Message><ID>96</ID><RID>1</RID><Message>Majama?</Message><PostedDate>2009-04-06T01:37:26</PostedDate></Message><Message><ID>97</ID><RID>1</RID><Message>HA</Message><PostedDate>2009-04-06T01:38:26</PostedDate></Message></Messages>';


DECLARE @handle INT

EXEC sp_xml_preparedocument @handle OUTPUT, @XMLData

SELECT * FROM OPENXML (@handle, '/Messages/Message', 2)
WITH ( ID VARCHAR(20),
RID NVARCHAR(20),
PostedDate NVARCHAR(20)
) tmpSqlTable

tmpSqlTable you Will get all data in XML String as SQL Table.
you can use this table for joining with other table or inserting data in sql table..
Hope This Will Help You .
Thanks....

Length Required error For Mozilla(Error Code-411)

Hi Friends..

While you Developing webapplication with XmlHttp Object
If You Get This error With Error Code 411.
You can Solve this By Spacyfying Content Length Property Of XmlHttp object..
xmlhttp.open("GET","Your Url Generationg Response.aspx .ashx",true);
xmlhttp.setRequestHeader('Content-Type', 'text/html');
xmlhttp.setRequestHeader('Content-length', '1000');

This Error Occurs only in Mozilla not on Safari and I.E

Thanks..

Truncated responseText Problem of XmlHttp Object in I.E

Hi Friends..
have you ever Work XmlHttp Object for Async Request to server ??
if yes this stuff can help you some time in programming..
when you send request and get result in OnStateChange Event of XmlHttp object(xmlhttp.onreadystatechange ).

Some time In Some browsers like (I.E 7) you output Will Truncated..

For Example:
Your server returns "Hi Haresh Dhameliya!!How R U??.......This Will Truncated.."
and in output(xmlhttp.responseText) will Get Only "Hi Haresh Dhameliya!!How R U??"
then you have to Find Solution.
Here is the Solution..
(1):Internet Explorer
I.E Cause this if You Have Use GET Method like:

xmlhttp.open("GET","Your Url Generationg Response.aspx .ashx",true);

To Solve This In Case of I.E You Have To Put.

xmlhttp.open("POST","Your Url Generationg Response.aspx .ashx",true);

If you Write Post In Place of GET I.E Will not Cause Truncation of responseText.
This is Strange problem.I cant geting why this occurs in I.E ??
please tell me if u know..or you have other solution than this..
Thanks..

Sunday, April 5, 2009

Find Distance between two Geographical points Using SQl Server..

Hi Friends...
If you have ever worked with google map you will find this most interesting..
Google map provides API for integrating interactive map in you web Apllication.
You can find out Place on map By providing Address of that Place.for that Google provides Built-In API functions.
Any Place on the earth can Exactly Located By it's Latitude and Lonitude .
if you have this Latitude and Longitude you can Use Trigonomatry to Find out Distance Between Two Places on the earth.....

Depending Your Application's Business Logic You Need to find it In your Javascript Code,SQL Server,or IN C# or Whats ever you like..
For My need i Developed it With Sql Server.

This is My Function..

ALTER function [dbo].[CalculateDistance](@latitudet1 numeric(18,10),@latutudet2 numeric(18,10),@longitude1 numeric(18,10),@longitude2 numeric(18,10))
returns numeric(18,10)
as
Begin


declare @radious numeric(18,8)
set @radious=3963.1

declare @pi numeric(18,15)
set @pi=3.14159265358979323846

declare @lat_1 numeric(18,8)
set @lat_1=cast(@latitudet1 as numeric(18,5)) * ( @pi / 180)

declare @lat_2 numeric(18,8)
set @lat_2= @latutudet2 * (@pi / 180)

declare @lon_1 numeric(18,8)
set @lon_1= @longitude1 * (@pi / 180)

declare @lon_2 numeric(18,8)
set @lon_2= @longitude2 * (@pi / 180)

declare @distance numeric(18,8)
set @distance= (Acos(Cos(@lat_1) * Cos(@lon_1) * Cos(@lat_2) * Cos(@lon_2) + Cos (@lat_1) * Sin(@lon_1) * Cos(@lat_2) * Sin(@lon_2) + Sin(@lat_1) * Sin(@lat_2)) * @radious)

return @distance

END
--Select [dbo].[CalculateDistance] (1,4,7,9)


To Calcuate distance between two point Provide their Latitude and Longitude as argument This function will resurt distance in mile..
you can convert this Distance in kilometer multilyig by 1.6
I also have this function in C# language..Using C# u can calculate distance between two points ..
You can Find this on ..
http://forum.softwebsolutions.com/forum/default.aspx?g=posts&t=49...
Hope this will Help You...
Happy Programming..

Saturday, April 4, 2009

Split String In Javascript.

Hi Friends.here we will see How to split string in javasript..

Like C# Function You can Also Split string from some characters.

for example to split String

(1)var str1="123456789";

we can use regular expression

(1)var tmpArr= str1.match(/[1-9]/g)

In Example (1) str1.match will return Array of matching elements .

array tmpArr will contain array of elements (1,2,3,4,5,6,7,8,9)

(2)var str2="1,2,3,a,b,c";

We can Use Split function of string object.

(2) var tmpArr= str2.split(',');

In Example (2) array tmpArray Contains elements separated from character (,)

You can also use Regular Expression as argument of Split Function.

this will help you in splition string from multiple characters

(3)var str3="1,2,3-4,5,6";

to split this from( , ) as well ( - ) you can use Below Javascript.

(3) var tmpArr=str3.split(/[,-]/);

here tmpArray Contains 1,2,3,4,5,6 as Elements...


Thanks..