Solved

SQL select using page-load session variable produces the variable I need for second sql query

Posted on 2013-01-23
7
553 Views
Last Modified: 2013-01-23
Hi Experts,

Wondering how best to handle this, I create a session variable in my page load event:
System.Security.Principal.IPrincipal user;

        user = System.Web.HttpContext.Current.User;

        System.Security.Principal.IIdentity identity;

        identity = user.Identity;

        Session["username"] = identity.Name.Substring(identity.Name.IndexOf(@"\") + 1);

Open in new window


and use it to get the associated staffid from our database:

<asp:SqlDataSource ID="GetUserID" ConnectionString="<%$ connectionStrings:Intranet %>"
        SelectCommand="Select staffid from StaffDirectory where username=@username" runat="server">
        <SelectParameters>
        <asp:SessionParameter SessionField="username" Name="username" />
        </SelectParameters></asp:SqlDataSource>

Open in new window


But what I really want to do then is use 'staffid' as a parameter in a second SQL select:
<asp:SqlDataSource ID="CPDItems" ConnectionString="<%$ connectionStrings:CPD %>"
        SelectCommand="Select item.CPDDesc, item.CPDHours, item.CPDDate, record.UserId, format.FormatName, Cat.CPDCategoryDesc 
    from CPDItems item
    left join CPDFormat format on item.CPDFormat = format.FormatID
    left join CPDCategory Cat on item.CPDCat = Cat.CategoryID
    right join CPDRecord record on item.CPDID = record.CPDID
    Where UserId = @staffid Order by item.CPDDate asc" runat="server"></asp:SqlDataSource>

Open in new window


 but I need to do all this pre binding, so effectively on loading the page.
0
Comment
Question by:forsters
  • 4
  • 3
7 Comments
 
LVL 23

Expert Comment

by:apresto
ID: 38809501
If you are using SqlDataSource would you not just set it in the page_load as you have already mentioned?

Personally i used Stored Procedures and populate my controls in code, but if you prefer to use the SqlDataSource then i don't know how else you would set the parameter values, you would need to go through page_load to maintain state. Have a look here, this example is quite fitting :)

http://forums.asp.net/t/1062765.aspx

sorry if i have misunderstood your question
0
 

Author Comment

by:forsters
ID: 38809579
Hi apresto,

Thanks for comment, maybe a sp is the answer, but yes I think you're slightly missing the crux of the problem.

So I can grab a users login username on page load and create a session variable - thats fine.
I can then use that session variable to pull data from SQL - that's also fine, so in this case I use Session[username] to return that persons staffid which is an int.

So that all works and I can print my staffid on the page.

But before my page loads I then need to take that staffid and go back to sql with it to get a different set of data based on the staffid I have...so that becomes my new session variable if you like.

So it's exactly as you have described with the link except that I am effectively exchaniging one session variable for another via a sql query and then returning to sql to get my data, so i'm cycling through the process twice befor page load - which I'm not sure how to do because obviously I need to do it sequentially or it will go to get my final data but won't have got the staffid first.

If you think I might best achieve this with a session variable can you give me an example?
0
 
LVL 23

Assisted Solution

by:apresto
apresto earned 500 total points
ID: 38809810
I see what you mean. Well there are a couple of ways to do it.

Standard procedure when logging in a user is to store their ID in a session so this is absolutely fine.

However i don't think using SqlDataSource object is the best way to go. I would suggest coding the queries using methods, for example:

protected void Page_Load(object sender, EventArgs e)
        {
            ....

            int staffId = GetUserIdByUsername(Session["Username"].ToString());
            DataSet ds = GetOtherStaffInfo(staffId);

            YourControl.DataSource = ds;
            YourControl.DataBind();
        }

        public int GetUserIdByUsername(string username)
        {
            int staffId = -1;

            SqlConnection conn = new SqlConnection("Your connection string");

            SqlCommand cmd = new SqlCommand("Select staffid from StaffDirectory where username='" + username + "'", conn);
            cmd.CommandType = CommandType.Text;

            try
            {
                conn.Open();

                string tmpStaffId = Convert.ToString(cmd.ExecuteScalar());

                if (tmpStaffId != "")
                {
                    staffId = Convert.ToInt32(tmpStaffId);
                }
            }
            catch (Exception ex)
            {
                //Log error here
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

            return staffId;
        }

        public DataSet GetOtherStaffInfo(int staffId)
        {
            DataSet ds = new DataSet();
            
            SqlConnection conn = new SqlConnection("Your connection string");

            SqlCommand cmd = new SqlCommand("..... UserId=" + staffId.ToString(), conn);
            cmd.CommandType = CommandType.Text;

            try
            {
                conn.Open();

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                //Log error here
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

            return ds;
        }

Open in new window

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 23

Assisted Solution

by:apresto
apresto earned 500 total points
ID: 38809818
You have a method names: GetUserIdByUsername

this is to return the Staff ID based on the username you give it.

You then have another method which will return another dataset based on the staffId you give it.

This is just an example, but I'm not sure SqlDataSource is the most suitable or best way to achieve what you want. It certainly isn't the only option
0
 

Author Comment

by:forsters
ID: 38809889
Ah yes I see where you're going, thats helpful thanks, I was wondering If I could do it as a subquery but actually it would make more sense to have a seperate SP to do the convert username to staffID part - that would make it easy to reuse. And then I should in theory be able to refer to that SP in my main SQL select...sound plausible?
0
 
LVL 23

Accepted Solution

by:
apresto earned 500 total points
ID: 38810099
The above is using a method, stored procedures are actually compiled queries that are saved in your database. Have a look here for more information:

http://www.sql-server-performance.com/2003/stored-procedures-basics/

The above are C# methods, which are in turn are executing simple text queries using the SqlCommand objects to do so.

Using SP's will certainly make your operation more secure, and scalable. There are plenty of advantages of using stored procedures. Using C# methods is something different. C# is an object oriented language, using methods effectively will definitely make things more scalable and allow for a lot more code reuse.

So in shore, yes, sound very plausible :)

Note : When using SqlConnection/SqlCommand you will need to use the System.Data.SqlClient namespace
0
 

Author Closing Comment

by:forsters
ID: 38810561
Many thanks for the advice, I will go the SP route
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now