Solved

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

Posted on 2013-01-23
7
558 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 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
Percona Live Europe 2017 | Sep 25 - 27, 2017

The Percona Live Open Source Database Conference Europe 2017 is the premier event for the diverse and active European open source database community, as well as businesses that develop and use open source database software.

 
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

Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

Question has a verified solution.

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

PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
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…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

617 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