Server side variable in databinding

Jquery Ajax Message reading techniques

It is a time where almost every Asp.net web developer is aware of Jquery, its usage and ajax.
Using Jquery Ajax in Asp.net with JSON is no more a hot topic.



This is one of the ajax example below.


function LoadDropDown() {
$.ajax({
type: "POST",
url: "http://localhost/Line/JqueryMethods/JqueryAjax.aspx/LoadCountries",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("<option value='0'>Select</option>").appendTo('#<%=ddlCountries.ClientID %>');
$('#<%=imgCountry.ClientID %>').attr("Src", ("Common/_assets/img/flags/XX.png"));
for (var i = 0; i <= msg.d.length - 1; i++) {
$("<option value='" + msg.d[i].ID + "'>" +
  msg.d[i].COUNTRY1 + ":" + msg.d[i].TLD + "</option>").appendTo('#<%=ddlCountries.ClientID %>');
                    }
}
});
}

here I want to show how to read the return value of the server side method.
I had a big issue once with asp.net 2.0 , 3.5 and different version of jquery.
so if any one have issues on how to read the return values then here is below
note: above example is reading a List<> object.

1. msg
function(msg) {
$('#Divid').html(eval(msg)) ;
},
2. msg.d
function(msg) {
$('#Divid').html(eval(msg.d)) ;
},

3. eval('(' + msg + ')').d
function(msg) {
$('#Divid').html(eval('(' + msg + ')').d)
},


I spent more than 4 hrs on this ways because of no clue, whether using 3.5 sp1, or different versions of jquery. But just using "debugger;" we can easily findout which is suitable.

Happy coding ;)

Tree structure in MSSQL 2005 Hierarchy.( Comment child lists )

Here comes another approach to build the tree structure - hierarchial flow of information. This is an simple and raw approach but effective to show the structure of hierarchy.

Let us create the database now....






GO
/****** Object: Table [dbo].[Comments] Script Date: 10/12/2009 14:06:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Comments](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Type] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Comment] [varchar](800) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Title] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[CreatedBy] [uniqueidentifier] NULL,
[CreateTime] [datetime] NULL,
[ModifiedBy] [uniqueidentifier] NULL,
[Modifiedtime] [datetime] NULL,
[IPAddress] [varchar](18) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[RefComment] [int] NULL,
[Blocked] [bit] NULL,
[Rating] [int] NULL,
[ImageURL] [varchar](200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Comments_ImageURL] DEFAULT ('a'),
CONSTRAINT [PK_Comments] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF



Now Stored Procedure.


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROC [dbo].[ShowComments]
(
@Root int
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @ID int, @Comments varchar(2800)
--SET @Comments = (SELECT id+'*Comments*'+Comment+'*CreatedBy*'+CreatedBy+'*CreateTime*'+CreateTime+'*IPAddress*'+IPAddress+'*Rating*'+Rating+'*ImageURL*'+ImageURL FROM comments WHERE ID = @Root)

--SET @Comments = (SELECT '<root><id>'+CAST(id as varchar(10))+'</id><comment>'+Comment+'</comment><createdby>'+CAST(CreatedBy as varchar(36))+'</createdby><createdtime>'+CAST(CreateTime as varchar(15))+'</createdtime><ip>'+CAST(IPAddress as varchar(15)) +'<ip><image>'+ ImageURL +'</image><rating>'+CAST(Rating as varchar(15))+'</rating></root>' FROM comments WHERE ID = @Root)
SET @Comments = (SELECT '<root><id>'+CAST(id as varchar(10))+'</id><comment>'+Comment+'</comment><createdby>'+CAST(CreatedBy as varchar(36))+'</createdby><createdtime>'+Convert(nvarchar,CreateTime,103)+' '+Convert(nvarchar,CreateTime,114) +'</createdtime><ip>'+CAST(IPAddress as varchar(15)) +'<ip><image>'+ ImageURL +'</image><rating>'+CAST(Rating as varchar(15))+'</rating></root>' FROM comments WHERE ID = @Root)
PRINT REPLICATE('-', @@NESTLEVEL * 4) + @Comments
SET @ID = (SELECT MIN(ID) FROM comments WHERE RefComment = @Root )
WHILE @ID IS NOT NULL
BEGIN
EXEC ShowComments @ID
SET @ID = (SELECT MIN(ID) FROM comments WHERE RefComment = @Root AND ID > @ID )
END
END







MSSql Hierarchial- Comment like tree structure.

Approach 1:



USE [StudentInfo]
GO
/****** Object: Table [dbo].[Testcomments] Script Date: 10/12/2009 13:51:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Testcomments](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DeviceType] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[ParentId] [int] NULL,
CONSTRAINT [PK_Testcomments] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (1, N'Object ', NULL)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (2, N'WebServer', 4)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (3, N'Database Server', 4)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (4, N'Server', 1)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (5, N'File Server', 4)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (6, N'Mail Server ', 4)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (7, N'IIS web server', 2)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (8, N'Virtual servers', 4)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (9, N'V S Guest OS', 8)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (10, N'VS Hosts', 8)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (11, N'New master', NULL)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (12, N'new master child', 11)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (13, N'new child1', 12)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (14, N'new child2', 13)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (15, N'new child4', 11)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (16, N'new child5', 12)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (17, N'new child6', 12)
INSERT [dbo].[Testcomments] ([Id], [DeviceType], [ParentId]) VALUES (19, N'new child7', 13)








Stored procedure







set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

-- this can be used when we know the last child node of the tree

alter PROC [dbo].[TestHierar]
AS
BEGIN
declare @ID int
set @ID = 19;
--SET @ID = (SELECT max(ID) FROM dbo.TestComments )
with Hierarchy(ParentID,ID,level,Devicetype,Sort) As
(

Select ParentId,Id,0,DeviceType,cast(DeviceType as nvarchar(1024))
from testcomments
where Id= @ID
union all
select dt.ParentId, dt.ID, level+1,dt.DeviceType , cast(Sort +'|'+dt.Devicetype as nvarchar(1024))
from TestComments dt inner join hierarchy h on dt.Id = h.parentId
)
,HierarchyReverse(ParentID,ID, level, DeviceType, Sort) as

(
select parentId, Id, 0, DeviceType, Cast(DeviceType as nvarchar(1024))
from hierarchy
where parentId is null
union all
Select h.parentId,h.id,hr.LEVEL+1, h.deviceType, cast(hr.Sort + '|' +h.sort as nvarchar(1024))
from Hierarchy h inner join HierarchyReverse hr on h.ParentId = hr.ID
)
select Id, ParentId, DeviceType, Level,Sort
from HierarchyReverse
order by sort


END












Key Points:
This approach is easy and very helpful to display the hierarchy either in treeview or any div structure using Jquery. Unfortunately it is helpful only when you have the last child id.
In stored proc for @ID you need to send the last child id.

There is an another approach of simple hierarchial structure in MSSQL 2005 in my next article.

Extract Internal and External CSS into a string using Javascript


While looking to generate HTML to PDF, i came across how to create PDF exactly as HTML using its stylesheet.
After working out for nearly 4 hrs I found something from Stackoverflow which extract inline and external css beautifully.

limitation: Right now this function extracts from current page...I need a dynamic rul where defining the url we can create PDF according to the stytle-sheet... Code is given below..

Ref:http://stackoverflow.com/questions/641221/how-to-use-jquery-or-similar-to-extract-all-of-the-css/1470384#1470384

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExtractStyleSheet.aspx.cs" Inherits="Common_UserControls_Lab_HtmltoPDF_ExtractStyleSheet" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="../../../_assets/css/addressbook.css" rel="stylesheet" type="text/css" />
<link href="../../../_assets/css/CleanForm.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.grid
{
font-family:Arial;
font-size:12px;
width:800px;
}
/* gridview styles */
.grid .gridview
{
width:100%;
border:solid 2px #5E8CC6;
empty-cells:show;
border-top-width:1px;
}
</style>
<script type="text/javascript" >
function getStyles() {
if (!document.styleSheets) return false; // return false if browser sucks
var rules = new Array();
for (var i = 0; i < document.styleSheets.length; i++) {
var x = 0;
styleSheet = document.styleSheets[i];
if (styleSheet.cssText) { // if this is IE, get the rules directly
rules.push(styleSheet.cssText);
} else {
// otherwise get them individually
do {
cssRule = styleSheet.cssRules[x];
if (cssRule) rules.push(cssRule.cssText);
x++;
} while (cssRule);
}
}
var compositeCSS = '';
debugger;
for (i = 0; i < rules.length ; i++) {
compositeCSS += rules[i];
}
return compositeCSS;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClientClick="getStyles()" Text="Button" />
</div>
</form>
</body>
</html>

Simple Asp.net -Google map by address without Geocode

Simple Asp.net -Google map by address without Geocode using Jquery 





Using google map in Asp.net is not a new stuff to rise your eye brow.
But yes a simple way of coding, understandable code and dynamic google map will definetly attract attention of a developer.


Since 2 months I was trying so many options, user controls which are bulk and difficult to understand. So since yesterday i thought let me make a simple one which i can use for dynamic address on google map and not with geocode or langitude or latitude.

Here we go...
Parent page (any page, html or aspx)
Let us assume we have an anchor, which will have href directed to a google map page ,
so we better send address by query string. like below
<a  href="javascript: window.open('http://localhost/Test/common/usercontrols/Generalmap.aspx?address=Banagalore,INDIA&id=4','Window1','menubar=no,width=550,height=550,toolbar=no');"  title="pageSlide Demo">Click for a pageSlide demo.</a>
where  address=Banagalore,INDIA is a dynamic address.

on clicking this anchor it will open a pop-up screen. so in our pop-up screen we must have..
1. a Jquery ref script
2. Google map api reference.... For this we need google api key.
For localhost you can use the same api key which i have used.
for other domain you can get api key here :

Now back to code, on ready func() we need to read the querystring (address).
Follow this code you will understand.







<div id="map" style="width:550px;height:550px;"></div>
<script src="../Scripts/jQuery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAIKI1RJamIEvP7_Du5ZGi6xS4M_PhMYp3D1A5cqeLLIOnkUYWYhS8jdwSdUjZxBwswqHipWYzfju7fA"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var originaladdress = null; // global variable to store address
qs();
var qsParm = new Array();
function qs() {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i = 0; i < parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0) {
var key = parms[i].substring(0, pos);
var val = parms[i].substring(pos + 1);
if (key == 'address') { // fill only the adddress
originaladdress = val;
}
}
}
}
var geocoder;
var map;
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(34, 0), 1);
geocoder = new GClientGeocoder();
var location = originaladdress; //$("#location").val();
var address = location;
geocoder.getLocations(address, addAddressToMap);
// addAddressToMap() is called when the geocoder returns an
// answer. It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
map.clearOverlays();
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address");
}
else {
place = response.Placemark[0]; // marking a label on the address.
point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
marker = new GMarker((point), 8);
map.addOverlay(marker);
marker.openInfoWindowHtml(place.address);
// optional for zooming purpose
ne = new GLatLng(place.Point.coordinates[1] + 0.05, place.Point.coordinates[0] + 0.05); // zooming the location
bound = new GLatLngBounds(point, ne);
map.setZoom(map.getBoundsZoomLevel(bound));
map.panTo(bound.getCenter());
}
}
return false;
});
</script>

Thats it, you got ur simple google map in your Asp.net application.

Happy coding

iTextsharp simple Image to PDF c#

Very simple code.


public void ImagetoPDF()
{
string pdfpath = Server.MapPath("PDFs");
string imagepath = Server.MapPath("Images");
Document doc = new Document();
try
{
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(Server.MapPath("") + "/testasp3.gif");
png.ScaleToFit(475f, 1500f);
doc.Add(png);
}
catch (DocumentException dex)
{
Response.Write(dex.Message);
}
catch (IOException ioex)
{
Response.Write(ioex.Message);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
doc.Close();
Response.Redirect("PDFs/Images.pdf");
}
}

Wireless Zero Configuration auto start on boot

Start > Run > sc config wzcsvc start= auto&sc start wzcsvc



Done. :)

UserControl Javascript Worst problem and Best Solution

Working on Jquery is fun and exciting. Same time it makes us to scratch our head countless times. :)

I was making a User Control which will have a dropdown and a image control, in which dropdown which loads countries.
On selecting a country in dropdown it has to show selected country flag image and the tooltip is to show the details of the country yes without any postback and using Jquery.

It was simple and used this...


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.ddlCountries.Attributes.Add("onchange", "getCountryDescription()");
}
}




and ASPX:


<script type="text/javascript">
function getCountryDescription() {
$.ajax({
type: "POST",
url: "http://localhost/OnActionC/JqueryMethods/JqueryAjax.aspx/LoadFlag",
data: "{'StrCountryText':'" + $("#<%=ddlCountries.ClientID %> option:selected").text() + "', 'StrCountryValue':'" + $('#<%=ddlCountries.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#<%=imgCountry.ClientID %>').attr("Src", (msg.d[0]));
$('#<%=imgCountry.ClientID %>').attr("title", (msg.d[1]));
}
});
}
</script>




<div>
<asp:DropDownList ID="ddlCountries" class="grey" ForeColor="#FAFAFA" style="font-size:0.8em; background-color:#414141;" runat="server" >
</asp:DropDownList>
<a href="#" runat="server" id="countrytooltip" >
<img id="imgCountry" runat="server" alt="" />
</a>
</div>

This was pretty good and I used this user control in a screen which has 2 seperate controls in a single page...







Ohh!! there is a problem...i found.. we are calling a single function getCountryDescription
for both controls, even though the contorlid of individual are different it was causing the problem since one control was refereing to other...

So the possible solutions are :
1. Better create as many as functions as we use the user control in a single page.
Ohhh!! no... I cant do this... I cant afford to deal with this messy issue.

2. So the next idea was to make the function dynamic , yes so each control will refer to its corresponding function only, so the possible way is to play with ClientId.

then I made the following changes.





function getCountryDescription<%=ddlCountries.ClientID %>() {
$.ajax({
type: "POST",
url: "http://localhost/OnActionC/JqueryMethods/JqueryAjax.aspx/LoadFlag",
data: "{'StrCountryText':'" + $("#<%=ddlCountries.ClientID %> option:selected").text() + "', 'StrCountryValue':'" + $('#<%=ddlCountries.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#<%=imgCountry.ClientID %>').attr("Src", (msg.d[0]));
$('#<%=imgCountry.ClientID %>').attr("title", (msg.d[1]));
}
});
}

and





protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.ddlCountries.Attributes.Add("onchange", "getCountryDescription"+this.ddlCountries.ClientID+"()");
}
}

in c#.


Yes now i am able to use as many as user controls as i wish...

Happy coding.



Jquery javascript Dropdown selected value , Text

How to get the selected value of the dropdown in Jquery

var StrCountryValue = $('#<%=ddlCountries.ClientID %>').val();

to get selected text of the dropdown

var StrCountryText = $("#<%=ddlCountries.ClientID %> option:selected").text();