mstsc /v ServerName /admin /public
Wednesday, December 7, 2011
Friday, October 21, 2011
How to hide/display item of gridview like button or Image
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Here Documentname : Is the columan name of gridview
string docName = DataBinder.Eval(e.Row.DataItem, "Documentname").ToString();
if (docName.Length == 0)
{ // Here lnkDetails : is the control embeded in gridview
((LinkButton)e.Row.FindControl("lnkDetails")).Visible = false;
}
}
}
Wednesday, August 3, 2011
Javascript for calculating age
<script type="text/javascript">
function showAge() {
var d = document.getElementById('<%= txtDateOfBirth.ClientID %>').value.split('/');
var today = new Date();
var bday = new Date(d[2], d[1], d[0]);
var by = bday.getFullYear();
var bm = bday.getMonth() - 1;
var bd = bday.getDate();
var age = 0; var dif = bday;
while (dif <= today) {
var dif = new Date(by + age, bm, bd);
age++;
}
age += -2;
document.getElementById("<%=txtCurrentAge.ClientID %>").value = age;
alert('You are ' + age + ' years old')
}
</script>
function showAge() {
var d = document.getElementById('<%= txtDateOfBirth.ClientID %>').value.split('/');
var today = new Date();
var bday = new Date(d[2], d[1], d[0]);
var by = bday.getFullYear();
var bm = bday.getMonth() - 1;
var bd = bday.getDate();
var age = 0; var dif = bday;
while (dif <= today) {
var dif = new Date(by + age, bm, bd);
age++;
}
age += -2;
document.getElementById("<%=txtCurrentAge.ClientID %>").value = age;
alert('You are ' + age + ' years old')
}
</script>
//On page load write this..
this.txtDateOfBirth.Attributes.Add("OnBlur", "javascript:return showAge();");
Validation on Checkbox
<script language="javascript" type="text/javascript">
function validateCheckBox1(source, args)
{
args.IsValid = document.getElementById('<%= Chk1.ClientID %>').checked;{
}
</script>
// call this with custom validator in HTML page
CheckBox ID="Chk1" runat="server" />
<asp:CustomValidator runat="server" ID="CustomValidator4" Visible="true"
ClientValidationFunction="validateCheckBox2"
ErrorMessage="Please confirm the authorisation 1" Display="Dynamic" />
ClientValidationFunction="validateCheckBox2"
ErrorMessage="Please confirm the authorisation 1" Display="Dynamic" />
Validation in Radiobutton List
<script language="javascript" type="text/javascript">
function ValidateRadioButtonListSIALenece() {
var RBL = document.getElementById('<%= RbtnSIA.ClientID %>');
var radiobuttonlist = RBL.getElementsByTagName("input");
var counter = 0;
var atLeast = 1;
for (var i = 0; i < radiobuttonlist.length; i++) {
if (radiobuttonlist[i].checked) {
var RBL = document.getElementById('<%= RbtnSIA.ClientID %>');
var radiobuttonlist = RBL.getElementsByTagName("input");
var counter = 0;
var atLeast = 1;
for (var i = 0; i < radiobuttonlist.length; i++) {
if (radiobuttonlist[i].checked) {
if (radiobuttonlist[i].value == "Yes") {
// alert('y');
document.getElementById("<%=txtDateOfApplication.ClientID %>").value = "";
document.getElementById("<%=txtDateOfApplication.ClientID %>").readOnly = false;
document.getElementById("<%=Img29.ClientID %>").style.visibility = 'visible';
document.getElementById("<%=RegularExpressionValidator10.ClientID %>").readOnly = false;
}
if (radiobuttonlist[i].value == "No") {
// alert('N');
document.getElementById("<%=txtDateOfApplication.ClientID %>").value = "";
document.getElementById("<%=txtDateOfApplication.ClientID %>").readOnly = true;
document.getElementById("<%=Img29.ClientID %>").style.visibility = 'hidden';
document.getElementById("<%=RegularExpressionValidator10.ClientID %>").readOnly = true;
if (radiobuttonlist[i].value == "No") {
// alert('N');
document.getElementById("<%=txtDateOfApplication.ClientID %>").value = "";
document.getElementById("<%=txtDateOfApplication.ClientID %>").readOnly = true;
document.getElementById("<%=Img29.ClientID %>").style.visibility = 'hidden';
document.getElementById("<%=RegularExpressionValidator10.ClientID %>").readOnly = true;
}
counter++;
}
}
}
</script>
I am calling this on radiobutton list click event
this.RBtnList.Attributes.Add("OnClick", "javascript:return ValidateRadioButtonListSIALenece();");
Saturday, July 30, 2011
The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
The above error will be thrown at the time of updating Library or Lists items due to authentication problem, or We didn’t have the rights to update the items.
By using the follwoing code, We can resolve this as,
Web.AllowUnsafeUpdates = true;
item["Title"]=”Sample”;
item.Update();
or we can also use the follwoing code to overcome the above error, this will affect the WebApplication. This will change the Security settings of a Web Application to allow the anonymous user to update item.
web.Site.WebApplication.FormDigestSettings.Enabled = false;
item["Title"]=”Sample”;
item.Update();
web.Site.WebApplication.FormDigestSettings.Enabled = true;
or we can change the settings in Central Administration to anonymously update the items. But this method will be dangerous.
Central Administration > Application Management > Web Application General Settings
Choose the WebApplication to overwrite the settings
Select the option Off in Web Page Security Validation as follows,
The above error will be thrown at the time of updating Library or Lists items due to authentication problem, or We didn’t have the rights to update the items.
By using the follwoing code, We can resolve this as,
Web.AllowUnsafeUpdates = true;
item["Title"]=”Sample”;
item.Update();
or we can also use the follwoing code to overcome the above error, this will affect the WebApplication. This will change the Security settings of a Web Application to allow the anonymous user to update item.
web.Site.WebApplication.FormDigestSettings.Enabled = false;
item["Title"]=”Sample”;
item.Update();
web.Site.WebApplication.FormDigestSettings.Enabled = true;
or we can change the settings in Central Administration to anonymously update the items. But this method will be dangerous.
Central Administration > Application Management > Web Application General Settings
Choose the WebApplication to overwrite the settings
Select the option Off in Web Page Security Validation as follows,
Wednesday, June 8, 2011
Date Validation at code behind in c#
string strDOB = ""; string strDebtType = "";
txtJudgementdate.Text = hdnJudgementdate.Value;
txtCostCertificationDate.Text = hdnCostCertificationDate.Value;
txtDefaultDate.Text = hdnDefaultDate.Value;
if (ddlDay.SelectedIndex > 0)
if (ddlMonth.SelectedIndex > 0 && ddlYear.SelectedIndex > 0)
{
if (ddlMonth.SelectedIndex == 4 || ddlMonth.SelectedIndex == 6 || ddlMonth.SelectedIndex == 9 || ddlMonth.SelectedIndex == 11)
{
if (ddlDay.SelectedIndex > 30)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
}
else if (ddlMonth.SelectedIndex == 2)
{
if (Convert.ToInt32(ddlYear.SelectedValue) % 4 == 0)
{
if (ddlDay.SelectedIndex > 29)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
}
else
{
if (ddlDay.SelectedIndex > 28)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
}
}
strDOB = new DateTime(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt16(ddlMonth.SelectedIndex), Convert.ToInt16(ddlDay.SelectedValue)).ToString("dd/MM/yyyy");
//strDOB = DateTime.Parse(ddlDay.SelectedValue + "/" + Convert.ToInt16(ddlMonth.SelectedIndex) + "/" + Convert.ToInt32(ddlYear.SelectedValue)).ToString("dd/MM/yyyy");
}
else
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
else if (ddlMonth.SelectedIndex > 0)
if (ddlDay.SelectedIndex > 0 && ddlYear.SelectedIndex > 0)
{
if (ddlMonth.SelectedIndex == 4 || ddlMonth.SelectedIndex == 6 || ddlMonth.SelectedIndex == 9 || ddlMonth.SelectedIndex == 11)
{
if (ddlDay.SelectedIndex > 30)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}}
else if (ddlMonth.SelectedIndex == 2)
{
if (Convert.ToInt32(ddlYear.SelectedValue) % 4 == 0)
{
if (ddlDay.SelectedIndex > 29)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
}
else
{
if (ddlDay.SelectedIndex > 28)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
}
}
strDOB = new DateTime(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt16(ddlMonth.SelectedIndex), Convert.ToInt16(ddlDay.SelectedValue)).ToString("dd/MM/yyyy");
}
else
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
else if (ddlYear.SelectedIndex > 0)
if (ddlMonth.SelectedIndex > 0 && ddlDay.SelectedIndex > 0)
{
if (ddlMonth.SelectedIndex == 4 || ddlMonth.SelectedIndex == 6 || ddlMonth.SelectedIndex == 9 || ddlMonth.SelectedIndex == 11)
{
if (ddlDay.SelectedIndex > 30)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}}
else if (ddlMonth.SelectedIndex == 2)
{
if (Convert.ToInt32(ddlYear.SelectedValue) % 4 == 0)
{
if (ddlDay.SelectedIndex > 29)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
}
else
{
if (ddlDay.SelectedIndex > 28)
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
}
}
strDOB = new DateTime(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt16(ddlMonth.SelectedIndex), Convert.ToInt16(ddlDay.SelectedValue)).ToString("dd/MM/yyyy");
}
else
{
lblError.Text = "Please Select Valid Date of Birth.";
return;
}
Tuesday, May 24, 2011
Check If A String Value Is Numeric or Not
Following is the example for testing string value as number or not
string str123 = "1245"
Double res = 0;
bool b12=Double.TryParse(str123, out res);
this will return true. for the above example. If however, str123="123ab" then the above code will return false.
string str123 = "1245"
Double res = 0;
bool b12=Double.TryParse(str123, out res);
this will return true. for the above example. If however, str123="123ab" then the above code will return false.
Friday, May 20, 2011
How to merge two diffrent Hashtable in asp.net
//Method return an XML
public Hashtable GetSimpleCollection()
{
Hashtable XMLmappingHash = new Hashtable();
////Test XML parser....
XmlTextReader testXMlReader = XMLparse();
//Load the Loop
while (!testXMlReader.EOF)
{
//Go to the name tag
testXMlReader.Read();
//if not start element exit while loop
//if (!testXMlReader.IsStartElement())
//{
// break; // TODO: might not be correct. Was : Exit While
//}
string nodetype = testXMlReader.Name;
string attributeValue = string.Empty;
if (nodetype == "excelcol")
{
while (testXMlReader.MoveToNextAttribute())
{
attributeValue = testXMlReader.Value;
}
XMLmappingHash.Add(testXMlReader.ReadElementString("excelcol"), attributeValue);
}
}
return XMLmappingHash;
}
// Another Mehtod return hashtable
public Hashtable GetCompositeHashtable()
{
string val =string.Empty;
StringBuilder sb;
Hashtable CompHashtable=new Hashtable();
XmlDocument XMLRead = new XmlDocument(); // Create instance of XmlDocument class
//XMLRead.Load(Server.MapPath("Page1.xml")); // Load Xml file
XMLRead.Load("D:\\Work\\GetExcelSheetNames\\XMLFile.xml");
XmlNodeList nodes = XMLRead.SelectNodes(@"excelMapping/tableName");
foreach (XmlNode node in nodes)
{
XmlNodeList nodes2list = node.ChildNodes;
for (int i = 0; i < nodes2list.Count; i++)
{
string key = "comp1" + i;
string Nodetype = nodes2list[i].Name;
if (Nodetype == "excelsComposite")
{
XmlNode CompositeNode = nodes2list.Item(i);
XmlNodeList CompNodeChild = CompositeNode.ChildNodes;
sb = new StringBuilder();
foreach (XmlNode CompChild in CompNodeChild)
{
if (CompChild.Attributes["operation"].Value == "Add")
{
foreach (XmlNode CompChildNodeValue in CompChild)
{
//sb = sb.Append("SUM");
sb = sb.Append(CompChildNodeValue.InnerText);
sb= sb.Append(",");
}
if (sb.Length!=0)
{
sb.Remove(sb.Length - 1, 1);
}
}
if (CompChild.Attributes["operation"].Value == "Divide")
{
sb = sb.Append(CompChild.InnerText);
//val = "(x1+x2)/x3";
}
//string ControlID = n2a.InnerText.Trim();
// string ControlType = n2a.Attributes["ControlType"].Value;
// string AccessMode = n2a.Attributes["AccessType"].Value;
// AddControl(ControlType, ControlID, AccessMode);
}
CompHashtable.Add(key, sb);
}
}
}
return CompHashtable;
}
////Method that merge two diffrent Hashtables
public Hashtable GetCompleteCollection()
{
string HashKey = string.Empty;
string HashValue = string.Empty;
Hashtable DatafieldHashmap = new Hashtable();
Hashtable CompHashMap = new Hashtable();
DatafieldHashmap = GetSimpleCollection();
CompHashMap = GetCompositeHashtable();
IDictionaryEnumerator Hashmap = CompHashMap.GetEnumerator();
while (Hashmap.MoveNext())
{
HashKey = Hashmap.Key.ToString();
HashValue = Hashmap.Value.ToString();
DatafieldHashmap.Add(HashKey,HashValue);
}
return DatafieldHashmap;
}
//// Call this on page load like this
Hashtable XMLCollectionreturn = new Hashtable();
XMLCollectionreturn = GetCompleteCollection();
public Hashtable GetSimpleCollection()
{
Hashtable XMLmappingHash = new Hashtable();
////Test XML parser....
XmlTextReader testXMlReader = XMLparse();
//Load the Loop
while (!testXMlReader.EOF)
{
//Go to the name tag
testXMlReader.Read();
//if not start element exit while loop
//if (!testXMlReader.IsStartElement())
//{
// break; // TODO: might not be correct. Was : Exit While
//}
string nodetype = testXMlReader.Name;
string attributeValue = string.Empty;
if (nodetype == "excelcol")
{
while (testXMlReader.MoveToNextAttribute())
{
attributeValue = testXMlReader.Value;
}
XMLmappingHash.Add(testXMlReader.ReadElementString("excelcol"), attributeValue);
}
}
return XMLmappingHash;
}
// Another Mehtod return hashtable
public Hashtable GetCompositeHashtable()
{
string val =string.Empty;
StringBuilder sb;
Hashtable CompHashtable=new Hashtable();
XmlDocument XMLRead = new XmlDocument(); // Create instance of XmlDocument class
//XMLRead.Load(Server.MapPath("Page1.xml")); // Load Xml file
XMLRead.Load("D:\\Work\\GetExcelSheetNames\\XMLFile.xml");
XmlNodeList nodes = XMLRead.SelectNodes(@"excelMapping/tableName");
foreach (XmlNode node in nodes)
{
XmlNodeList nodes2list = node.ChildNodes;
for (int i = 0; i < nodes2list.Count; i++)
{
string key = "comp1" + i;
string Nodetype = nodes2list[i].Name;
if (Nodetype == "excelsComposite")
{
XmlNode CompositeNode = nodes2list.Item(i);
XmlNodeList CompNodeChild = CompositeNode.ChildNodes;
sb = new StringBuilder();
foreach (XmlNode CompChild in CompNodeChild)
{
if (CompChild.Attributes["operation"].Value == "Add")
{
foreach (XmlNode CompChildNodeValue in CompChild)
{
//sb = sb.Append("SUM");
sb = sb.Append(CompChildNodeValue.InnerText);
sb= sb.Append(",");
}
if (sb.Length!=0)
{
sb.Remove(sb.Length - 1, 1);
}
}
if (CompChild.Attributes["operation"].Value == "Divide")
{
sb = sb.Append(CompChild.InnerText);
//val = "(x1+x2)/x3";
}
//string ControlID = n2a.InnerText.Trim();
// string ControlType = n2a.Attributes["ControlType"].Value;
// string AccessMode = n2a.Attributes["AccessType"].Value;
// AddControl(ControlType, ControlID, AccessMode);
}
CompHashtable.Add(key, sb);
}
}
}
return CompHashtable;
}
////Method that merge two diffrent Hashtables
public Hashtable GetCompleteCollection()
{
string HashKey = string.Empty;
string HashValue = string.Empty;
Hashtable DatafieldHashmap = new Hashtable();
Hashtable CompHashMap = new Hashtable();
DatafieldHashmap = GetSimpleCollection();
CompHashMap = GetCompositeHashtable();
IDictionaryEnumerator Hashmap = CompHashMap.GetEnumerator();
while (Hashmap.MoveNext())
{
HashKey = Hashmap.Key.ToString();
HashValue = Hashmap.Value.ToString();
DatafieldHashmap.Add(HashKey,HashValue);
}
return DatafieldHashmap;
}
//// Call this on page load like this
Hashtable XMLCollectionreturn = new Hashtable();
XMLCollectionreturn = GetCompleteCollection();
How to read and return an XML in asp.net
public XmlTextReader XMLparse()
{
XmlTextReader m_xmlr = null;
//Create the XML Reader
m_xmlr = new XmlTextReader("D:\\Work\\GetExcelSheetNames\\XMLFile.xml");
//Disable whitespace so that you don't have to read over whitespaces
m_xmlr.WhitespaceHandling = WhitespaceHandling.None;
//read the xml declaration and advance to family tag
m_xmlr.Read();
//read the family tag
m_xmlr.Read();
//Load the Loop
while (!m_xmlr.EOF)
{
//Go to the name tag
m_xmlr.Read();
//if not start element exit while loop
if (!m_xmlr.IsStartElement())
{
break; // TODO: might not be correct. Was : Exit While
}
//Get the Gender Attribute Value
string genderAttribute = m_xmlr.GetAttribute("gender");
//Read elements firstname and lastname
m_xmlr.Read();
//Get the firstName Element Value
string firstNameValue = m_xmlr.ReadElementString("firstname");
//Get the lastName Element Value
string lastNameValue = m_xmlr.ReadElementString("lastname");
//Write Result to the Console
Response.Write("Gender: " + genderAttribute + " FirstName: " + firstNameValue + " LastName: " + lastNameValue);
// Console.Write(Constants.vbCrLf);
}
//close the reader
m_xmlr.Close();
return m_xmlr;
}
{
XmlTextReader m_xmlr = null;
//Create the XML Reader
m_xmlr = new XmlTextReader("D:\\Work\\GetExcelSheetNames\\XMLFile.xml");
//Disable whitespace so that you don't have to read over whitespaces
m_xmlr.WhitespaceHandling = WhitespaceHandling.None;
//read the xml declaration and advance to family tag
m_xmlr.Read();
//read the family tag
m_xmlr.Read();
//Load the Loop
while (!m_xmlr.EOF)
{
//Go to the name tag
m_xmlr.Read();
//if not start element exit while loop
if (!m_xmlr.IsStartElement())
{
break; // TODO: might not be correct. Was : Exit While
}
//Get the Gender Attribute Value
string genderAttribute = m_xmlr.GetAttribute("gender");
//Read elements firstname and lastname
m_xmlr.Read();
//Get the firstName Element Value
string firstNameValue = m_xmlr.ReadElementString("firstname");
//Get the lastName Element Value
string lastNameValue = m_xmlr.ReadElementString("lastname");
//Write Result to the Console
Response.Write("Gender: " + genderAttribute + " FirstName: " + firstNameValue + " LastName: " + lastNameValue);
// Console.Write(Constants.vbCrLf);
}
//close the reader
m_xmlr.Close();
return m_xmlr;
}
Thursday, April 21, 2011
How to make and use Split function in sql Server
1. Create a Function in SQL as follows:
Create FUNCTION dbo.StringSplit
(
@SplitStr nvarchar(2000),
@SplitChar nvarchar(20)
)
RETURNS @RtnValue table
(
Data nvarchar(2000)
)
AS
BEGIN
Declare @Count int
Set @Count = 1
While (Charindex(@SplitChar,@SplitStr)>0)
Begin
Insert Into @RtnValue (Data)
Select
Data = ltrim(rtrim(Substring(@SplitStr,1,Charindex(@SplitChar,@SplitStr)-1)))
Set @SplitStr = Substring(@SplitStr,Charindex(@SplitChar,@SplitStr)+1,len(@SplitStr))
Set @Count = @Count + 1
End
Insert Into @RtnValue (Data)
Select Data = ltrim(rtrim(@SplitStr))
Return
END
2. you need to pass two parameter one is string and otherone is spliting character
here is example
select * from SplitString('Contact-No-Deal\Email\08-30-2010\SP10000175-08-30-2010-16-56-28-5322-BalanceRequest.doc', '\')
output will be like this:
Contact-No-Deal
Email
08-30-2010
SP10000175-08-30-2010-16-56-28-5322-BalanceRequest.doc
Create FUNCTION dbo.StringSplit
(
@SplitStr nvarchar(2000),
@SplitChar nvarchar(20)
)
RETURNS @RtnValue table
(
Data nvarchar(2000)
)
AS
BEGIN
Declare @Count int
Set @Count = 1
While (Charindex(@SplitChar,@SplitStr)>0)
Begin
Insert Into @RtnValue (Data)
Select
Data = ltrim(rtrim(Substring(@SplitStr,1,Charindex(@SplitChar,@SplitStr)-1)))
Set @SplitStr = Substring(@SplitStr,Charindex(@SplitChar,@SplitStr)+1,len(@SplitStr))
Set @Count = @Count + 1
End
Insert Into @RtnValue (Data)
Select Data = ltrim(rtrim(@SplitStr))
Return
END
2. you need to pass two parameter one is string and otherone is spliting character
here is example
select * from SplitString('Contact-No-Deal\Email\08-30-2010\SP10000175-08-30-2010-16-56-28-5322-BalanceRequest.doc', '\')
output will be like this:
Contact-No-Deal
08-30-2010
SP10000175-08-30-2010-16-56-28-5322-BalanceRequest.doc
Tuesday, March 8, 2011
Dynamically passing dates between clause
Create PROCEDURE dbo.test
(
@Table nvarchar(50),
@Field nvarchar(50),
@BeginDate DateTime,
@EndDate DateTime
)
AS
DECLARE @Sql nvarchar(1000)
SET @Sql = 'SELECT ' + @Table + '.* FROM ' + @Table + ' WHERE ' + @Field + ' BETWEEN ''' + convert(nvarchar(20), @BeginDate) + ''' AND ''' + convert(nvarchar(20), @EndDate) + ''''
EXEC sp_executesql @Sql
(
@Table nvarchar(50),
@Field nvarchar(50),
@BeginDate DateTime,
@EndDate DateTime
)
AS
DECLARE @Sql nvarchar(1000)
SET @Sql = 'SELECT ' + @Table + '.* FROM ' + @Table + ' WHERE ' + @Field + ' BETWEEN ''' + convert(nvarchar(20), @BeginDate) + ''' AND ''' + convert(nvarchar(20), @EndDate) + ''''
EXEC sp_executesql @Sql
Wednesday, March 2, 2011
function which will return st, th, nd and rd with date in SQL SERVER
1.create a function as below
create function [dbo].[get_tidy_date]
(
@date datetime = null
)
returns nvarchar(50)
as begin
declare @d int,
@m nvarchar(15),
@y nvarchar(4),
@end nvarchar(1),
@return nvarchar(50)
if @date is null
set @date=getdate()
select @d=datepart(d, @date), @m=datename(m, @date), @Y=
datename(yyyy,@date), @end=right(convert(nvarchar(2), @d),1)
set @return=
convert(nvarchar(2), @d)
+case
when @d in(11, 12, 13) then 'th'
when @end='1' then 'st'
when @end='2' then 'nd'
when @end='3' then 'rd'
else 'th'
end
+' '+@m+' '+@y
return @return
end
2.Call this function as follows:
SELECT dbo.get_tidy_date(GETDATE())
Output is like this
2nd March 2011
create function [dbo].[get_tidy_date]
(
@date datetime = null
)
returns nvarchar(50)
as begin
declare @d int,
@m nvarchar(15),
@y nvarchar(4),
@end nvarchar(1),
@return nvarchar(50)
if @date is null
set @date=getdate()
select @d=datepart(d, @date), @m=datename(m, @date), @Y=
datename(yyyy,@date), @end=right(convert(nvarchar(2), @d),1)
set @return=
convert(nvarchar(2), @d)
+case
when @d in(11, 12, 13) then 'th'
when @end='1' then 'st'
when @end='2' then 'nd'
when @end='3' then 'rd'
else 'th'
end
+' '+@m+' '+@y
return @return
end
2.Call this function as follows:
SELECT dbo.get_tidy_date(GETDATE())
Output is like this
2nd March 2011
Gridview Sorting with up and down arrow + paging
1. Add Gridview and enable sorting and write sortexpression field
<asp:GridView ID="grdCompany" runat="server" AutoGenerateColumns ="False"
DataKeyNames="ID,TraceStatus,CaseRefNo" Width="100%"
onrowdatabound="grdCompany_RowDataBound" AllowPaging="True" AllowSorting="True"
onrowcreated="grdCompany_RowCreated" onsorting="grdCompany_Sorting"
onpageindexchanging="grdCompany_PageIndexChanging">
<Columns>
<asp:hyperlinkfield headertext="Reference No." datatextfield="CaseRefNo" SortExpression="CaseRefNo"
ItemStyle-Width="80px"
datanavigateurlformatstring="viewcase.aspx?refid={0}&TraceType=C"
datanavigateurlfields="CaseRefNo" >
<HeaderStyle ForeColor="White" />
<ItemStyle Width="80px" />
</asp:hyperlinkfield>
<%--<asp:BoundField DataField="CompanyName1" HeaderText="Company Name" ItemStyle-Width ="100px" />
<asp:BoundField DataField="PropertyName1" HeaderText="Property Name" ItemStyle-Width ="100px" /> --%>
<asp:TemplateField HeaderText="Company Name/ <br/>Property Name" SortExpression="CompanyName1">
<ItemTemplate>
<%#Eval("CompanyName1")%>
<br />
<%#Eval("PropertyName1") %>
</ItemTemplate>
<HeaderStyle ForeColor="White" />
</asp:TemplateField> <asp:TemplateField HeaderText="Trace Level<br/>Date of Submission" SortExpression="Tracelevel">
<ItemTemplate>
<%#Eval("Tracelevel")%>
<br />
<%#Eval("DOS")%>
</ItemTemplate>
<HeaderStyle ForeColor="White" />
</asp:TemplateField>
<%--<asp:BoundField DataField="Tracelevel" HeaderText="Trace Level" ItemStyle-Width ="100px" />
<asp:BoundField DataField="DOS" HeaderText="Date of Submission" ItemStyle-Width ="100px" />
<asp:BoundField DataField="TraceStatus" HeaderText="Status" ItemStyle-Width ="100px" /> --%>
<asp:TemplateField HeaderText="Status" SortExpression="TraceStatus">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<% #Eval("TraceStatus") %>' ></asp:Label>
<asp:HyperLink ID="vwReport" runat="server" Text="View Report"></asp:HyperLink>
</ItemTemplate>
<HeaderStyle ForeColor="White" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass ="t-heading" height="35px" /> <RowStyle CssClass ="b-table-text-inside3" height="30px" />
</asp:GridView>
2. write following code in code behind page.
DataView dv = new DataView();
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
//Write a method which return view
private DataView bindgridSort()
{
clsCase objCase = new clsCase();
objCase.pClientId = clsSessions.sesUserID;
objCase.pTraceType = "C";
DataSet dsCase = new DataSet();
dsCase = objCase.GetAllCases();
if (dsCase.Tables[0].Rows.Count > 0)
{
if (ViewState["sortExpr"] != null)
{
dv = new DataView(dsCase.Tables[0]);
dv.Sort = (string)ViewState["sortExpr"];
}
else
dv = dsCase.Tables[0].DefaultView;
}
else
{
lblMsg.Text = "No Details Found.";
}
return dv;
// Add row_created events
protected void grdCompany_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
int sortColumnIndex = GetSortColumnIndex();
if (sortColumnIndex != -1)
{
AddSortImage(sortColumnIndex, e.Row);
}
}
}
// Add sorting event
protected void grdCompany_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
ViewState["SortExpression"] = sortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private int GetSortColumnIndex()
{
// Iterate through the Columns collection to determine the index
// of the column being sorted.
foreach (DataControlField field in grdCompany.Columns)
{
if (field.SortExpression == (string)ViewState["SortExpression"])
{
return grdCompany.Columns.IndexOf(field);
}
}
return -1;
}
private void AddSortImage(int columnIndex, GridViewRow headerRow)
{
// Create the sorting image based on the sort direction.
Image sortImage = new Image();
if (GridViewSortDirection == SortDirection.Ascending)
{
sortImage.ImageUrl = "Images/uparrow.gif";
sortImage.AlternateText = "Ascending Order";
sortImage.ImageAlign = ImageAlign.Top;
sortImage.ImageAlign = ImageAlign.Middle;
}
else
{
sortImage.ImageUrl = "Images/downarrow.gif";
sortImage.ImageAlign = ImageAlign.AbsBottom;
sortImage.ImageAlign = ImageAlign.Middle;
sortImage.AlternateText = "Descending Order";
}
// Add the image to the appropriate header cell.
// headerRow.Cells[columnIndex].Controls.Add(space);
headerRow.Cells[columnIndex].Controls.Add(sortImage);
}
private SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
private void SortGridView(string sortExpression, string direction)
{
DataView dv = bindgridSort();
dv.Sort = sortExpression + direction;
grdCompany.DataSource = dv;
grdCompany.DataBind();
}
protected void grdCompany_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdCompany.PageIndex = e.NewPageIndex;
BindCaseDetails("C");
}
<asp:GridView ID="grdCompany" runat="server" AutoGenerateColumns ="False"
DataKeyNames="ID,TraceStatus,CaseRefNo" Width="100%"
onrowdatabound="grdCompany_RowDataBound" AllowPaging="True" AllowSorting="True"
onrowcreated="grdCompany_RowCreated" onsorting="grdCompany_Sorting"
onpageindexchanging="grdCompany_PageIndexChanging">
<Columns>
<asp:hyperlinkfield headertext="Reference No." datatextfield="CaseRefNo" SortExpression="CaseRefNo"
ItemStyle-Width="80px"
datanavigateurlformatstring="viewcase.aspx?refid={0}&TraceType=C"
datanavigateurlfields="CaseRefNo" >
<HeaderStyle ForeColor="White" />
<ItemStyle Width="80px" />
</asp:hyperlinkfield>
<%--<asp:BoundField DataField="CompanyName1" HeaderText="Company Name" ItemStyle-Width ="100px" />
<asp:BoundField DataField="PropertyName1" HeaderText="Property Name" ItemStyle-Width ="100px" /> --%>
<asp:TemplateField HeaderText="Company Name/ <br/>Property Name" SortExpression="CompanyName1">
<ItemTemplate>
<%#Eval("CompanyName1")%>
<br />
<%#Eval("PropertyName1") %>
</ItemTemplate>
<HeaderStyle ForeColor="White" />
</asp:TemplateField> <asp:TemplateField HeaderText="Trace Level<br/>Date of Submission" SortExpression="Tracelevel">
<ItemTemplate>
<%#Eval("Tracelevel")%>
<br />
<%#Eval("DOS")%>
</ItemTemplate>
<HeaderStyle ForeColor="White" />
</asp:TemplateField>
<%--<asp:BoundField DataField="Tracelevel" HeaderText="Trace Level" ItemStyle-Width ="100px" />
<asp:BoundField DataField="DOS" HeaderText="Date of Submission" ItemStyle-Width ="100px" />
<asp:BoundField DataField="TraceStatus" HeaderText="Status" ItemStyle-Width ="100px" /> --%>
<asp:TemplateField HeaderText="Status" SortExpression="TraceStatus">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<% #Eval("TraceStatus") %>' ></asp:Label>
<asp:HyperLink ID="vwReport" runat="server" Text="View Report"></asp:HyperLink>
</ItemTemplate>
<HeaderStyle ForeColor="White" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass ="t-heading" height="35px" /> <RowStyle CssClass ="b-table-text-inside3" height="30px" />
</asp:GridView>
2. write following code in code behind page.
DataView dv = new DataView();
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
//Write a method which return view
private DataView bindgridSort()
{
clsCase objCase = new clsCase();
objCase.pClientId = clsSessions.sesUserID;
objCase.pTraceType = "C";
DataSet dsCase = new DataSet();
dsCase = objCase.GetAllCases();
if (dsCase.Tables[0].Rows.Count > 0)
{
if (ViewState["sortExpr"] != null)
{
dv = new DataView(dsCase.Tables[0]);
dv.Sort = (string)ViewState["sortExpr"];
}
else
dv = dsCase.Tables[0].DefaultView;
}
else
{
lblMsg.Text = "No Details Found.";
}
return dv;
// Add row_created events
protected void grdCompany_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
int sortColumnIndex = GetSortColumnIndex();
if (sortColumnIndex != -1)
{
AddSortImage(sortColumnIndex, e.Row);
}
}
}
// Add sorting event
protected void grdCompany_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
ViewState["SortExpression"] = sortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private int GetSortColumnIndex()
{
// Iterate through the Columns collection to determine the index
// of the column being sorted.
foreach (DataControlField field in grdCompany.Columns)
{
if (field.SortExpression == (string)ViewState["SortExpression"])
{
return grdCompany.Columns.IndexOf(field);
}
}
return -1;
}
private void AddSortImage(int columnIndex, GridViewRow headerRow)
{
// Create the sorting image based on the sort direction.
Image sortImage = new Image();
if (GridViewSortDirection == SortDirection.Ascending)
{
sortImage.ImageUrl = "Images/uparrow.gif";
sortImage.AlternateText = "Ascending Order";
sortImage.ImageAlign = ImageAlign.Top;
sortImage.ImageAlign = ImageAlign.Middle;
}
else
{
sortImage.ImageUrl = "Images/downarrow.gif";
sortImage.ImageAlign = ImageAlign.AbsBottom;
sortImage.ImageAlign = ImageAlign.Middle;
sortImage.AlternateText = "Descending Order";
}
// Add the image to the appropriate header cell.
// headerRow.Cells[columnIndex].Controls.Add(space);
headerRow.Cells[columnIndex].Controls.Add(sortImage);
}
private SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
private void SortGridView(string sortExpression, string direction)
{
DataView dv = bindgridSort();
dv.Sort = sortExpression + direction;
grdCompany.DataSource = dv;
grdCompany.DataBind();
}
protected void grdCompany_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdCompany.PageIndex = e.NewPageIndex;
BindCaseDetails("C");
}
Friday, February 18, 2011
Download file from griedview cell link in asp.net
1. Add gridview
<asp:GridView ID="GridView1" runat="server" SkinID="gridviewSkin" DataKeyNames="UploadID,UserId,AllocatedTo,AllocatedforQC"
OnRowCommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField HeaderText="Job#" DataField="uploadID" />
<asp:TemplateField HeaderText="Client Name-Uploaded By/ <br>Uploaded Date/<br>Duration/<br>File Size/<br>" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="left">
<ItemTemplate>
<b><%#Eval("ClientName")%></b>-<%#Eval("FullName")%><img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
<%#Eval("CLIENT_UPLOAD_DATE")%><img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
<%#Eval("Duration")%> [HH:MM:SS]<img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
<%#Eval("fileSize")%> kb<img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Transcribe By" DataField="ALLOCATEDTONAME" />
<asp:TemplateField HeaderText="Transcription File" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton Text='<img src="Images/downloadaudio.gif" alt="" border="0">' runat="server" ID="lnkDownload" CommandArgument='<%#Eval("CLIENT_UPLOAD_FILENAME") %>' CommandName="lnkDownload" BorderStyle="None" BorderWidth="0"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download File(s)<br> for QC" HeaderStyle-Width="2%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="FileImage1" CssClass="handcursor" runat="server" ImageUrl="Images/downloaddoc.gif" onclick='<%#Eval("UPLOADID", "return ShowPopup(\"{0}\")")%>' />
</ItemTemplate>
<HeaderStyle Width="2%"></HeaderStyle>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Upload" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton ID="lnkUpload" runat="server" Text="Upload" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Accept/Reject QC" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkAcceptQC" runat="server" Text="Release to QC" CommandArgument='<%#Eval("UploadID") %>' CommandName="AcceptQC"></asp:LinkButton>--%>
<asp:LinkButton ID="lnkAccept" runat="server" Text="Release to Client" OnClientClick="return confirmB();" CommandArgument='<%#Eval("UploadID") %>' CommandName="Accept"></asp:LinkButton>
<br /><br />
<asp:LinkButton ID="lnkReject" runat="server" Text="Reject" CommandArgument='<%#Eval("UploadID") %>' CommandName="Reject"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Status" HeaderStyle-Width="10%" DataField="STATUS" ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="8%"></HeaderStyle>
<ItemStyle Wrap="true" />
</asp:BoundField>
</Columns>
</asp:GridView>
2. add code in code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("lnkDownload"))
{
string strFilePath = System.Configuration.ConfigurationManager.AppSettings["uploadDictationFolder"].ToString();
//+ "/" + e.CommandArgument.ToString()
DownloadFile(e.CommandArgument.ToString(),strFilePath);
//Response.Write(strFilePath);
}
}
public int DownloadFile(string fileName, string Path)
{
HttpResponse response = HttpContext.Current.Response;
FileInfo file = null;
int messageToReturn = 0;
string path = Path + "\\" + fileName;
try
{
file = new FileInfo(path);
if (file.Exists)
{
response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
response.AddHeader("Content-Length", file.Length.ToString());
response.ContentType = GetContentType(file);
response.TransmitFile(file.FullName);
response.Buffer = true;
response.End();
messageToReturn = (int)FileHandlerEnum.Success;
messageToReturn = (int)FileHandlerEnum.Success;
}
else
{
messageToReturn = (int)FileHandlerEnum.FailedFileNotExist;
}
}
catch (IOException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//file = null;
//response.End();
}
return messageToReturn;
}
<asp:GridView ID="GridView1" runat="server" SkinID="gridviewSkin" DataKeyNames="UploadID,UserId,AllocatedTo,AllocatedforQC"
OnRowCommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField HeaderText="Job#" DataField="uploadID" />
<asp:TemplateField HeaderText="Client Name-Uploaded By/ <br>Uploaded Date/<br>Duration/<br>File Size/<br>" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="left">
<ItemTemplate>
<b><%#Eval("ClientName")%></b>-<%#Eval("FullName")%><img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
<%#Eval("CLIENT_UPLOAD_DATE")%><img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
<%#Eval("Duration")%> [HH:MM:SS]<img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
<%#Eval("fileSize")%> kb<img src="images/spacer.gif" alt="" width="10" height="13px" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Transcribe By" DataField="ALLOCATEDTONAME" />
<asp:TemplateField HeaderText="Transcription File" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton Text='<img src="Images/downloadaudio.gif" alt="" border="0">' runat="server" ID="lnkDownload" CommandArgument='<%#Eval("CLIENT_UPLOAD_FILENAME") %>' CommandName="lnkDownload" BorderStyle="None" BorderWidth="0"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download File(s)<br> for QC" HeaderStyle-Width="2%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="FileImage1" CssClass="handcursor" runat="server" ImageUrl="Images/downloaddoc.gif" onclick='<%#Eval("UPLOADID", "return ShowPopup(\"{0}\")")%>' />
</ItemTemplate>
<HeaderStyle Width="2%"></HeaderStyle>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Upload" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton ID="lnkUpload" runat="server" Text="Upload" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Accept/Reject QC" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkAcceptQC" runat="server" Text="Release to QC" CommandArgument='<%#Eval("UploadID") %>' CommandName="AcceptQC"></asp:LinkButton>--%>
<asp:LinkButton ID="lnkAccept" runat="server" Text="Release to Client" OnClientClick="return confirmB();" CommandArgument='<%#Eval("UploadID") %>' CommandName="Accept"></asp:LinkButton>
<br /><br />
<asp:LinkButton ID="lnkReject" runat="server" Text="Reject" CommandArgument='<%#Eval("UploadID") %>' CommandName="Reject"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Status" HeaderStyle-Width="10%" DataField="STATUS" ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="8%"></HeaderStyle>
<ItemStyle Wrap="true" />
</asp:BoundField>
</Columns>
</asp:GridView>
2. add code in code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("lnkDownload"))
{
string strFilePath = System.Configuration.ConfigurationManager.AppSettings["uploadDictationFolder"].ToString();
//+ "/" + e.CommandArgument.ToString()
DownloadFile(e.CommandArgument.ToString(),strFilePath);
//Response.Write(strFilePath);
}
}
public int DownloadFile(string fileName, string Path)
{
HttpResponse response = HttpContext.Current.Response;
FileInfo file = null;
int messageToReturn = 0;
string path = Path + "\\" + fileName;
try
{
file = new FileInfo(path);
if (file.Exists)
{
response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
response.AddHeader("Content-Length", file.Length.ToString());
response.ContentType = GetContentType(file);
response.TransmitFile(file.FullName);
response.Buffer = true;
response.End();
messageToReturn = (int)FileHandlerEnum.Success;
messageToReturn = (int)FileHandlerEnum.Success;
}
else
{
messageToReturn = (int)FileHandlerEnum.FailedFileNotExist;
}
}
catch (IOException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//file = null;
//response.End();
}
return messageToReturn;
}
Dynamically Renaming or re-writing ASPX page name in asp.net
1. Add global.asax file and include this code
here i will rename MP4B.aspx and will put logo and content of page dynamically
void Application_BeginRequest(object sender, EventArgs e)
{
string fullOrigionalpath = Request.Url.ToString();
if (fullOrigionalpath.Contains("/Mobile4Business/"))
{
Context.RewritePath("/Mobile4Business/MP4B.aspx");
}
}
private string GetPageName(string url)
{
int startIndex = url.LastIndexOf('/');
startIndex = startIndex + 1;
int endindex = url.LastIndexOf('?');
if (endindex == -1)
{ endindex = url.Length;
}
return url.Substring(startIndex, (endindex - startIndex));
}
2. write code in code behind ....Here you can use your own code for binding page
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string fullOrigionalpath = Request.RawUrl.ToString();
string rawURL = GetPageName(fullOrigionalpath);
string[] RID = rawURL.Split('.');
Session["RID"] = Convert.ToString( Convert.ToInt32(RID[0]));
fillpageinfo();
}
}
private void fillpageinfo()
{
SqlDataReader dr;
dr = objReseller.GetRsellerDetails();
if(dr.HasRows)
{
dr.Read();
HtmlImage RLogo1 = (HtmlImage)this.Page.FindControl("RLogo");
RLogo1.Src = "..\\images\\" + dr["LogoFileName"].ToString();
ResellerPageText.InnerHtml = dr["PageContent"].ToString();
}
}
private string GetPageName(string url)
{
int startIndex = url.LastIndexOf('/');
startIndex = startIndex + 1;
int endindex = url.LastIndexOf('?');
if (endindex == -1)
{
endindex = url.Length;
}
return url.Substring(startIndex, (endindex - startIndex));
}
here i will rename MP4B.aspx and will put logo and content of page dynamically
void Application_BeginRequest(object sender, EventArgs e)
{
string fullOrigionalpath = Request.Url.ToString();
if (fullOrigionalpath.Contains("/Mobile4Business/"))
{
Context.RewritePath("/Mobile4Business/MP4B.aspx");
}
}
private string GetPageName(string url)
{
int startIndex = url.LastIndexOf('/');
startIndex = startIndex + 1;
int endindex = url.LastIndexOf('?');
if (endindex == -1)
{ endindex = url.Length;
}
return url.Substring(startIndex, (endindex - startIndex));
}
2. write code in code behind ....Here you can use your own code for binding page
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string fullOrigionalpath = Request.RawUrl.ToString();
string rawURL = GetPageName(fullOrigionalpath);
string[] RID = rawURL.Split('.');
Session["RID"] = Convert.ToString( Convert.ToInt32(RID[0]));
fillpageinfo();
}
}
private void fillpageinfo()
{
SqlDataReader dr;
dr = objReseller.GetRsellerDetails();
if(dr.HasRows)
{
dr.Read();
HtmlImage RLogo1 = (HtmlImage)this.Page.FindControl("RLogo");
RLogo1.Src = "..\\images\\" + dr["LogoFileName"].ToString();
ResellerPageText.InnerHtml = dr["PageContent"].ToString();
}
}
private string GetPageName(string url)
{
int startIndex = url.LastIndexOf('/');
startIndex = startIndex + 1;
int endindex = url.LastIndexOf('?');
if (endindex == -1)
{
endindex = url.Length;
}
return url.Substring(startIndex, (endindex - startIndex));
}
Progress bar using Ajax
1. Add Scipt manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
2.Add update panel and add ajax progress in it and file upload control in it
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="middleFormField2">
<asp:Label ID="lblNew" Text="Upload New Dictation:" runat="server"></asp:Label>
<asp:Label ID="lblUpdate" Text="File Name:" runat="server"></asp:Label><strong><font
color="#FF0000">*</font></strong>
</td>
<td align="left" class="middleFormField2">
<table>
<tr>
<td valign="top">
<asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<div style="visibility: hidden" id="progressBarDiv">
<font style="color: #000000" color="#336633" size="2"></font>
<img src="images/preloader.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
<td>
<asp:FileUpload ID="txtUploadDictation" runat="server" Font-Names="verdana" Font-Size="Small" />
<asp:RequiredFieldValidator ID="txtUploadDictation_validate" runat="server" ControlToValidate="txtUploadDictation"
Display="None" ErrorMessage="You have not uploaded a file for dictation. Please upload a file to proceed"
SetFocusOnError="true" ValidationGroup="client" />
<asp:Label ID="lblFileName" runat="server" Font-Bold="true" Text=""></asp:Label>
<div style="visibility: hidden" id="progressBarDivText">
<font style="color: Purple" size="1">Processing, Please Wait...</font>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" valign="top" class="middleFormField">
<div align="center">
<asp:ImageButton ID="submitButton" runat="server" ImageUrl="images/submitDictationBtn.gif"
CausesValidation="true" Width="137" Height="20" border="0" OnClick="submitButton_Click"
OnClientClick="javascript:showWait();" ValidationGroup="client" />
</div>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="submitButton"></asp:PostBackTrigger>
</Triggers>
</asp:UpdatePanel>
</asp:UpdatePanel>
3.Add Javascript which will fire on submit button
<script language="javascript" type="text/javascript">
function showWait() {
var FUpload = document.getElementById('<%= txtUploadDictation.ClientID %>');
if (FUpload.value.length > 0) {
$get('ctl00_pageContent_UpdateProgress2').style.display = 'block';
}
var div = document.getElementById('progressBarDiv');
div.style.visibility = 'visible';
document.getElementById('progressBarDiv').innerHTML = '<img src=images/preloader.gif><font size=2></font>';1. Add Scipt manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
2.Add update panel and add ajax progress in it and file upload control in it
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="middleFormField2">
<asp:Label ID="lblNew" Text="Upload New Dictation:" runat="server"></asp:Label>
<asp:Label ID="lblUpdate" Text="File Name:" runat="server"></asp:Label><strong><font
color="#FF0000">*</font></strong>
</td>
<td align="left" class="middleFormField2">
<table>
<tr>
<td valign="top">
<asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<div style="visibility: hidden" id="progressBarDiv">
<font style="color: #000000" color="#336633" size="2"></font>
<img src="images/preloader.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
<td>
<asp:FileUpload ID="txtUploadDictation" runat="server" Font-Names="verdana" Font-Size="Small" />
<asp:RequiredFieldValidator ID="txtUploadDictation_validate" runat="server" ControlToValidate="txtUploadDictation"
Display="None" ErrorMessage="You have not uploaded a file for dictation. Please upload a file to proceed"
SetFocusOnError="true" ValidationGroup="client" />
<asp:Label ID="lblFileName" runat="server" Font-Bold="true" Text=""></asp:Label>
<div style="visibility: hidden" id="progressBarDivText">
<font style="color: Purple" size="1">Processing, Please Wait...</font>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" valign="top" class="middleFormField">
<div align="center">
<asp:ImageButton ID="submitButton" runat="server" ImageUrl="images/submitDictationBtn.gif"
CausesValidation="true" Width="137" Height="20" border="0" OnClick="submitButton_Click"
OnClientClick="javascript:showWait();" ValidationGroup="client" />
</div>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="submitButton"></asp:PostBackTrigger>
</Triggers>
</asp:UpdatePanel>
</asp:UpdatePanel>
3.Add Javascript which will fire on submit button
<script language="javascript" type="text/javascript">
function showWait() {
var FUpload = document.getElementById('<%= txtUploadDictation.ClientID %>');
if (FUpload.value.length > 0) {
$get('ctl00_pageContent_UpdateProgress2').style.display = 'block';
}
var div = document.getElementById('progressBarDiv');
div.style.visibility = 'visible';
document.getElementById('progressBarDiv').innerHTML = '<img src=images/preloader.gif><font size=2></font>';
var div1 = document.getElementById('progressBarDivText');
div1.style.visibility = 'visible';
//document.getElementById('progressBarDiv').innerHTML = '<img src=images/Progress4.gif><font size=2></font>';
}
</script>
var div1 = document.getElementById('progressBarDivText');
div1.style.visibility = 'visible';
//document.getElementById('progressBarDiv').innerHTML = '<img src=images/Progress4.gif><font size=2></font>';
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
2.Add update panel and add ajax progress in it and file upload control in it
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="middleFormField2">
<asp:Label ID="lblNew" Text="Upload New Dictation:" runat="server"></asp:Label>
<asp:Label ID="lblUpdate" Text="File Name:" runat="server"></asp:Label><strong><font
color="#FF0000">*</font></strong>
</td>
<td align="left" class="middleFormField2">
<table>
<tr>
<td valign="top">
<asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<div style="visibility: hidden" id="progressBarDiv">
<font style="color: #000000" color="#336633" size="2"></font>
<img src="images/preloader.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
<td>
<asp:FileUpload ID="txtUploadDictation" runat="server" Font-Names="verdana" Font-Size="Small" />
<asp:RequiredFieldValidator ID="txtUploadDictation_validate" runat="server" ControlToValidate="txtUploadDictation"
Display="None" ErrorMessage="You have not uploaded a file for dictation. Please upload a file to proceed"
SetFocusOnError="true" ValidationGroup="client" />
<asp:Label ID="lblFileName" runat="server" Font-Bold="true" Text=""></asp:Label>
<div style="visibility: hidden" id="progressBarDivText">
<font style="color: Purple" size="1">Processing, Please Wait...</font>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" valign="top" class="middleFormField">
<div align="center">
<asp:ImageButton ID="submitButton" runat="server" ImageUrl="images/submitDictationBtn.gif"
CausesValidation="true" Width="137" Height="20" border="0" OnClick="submitButton_Click"
OnClientClick="javascript:showWait();" ValidationGroup="client" />
</div>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="submitButton"></asp:PostBackTrigger>
</Triggers>
</asp:UpdatePanel>
</asp:UpdatePanel>
3.Add Javascript which will fire on submit button
<script language="javascript" type="text/javascript">
function showWait() {
var FUpload = document.getElementById('<%= txtUploadDictation.ClientID %>');
if (FUpload.value.length > 0) {
$get('ctl00_pageContent_UpdateProgress2').style.display = 'block';
}
var div = document.getElementById('progressBarDiv');
div.style.visibility = 'visible';
document.getElementById('progressBarDiv').innerHTML = '<img src=images/preloader.gif><font size=2></font>';1. Add Scipt manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
2.Add update panel and add ajax progress in it and file upload control in it
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="middleFormField2">
<asp:Label ID="lblNew" Text="Upload New Dictation:" runat="server"></asp:Label>
<asp:Label ID="lblUpdate" Text="File Name:" runat="server"></asp:Label><strong><font
color="#FF0000">*</font></strong>
</td>
<td align="left" class="middleFormField2">
<table>
<tr>
<td valign="top">
<asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<div style="visibility: hidden" id="progressBarDiv">
<font style="color: #000000" color="#336633" size="2"></font>
<img src="images/preloader.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
<td>
<asp:FileUpload ID="txtUploadDictation" runat="server" Font-Names="verdana" Font-Size="Small" />
<asp:RequiredFieldValidator ID="txtUploadDictation_validate" runat="server" ControlToValidate="txtUploadDictation"
Display="None" ErrorMessage="You have not uploaded a file for dictation. Please upload a file to proceed"
SetFocusOnError="true" ValidationGroup="client" />
<asp:Label ID="lblFileName" runat="server" Font-Bold="true" Text=""></asp:Label>
<div style="visibility: hidden" id="progressBarDivText">
<font style="color: Purple" size="1">Processing, Please Wait...</font>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" valign="top" class="middleFormField">
<div align="center">
<asp:ImageButton ID="submitButton" runat="server" ImageUrl="images/submitDictationBtn.gif"
CausesValidation="true" Width="137" Height="20" border="0" OnClick="submitButton_Click"
OnClientClick="javascript:showWait();" ValidationGroup="client" />
</div>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="submitButton"></asp:PostBackTrigger>
</Triggers>
</asp:UpdatePanel>
</asp:UpdatePanel>
3.Add Javascript which will fire on submit button
<script language="javascript" type="text/javascript">
function showWait() {
var FUpload = document.getElementById('<%= txtUploadDictation.ClientID %>');
if (FUpload.value.length > 0) {
$get('ctl00_pageContent_UpdateProgress2').style.display = 'block';
}
var div = document.getElementById('progressBarDiv');
div.style.visibility = 'visible';
document.getElementById('progressBarDiv').innerHTML = '<img src=images/preloader.gif><font size=2></font>';
var div1 = document.getElementById('progressBarDivText');
div1.style.visibility = 'visible';
//document.getElementById('progressBarDiv').innerHTML = '<img src=images/Progress4.gif><font size=2></font>';
}
</script>
var div1 = document.getElementById('progressBarDivText');
div1.style.visibility = 'visible';
//document.getElementById('progressBarDiv').innerHTML = '<img src=images/Progress4.gif><font size=2></font>';
}
</script>
Subscribe to:
Posts (Atom)