Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2013-01-23
7
Medium Priority
?
559 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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
Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

 
LVL 23

Assisted Solution

by:apresto
apresto earned 2000 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 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

715 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