Saturday, February 13, 2010

User Controls; the reusability!

You can call the same UserControls any number of times

In the ASPX file, reference goes as..




My User Control Code Behind does the job of fetching Latest News for Area.
It accepts AreaId and NewsCount(Number of Records) as input.

I am going to use this User Control to fetch Latest news for different areas.
Say, I wanted to display Bangalore, Hyderabad, and Delhi News.

Here All i need to do is to create a UserControl which accepts the paramenters AreaId and NewCount.

I can drag and drop this user control in the page three times to display the news for three Areas.

This is my UserControl CodeBehind file

public partial class News_UCLatestNews : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
BindDataList();
}
private Int64 areaId;
public Int64 AreaId
{
get { return areaId; }
set { areaId= value; }
}
private Int64 newsCount;
public Int64 NewsCount
{
get { return newsCount; }
set { newsCount = value; }
}
private void BindDataList()
{
List oList = new List();
NewsEntityShort oEntity = new NewsEntityShort();
NewsLogic oLogic = new NewsLogic();

oEntity.NewsCount = NewsCount;
oEntity.ParkId = AreaId;

oList = oLogic.GetNewsUpdatesForPark(oEntity);
DLLatestNews.DataSource = oList;
DLLatestNews.DataBind();

}
}

Note down, UserControl is not assigning values for AreaId and NewsCount. Instead, it declares these as PUBLIC propeties which can be added from any other page which make use of (consume) this User Control.

The code behind file of the Home page, where this user control has been dragged and dropped THREE times, will assign the AreaId and NewsCount for each UserControl.

The home page Code Behind will be as simple as this
protected void Page_Load(object sender, EventArgs e)
{
UCLatestNews1.NewsCount = 10;
UCLatestNews1.AreaId = 2; // Bangalore

UCLatestNews2.NewsCount = 10;
UCLatestNews2.AreaId = 3; // Hyderabad

UCLatestNews3.NewsCount = 5;
UCLatestNews3.AreaId = 4; // Delhi

Wednesday, February 10, 2010

Retrieving the COM class factory for component with CLSID {3D42CCB1-4665-4620-92A3-478F47389230} failed due to the following error: 8007042d

Retrieving the COM class factory for component with CLSID {3D42CCB1-4665-4620-92A3-478F47389230} failed due to the following error: 8007042d

This error is related to the SharePoint Search.

Check Services running in the farm for the Office SharePoint Server Search.

Make sure that Office SharePoint Server Search, is started in the farm. If running, and still having error, check it in the services.msc

Start the service. If its not starting, check the "log on" by right click and make sure the Log On password is correct. and start manually.

Access to the site is locked. SharePoint

"Access to this Web site has been blocked.
Please contact the administrator to resolve this problem."

If this is the message you are getting while browsing your sharepoint site,

Check the site status using the STSADM command

stsadm -o getsitelock -url http://server_name

If it is locked, use the following command to unlock the site to start browsing.

stsadm -o setsitelock -url http://server_name -lock noaccess

Site starts working now.
(Normally this feature is used during the site back up process. This make sure that no data is missed during the back up prosses by locking the access from the user.)

Friday, January 29, 2010

C#: Exporting the Table content of an HTML Page on Button Click to MS Excel.

Exporting the Table content of an HTML Page on Button Click to MS Excel.

protected void Button1_Click(object sender, EventArgs e)
{
string fileName = "CompanyProfile.xls";

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

HtmlForm oFrm = new HtmlForm();

tblExport.Parent.Controls.Add(oFrm);
oFrm.Attributes["runat"] = "server";
oFrm.Controls.Add(tblExport);
oFrm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

}

Export a GridView Content to MS Excel : C# (Few more Find Controls to be added if the Gridview has some controls in it.)

private void ExportGridView()

{
string attachment = "attachment; filename=SalesVsExpenses.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GrvMerged.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GrvMerged);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Method, if GridView has some controls in it.

private static void PrepareControlForExport(Control control)
{
int i = 0;
while ((i < control.Controls.Count))
{
Control current = control.Controls[i];
if ((current is LinkButton))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((LinkButton)current).Text));
}
else if ((current is ImageButton))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((ImageButton)current).AlternateText));
}
else if ((current is HyperLink))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((HyperLink)current).Text));
}
else if ((current is DropDownList))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((DropDownList)current).SelectedItem.Text));
}
else if ((current is CheckBox))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((CheckBox)current).Checked.ToString()));
}if (current.HasControls())
{PrepareControlForExport(current);}
i = (i + 1);
}
}

Sunday, December 6, 2009

ASP.Net Validation dos and don'ts

The many languages available for working with the .NET Framework make it easy to develop code that validates data entered by a user before sending it to a database table. In addition, ASP.NET provides numerous validation controls that make it easy to validate data entered via a Web Form.

Though your .NET development toolbox is well-stocked, these tools are useless if you use them ineffectively. Be aware of what type of data checks you need to perform to ensure data integrity. The following list outlines how you should approach data validation:

Required: One of the most basic validation methods is defining certain fields as required, so that users must enter something in the field before they can save the data. Likewise, database tables may contain required columns—passing null data to these columns will raise an exception.

Data type: Another obvious way to validate user input is checking the data type against what is expected. For example, a date field should only accept legal dates (although there are numerous format options). Trying to pass an invalid date value to a database date column will trigger an exception.

Length: The length of a date entry field is one of the most common validation errors that I encounter. You must adhere to the size limit defined in the database or data store to ensure an exception isn't raised. This is easy in both ASP.NET Web and Windows Forms by using a field's MaxLength property or attribute. You should also validate the data length in the code since Web Forms may be bypassed by passing data to the server via HTTP Server variables.

Format: A field's type can determine its proper format. A good example is a date field that may use the xx/xx/xxxx format. Likewise, telephone number and salary fields utilize specific formats. You may create a custom field control, utilize JavaScript in ASP.NET, or apply formatting via code and the String.Format method or using regular expressions to apply necessary formatting to user data. This may be part of data validation, and the validation shouldn't accept improperly formatted data.

Range of values: Utilizing a range of values as a guide for data entry allows you to easily check if an entered value falls within it. This type of check may be used for entering salaries, zip codes, and so forth.
Check against another field value: You may validate a field's value against another field on the form. The second field could be hidden or entered by the user. One common example is date entries where a user may enter start and end dates, and the end date should always be greater than or equal to the start date.
Putting this list in action depends on the application type. We'll examine an example using the ASP.NET platform. The sample Web Form has four fields:


Username: Required text field limited to 50 characters. A RequiredFieldValidator control is used to ensure a value is entered.

Zip code: Text field accepting a five character zip code in the integer range of 00000 and 99999. It's not required, so validation is performed only if a value is entered. A RegularExpressionValidator control is used to ensure only five numeric digits are entered. A RangeValidator control verifies the value is in the legal range.

Start date: Text field accepting a date value. A RequiredFieldValidator control is used to make sure a value is entered. A CompareValidator control is used to ensure only a date type of date is entered, and another CompareValidator control is used to verify the start date is less than the end date.

End date: Text field accepting a date value. A RequiredFieldValidator control is used to make sure a value is entered. A CompareValidator control is used to make sure a date is entered in the field, and another CompareValidator control verifies the end date is greater than the start date.

Monday, November 30, 2009

Calling an ASP.Net Web Service from Javascript


Page which calls the service has to have Script Manager and the Script Manager has to mention the ServiceReference attribute.

ScriptManager runat="server" ID="ScrpMgr1">
ScriptManagers>

Also, the Web.config file should have an extra entry for ScriptHandlerFactory.

System.Web.Script.Services.ScriptHandlerFactory" />

Below is my JavaScript method which calls the WebService. This has got a SuccessCallBack method to which the Service returns the result set.

var DivIDAct;
function MyWebServiceCallForActuals(ActualsDivId, BudgetYear, BudgetVersion, SalesDivision, row, Display)
{
expandcollapse(ActualsDivId, row, 2);
BrandSerivces.GetBrandsForActuals(BudgetYear, BudgetVersion, SalesDivision, '', SuccessCallBackActuals);
ActualsDivId = 'Division' + ActualsDivId;
var ActualsDivObj = document.getElementById(ActualsDivId);
DivIDAct = ActualsDivObj;
}

function SuccessCallBackActuals(result)
{
DivIDAct.innerHTML = result;
}

This is just to show an Expand Collapse button on click of each row item. A new row item would be displayed under the clicked row, which will show the details of the current row. The Javascript ExpandCollapse method takes care about swaping the Expand(Plus Image) and Collapse(Minus image) images. I am not going to explain much about this as this is self explanatory, just walk through the code.

function expandcollapse(obj, row, ch) {

var div;
var img;
if (ch == 1) {
div = document.getElementById('Div' + obj);
img = document.getElementById('img' + obj);
} else if (ch == 2) {
div = document.getElementById('Division' + obj);
img = document.getElementById('imgActuals' + obj);
}

if (div.style.display == "none") {
div.style.display = "block";
if (row == 'alt') {
img.src = "../App_Themes/Two/images/minus.gif";
}
else {
img.src = "../App_Themes/Two/images/minus.gif";
}
img.alt = "Close to view other Details";
}
else {
div.style.display = "none";
if (row == 'alt') {
img.src = "../App_Themes/Two/images/plus.gif";
}
else {
img.src = "../App_Themes/Two/images/plus.gif";
}
img.alt = "Expand to show Details";
}
}


Make a Dynamic Javascript Function Call from the ASP.Net Gridview Template fields.


Keep an Empty Div in a new Template Field where the Web Service result set (This result set would be returned by the SuccessCallBack method of javascript.) would be displayed. A detailed table for the corresponding row item.

<>
<div id="Division" style="overflow: auto; width: 100%">div>


Thursday, November 26, 2009

Calculating Percentage(%) in the ASP.Net Grid View Footer

Yet another scenario, calculating the percentage based on an common property. Say your Stored Procedure returns the ales and Expenses data pinned together, ORDER BY a particular field. Have a look at the below Grid view control. My stored procedure was returning only the Planned-Sales and Planned Expenses for each Division, for each year. M1, M2 M3...M12 represents the Months.
The data which the Stored Procedure returns will be a repeated with Planned-Sales, Planned-Expense for each Sales Division.
Bind your ASP>Net grid view control with data. Rest to be taken care at the Row Data Bound Event of the grid view control.
private void BindMainGrid()
{
string vBdgYear = "2010";
string vSalesDivision = "1";
string vYtdOrMtd = "YTD";

if (DrpBudgetYear.SelectedValue == "0")
{ vBdgYear = null; }
else { vBdgYear = DrpBudgetYear.SelectedValue; }
List oEntity = new List();
DashboardAnalyticsLogic oLogic = new DashboardAnalyticsLogic();
oEntity = oLogic.DashboardAnalytics(vBdgYear, vSalesDivision, vYtdOrMtd);

if (oEntity.Count != 0)
{
GrvMain.DataSource = oEntity;
GrvMain.DataBind();
}
else
{
LblMsg.Text = "No Record found";
}
}
Declare some public variables to calculate the percentage of Expenses against Sales. Go through the code snippet below, First IF condition checks for each data row, you can access each cell item values here with its index mentioned. Obviously, you would be knowing the number of coulmns of the grid view after bind. (I didnt get a chance where the same to be done with dynamicall colum growing grid ) . The second IF finds the footer row and puts data into each cells after the calculation, which would be available from the public variable.
See, first IF condition takes you in when it is a data row with data. (Header row and Footer rows cant get into this loop.)
System.Int64 TotalM1, TotalM2, TotalM3, TotalM4, TotalM5, TotalM6;
protected void GrvMain_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (TotalM1 == 0) { TotalM1 = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M1")); }
else { TotalM1 = (Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M1")) * 100) / TotalM1; }

if (TotalM2 == 0) { TotalM2 = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M2")); }
else { TotalM2 = (Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M2")) * 100) / TotalM2; }

if (TotalM3 == 0) { TotalM3 = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M3")); }
else { TotalM3 = (Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M3")) * 100) / TotalM3; }

if (TotalM4 == 0) { TotalM4 = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M4")); }
else { TotalM4 = (Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M4")) * 100) / TotalM4; }

if (TotalM5 == 0) { TotalM5 = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M5")); }
else { TotalM5 = (Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M5")) * 100) / TotalM5; }

if (TotalM6 == 0) { TotalM6 = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M6")); }
else { TotalM6 = (Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "M6")) * 100) / TotalM6; }
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "Percentage";
e.Row.Cells[4].Text = Convert.ToString(TotalM1) + "%";
e.Row.Cells[5].Text = Convert.ToString(TotalM2) + "%";
e.Row.Cells[6].Text = Convert.ToString(TotalM3) + "%";
e.Row.Cells[7].Text = Convert.ToString(TotalM4) + "%";
e.Row.Cells[8].Text = Convert.ToString(TotalM5) + "%";
e.Row.Cells[9].Text = Convert.ToString(TotalM6) + "%";
e.Row.Cells[1].HorizontalAlign = e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
e.Row.Font.Bold = true;
e.Row.Height = 28;
}
Let me tell you what i did in the Row Data Bound. You agree that the public variables would have value zero at the first time check from the IF condition? If