You are currently browsing the tag archive for the ‘ASP.NET’ tag.

How to: DISTINCT, SUM, COUNT the DataTable for a given XML?

 

SharePoint: Using custom HttpHandler to Response.Redirect() users

This post generated from a question at StackOverflow; the question raised was, to how to redirect users in SharePoint using custom HttpHandler, when you do not have access to the server – or – have no permission to access the server/configuration.

HttpHandlers are used by IIS to “handle” different document types, for instance you have separate .asmx handle, .aspx handler, .ascx handler, etc.

Workaround 1: Look into SPUtility.Redirect

You can use the SPUtility.Redirect method whenever you want to direct the user to a different page. For example, you might create a landing page that determines the user’s role membership, and based on that information you can redirect them to an appropriate page. Or, based on the contents of a query string issued by the user’s browser, you might redirect them to a page that can process the query string, such as the Search Center results page.

Workaround 2: Disposable Windows SharePoint Services
Alternatively, you can look into Using Disposable Windows SharePoint Services Objects.

Workaround 3: Custom Handler in SharePoint
Create a custom HttpHandler in Windows SharePoint Services 3.0; whenever a user requests a url, your custom HttpHandler is going to process that. .Redirect() if you like the url, else otherwise.

But for your custom HttpHandler to work, it should be called first – so in your config file you will have to provide the value in path. Usually an extension is added here. But you can replace that with a * to work for all request. I believe that would work.

Workaround 4:
Assuming that you have “access” to pages so that you can write javascript in it, you can use the javascript in following way.


function RedirectIfUnAuthorized()
{
//Get the location of the current page.
var currentUrl = new String( document.location.href )

//See if it belongs to the urls you are looking for; redirect if so.
if (currentUrl == "http://www.thisUrl.com/page1.aspx") {Response.Redirect("http://www.GOOGLE.com")}
if (currentUrl == "http://www.thisUrl.com/page2.aspx") {Response.Redirect("http://www.BING.com")}
if (currentUrl == "http://www.thisUrl.com/page3.aspx") {Response.Redirect("http://www.someother.com")}
}

Happy coding!

ModalPopupExtender: .Show() not working!

Are you having problem with your ModalPopupExtender.Show() method working in other project but not on this project?

Do not set the hidden button to false; it wont render on client at all!

Set property Style=”display: none”, like following.


Happy coding!

How to validate user controls?

There is no quick way of validating user control. Following solutions might help.

Solution 1:
Usually, you can validate like following:

Page.Validate("MyValidationGroupOfDateUserControl");//Date user control
Page.Validate("MyValidationGroupOfAddressUserControl");//Address user control
if(Page.IsValid)
{
//Do Something, Save/etc.
}
else
ShowError("Some method to show error; "missing fields.");

But what if you want the validation to be client side?

One way could be to add a public property in your user control for validation group

public string ValidationGroup
{
set
{
SetValidationGroup(value);
}
}

//Sets the validations for all your controls
private void SetValidationGroup(string val)
{
txtName.ValidationGroup = val;
txtLocation.ValidationGroup = val;
RequiredFieldValidator1.ValidationGroup = val;
RequiredFieldValidator2.ValidationGroup = val;
}

And in your markup set it like:


Or if its in tab panel, that is, if you have your control displayed under a tab. Use following code:

<_asp:TabPanel runat="server" ID="pnlAddress" HeaderText="">


Solution 2:

Add the validation group in the base class; and sub class your controls from it.

public class UserControlBase : UserControl
{
public UserControlBase()
{
this.Load += new EventHandler(UserControlBase_Load);
}

void UserControlBase_Load(object sender, EventArgs e)
{
SetValidationGroup();
}

///
/// Sets the validation group.
///

private void SetValidationGroup()
{
foreach (Control control in this.Controls)
{
//See if its ValidationGroup'able?
if (control.GetType().GetProperty("ValidationGroup") == null) continue;

//If you want to set validation for specific controls,
//for instance only for text boxes and drop down lists.
//then, iterate through following.
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.DropDownList":
case "System.Web.UI.WebControls.TextBox":
control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
break;
}

//Set for all controls; if you want.
//control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
}
}

public string ValidationGroup
{
get { return (string)ViewState["ValidationGroup"]; }
set { ViewState["ValidationGroup"] = value; }
}

///
/// Clears the controls.
///

///

The parent.public void ClearControls(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ClearControls(c);
}
else
{
switch (c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;
case "System.Web.UI.WebControls.DropDownList":
((DropDownList)c).SelectedIndex = -1;
break;
}
}
}
}

///
/// Quick changes the page if you have grid in your user control.
///

///

The grid.///

The data table.///

The event object instance containing the event data.public void ChangePage(GridView gvGrid, DataTable dt, GridViewPageEventArgs e)
{
gvGrid.PageIndex = e.NewPageIndex;
try
{
gvGrid.DataSource = dt;
gvGrid.DataBind();
}
catch { throw; }
}
}

In your control, write:

//Address user control
public partial class UCtlAddress : System.Web.UI.UserControl
{
...
}

Note couple of utility functions that you provide in your base user control; just so it may come handy at any time.

Use it similar to above in your markup;


Happy coding, and yep… I love GhostDoc! (0:

How to sort a GridView without hitting the database?

DataView dv = dt.DefaultView;//Your datatable, dt.
dv.RowFilter = "";//Set row filter to none.
if ((strSortBy != null) && (strSortAscending != null))
dv.Sort = strSortBy/*Column name*/ + " " + strSortAscending /*ASC, for instance.*/;

grd.DataSource = dv;
grd.DataBind();

Happy sorting!

ASP.NET: Add a serial number in GridView
1. Add a template field tag in your GridView markup
2. Add Container.DataItemIndex + 1 code
3. Enjoy






Happy coding!

How to view arabic in Console apps?

You cant;

The Console applications do not support Arabic Text for input and output due to a limitation in the operating system console support. MSDN

Reason might be because Console is not set to handle multi-byte character-sets or 16-bit Unicode.

So, how to view Arabic numbers in WinForms or WebForms?

It seems that generally Arabic numerals are used in English. Though, the Date controls are culture-aware, the numbers are not 🙂

This means you will have to convert the numerals to arabic manually, at least so it seems.

So, you can write an extension method to achieve that:

public static string ToArabicEx(this string str)
{
if (!string.IsNullOrEmpty(str))
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ar-AE");
string[] nativeDigits = Thread.CurrentThread.CurrentCulture.NumberFormat.NativeDigits;

return str.Replace('0', nativeDigits[0].ToCharArray()[0])
.Replace('1', nativeDigits[1].ToCharArray()[0])
.Replace('2', nativeDigits[2].ToCharArray()[0])
.Replace('3', nativeDigits[3].ToCharArray()[0])
.Replace('4', nativeDigits[4].ToCharArray()[0])
.Replace('5', nativeDigits[5].ToCharArray()[0])
.Replace('6', nativeDigits[6].ToCharArray()[0])
.Replace('7', nativeDigits[7].ToCharArray()[0])
.Replace('8', nativeDigits[8].ToCharArray()[0])
.Replace('9', nativeDigits[9].ToCharArray()[0]);
}
else return str;
}

Usage:

for (int i = 0; i <= 9; i++)
{
Response.Write(strLineBreak + i.ToString().ToArabicEx());
Response.Write(strLineBreak + DateTime.Now.ToString().ToArabicEx());

}

Happy coding!

While sitting in just another meeting with another lead developer, I was told that they are using UpdatePanels with jQuery just because they read it somewhere over the internet.

I threw them with PageMethods alternate solution; (although it can be script’ize using ScriptManager.RegisterClientScriptBlock), especially when used with jQuery. To my bewilderment she did not know about the PageMethods; and I was gladly eager to tell her more! (0:

It is not “just another” way of interacting with server; its reliable, and communicates in the shortest forms possible – lowest client/server data exchange; plus, the response by the WebMethod gives the freedom to manipulate and interact with the HTML the way we want.

Its a static method that is exposed using WebMethod attribute; and is called using Javascript. Follow the following steps:

1. Set the `.EnablePageMethods` property of ScriptManager to True.

2. Mark the static method with WebMethod attribute
3. Call method using javascript. Like:

PageMethods.MyMethod(
Arg1,
Arg2,
ArgN,
Incase_Success/*Optional*/,
Incase_Failure/*Optional*/);

function Incase_Success(results/*Returned by the method call*/ , userContext, methodName) {
alert(results);
}

function Incase_Failure(errors, userContext, methodName) {
alert(errors.get_Message());
}

The PageMethod calls the web method MyMethod with the defined number of arguments, and upon successful completion of the function call, it redirects the response to SuccessFunction or FailureFunction according the status that it has.

When calling the method, the first N parameters in the PageMethods call matches the parameters of the class method. In this example we have only only one parameter.

There are two optional parameters that takes the names of the methods to be called in case of failure or success. The callback for success, followed by the callback for failure.

Following is a quick comparison between UpdatePanel, and PageMethod from Encosia.

PageMethod data exchange,

An important point to note, is that most of us relate the the term web service with SOAP and XML. But in this case ASP.NET AJAX doesn’t use SOAP and XML.

Btw, this article is a MUST READ!

Happy coding!

Crystal Report Viewer “This field name is not known.” Error!

I was using Crystal Reports Viewer control in my ASP.NET web application; when some of the reports, out of thousands, didn’t seem to work. Although, those reports worked fine in Crystal Reports Designer IDE; but when run in my web app, I was thrown this this field name is not known error. So, had to dig in and fix the thing up on production.

Problem symptoms:

  • When trying to view a report in Report Viewer the report prompts for parameters and then gets stuck with an error message box titled “Crystal Report Viewer” and the error is “This field name is not known.”
  • Some reports are showing error that “This field name is not known.” – problem in report formula?

  • Same report, I can view with CR Designer IDE but CR Viewer (web based) throws the error “This field name is not known.”.

Refer to this discussion for more information. And the problem that I was having, see following figure.

Dint find anything useful on Business Objects’s search-unfriendly web forum. Then I came across this Crystal Reports Fix (HTTP location, or FTP location); following two issues made me try this fix:

 Which, un/fortunately didn’t work either!

Resolution:
What actually helped, atlast, is this post here on MSDN forum, in guessing” the possible reasons of what might have been going wrong.

Following actually worked:

string strLocation = connectionInfo.DatabaseName + ".dbo." + table.Location.Substring(table.Location.LastIndexOf(".") + 1);

table.Location = strLocation;

So, after applying the new ApplyLogOnInfo(), you will need to set the table location explicitly – again – so that, it would remove old values and apply anew.

Following generic method might help:

private void SetDBLogonToTables(CrystalDecisions.Shared.ConnectionInfo connectionInfo, CrystalDecisions.CrystalReports.Engine.ReportDocument reportDocument)
{
CrystalDecisions.CrystalReports.Engine.Tables tables = reportDocument.Database.Tables;

foreach (CrystalDecisions.CrystalReports.Engine.Table table in tables)
{
CrystalDecisions.Shared.TableLogOnInfo tableLogonInfo = table.LogOnInfo;

tableLogonInfo.ConnectionInfo = connectionInfo;
table.ApplyLogOnInfo(tableLogonInfo);

//Following, did the trick!
try
{
string strLocation = connectionInfo.DatabaseName + ".dbo." + table.Location.Substring(table.Location.LastIndexOf(".") + 1);

table.Location = strLocation;
}
catch (Exception ex)
{//Catch
}
}
}

Will Rickards has provided a nice example, accessing multiple databases changing the datasource location of the report during runtime.

Someone pretty pissed off, wrote:

“…and no thanks to anyone involved in the development of Crystal Reports. There is no good excuse for the dozens of problems that Crystal Reports has and continues to have.
…so it won’t be long before the Crystal company (currently Business Objects?) is sueing Microsoft for putting them out of business by creating a superior product.”

David Hilton in the end, adds to the post that I referred to earlier:

We don’t have a good process for publishing the release notes for Crystal Reports to the SDN yet. We are discussing this issue with the program managers to have them released regularly.

Happy crystallizing the reports! (0:

JavaScript: A Quick ‘Back-Button’

Some time back I wanted to a quick Javascript based ‘Back Button’ functionality. So I used following:

Back

Though above did come handy as a solution, but it was full of surprises as well. The “con” that comes along is something that your application may not desire/intend.

For instance, in cases where you, lets say, are designing a page that performs an online bank account transaction; and along with other forms’ elements you also have a “Submit” button, that gets disabled after you click it; precisely to avoid duplicate transaction.

You click on the submit button and the application throws you on to a next page that has this “<< Go Back” link. Now your spine may get a shiver or two to know that after coming back to the orignal “online-transaction” page, your “Submit” button is disabled. Now WTF?

It is because, usually, when a Form gets validated, we tend to disable the Submit button to avoid multiple hits; Specially in cases of online/form based transactions.

So what can we do about it?

1. Use Back Button where validation is not being performed. Or there is no Form/elements.

2. Use AJAX for on-the-fly validation, and show validation messages on the same page.

3. Use Server.Transfer(Url) to go back.

4. Or probably handle the UnLoad event which will enable the button back to original state using JavaScript.

Happy Go-Back buttoning! (0:

%d bloggers like this: