I am fairly new to c# and am getting an error "Object reference not set to an instance of an object." I am creating an XML packet and sending it to an external device for control. If I put the following code on the form in a click event it works beautifully.
On the btn Click event it looks like this:
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
this.PopulateTestDataXml();
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
However, If I move my entire function out of the form and try to call it when clicking a button I get the error.
written in a method off the form in a .cs file it reads:
public static SetTestInfoResponse SetTestData()
{
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
The error occurs when building stringRequestXml.
Part of my problem is the PopulateTestData() is a method on the form itself. Its purpose is to take data from txtboxes and cmbboxes and assign them to their respective arguments..
private TestInformation PopulateTestDataXml()
{
TestInformation UiTestData = new TestInformation();
UiTestData.TestID = txtTestId.Text;
UiTestData.TestUser = cmbUsers.SelectedItem.ToString();
UiTestData.TestSampleType = txtSampleType.Text;
UiTestData.TestSampleId = txtSampleId.Text;
UiTestData.TestMethodNumber = Convert.ToInt32(cmbMethod.SelectedItem);
UiTestData.TestTubeSn = txtTubeSerialNum.Text;
UiTestData.TestComments = txtComments.Text;
return UiTestData;
}
Here is the SetTestInformation() method where I am getting the error:
public static string SetTestInformation(TestInformation testInfo, string stringTestId, string stringUser, string stringSampleType, string stringSampleId, int intMethodNumber, string stringTubeSn, string stringComments)
{
try
{
string stringRequestXMLPacket = string.Empty;
string stringType = #"Request";
string stringCommand = #"Set";
string stringArgument = #"TestInformation";
CommunicationPacket requestXMLPacket = new CommunicationPacket(stringRootTag, stringXMLVersion, stringType, stringCommand);
requestXMLPacket.AddCommandArgument(stringArgument);
requestXMLPacket.AddArgumentItem(stringArgument, "sTestId", testInfo.TestID.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sUser", testInfo.TestUser.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sSampleType", testInfo.TestSampleType.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sSampleId", testInfo.TestSampleId.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "nMethodNumber", testInfo.TestMethodNumber.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sTubeSn", testInfo.TestTubeSn.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sComments", testInfo.TestComments.ToString());
stringRequestXMLPacket = requestXMLPacket.CreateXMLPacket();
return stringRequestXMLPacket;
}
catch (Exception ex)
{
throw ex;
}
}
Iknow I am having trouble with the variable scope here. I still have to use the method PopulateTestDataXml on the form before I call the setTestData() method. But when I call the Method I have to declare testInfo = null or the parameters for SetTestInformation are not valid ("Does not exist in the current context"). What would I need to pass and how for this to work as a called method on the form btn click? I need to do this as I have alot of deserializing functions written as well to catch error messages in the response xml (these all work fine) and its just too much info on the click event. (And I need to learn).
Thanks
Neither of your examples should work (regardless of where you put them). This is simply incorrect:
TestInformation testInfo = null;
// ...
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo,
testInfo.TestID, ...);
// ^^ BANG!
Your testInfo object is null. When you try and access anything on a null object.. a NullReferenceException is thrown. You need to initialize it first. You're trying to do that in your PopulateTestDataXml method.. which returns the object your after. So change your code to this:
TestInformation testInfo = PopulateTestDataXml(); // assign it
Here is your problem..
public static SetTestInfoResponse SetTestData()
{
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
Are you assigning values for these objects I see they are just declared but never assigned.
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
i don't see you use null objects, so i'm wonder if you set them later, also u said the error happen on
private TestInformation PopulateTestDataXml()
{
TestInformation UiTestData = new TestInformation();
UiTestData.TestID = txtTestId.Text;
UiTestData.TestUser = cmbUsers.SelectedItem.ToString();
UiTestData.TestSampleType = txtSampleType.Text;
UiTestData.TestSampleId = txtSampleId.Text;
UiTestData.TestMethodNumber = Convert.ToInt32(cmbMethod.SelectedItem);
UiTestData.TestTubeSn = txtTubeSerialNum.Text;
UiTestData.TestComments = txtComments.Text;
return UiTestData;
}
after moving it out of your form, which mean possibly it's text box references is broken...
so what you can do, is store a pointer, like in your program.cs where you call your form to show up,
you can create an static object of form, and then put it in your class, then set it in program.cs file like :
Form1 f=new Form();
MyClass.staticFormPointer = f;
and also replace (new Form()), with (f) on the calling method,
your my class is like this:
class MyClass{
public static Form1 staticFormPointer = null;
//your code
.
.
.
// and in your methods you call it like this txtBox1.Text -> staticFormPointer.txtBox1.Text
}
Related
I'm using asp.net and c# for backend code and html, javascript/jquery on frontend
User clicks "Details" on website to view and edit requests previously created.
jquery/ajax calls method on backend to get infomation about requests.
An object, newWaferRequest, is created which holds this information. The object is returned from ajax call and the site populates a form with that information. The user can then edit the form, add new programs to requests, modify existing requests info etc...
The problem I'm getting is when the user selects "Save pgm", ajax calls backend savePgm method which is supposed to update the Object newWaferRequest previously created, but I'm receiving a nullReferenceException. The exception is pointing to the newWaferRequest object being null. This happens at different times when the user is updating the request. Sometimes the user can update the program and add new programs, with a correct response from backend. Other times the exception occurs.
I must not have a full grasp of how variables are "stored" when using the web. I read multiple post on here and have read about Session and ViewState variables. I've tried saving the Object in a Session with no luck.
This is just showing the beginning of my c# code, I tried using static variables initially. All the objects are in App_code cs files.
public partial class Nbump_Request : System.Web.UI.Page
{
//public static person currentPerson = new person();
//public static requestSearch searchRequest;
//public static waferRequest newWaferRequest;
//public static waferRequestObject newWaferRequestObject;
static person currentPerson = new person();
static requestSearch searchRequest;
static waferRequest newWaferRequest;
static waferRequestObject newWaferRequestObject;
Here is ajax method for existing requests, which creates objects
[WebMethod]
public static string queryRequestExisting(string request_pk)
{
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
newWaferRequest = new waferRequest(request_pk, "EXISTINGREQUEST");
newWaferRequestObject = newWaferRequest.CURRENTREQUEST;
string json = js.Serialize(newWaferRequest);
return json;
}
catch (Exception)
{
return null;
}
}
Here is ajax code for when user saves or updates program information. I added in the code to check and return with the object was null.
public static string savePgmData(Dictionary<string, string> pgm_requests)
{
PgmRequestObject currentPgm;
if (newWaferRequest != null)
{
try
{
//if (!Convert.ToBoolean(pgm_requests["pgmEdit"])) //not performed when request pgm being edited
string rtnMessage;
//create new pgm in waferRequest object
if (pgm_requests["PGMRT_INDEX_PK"] == null)
{
int index = newWaferRequest.addNewPGMRequest() - 1;
currentPgm = (PgmRequestObject)newWaferRequest.PGMREQUESTLIST[index];
string pgmPrimaryKey = currentPgm.PGMRT_INDEX_PK;
rtnMessage = "{\"message\": \"Added and saved new pgm successfully\", \"primaryKey\":\"" + pgmPrimaryKey + "\"}";
}
//get pgm to update at index provided
else if (pgm_requests["pgmRowIndex"] != "-1")
{
int index = Convert.ToInt32(pgm_requests["pgmRowIndex"]);
currentPgm = (PgmRequestObject)newWaferRequest.PGMREQUESTLIST[index];
rtnMessage = "Edited and saved pgm successfully";
}
//save initial pgm
else
{
currentPgm = (PgmRequestObject)newWaferRequest.PGMREQUESTLIST[0];
rtnMessage = "Initial pgm added successfully";
}
currentPgm.updatePGM(pgm_requests["pgmNameList"], pgm_requests["pgmNameText"]);
currentPgm.updateStatus(pgm_requests["pgmStatus"]);
currentPgm.updateWafers(pgm_requests["pgmWfrList"], pgm_requests["pgmWfrNum"]);
currentPgm.updatePriority(pgm_requests["pgmTestOrder"]);
currentPgm.updateFailBinRetest(pgm_requests["pgmFbr"], pgm_requests["pgmFbrBins"]);
//currentPgm.CommitIntoDatabase(); // -- Called on individual requests updates before request saved
return rtnMessage;
}
catch (Exception ex)
{
return "Failed to save program\n\n" + ex.Data + "\n" + ex.Message + "\n" + ex.StackTrace + "\n";
}
}
else
{
return "newWaferRequest object is null\n";
}
}
This is a short snippet of the class for waferRequest. This is located in the app_code and is a cs file. The pgmRequestList contains an array of pgm objects. That is what I update when user selects "Save Program".
public class waferRequest
{
/*The class will hold request information, creation and delete.
*
*/
private waferRequestObject currentRequest;
private ArrayList WaferRequestList = new ArrayList();
private ArrayList PGMRequestList = new ArrayList();
Here is an example of what I tried for Session. I got rid of static variables and modified the methods
[WebMethod(EnableSession=true)]
public static string queryRequestExisting(string request_pk)
{
waferRequest newWaferRequest;
waferRequestObject newWaferRequestObject;
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
newWaferRequest = new waferRequest(request_pk, "EXISTINGREQUEST");
newWaferRequestObject = newWaferRequest.CURRENTREQUEST;
HttpContext.Current.Session["newWaferRequest"] = newWaferRequest;
HttpContext.Current.Session["newWaferRequestObject"] = newWaferRequestObject;
string json = js.Serialize(newWaferRequest);
return json;
}
catch (Exception)
{
return null;
}
}
//snippet of savePgmData with session
public static string savePgmData(Dictionary<string, string> pgm_requests)
{
waferRequest newWaferRequest = HttpContext.Current.Session["newWaferRequest"];
PgmRequestObject currentPgm;
if (newWaferRequest != null)
{
try
{
//if (!Convert.ToBoolean(pgm_requests["pgmEdit"])) //not performed when request pgm being edited
string rtnMessage;
//create new pgm in waferRequest object
if (pgm_requests["PGMRT_INDEX_PK"] == null)
{
int index = newWaferRequest.addNewPGMRequest() - 1;
currentPgm = (PgmRequestObject)newWaferRequest.PGMREQUESTLIST[index];
I am limited to the code I'm allowed to show because of work security. Please let me know if more information is needed.
Also, the code seems to work fine on my local server. The issue is when I put it on the production server or development server -- Both of which I don't have access to make changes on.
I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.
I'm trying to set variables in code on an SSIS package I'm kicking off from C#.
Package pkg = app.LoadPackage(ConfigurationManager.AppSettings["SsisPkg"].ToString(), null);
pkg.Variables["User::FolderPath"].Value = Path.GetDirectoryName(e.FullPath);
pkg.Variables["User::FileName"].Value = Path.GetFileNameWithoutExtension(e.FullPath);
While debugging, I inspect the values directly after setting them, but nothing has changed. I can drill into the value (hover, navigate to it, edit value) so it doesn't seem to be that they aren't editable.
Any ideas what I'm doing wrong here?
Update: Thanks to billinkc, I'm comfortable what I'm doing should work so long as possibly other conditions are met. I've found that direct assignments in code fail (no error, just don't "take") and I cannot edit the values in the watch window. I can edit values when I'm inspecting them.
Could the actual issue be that there's a setting flagging these as read-only?
Answer Found: Needed to make the variables writable before setting the value:
pkg.Variables["User::FileName"].EvaluateAsExpression = false;
You're doing it right. I created a basic SSIS package. Has one Variable, FolderPath, type string. There is a single script task that fires an Information event and the contents of that expose the value of the FolderPath variable
I then created a basic C# console app like this
public class InformationListener : DefaultEvents
{
public override void OnInformation(DtsObject source, int informationCode, string subComponent, string description, string helpFile, int helpContext, string idofInterfaceWithError, ref bool fireAgain)
{
//base.OnInformation(source, informationCode, subComponent, description, helpFile, helpContext, idofInterfaceWithError, ref fireAgain);
Console.WriteLine(string.Format("{0} {1}", subComponent, description));
}
}
class Program
{
static void Main(string[] args)
{
string sourcePackage = string.Empty;
string path = string.Empty;
string variableName = string.Empty;
string designValue = string.Empty;
string newValue = string.Empty;
InformationListener listener = null;
sourcePackage = #"J:\Src\SO\SSIS\Package.dtsx";
path = #"J:\runtime";
variableName = "User::FolderPath";
listener = new InformationListener();
Application app = new Application();
Package pkg = null;
Variable ssisVariable = null;
pkg = app.LoadPackage(sourcePackage, null);
ssisVariable = pkg.Variables[variableName];
designValue = ssisVariable.Value.ToString();
Console.WriteLine(string.Format("Designtime value = {0}", designValue));
ssisVariable.Value = path;
newValue = ssisVariable.Value.ToString();
Console.WriteLine(string.Format("new value = {0}", newValue));
DTSExecResult results = DTSExecResult.Canceled;
results = pkg.Execute(null, null, listener, null, null);
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
}
As you can tell from the variable inspection
and from my print statements
the design-time value of C:\designTime goes to J: because I forgot to escape my string above but we can pretend it shows J:\runtime.
All this said, unless we serialize the package with a call to the SaveToXml method, the value of User::FolderPath resets to the design time value once the object goes out of scope. Permanently updating would look like
app.SaveToXml(sourcePackage, pkg, null);
OP EDIT this discussion and examples led me to the answer:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/dad8e218-1fe0-49db-89da-5715fb6d4b21/sql-2008-r2-ssis-c-script-task-not-setting-variable
I have method that should return a set of data. But at last when returning data then error shows like :"can not convert type 'WebApplication1.Webrefernce13.DT_value[]' to 'WebApplication1.Webrefernce13.DT_value"
public class InputHelp
{
public DT_Value Priority()
{
WebReference13.DT_SM_InputHelp_Request IncomingtypeReq = new WebReference13.DT_SM_InputHelp_Request();
WebReference13.DT_SM_InputHelp IncomingTypeResp;
WebReference13.SI_CreateSM_OBService _proxy1 = new WebReference13.SI_CreateSM_OBService();
CookieContainer cookie = new CookieContainer();
_proxy1.Credentials = new NetworkCredential("xxxx", "xxxxx"); // use credential to acess to the SAP system
_proxy1.CookieContainer = cookie;
IncomingtypeReq.Mode = "Create";
IncomingtypeReq.Language = "EN";
IncomingtypeReq.OptionalText1 = "ZLFN";
IncomingtypeReq.OptionalText2 = "";
IncomingtypeReq.WSCallID = "223424dgdf";
IncomingTypeResp = _proxy1.SI_GetInputHelp(IncomingtypeReq);
DT_Value[] ab=new DT_Value[10];
ab= IncomingTypeResp.Priority;
return ab; // error is here
}
I will be grateful if you can help me on this issue.
change your method signature to
public DT_Value[] Priority(){...}
also
DT_Value[] ab=new DT_Value[10];
ab = IncomingTypeResp.Priority; //<-- something doesn't look right here.
if IncomingTypeResp.Priority is of type DT_Value[] then you can just do
DT_Value[] ab = IncomingTypeResp.Priority;
You've declared ab as an array of DT_Value, but the method returns DT_Value (a single DT_Value instance).
If you want Priority to return an array you should change the declaration to this:
public DT_Value[] Priority()
You are defining ab as an array of DT_Value but the method contract is to return only one DT_Value. If you want to return only the first value (if it exists), make your last line
return ab[0];
Declare like below and might help you:
DT_Value ab=new DT_Value;
I am able to create controls pro grammatically using the code below without issue:
FileListReader fReader = (FileListReader)LoadControl("~/Controls/FileListReader.ascx");
phFileLists.Controls.Add(fReader);
However, I would like to change the control so that I can give it a constructor like this:
public FileListReader(Int32 itemGroupId, Int32 documentType, String HeaderString, String FooterString, bool isAdminUser)
{
base.Construct();
this.itemGroupId = itemGroupId;
this.documentType = documentType;
this.HeaderString = HeaderString;
this.FooterString = FooterString;
this.isAdminUser = isAdminUser;
}
and then I should be able to call the control like this:
FileListReader fReader = (FileListReader)LoadControl(typeof(FileListReader), new Object[] { itemGroupId, 6, "Sell Sheets", "<br /><br />", isAdminUser });
However, when I do this I always get an error that my in page controls within my FileListReader Control have not been instantiated and I get a null reference error. So for example I have an <asp:Label></asp:label> control that errors out when I try to set it's text on the Page_Load method. What is causing this? I figured the base.Construct() would have solved this issue but it obviously has not.
The proper way to inherit a constructor is like this:
class FileListReader : WebControl
{
public FileListReader(Int32 itemGroupId,
Int32 documentType,
String HeaderString,
String FooterString,
bool isAdminUser) : base() // <-- notice the inherit
{
this.itemGroupId = itemGroupId;
this.documentType = documentType;
this.HeaderString = HeaderString;
this.FooterString = FooterString;
this.isAdminUser = isAdminUser;
}
// ... other code here ... //
}
Does changing your constructor like that fix the issue?
I am not sure that calling base.Contruct() is what you should be doing, try calling the default contructor of the base class example below:
public FileListReader(Int32 itemGroupId, Int32 documentType, String HeaderString, String FooterString, bool isAdminUser) :base()
{
base.Construct();
this.itemGroupId = itemGroupId;
this.documentType = documentType;
this.HeaderString = HeaderString;
this.FooterString = FooterString;
this.isAdminUser = isAdminUser;
}