Improve company productivity with a Business Account.Sign Up

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
?
564 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 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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
There is a wide range of advantages associated with the use of ASP.NET. This is why this programming framework is used to create excellent enterprise-class websites, technologies, and web applications.
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…

608 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