Solved

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

Posted on 2013-01-23
7
557 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

751 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