i have this code for doing a remoting i m giving you all the necessary file codes

this application working fine when im using the client as a windows form but when im triyng to use it with a web form it gives an exception

at

bool st=login.CheckUn(txtun.Text);

its giving an null refereance exception

please can any one tell me what im doing wrong here

here's the code for client
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

using LoginComponent;




namespace NewTechBooks
{
/// <summary>
/// Summary description for Home_beforelogin.
/// </summary>
public class Home_beforelogin : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.TextBox txtun;
protected System.Web.UI.WebControls.TextBox txtpwd;
protected System.Web.UI.WebControls.Button btnsign;
protected System.Web.UI.WebControls.CustomValidator cvun;
protected System.Web.UI.WebControls.CustomValidator cvpwd;
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Label lbls;


ILogin login=null;


private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
try
{
ChannelServices.RegisterChannel(new TcpChannel());
login=(ILogin)Activator.GetObject(typeof(LoginComponent.ILogin),"tcp://localhost:6392/theLogin");
}
catch(Exception ex)
{
lbls.Text=ex.ToString();
}
}

private void btnsign_Click(object sender, System.EventArgs e)
{
bool st=login.CheckUn(txtun.Text);
}
}}}

here is the server code
+++++++++++++++++++++++++++++++++++++++++++++++++

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace NTBS_Server
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Server
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
ChannelServices.RegisterChannel(new TcpChannel(6392));
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Login),"theLogin",WellKnownObjectMode.SingleCall);
}
catch(Exception ex)
{
Console.WriteLine(ex);

}
System.Console.WriteLine("Press Enter to exit....");
System.Console.ReadLine();
}
}
}

here is the code for login class

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=

using System;
using System.Data;
using System.Data.SqlClient;
using LoginComponent;


namespace NTBS_Server
{
/// <summary>
/// Summary description for Login.
/// </summary>
public class Login : MarshalByRefObject, ILogin
{
DBConnector dbc = null;
public Login()
{
dbc= new DBConnector();
dbc.OpensCon();

}


public bool CheckUn(string un)
{
SqlDataReader sdr=dbc.ExecuteSQlUsingReader("select cFirst_Name from Customer_Details where cUser_Name='"+un+"'");

if(sdr.HasRows)
{
System.Console.WriteLine("1");
return true;
}
else
{
System.Console.WriteLine("1");
return false;
}

}
/*public bool CheckPwd(string pwd)
{
return true;
}

public string getValue(string un, string pwd)
{
return pwd;

}*/


}
}

here is the code for the remote inter face code

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

using System;

namespace LoginComponent
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public interface ILogin
{
bool CheckUn(string un);



}
}

like i said erlier this code is working fine with the windows form but i wan to know how to use thi in a webform aspx file above clien is my aspx file

thank you in advance

Recommended Answers

All 12 Replies

Make sure that variable txtun is initialized. I only saw you declaring it. If I'm not wrong, C# does not error on un-initialized class variables, only on local ones. Init txtun first.

I could be wrong here but textun.Text would be a text box within the web form itself not a variable to be initialized.

The way I'm reading it he's passing the text value of a TextBox named "textun" to a process named "CheckUN" within class "login".

Beyond that, as I look through the code, I'm not seeing any reason (provided all the classes and interfaces are properly initialized) that you wouldn't be receiving a true/false response from your bool inquiry in the above code segments.

As a side note, your sql query to determine merely if there is or isn't a username that matches in the DB can be accomplished using ExecuteNonQuery() instead of using a reader since all you need to know is whether there are rows returned or not. ExecuteNonQuery() will return a numeric value only as an indication of affected rows so your code could be set to trigger on 0 or > 0 results instead. But that's just my thougt on the matter ;)

i understand what u say but the thing is it's not not connecting at all what im guessing. is there any special reference that u need make other than the remoting and the dll , or anything special u have to do.

Well I'm making the assumption that your DBConnector function is well formed as you didn't include any of it's code but...

Assuming that the db connection properties are well formed I'm not seeing any issues with your code off-hand.

An example of what I generally utilize in web-apps for DB connection would be:

blConn loadConn = new blConn(); //Represents separate class for DB connection strings to mask from primary class

    private bool checkUN(string userName)
    {
        string connStr = @loadConn.cString;
        SqlConnection loadMsgConn = new SqlConnection(@connStr);
        SqlCommand loadMsgCmd = new SqlCommand();
        loadMsgCmd = loadMsgConn.CreateCommand();
        loadMsgCmd.CommandText = @"select * from Customer_Details where cUser_Name='@un'");
        loadMsgCmd.Parameters.Add("@un", SqlDbType.VarChar);
        loadMsgCmd.Parameters["@un"].Value = userName;
        loadMsgConn.Open();
        int queryReply = loadMsgCmd.ExecuteNonQuery();
        bool respond = false;
        if (queryReply > 0)
        {
            respond = true;
        }
        return respond;
    }

Bear with my code as the names are from a cut'n'paste from a project I recently was working on. Essentially, assuming your SQL connection string is correctly set and you pass userName to the process it should return a bool reply based on a 0 or non-0 reply to the SQL query.

Alternately you can do this method:

blConn loadConn = new blConn(); //Represents separate class for DB connection strings to mask from primary class

    private bool checkUN(string userName)
    {
        bool respond = false;
        string connStr = @loadConn.cString;
        SqlConnection loadMsgConn = new SqlConnection(@connStr);
        SqlDataAdapter loadMsgAdapt = new SqlDataAdapter(@"select * from Customer_Details where cUser_Name='"+userName+"'", loadMsgConn);
        SqlCommandBuilder loadMsgBuilder = new SqlCommandBuilder(loadMsgAdapt);
        DataSet loadMsgSet = new DataSet();
        loadMsgAdapt.Fill(loadMsgSet, "unCheck");
        loadMsgConn.Close();
        if (loadMsgSet.Tables["unCheck"].Rows.Count > 0)
        {
            respond = true;
        }
        return respond;
    }

Again, without seeing more of your behind the scenes code I can't assume that things are well formed or otherwise so I hope my above example helps in some way. By the way, the above code assumes the use of MS SQL, you would need to modify accordingly if you are using a differnt DB type.

thank you

here is my db connector code like i said this code is working fine with awin form this exception is only comming when im using it the web form so thats why ididnt include db code

and the thing is even when the server is not running it gives the same exception without any other. and the exception is occurring when this code is executing bool st=login.CheckUn(txtun.Text);

db code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.ComponentModel;
using System.Configuration;

namespace NTBS_Server
{
    /// <summary>
    /// Summary description for DBConnector.
    /// </summary>
    public class DBConnector
    {
        string conStr=null;
        protected SqlConnection sCon;
        protected SqlDataAdapter da;
        protected SqlCommand comm;
        protected SqlDataReader sdr;

        public DBConnector()
        {
            conStr="Persist Security Info=False;User ID=sa;Password=;Initial Catalog=NewTechBookStore;Data Source=Kalpa";
            sCon=new SqlConnection(conStr);
        }

        public void OpensCon()
        {
            sCon.Open();
        }

        public void ClosesCon()
        {
            sCon.Close();
        }

        public SqlDataReader ExecuteSQlUsingReader(string sql)
        {
            comm= new SqlCommand(sql, sCon);
                sdr=comm.ExecuteReader();

            return sdr;

        }

    }
}

here is the exception message

+++++++++++++++++++++++++++++++++++++++++++++++
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 224: private void btnsign_Click(object sender, System.EventArgs e)
Line 225: {
Line 226: bool st=login.CheckUn(txtun.Text);
Line 227: }
Line 228: }


Source File: c:\inetpub\wwwroot\newtechbooks\home_beforelogin.aspx.cs Line: 226

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
NewTechBooks.Home_beforelogin.btnsign_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\newtechbooks\home_beforelogin.aspx.cs:226
System.Web.UI.WebControls.Button.OnClick(EventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain() +1277


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573

I just had a thought...

I've never used MarshalByRefObject so I'm not 100% on how it works. I'm assuming that your ILogin interface indirectly initializes your Login class through the statement

public class Login : MarshalByRefObject, ILogin

is this correct?

Because the only thing I can think of is that the Login class isn't initialized in the .cs file for the webform but I'm sure that it is or you'd be receiving some very angry errors from implementing

bool st=login.CheckUn(txtun.Text);

My assumption here (having not used MarshalByRefObject before) is that the call to

ILogin login=null;

works in a similar way to

Login myLogin = new Login()

Is that correct?

Now, your most recent post about the actual error message gets me thinking that the initialization issue might be in fact the case as the error indicates that you are pointing to a value that isn't initialized somewhere.

Based on the error segment it spat out:

Line 224: private void btnsign_Click(object sender, System.EventArgs e)
Line 225: {
Line 226: bool st=login.CheckUn(txtun.Text);
Line 227: }

It's indicating that one of 2 things (from what I can see) is not 'present' to the system. Those being login.CheckUN or txtun.Text. The issue could be that the .Text value for txtun is being lost somehow in the button click (unlikely since it would at the least provide a "" value) or that (as I theorized above) login is not initialized properly.

Sorry I got so verbose but in the middle of posting a reply to you, you added more info lol.

Last thought on the matter, I notice that your code is login.CheckUn(txtun.Text) and your class is Login... maybe a capital L might help? ;)

login is the taken from chanel configuration and from the to it's the interface

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ILogin login;


#
ChannelServices.RegisterChannel(new TcpChannel());
#
login=(ILogin)Activator.GetObject(typeof(LoginComponent.ILogin),"tcp://localhost:6392/theLogin");

and the MarshalByRefObject allows to access the ILogin interface.

and maby becouse it's an interface but the (Login myLogin = new Login()) doesn't work it gives an error

My eyes are burning lol.

I must've missed that step where you initialized login before, sorry.

Well, dude, I'm flat out of ideas.

I've never directly worked with remoting applications like you're doing here so I don't know if there are specific variables to the way this process works that are different between web and windows forms apps.

As I follow your code step by step it all appears fine, I'm not seeing any particular reason why it won't work.

The System.NullReferenceException you are getting indicates to me that you're calling on a variable that 'doesn't exist' somewhere but the point at which it gives it would narrow it down to either txtun.Text or your interface 'login.CheckUN()'. If it was the latter, I would assume the error message would indicate a specific position within the CheckUN procedure where it was running into an issue unless it was 'login' itself that was coming back null... WAIT!!!

#
ILogin login=null;
 
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
try
{
ChannelServices.RegisterChannel(new TcpChannel());
login=(ILogin)Activator.GetObject(typeof(LoginComponent.ILogin),"tcp://localhost:6392/theLogin");
}
catch(Exception ex)
{
lbls.Text=ex.ToString();
}

If you are using visual studio, set a breakpoint at the end of this segment and go into debug mode. I'm willing to bet that "login=(ILogin)Activator.GetObject(typeof(LoginComponent.ILogin),"tcp://localhost:6392/theLogin");" is your culprit right there as it's in a 'Try' block and if it fails leaves login = null. I'll even go so far as to narrow it down to just the ""tcp://localhost:6392/theLogin"" portion ;)

thanks for you hel i look in to it

Lusiphur thanks for the help and your time man i finally figured out whats wrong
every time the method is initilized with the value

login=(ILogin)Activator.GetObject(typeof(LoginComponent.ILogin),"tcp://localhost:6392/theLogin");

code has to be with it so when i did it like this it just worked fine

login=(ILogin)Activator.GetObject(typeof(LoginComponent.ILogin),"tcp://localhost:6392/theLogin");
bool st=login.CheckUn(txtun.Text);

i have put it the two of them in the button click

Well I'm glad we finally got to the root of the issue (the login=null part) and you got it figured out :D 4:11am here, I'm goin' to sleep now lol.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.