Thursday, December 31, 2009

Manual comma separation versus the cool CommaDelimitedStringCollection class!

Some time back while looking around for something else, I was stumbled upon this class, and I simply enjoy using it!

A "wow"-class; I would say. Though, not a lot of documentation is available, but it is worth using this class for those who frequently manage in-memory data with lists/arrays/etc.

A not-so-cool code, somewhere in the asp.net page, goes as follows:
ListBox ctl = ((ListBox)someControlHolder.FindControl("objControl" + i.ToString()));
for (int j = 0; j < ctl.Items.Count; j++)
{
   if (ctl.Items[j].Selected)
   str +=ctl.Items[j].Text + ",";//make it comma separated.
}
str.Remove(str.ToString().Length - 1, 1); //remove the last extra comma.

or And for oCommaDelimitedStringCollection reason, a cool/neat/clean is as follows:
ListBox ctl = ((ListBox)someControlHolder.FindControl("objControl" + i.ToString()));
CommaDelimitedStringCollection strCsv = new CommaDelimitedStringCollection();
for (int j = 0; j < ctl.Items.Count; j++)
{
  if (ctl.Items[j].Selected)
  {
   strCsv.Add(ctl.Items[j].Text);
  }
}

And yes, you are right, doing strCsv.ToString() will write the comma separated string (0:

Enjoy...!

Wednesday, December 30, 2009

Javascript: How to create ASP.NET Reset Button?

Wondering, how to create an ASP.NET based reset button; which is not an Html Reset(input type=reset)?

Type-in the following Javascript code into any ASP.NET control(Button, ImageButton, Link, etc) that exposes OnClientClick public property:

this.form.reset(); return false;

But why would I need this when there already is an Html based reset button available?

Sometimes you need this when you have a theme/skin applied over the page(that is, controls/buttons/textboxes/etc), and you want a button to be consistent with the site theme.

Note that you can append just about any Javascript code/function to objects and controls which then call straight up that Javascript function.

Thursday, December 24, 2009

ASP.NET - Crystal Reports: PrintControl.Cab ActiveX problem

Crystal Reports: PrintControl.Cab ActiveX problem

Problem:
I have a crystal report (some version) with asp.net (usually v2.0), I am using the ActiveX to print the report; I get an error with following symptoms.

-Upon print button click it shows the pop-up window and stop without continue the printing.
-It shows the small print window and vanishes away - nothing happens!
-Print works on some client machines and does not work on some machines.

Workaround:
Specify the version number of the print control in the web
site's web.config file; so, the first time it would download and rest of times it would reuse the print control.

In your web.config file, add the following section with the given url.










The print control is ActiveX and it requires to be downloaded and installed on the client browser. On the systems that still do not print, requires a check if they have enough privileges to install the ActiveX control? Or that they have any printer installed. If they don't then an error is always expected.

Please see this resource shared by Business Objects for more detailed reference.

And also, you may download the PrintControl.CAB file explicitly from this location.

Update: Adding/Configuring a Crystal Report Viewer in web.config.

Update 2011-MAY-11:
You can also try adding the link to "Trusted Sites"; the link from where you are pulling the reports.

Internet Explorer -> Tools ->Internet Options ->Security Tab ->Trusted Sites Security Zone -> Click Sites

and add the url.

Thursday, December 17, 2009

Pomodoro Technique

I reset the clock once again, and start to focus on an activity out of my todo list, then I feel hunger, then I realize I need to make an important call, and I also was just thinking that I want to check my favorite online forum, and then I must read my email and also reply "immediately"... and oh! it has been years I updated by blog - today is the day; and that’s not to mention the most recurring of all my instincts — refilling my tea cup whenever its empty... while 'shedding some light' about the daily-rumours!

Is it? Isn't it? So true... in this overwhelming ever expanding information-village.

So how could we manage time? So challenging!

Monday, December 14, 2009

LDAP: How to get the list of UserIDs from active directory

LDAP: How to get the sorted list all userids that exist on active directory. See following snip:

/// 
    /// List all UserIDs(not user names) that exist on active directory
    /// 
    /// 
    public static List GetAllDomainUsersEx()
    {
        string strLdap = Common.Utility.Constants.LDAP_URL;
        DirectoryEntry objOU = new DirectoryEntry(strLdap);

        //Properties that 
        string[] loadProps = new string[] { "cn"/*Canonical name*/, 
                                            "samaccountname"/*UserID*/, 
                                            "name"/*User Name*/, 
                                            "distinguishedname" /*LDAP unique path to the user*/
                                          };

        //Create a directory searcher object
        DirectorySearcher objUserSearcher = new DirectorySearcher(objOU, "(&(objectClass=user)(objCategory=person))", loadProps);
        SearchResultCollection objResults;

        //Filter criteria.
        objUserSearcher.Filter = "(objectClass=user)";

        //Find all records
        objResults = objUserSearcher.FindAll();

        List lstUsers = new List();
        
        //Loop through
        foreach (SearchResult objResult in objResults)
        {
            string str = objResult.Properties["samaccountname"][0].ToString();
            if(!str.Contains("$")) //remove system users, thats is, users with dollar sign
            {
                lstUsers.Add(str.ToLower());
            }
        }

        return lstUsers.Sort();
    }


Usage:
Following is how you would use; or bind it with a drop down list box.
private void ReloadDomainUserList()
{
List lstUsers = new List();
lstUsers = CLDAPManager.GetAllDomainUsersEx();

ddlADUsers.DataSource = lstUsers;
ddlADUsers.DataBind();
}

Wednesday, December 9, 2009

Microsoft Data Access Application Block

Microsoft Enterprise Library: Microsoft Application Blocks (Data Access)

I have been using Microsoft’s Data Access Application Block for windows forms; and this time I plan to use ‘em in my ASP.NET project. I tend to like application block framework, mostly because for me it saves a lot of time and it provides a bug free code.

I mean seldom you feel a need to write your own data layer unless otherwise is explicitly required/demanded. So I get more time to think about my applications’ logic.

Just for those who have no idea what a data access application block is, following would reveal the before-and-after scenarios; and how it can push you into the “flow” that we seek during our development phase.

1. Code - Without application block
Following the code that create, and opens a connection, make a query, load the data into result and then binds it to the grid.

// Open connection
SqlConnection theConnection = new SqlConnection("Server=(local);Database=TestDB;Integrated Security=True;");
theConnection.Open();

//Create stored procedure command object
SqlCommand theCommand = new SqlCommand("GetEmployeesByDepartment", theConnection);
theCommand.CommandType = CommandType.StoredProcedure;

//Add parameter for stored procedure
theCommand.Parameters.Add("@DepartmentID", SqlDbType.Int); 
theCommand.Parameters["@DepartmentID"].Value = 9; 

//create DataAdapter and DataSet objects
SqlDataAdapter theAdapter = new SqlDataAdapter(theCommand);
DataSet dsResult = new DataSet("Result");

//fill dataset
theAdapter.Fill(dsResult);

//databind the grid
DataGrid1.DataSource = dsResult;
DataGrid1.DataBind();

//clean up
theConnection.Close();

2. Code - With application block
Following does the same as above but with lesser code.

//Make connection
string theConnection = "Server=(local);Database=TestDB;Integrated Security=True;";

//Execute
DataSet dsResult = SqlHelper.ExecuteDataset(theConnection, CommandType.StoredProcedure,"GetEmployeesByDepartment", new SqlParameter("@DepartmentID", 9) );

//Assign and bind
dgvResult.DataSource = dsResult;

dgvResult.DataBind();

Data Access Application Block
The Data Access Application Block simplifies many common data access tasks such as reading data for display, passing data through application layers, and submitting changed data back to the database system. It includes support for both stored procedures and in-line SQL, and provides access to the most often used features of ADO.NET in simple-to-use classes.

Key Scenarios
The Data Access Application Block is suitable if you encounter any of the following
situations:
  • Using a DataReader or DataSet to retrieve multiple rows of data.
  • Executing a command and retrieve the output parameters or a single-value item.
  • Performing multiple operations within a transaction.
  • Retrieving XML data from a SQL Server.
  • Updating a database with data contained in a DataSet object.
  • Adding or extend implementations of database providers.
When to Use
The Data Access Application Block is ideal for addressing the following requirements:
  • You need simplicity and convenience while helping developers use the functionality provided by ADO.NET with best practices.
  • You need to reduce the requirement for boilerplate code to perform standard data access tasks.
  • You need to maintain consistent data access practices, both within an application and across the enterprise.
  • You need to make it easy to change the target database type through configuration, and reduce the amount of code that developers must write when they port applications to different types of databases.
  • You need to relieve developers from learning different programming models for different types of databases.
Considerations
The following considerations apply to using the Data Access Application Block:
  • The Data Access Application Block is a complement to ADO.NET; it is not a replacement.
  • If your application must retrieve data in a specialized way, or take advantage of features specific to a particular database, consider using ADO.NET directly.

Download; you may download the msi from here.

Reference to assembly; add reference to the Microsoft.ApplicationBlocks.Data.dll assembly and start using Microsoft.ApplicationBlocks.Data.

MSDN; Also go through the Data Access Application Block documentation at Microsofts website.

Btw, v5.0 is still(as of now); under construction.

Microsoft Application Architecture Guide - Second Edition 2009 (p489)

Related Posts

Popular Posts