Link to home
Start Free TrialLog in
Avatar of deloused
deloused

asked on

send logged in user's username to stored procedure

I would like to pass the logged in User's username value to a Sql Server 2005 stored procedure.  This is what I have right now but it's not working.  How do I send the username value to the stored procedure?

        string strGary = System.Configuration.ConfigurationManager.ConnectionStrings["CEPDBConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(strGary);
        SqlCommand cmd = new SqlCommand("aspnet_GetMemberEvents");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@UserName", UserName);

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
        MyEventsView.DataBind();
Avatar of DotNetThinker
DotNetThinker
Flag of United States of America image

Where is it failing? What is the error?
Avatar of Gautham Janardhan
Gautham Janardhan

what is the error and what is that u want .. there is nothing wrong with the code it seems
Avatar of deloused

ASKER

Well I was just trying to get the UserName to show up on the page so I added this code:
    void InitPageData()
    {
        MembershipUser user = Membership.GetUser();
        DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
        DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
        if (dt.Rows.Count == 1)
        {
            DataSet.MemberInfoRow mr = dt[0];
            UserName.Text = user.UserName;
        }
    }

I put a label on the page with the Id="UserName" and it shows up fine.  

When I try and run the above mentioned code I get this error:  No mapping exists from object type System.Web.UI.WebControls.Label to a known managed provider native type.

cmd.Parameters.AddWithValue("@UserName", UserName);

... I think that line is looking at your Label which is throwing the error you mentioned above.
Yeah, but I'm not sure how to just add the value on it's own.  Without the label nothing showed up at all on the page.  The stored procedure works fine when I add the username value in the database.  
try this

cmd.Parameters.AddWithValue("@UserName", user.UserName);
<Without the label nothing showed up at all on the page>

what does this mean are u returning something from the proc
If you're trying to get it from the label, use this
cmd.Parameters.AddWithValue("@UserName", UserName.Text)

I'd get it straight from user as gauthampj pointed out
Trying gauthampj idea I get:
The name 'user' does not exist in the current context

Using ibost's idea I get nothing showing again.  I thought this would be easy.  

what does your stored proc do?  Maybe it's just a logic error in the proc now.
<Using ibost's idea I get nothing showing again>

what is that u want to be shown
I'm trying to generate the datasource for a gridview.  
The stored procedure runs and generates data, it's a problem of getting that data transfered to the gridview.  Do I need to do something else besides MyEventsView.DataBind(); after the stored procedure is run?
try doing this:

void InitPageData()
    {
        MembershipUser user = Membership.GetUser();
        DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
        DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
        if (dt.Rows.Count == 1)
        {
            DataSet.MemberInfoRow mr = dt[0];
            UserName.Text = user.UserName;
            Session.Add("UserName", user.UserName);
        }


string strGary = System.Configuration.ConfigurationManager.ConnectionStrings["CEPDBConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(strGary);
        SqlCommand cmd = new SqlCommand("aspnet_GetMemberEvents");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
        MyEventsView.DataBind();
    }
void InitPageData()
    {
        MembershipUser user = Membership.GetUser();
        DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
        DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
        if (dt.Rows.Count == 1)
        {
            DataSet.MemberInfoRow mr = dt[0];
            UserName.Text = user.UserName;
            Session.Add("UserName", user.UserName);
        }


string strGary = System.Configuration.ConfigurationManager.ConnectionStrings["CEPDBConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(strGary);
        SqlCommand cmd = new SqlCommand("aspnet_GetMemberEvents");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());
        sqldataadpter FAdp = new
sqldataadpter (cmd)
       DatSet FSet = new DataSet();
       Fadp.Fill(Fset);
        MyEventsView.DataSource = FSet .Tables[0];
        MyEventsView.DataBind();
    }
DotNetThinker,
It doesn't fill anything in still.

gauthampj,
I'm getting several errors on yours:
The type or namespace name 'sqldataadpter' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'DatSet' could not be found (are you missing a using directive or an assembly reference?)

The name 'Fadp' does not exist in the current context      

The name 'Fset' does not exist in the current context


that would be
System.Data.SqlClient.SqlDataAdapter
        FAdp =
        new System.Data.SqlClient.SqlDataAdapter(cmd);
and

        System.Data.DataSet Fset = new DataSet();
Ok, now it works, err well It doesn't give errors.

I get a blank page again.  There must be a different problem.  I'm sure that this has to be working but I'm must be missing something small.  Ok...it I can put in the username in the stored procedure and it generates data.  This is the stored procedure:


CREATE     PROCEDURE [dbo].[aspnet_GetMemberEvents]
      @UserName NVarChar(255)
AS
DECLARE @UserId UNIQUEIDENTIFIER
SELECT @UserId = UserId FROM aspnet_users WHERE Username = @UserName

SELECT
      Events.*
FROM         Events INNER JOIN
             EventMembers ON Events.id = EventMembers.eventId INNER JOIN
             aspnet_Users ON EventMembers.memberId = aspnet_Users.UserId
WHERE
      EventMembers.MemberId = @UserId

group by
      Events.id,
      Events.starttime,
      Events.endtime,
      Events.title,
      Events.description,
      Events.staticURL,
      Events.location,
      Events.photo,
      Events.album,
      Events.cost

ORDER BY
      id ASC

Am I doing something wrong?
Fadp.Fill(Fset);
Response.Write(Fset.Tables.Count.ToString());
Response.Write(Fset.Tables[0].Rows.Count.ToString());
        MyEventsView.DataSource = FSet .Tables[0];
        MyEventsView.DataBind();
Still get a blank screen...I  have a sneaking suspicion the UserName is not being sent to the stored procedure properly.  Because I'm not getting any errors, but I'm also not getting any data back.  
SOLUTION
Avatar of Gautham Janardhan
Gautham Janardhan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Still getting nothing...
can u debug and find the value of either user.UserName
or

Fset.Tables[0].Rows.Count
go into query analyzer and just
select * from aspnet_users

Compare the list to what you Response.Write in InitPageData()
Well...I'm not getting anything on the response.write.    I'm not sure how to debug and see what the data is either.  I feel really daft at this point
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here is my full code, maybe I missed something.  I fixed a few typos.  The username comes from the aspnet_Membership table.  I'm using the AspNetSqlMembershipProvider as well.  

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class members_NewEvents : System.Web.UI.Page
{
    void InitPageData()
    {
        MembershipUser user = Membership.GetUser();
        DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
        DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
        if (dt.Rows.Count == 1)
        {
            DataSet.MemberInfoRow mr = dt[0];
            UserName.Text = user.UserName;
            Session.Add("UserName", user.UserName);
            Response.Write(user.UserName);
        }

        string strGary = System.Configuration.ConfigurationManager.ConnectionStrings["CEPDBConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(strGary);
        SqlCommand cmd = new SqlCommand("aspnet_GetMemberEvents");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());
        Response.Write(Session["UserName"].ToString());
        System.Data.SqlClient.SqlDataAdapter
        FAdp =
        new System.Data.SqlClient.SqlDataAdapter(cmd);
        DataSet FSet = new DataSet();
        FAdp.Fill(FSet);
        MyEventsView.DataSource = FSet.Tables[0];
        MyEventsView.DataBind();
    }

}

Thanks for sticking with this!  I know it has to be close!
try moving ur code to the page load

i,e from InitPageData event to page load event
When I tried to do the write"hello" I got this error:
'System.Web.HttpResponse' does not contain a definition for 'write'

moving to page load now...
try this:


        FAdp.Fill(FSet);
        cmd.Connection.Close(); <----- Insert this line into your code
        MyEventsView.DataSource = FSet.Tables[0];
Well, I get the username outputting now.  Is there a way to just pass a parameter through sql data source instead?  Because I can get the data that way, but I would just want to filter with the logged in user.
I don't think I understand what you're asking. You have the UserName and everything seems to be working but you want to change it?
I don't want to change it, but it's not working.  I'm not getting the data which is being populated by the stored procedure.  When I execute the proc., with the same UserName value as the logged in User on the webpage, in SqlServer I get an output that looks like this:
1      2007-03-23 10:32:00.000      2007-03-27 13:32:00.000      Northeast regional meeting      Northeast regional meeting      NULL      1      0      NULL      150.00

On the webpage I get the output:  UserName2794

I want the stored procedure to fill the dataview.  
would you mind posting the markup for your dataview?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NewEvents.aspx.cs" Inherits="members_NewEvents" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;</div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </form>
</body>
</html>
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok, so now it's obvious I'm not setting the "UserName" session variable properly.  When I test the query while creating the datasource and put in the same UserName as login, it returns the query.  On the web page it's blank.  I've been searching to see how I set the session variable for "UserName".  Thanks for you help guys.  
Where are you databinding your GridView1?
After your last post, my gridview now looks like this:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
            SelectCommand="GetMemberEvents" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:SessionParameter ConvertEmptyStringToNull="False" Name="UserName" SessionField="user.UserName"
                    Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Again, no data shows up.  I think I was trying the 'user.UserName' just to give it a try and forgot to change it back.  This is really weird.  It's always the easy stuff that kills me.  
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hallelujah!  It works and it's beautiful.  Wow.  I was about to give up hope.  Thank you so much!  
Not a problem, glad I could help.
I hope I split the point up ok.  And just for future refrencing here is the complete source:

    void page_load()
    {
        MembershipUser user = Membership.GetUser();
        DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
        DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
        if (dt.Rows.Count == 1)
        {
            DataSet.MemberInfoRow mr = dt[0];
            Session.Add("UserName", user.UserName);
            GridView1.DataBind();
        }

And the gridview looks like this:
        <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CEPDBConnectionString %>"
            SelectCommand="GetMemberEvents" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:SessionParameter Name="UserName" SessionField="UserName" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>