Monday, September 27, 2010

Paging using SP

SET @StartRow = (@PageIndex - 1) * @PageSize + 1
SET @EndRow = @StartRow + @PageSize - 1

SET @StartRow = (@PageIndex - 1) * @PageSize + 1
SET @EndRow = @StartRow + @PageSize - 1

SET @TotalRec = Select Count(*) from Test

-- If StartRow is less then Total Records then fetch all records between startrow and endrow else ignore start row only consider endrow
IF @StartRow <= @TotalRecords SET @SQL = ' SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY '+@Sort+') as [RowNumber] from Test )T1 WHERE RowNumber >= @StartRow AND RowNumber <= @EndRow'

SET @ParmDefinition = N'@StartRow int,@EndRow int,@Sort nvarchar(50)';
EXECUTE sp_executesql @SQL,@ParmDefinition,@StartRow=@StartRow,@EndRow=@EndRow,@Sort=@Sort;

END
ELSE
BEGIN
SET @SQL = '
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY '+@Sort+') as [RowNumber]
from Test
)T1
WHERE RowNumber <= @EndRow'

SET @ParmDefinition = N'@StartRow int,@EndRow int,@Sort nvarchar(50)';
EXECUTE sp_executesql @SQL,@ParmDefinition,@StartRow=@StartRow,@EndRow=@EndRow,@Sort=@Sort;
END



RETURN @TotalRec

paging for repeater

if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
PagedDataSource pgitems = new PagedDataSource();
DataView dv = new DataView(ds.Tables[0]);
pgitems.DataSource = dv;
pgitems.AllowPaging = true;
pgitems.PageSize = int.Parse(hidPageSize.Value.ToString());
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.PageCount > 1)
{
rptTopPages.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pgitems.PageCount; i++) pages.Add((i + 1).ToString()); rptTopPages.DataSource = pages; rptTopPages.DataBind(); } else { rptTopPages.Visible = false; } rptItem.DataSource = pgitems; rptItem.DataBind(); ASPX


<asp:Repeater ID="rptTopPages" runat="server" OnItemCommand="rptPages_ItemCommand">
<HeaderTemplate>
<table cellpadding="0" cellspacing="0" border="0">
<tr class="text">
<td>
<b>Page:</b>&nbsp;
</td>
<td>
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnPage" CssClass="ActiveNode" CommandName="Page" Visible='<%# SetVisible(Container.DataItem,true) %>'
CommandArgument="<%# Container.DataItem %>" runat="server"><%# Container.DataItem %></asp:LinkButton><asp:Label
ID="lblPage" runat="server" Text='<%# Container.DataItem %>' CssClass="InActiveNode"
Visible='<%# SetVisible(Container.DataItem,false) %>'></asp:Label>&nbsp;
</ItemTemplate>
<FooterTemplate>
</td> </tr> </table>
</FooterTemplate>
</asp:Repeater>

Thursday, September 23, 2010

Use FormsAuthenticationTicket to save LoggedIn UserID

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,id,DateTime.Now,DateTime.Now.AddMinutes(10), false, testid);

string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
HttpContext.Current.Response.Cookies.Add(cookie);


Fetch Data from FormsAuthenticationTicket :-


if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.AuthenticationType == "Forms")
{
System.Web.Security.FormsIdentity formsIdentity = default(System.Web.Security.FormsIdentity);
formsIdentity = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity;
string str = formsIdentity.Ticket.UserData;
}
}

Reflection + set/Get property

foreach (PropertyDescriptor properties in prop)
{
objClass.GetType().GetProperty(properties.Name).SetValue(objClass, objlistObject.GetType().GetProperty(properties.Name).GetValue(objlistObject, null), null);
}

Convert Datatable to List using reflection

public static List ConverttoList(DataTable dbTaskTable)
{
List lsttaskListBE = new List();
TaskListBE objtaskListBE = new TaskListBE();
PropertyDescriptorCollection prop = TypeDescriptor.GetProperties(objtaskListBE);
foreach(DataRow datarow in dbTaskTable.Select())
{
objtaskListBE=new TaskListBE();
foreach (PropertyDescriptor properties in prop)
{
objtaskListBE.GetType().GetProperty(properties.Name).SetValue(objtaskListBE, (((datarow[properties.Name])==System.DBNull.Value)?null:datarow[properties.Name]), null);
}
lsttaskListBE.Add(objtaskListBE);
}
return lsttaskListBE;
}

Create Array through reflection

// Create Array
Array objArray = Array.CreateInstance(objClass.GetType(), listCount);

//Set it's value
objArray.SetValue(objClass, j);

Call webservice without adding web reference

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Added for samplecode
using System.CodeDom.Compiler;
using System.Security.Permissions;
using System.Web.Services.Description;
using System.Reflection;
using System.CodeDom;
using System.Diagnostics;

namespace DynamicSoap
{

public static class DynamicWebService
{

public static Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, object[] args)
{

try
{
System.Net.WebClient client = new System.Net.WebClient();

//-Connect To the web service
System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

//Read the WSDL file describing a service.
ServiceDescription description = ServiceDescription.Read(stream);

//Load the DOM

//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);

//--Generate a proxy client.

importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.

importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);

//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.

ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);

if (warning == 0)
{

//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};

//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);

//--Check For Errors
if (results.Errors.Count > 0)
{

foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}

//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);

}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}

Reference link :- http://www.codeproject.com/KB/webservices/webservice_.aspx

Monday, September 13, 2010

asp.net Menu not working at chrome

To solve this you will need to tell .net the capabilities of the browser. For .net 2.0 & above you need to create a new browers file with the capabilities and upload it to your server.

In VS2008 Solution Explorer right click your application and add the “ASP.Net Folder” App_Browsers if you don’t already have it.
Add a New “Browser File” item to this special folder and call it safari.browser (if fixing the problem for Chrome)
Delete all the default stuff VS put in this file and replace it with the following:

<browsers>
<browser refID="safari1plus">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Menu" adapterType="" />
</controlAdapters>
</browser>
</browsers>

Save your file & test locally to see if all is well.
Now for the annoying bit. Upload the new app_browser folder & file to your production server, if you have used the “copy web site” menu option to upload or sharepoint or frontpage, these will create a new folder under app_browsers called vti_cnf
Manually delete the vti_cnf folder under app_browser on your production server. If you don’t you’ll get “Parse error: Data at the root level is invalid. Line 1, position 1.” in your new safari.browser file.
Remember to manually delete this vti_cnf folder everytime you make a change to the app_browser folder or contained files.
So there you go, how to solve the control rendering problems with Google’s Chrome.

For original post you can visit

http://fabenterprises.wordpress.com/2009/03/21/aspnet-menu-not-rendering-correctly-in-googles-chrome/

Tuesday, September 7, 2010

Sunday, September 5, 2010

Fire ItemCommand event of repeater from <div> click or <tr> click using javascript

HTML:-

<asp:Repeater ID="rpt" runat="server" OnItemCommand="rpt_ItemCommand" OnItemCreated="rpt_ItemCreated">
<HeaderTemplate>
<table width="100%" cellpadding="0" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr onclick='javascript:FireItemCommand(<%#DataBinder.Eval(Container, "ItemIndex", "")%>)'
style="cursor: pointer">
<td>
<%# Eval("Name") %>
</td>
<td>
<asp:LinkButton ID="lnkDim" runat="server" Text="lnk123" CommandArgument='<%# Eval("Name") %>'></asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Javascript:-
function FireItemCommand(index) {

__doPostBack('rpt$ctl0' + parseInt(index + 1).toString() + '$lnkDim', '');

}