Tuesday, December 21, 2010

Distinct in XSLT

This Example Use for sort the year in xslt for this we need to get unique year id i.e. in xslt generic-id bases we can trace unique here example below:----

Test XML Feed Here:--
<state id="26179" status="Approved" golive="Wednesday, December 22, 2010" created="Wednesday, December 22, 2010" golivetime="9:00:00 AM" createdtime="9:42:11 AM" creator="Indigo Consulting">
<elements state="26179" parent="0">
<element id="97398" position="1" type="Custom">
<content>
<day>6</day>
<month>February</month>
<year>1996</year>
<title>testing first new2</title>
<historyimage />
</content>
</element>
<element id="97399" position="1" type="Custom">
<content>
<day>4</day>
<month>February</month>
<year>1996</year>
<title>testing first similar new2</title>
<historyimage />
</content>
</element>
<element id="97403" position="1" type="Custom">
<content>
<day>4</day>
<month>October</month>
<year>2012</year>
<title>testing first new5</title>
<historyimage />
</content>
</element>
</elements>
</state>

XSL Content:-
-----------
<xsl:key name="distinctYear" match="state/elements/element[@type = 'Custom']/content" use="./year"></xsl:key>

---Under Applytemplate section--------------
<xsl:for-each select="state/elements/element[@type='Custom']/content[generate-id(key('distinctYear', ./year)) = generate-id()]">
<xsl:sort select="year"/>
<li>
<a href="#{year}">
<xsl:value-of select="year" />
</a>
</li>
</xsl:for-each>

Sunday, December 19, 2010

ASP.NET 2.0 MasterPages and FindControl()

Argh. I'm going through an older application and replacing a somewhat complex scheme of user control templating with Master Pages today. For the most part this has been going real well until I hit a page that that relies on page inheritance where there's a common page base class that needs to have access to the controls on the page.

ASP.NET has never made this exactly easy, because the base class doesn't allow you access to the controls from the lower level as ASP.NET adds the properties higher up in the hierarchy. In the past I've been working around this by adding properties for the controls to the base class and then overriding these properties, but in ASP.NET 2.0 the control definitions are auto-generate with no chance to override the control definitions. The only workaround has been using FindControl() and dynamically retrieve the control definitions.

And this is where things get a bit tricky with MasterPages. The problem is that when you use MasterPages the page hierarchy drastically changes. Where a simple this.FindControl() used to give you a control instance you now have to drill into the container hierarchy pretty deeply just to get to the content container.

protected Label lblError = null;

protected DataGrid dgItemList = null;

protected void AssignControls()

{

this.lblError = this.FindControl("lblError") as Label;

this.dgItemList = this.FindControl("dgItemList") as DataGrid;

}

you now have to drill into the containership with code like this:

protected void AssignControls()

{

this.lblError = this.Master.FindControl("Content").FindControl("lblError") as Label;

this.dgItemList = this.Master.FindControl("Content").FindControl("dgItemList") as DataGrid;

}
Image Is below:-


This isn't so bad, except when you're trying to figure out how to get to your controls.

It really seems lame that Microsoft hasn't added a recursive FindControl() method to the Control class that drills into child containers. While this certainly isn't optimal in terms of performance it sure would make life a lot easier in a lot of situations, and this surely is one of them.

Not exactly rocket science to create a method that does this:

/// <summary>
/// Finds a Control recursively. Note finds the first match and exists
/// </summary>
/// <param name="ContainerCtl"></param>
/// <param name="IdToFind"></param>
/// <returns></returns>

public static Control FindControlRecursive(Control Root, string Id)

{

if (Root.ID == Id)

return Root;

foreach (Control Ctl in Root.Controls)

{

Control FoundCtl = FindControlRecursive(Ctl, Id);

if (FoundCtl != null)

return FoundCtl;

}

return null;

}

with this the code becomes:

/// <summary>
/// Assigns controls from the subclassed control to this instance so
/// we always can access the controls in our base class.
/// </summary>

protected void AssignControls()

{

this.lblError = wwWebUtils.FindControlRecursive(this.Master,"lblError") as Label;

this.dgItemList = wwWebUtils.FindControlRecursive(this.Master, "dgItemList") as DataGrid;

}


Image Is below:-




Although this is easier, I suspect it's better to do the explicit thing if that option is available to you as it probably has better performance. Also I suspect Microsoft didn't include this sort of a function in ASP.NET natively because there's potential ambiguity here – there could be more than one control Id that matches a name.

Tuesday, December 14, 2010

Read XML File Node Wise using with xml DocumentElement And display on label


XMl FILE Strecture
<?xml version="1.0" encoding="utf-8" ?>
<adminModules>
<Module id="1" parentid="0" url="javascript:void(0);" title="Locator" real="false" />
</adminModules>
===================
using System.Xml;
string strFileName = Server.MapPath("~/Modules/ModuleMenu/AdminModules.xml");
XmlDocument oXmlDoc = new XmlDocument();
try
{
oXmlDoc.Load(strFileName);
}
catch (Exception ex)
{
lblMessage.Text ="Error: " + ex.Message;
}
XmlNode oNode = oXmlDoc.DocumentElement;
lblMessage.Text += "Node Name: " + oNode.Name;
XmlNodeList oNodeList = oNode.SelectNodes("/adminModules/Module/@title");
lblMessage.Text += "NodeList count=" + oNodeList.Count;
for (int x = 0; x < oNodeList.Count; x++)
{
lblMessage.Text += "NodeList Item#" + x + " " + oNodeList.Item(x).InnerText;
}

Thursday, December 9, 2010

Split string in xsl/xslt

I have written code here for split the text in xsl. might be this is helpfull to you.
this is a function that split the string and print here..
<xsl:template name="SplitText">
<xsl:param name="inputString"/>
<xsl:param name="delimiter"/>
<xsl:choose>
<xsl:when test="contains($inputString, $delimiter)">
<xsl:value-of select="substring-before($inputString,$delimiter)"/>
<xsl:text disable-output-escaping = "no"> </xsl:text>
<xsl:call-template name="SplitText">
<xsl:with-param name="inputString" select="substring-after($inputString,$delimiter)"/>
<xsl:with-param name="delimiter" select="$delimiter"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:if test="$inputString != ''">
<xsl:value-of select="$inputString"/>
</xsl:if>
</xsl:otherwise>
</xsl:choose>
</xsl:template>


Here i have call the parent method with two parameters
1. Input string (Full string)
2. Delimiter (Split by char string)

In My example i have pass varModuleId that is some number with are separated by comma, which i need to split and use in code might be this will helpful to all
==================================

<xsl:call-template name="SplitText">
<xsl:with-param name="inputString" select="$varModuleId"/>
<xsl:with-param name="delimiter">,</xsl:with-param>
<!--<xsl:with-param name="delimiter" select="$delimiter"/>-->
</xsl:call-template>

Replace String with space in Xsl/Xslt

Replace Method for Replace contents,

<xsl:template name="replaceCharsInString">
<xsl:param name="stringIn"/>
<xsl:param name="charsIn"/>
<xsl:param name="charsOut"/>
<xsl:choose>
<xsl:when test="contains($stringIn,$charsIn)">
<xsl:value-of select="concat(substring-before($stringIn,$charsIn),$charsOut)"/>
<xsl:call-template name="replaceCharsInString">
<xsl:with-param name="stringIn" select="substring-after($stringIn,$charsIn)"/>
<xsl:with-param name="charsIn" select="$charsIn"/>
<xsl:with-param name="charsOut" select="$charsOut"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$stringIn"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>


Below code for call the replace method and provided by three parameters
1. Full String
2. Replace text (charIn)
3 Replace from (charOut)
In my example i have used amp; i.e. & to replace with '' i.e. space for your reference code is here.

=========================
<xsl:variable name="myString" select="page/meta/sharefeed"/>
<xsl:variable name="myNewString">
<xsl:call-template name="replaceCharsInString">
<xsl:with-param name="stringIn" select="string($myString)"/>
<xsl:with-param name="charsIn" select="'amp;'"/>
<xsl:with-param name="charsOut" select="''"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="myNewRealString" select="string($myNewString)"/>

Thursday, November 25, 2010

Using Nested Repeater Controls

Yes, DataGrid, DataList and the Repeater Controls are the three main data display controls that ships with ASP.NET.
Well, knowing ‘which to use when’ is what’s important!

Why would Microsoft create three display controls?
Naturally, each of these controls is suited for different tasks and has their own plus and minus points.

Here are a few guidelines that will help you pick the appropriate control depending on your requirements.

DataGrid: (Example tabular display)

Amongst all, I’d say this one is the easiest to develop.
It provides us with features like: Sorting, Paging & Editing.
Its derived from the WebControl class,
and hence we can set its BorderStyle , BackColor etc.
But coming to the performance factor, The DataGrid Control is stated to have the worst performance of the three data web controls.
And another drawback is that, we can’t customize it much according to our needs.
The DataGrid sticks to its simple tabular layout, and that’s where the other two Controls win the poll.


DataList: (Example you'll find the snaps displayed column wise)

The DataList can be used to provide a more customizable interface to the user.
Again this one too is derived from the WebControl class, and hence we can set the same properties.
Using the RepeatColumns property, you can specify how many DataList items should appear per table row.
DataList does provide inline editing, but if you consider the development time required to add in such functionalities,
I’d say be wise in your decision coz this one’s a bit time consuming!


Repeater: (Example you'll find the snaps repeating one below the other)

This control does the least for us, It just does what it says - “Repeats”!
It supports neither paging nor editing.
It’s mainly used to show hierarchical data, like forums.
The control is real handy when it comes to providing a customizable interface to the user. The Repeater class is not derived from the WebControl class, and hence it lacks those stylistic properties.
Coming to the performance issue, this one rules over the other two controls.


Nested Repeater Controls

In this article I’m going to deal with the Repeater Control, to be specific – “Nested Repeater Controls”.
By Nested repeaters, I mean embedding one repeater control within another.


Note:
If you are looking for the source code to bind your data source to a single repeater control,
or for the basics of the Repeater control, then just type in your requirement in the search engine you find on top, and click Search.
Welcome back to this page when you are ready to learn about nesting repeater controls :-)



Where would you use nested repeaters???
Well, Let’s suppose we have a requirement to display all the States, and the list of the Schools within that particular State.

What would we do to get our output look like this
______________________

Kerala
Carmel School
St.Mary’s School
Crescent public school
Bangalore
Donbosco School
St.Josephs School
Chennai
Sacred Heart School
______________________

As we all know, the number of Schools can vary from state to state.
See, now that’s a situation where a nested repeater comes handy.


Let’s begin coding…
Paste the following code within the
tags of your .aspx file.

<TABLE id="Table1" border="0">
<asp:repeater id="myRepeater" runat="server">
<ItemTemplate>
<TR>
<TD><b><u><%#DataBinder.Eval(Container.DataItem, "State")%></u></b></TD>
</TR>
<asp:repeater id="NestedRepeater" runat="server">
<ItemTemplate>
<TR>
<TD><%#DataBinder.Eval(Container.DataItem,"School")%>
<br>
</TD>
</TR>
</ItemTemplate>
</asp:repeater>
</ItemTemplate>
</asp:repeater>
</TABLE>

Next, Move to your Page_Load( ) event and bind your main repeater.

private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection con= new SqlConnection("Enter your connection string here");
SqlDataAdapter sdap =
new SqlDataAdapter("select distinct(State) from listOFschools;select * from listOFschools",con);
DataSet ds = new DataSet();
sdap.Fill(ds);
ds.Relations.Add(
new DataRelation("NestThem",ds.Tables[0].Columns["State"], ds.Tables[1].Columns["State"])
);
myRepeater.DataSource = ds;
myRepeater.DataBind();
}

Finally, Enter the following Code in your Main Repeaters ItemDataBound( ) event to bind your nested repeater.

private void myRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
DataRowView dv = e.Item.DataItem as DataRowView;
if(dv != null)
{
Repeater nestedRepeater = e.Item.FindControl("NestedRepeater") as Repeater;
if(nestedRepeater != null)
{
nestedRepeater.DataSource = dv.CreateChildView("NestThem");
nestedRepeater.DataBind();
}
}
}

The codes are self-explanatory;
we’re just embedding a repeater control within another.
As you can see, it’s the Relations property of the dataset that draws out the required nested fields.

Run your program and that's it! We now have a nested repeater.
So, Use the Nested Repeater control at the appropriate situation and enhance the look of your page.

Wednesday, November 24, 2010

Search String From Passing Table Find All Columns No Need to Specify


This Code will Help to Find the string from all the Existing columns from passed table.
You Need to Pass only tableName and searchString


USE [dbCMS]
GO
/****** Object: UserDefinedFunction [dbo].[fnSearchQuery] Script Date: 11/24/2010 17:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[fnModuleSearchQuery](@Table_Name SYSNAME,@Search_String VARCHAR(100))
Returns Varchar(Max) As
BEGIN
Declare @Query_String Varchar(MAX); /*For Store the Full String*/
Set @Query_String = '';
Declare @Column_Name SYSNAME,
@Sql_String Varchar(MAX)

/*For Store All Column On the Table*/
Declare Column_Cur Cursor For SELECT Name FROM sys.columns
WHERE object_id = (Select object_id from sys.objects Where Name = @Table_Name)
AND system_type_id IN (167, 175, 231, 239)

Open Column_Cur
Fetch Next From Column_Cur INTO @Column_Name
WHILE (@@FETCH_STATUS = 0)
BEGIN
Set @Sql_String = 'SELECT * FROM ' + @Table_Name + ' WHERE '
+ @Column_Name + ' LIKE ''%' + @Search_String + '%'''

Set @Query_String = @Query_String + @Sql_String + ' UNION '
--Execute(@sql_string)
--Print @sql_string
FETCH NEXT FROM Column_Cur INTO @Column_Name
END

CLOSE Column_Cur
DEALLOCATE Column_Cur
Return (Substring(@Query_String,0,Len(@Query_String)-4))
END


--============For Display on the Records Need to call like this ==========

Declare @String varchar(MAX)
Select @String = dbo.fnSearchQuery('SiteDropBox','Bhilai')
Exec(@String)