C# Function calls using Services - c#

I am debugging a code that uses Services to execute Stored Procedures. The code is as follows:
void serviceClient_EvaluateScoresCompleted(object sender, EvaluateScoresCompletedEventArgs e)
{
if (e.Error == null)
{
this.GenerateExcelFiles(e.Result as System.Data.DataSet);
}
else
{
Response.Write(e.Error.Message);
Response.Write(e.Error.InnerException);
Response.Write(e.Error.StackTrace);
}
}
And the button click code is as follows:
protected void btnSubmit_Click(object sender, EventArgs e)
{
System.Collections.Generic.List<ConsultantShares> consultantShareList = this.GetConsultantShareList();
if (consultantShareList == null)
{
Response.Write("Please fix the Metioned Errors to Continue");
return;
}
CIServiceClient serviceClient = new CIServiceClient();
serviceClient.EvaluateScoresAsync(consultantShareList, this.ddlTargetProject.SelectedValue.Split(new char[] { '-' })[0], this.txtWorkclass.Text, this.ddlTargetProject.SelectedValue.Split(new char[] { '-' })[1]);
serviceClient.EvaluateScoresCompleted += new EventHandler<EvaluateScoresCompletedEventArgs>(serviceClient_EvaluateScoresCompleted);
}
There is no stored procedure named Evaluate Scores or Evaluate Scores Completed. The problem is with the e.Result as System.Data.DataSet above, as in the data in the DataSet is not correct and I want to see where this is calculated. Any help would be appreciated.

unless CIServiceClient is also developed by your group you likely won't be able to debug it. That's part of the reason to use web services, you keep the logic tucked away so the consumer has no need to see it.

Related

How to start a method multiple times, with different variables

I've been creating a autocheckout bot, and I'm very new to C#, and coding in general. I've gotten pretty far, almost done with the program, or so I thought, and now I want to have the ability to create multiple tasks, or run the task method multiple times. I also want to be able to input a different "profile", which has defined strings, such as login email, password, ect., on each task seperately. I'm very stuck and I have no idea where to even begin, maybe if someone could point me in the right direction for me to get started? last time I got some amazing help from this community, and it helped me a lot. Here is my current attempt:
public void KeywordTask1()
{
Start();
LogIn();
FindProductByKeyword();
stopwatch.Start();
AddToCart();
Checkout();
TimeSpan CheckoutTime = stopwatch.Elapsed;
}
public void KeywordTask2()
{
Start();
LogIn();
FindProductByKeyword();
stopwatch.Start();
AddToCart();
Checkout();
TimeSpan CheckoutTime = stopwatch.Elapsed;
}
I have buttons that start those tasks, but I also want the varibles to change, like a status text that I have set in my windows form. here is my GUI if it helps you understand my code a bit better:
https://gyazo.com/c6e9334e04aeb223e0afade6da8bec4e
Please let me know if you need anything else from me! I'm not sure if this is allowed but I'm willing to pay for someone to help me through this, not very much because I'm only 16 haha, but anyway, Thank you!
Well, I am not sure if this is what you want but if you want to run method with different variable value then create method:
public void MyMethod(string myVariable)
{
//do something with myVariable
}
And you can pass different variable value when calling method:
MyMethod("123abc");
or something like:
var newVariable="123abc"
MyMethod(newVariable);
To start method with different input create method with variable
public void MyUsername(string username)
{
MessageBox.Show(username);
}
private void buttonUsername1_Click(object sender, EventArgs e)
{
MyUsername("Adam");
}
private void buttonUsername2_Click(object sender, EventArgs e)
{
MyUsername("Jack");
}
To start method multiple time use loop
private void btnDoAllTask_Click(object sender, EventArgs e)
{
int count = 0;
// run 5 times
while(count < 5)
{
count++;
MyUsername("username" + count.ToString());
}
}
or loop through array
private void btnDoAllTask_Click(object sender, EventArgs e)
{
var listUsername = new string[] { "one", "two", "three" };
foreach (var username in listUsername)
{
MyUsername(username);
}
}

How to know the input buffer of the serial port has information, in C#?

I am building a program in C# to be used in one of my course at a college to demonstrate how Asynchronous connections work using RS-232 and two computers connected together. My course is not about programming, but data networks, so the connectivity is what I am looking for.
picture 1 - sample layout of GUI using Visual Studio 2015
One of the features I want to implement in my program is to show how a Master-slave, simplex connection works (i.e. the program can choose between been a master to send input from the keyboard; or slave to only receive information and print it on a textbox).
What I have already is the capability of initializing the serial port with specific characteristics (baud rate, data bits, stop bits, etc). This features are selected using combo boxes from the GUI, and assigned to the port when the user clicks a button to "open the port".
What I don't know is how to create the "slave" part of the program. My idea of what I could do is, after you choose the program to be "slave", you open the port waiting for some sort of flag or event to trigger when the input buffer has data stored.
I've been reading several forums and I can't find anything similar to what I need. I have, however, tested multiple alternatives that I believed would bring me closer to what I need with little to no result. I come to ask for an idea of what I could be doing wrong, or suggestions on how to tackle this problem. The problematic lines are bolded (or 2 stars ( * ) ):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace SerialCommTester
{
public partial class frmSerialComm : Form
{
static SerialPort _PuertoSerial;
public frmSerialComm()
{
InitializeComponent();
getAvailablePorts();
}
//---------------------------------my functions--------------------------------------
void getAvailablePorts()
{
string[] ports = SerialPort.GetPortNames();
cmbPortList.Items.AddRange(ports);
}
void activatePort()
{
//Note that all the combo boxes are named somewhat accordingly to what the information they are meant to display.
if (cmbPortList.Text != "" && cmbBaudRate.Text != "" && cmbParity.Text != "" && cmbStopBits.Text != "")
{
_PuertoSerial.PortName = cmbPortList.Text;
_PuertoSerial.BaudRate = Convert.ToInt32(cmbBaudRate.Text);
_PuertoSerial.RtsEnable = true;
_PuertoSerial.DtrEnable = true;
_PuertoSerial.DataBits = Convert.ToInt32(cmbDataBits.Text);
if (cmbParity.Text == "Even") { _PuertoSerial.Parity = Parity.Even; }
else if (cmbParity.Text == "Odd") { _PuertoSerial.Parity = Parity.Odd; }
else if (cmbParity.Text == "Space") { _PuertoSerial.Parity = Parity.Space; }
else if (cmbParity.Text == "Mark") { _PuertoSerial.Parity = Parity.Mark; }
else { _PuertoSerial.Parity = Parity.None; }
if (cmbStopBits.Text =="2") { _PuertoSerial.StopBits = StopBits.Two; }
else if (cmbStopBits.Text == "1.5") { _PuertoSerial.StopBits = StopBits.OnePointFive; }
else { _PuertoSerial.StopBits = StopBits.One; }
if (cmbHandShake.Text == "Software Flow Control") { _PuertoSerial.Handshake = Handshake.XOnXOff; }
else if (cmbHandShake.Text == "Hardware Flow Control") { _PuertoSerial.Handshake = Handshake.RequestToSend; }
else { _PuertoSerial.Handshake = Handshake.None; }
_PuertoSerial.ReadTimeout = 500;
_PuertoSerial.WriteTimeout = 500;
_PuertoSerial.Open();
//in my understanding, this line of code is needed to handle data being received. Does it trigger a flag or something?
**_PuertoSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);**
}
else
{
txtRecieve.Text = "Input selection missing 1 or more characteristics";
}
}
**
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort testing = (SerialPort)sender;
txtRecieve.AppendText(testing.ReadExisting()); //txtRecieve cannot be reached within this function. It indicates the following error: "An object reference is required for the non-static field, method, or property 'frmSerialComm.txtRecieve'
}
**
void enableDisableGUI(bool[] input)
{
grpConnection.Enabled = input[0];
grpCharacteristics.Enabled = input[1];
btnOpenPort.Enabled = input[2];
btnClosePort.Enabled = input[3];
txtSend.Enabled = ((cmbControlMasterSlave.Text == "Slave") ? false : true);
}
//----------------------------C# objects / functions--------------------------------------
private void btnOpenPort_Click(object sender, EventArgs e)
{
try
{
_PuertoSerial = new SerialPort();
activatePort();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
bool[] format = { false, false, false, true};
enableDisableGUI(format);
}
private void btnClosePort_Click(object sender, EventArgs e)
{
_PuertoSerial.Close();
bool[] format = { true, true, true, false};
enableDisableGUI(format);
}
private void txtSend_KeyPress(object sender, KeyPressEventArgs e)
{
_PuertoSerial.Write(e.KeyChar.ToString()); //this is how I send data through the serial port.
}
private void btnClearTxts_Click(object sender, EventArgs e)
{
txtRecieve.Clear();
txtSend.Clear();
}
} //class closes
} //program closes
I am not an experienced programmer, I just want to create something useful for my students. Any constructive criticism will be highly appreciated.
I don't have any definitive answers for you. You code looks like it should provide what you need once you get past the two possible glitches.
I think you should attach your SerialDataReceivedEventHandler BEFORE
you call _PuertoSerial.Open().
It may have no effect since event handlers can normally be enabled/disabled dynamically, but I base the advice on the following comment taken from the .Net source code for SerialPort on MSDN.
// all the magic happens in the call to the instance's .Open() method.
// Internally, the SerialStream constructor opens the file handle, sets the device control block and associated Win32 structures, and begins the event-watching cycle.
The "object reference" error might be resolved by removing the
static modifier from your DataReceivedHandler. If not, or if that
static modifier is necessary for some reason, then perhaps the
txtRecieve control has a private modifier which needs to be changed
to internal or public. You should be able to use Visual Studio in
debug mode to step into the InitializeComponent() method and see
where txtRecieve is being instantiated.
Well, I believe that I needed to read more. This is how I solved the problem (if this is not the real solution, at least is working for now):
I moved the "SerialDataReceivedEventHandler" line before the _PuertoSerial.open();
I followed the suggestions from this article:
https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(EHInvalidOperation.WinForms.IllegalCrossThreadCall);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)&rd=true
So my funtions (one existings + a new one) look like this:
void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
printReceivedText(_PuertoSerial.ReadExisting());
}
private void printReceivedText(string text)
{
if (this.txtSend.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(printReceivedText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtRecieve.AppendText(text);
_PuertoSerial.DiscardInBuffer();
}
}
For now seems to be working fine. The final testing will come when I connect another terminal and see the program interacting with each other.

Session returns with null after calling web service

The service is working fine and return the correct response. the problem is if I use sessions after calling the service, it converts to be null out of the scope which I called the service inside.
Edit 1: after tracing, I found that there is a line in MyOperation method in the service which write a text into file [ File.WriteAllText(Path, txt);], and if I comment this line, sessions works fine. any explanation ?
protected void Button1_Click(object sender, EventArgs e)
{
client = new MySvc.MyServiceClient();
var res = client.MyOperation(); // If I comment this line, sessions works fine.
Session["val"] = 2000;
}
protected void Button2_Click(object sender, EventArgs e)
{
var foo = Session["val"]; // always null
}
Please help me with that.
Wrap the three lines of code in Button1_Click in a try-catch block or just the first two lines in the try block and the last line in the finally block.
There may be an exception which is not being caught which would prevent the next line (Session["val"] = 2000;) from being performed correctly.

Difference between LoadState and navigationHelper_LoadState

I am new to windows store app development. Currently I am looking into passing and receiving parameter between xamls, using c#.
Can someone help explain difference between LoadState() and navigationHelper_LoadState() with some examples? Which should I go for receiving parameter?
So, NavigationHelper.LoadState requires two things:
OnNavigatedTo Invoked when this page is about to be displayed in a Frame.
NavigationMode.New Navigation is to a new instance of a page (not forward or back)
MSDN says:
In addition to providing the implementations described earlier, NavigationHelper also needs to be called from the OnNavigatedTo() and OnNavigatedFrom() event handlers that are implemented on each page. When these events occur, NavigationHelper calls a page-specific implementation of LoadState() and SaveState(). You can customize the implementation of these functions on each page. They should be used in place of OnNavigatedTo() and OnNavigatedFrom() respectively.
The raw code is:
public void OnNavigatedTo(NavigationEventArgs e)
{
var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
this._pageKey = "Page-" + this.Frame.BackStackDepth;
if (e.NavigationMode == NavigationMode.New)
{
var nextPageKey = this._pageKey;
int nextPageIndex = this.Frame.BackStackDepth;
while (frameState.Remove(nextPageKey))
{
nextPageIndex++;
nextPageKey = "Page-" + nextPageIndex;
}
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, null));
}
}
else
{
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey]));
}
}
}
For the sake of your question, there is no LoadState() override unless you define your own like this blog. He simply does this:
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
LoadState(e);
}
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
SaveState(e);
}
protected virtual void LoadState(LoadStateEventArgs e) { }
protected virtual void SaveState(SaveStateEventArgs e) { }
See, they are identical. Nothing different between them except the execution pipeline which might impact timing a little, but not likely. In the end, no real difference. People who need to use one over the other... they have to be mistaken, attributing a cause where something else is the influence.
Best of luck.
There are a lot of example online. You might be better off going through those and then coming back here for more specific questions.
http://marcominerva.wordpress.com/2013/10/10/a-base-page-class-for-windows-8-1-store-apps-with-c-and-xaml/

Resting a private variable that should not happen

I have a strange problem I'm checking in my code behind the user if he is active or not with as simple if .. in my Page_Load method as you can see here
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
this.getParameters();
if (!this.IsPostBack)
{
if (paramTR.ZevUser.Active == 0)
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
}
But when I make a go throw to this method I get allays nullreferenceexception why so ever .. but the private ZevUser variable is not null it's full..
I really don't have a clue why is this happing, it would be really cool if someone could explain me this why this is happening
Thanks for help and fast answer
You need to break your code down so you can debug it easier or add logging if you cannot debug this code locally.
Remember that when debugging something, the worse mistake you can make is to make assumptions. Start from the beginning and follow the process through. Don't assume that the problem is something and don't assume that the problem can't be something:
I've included a broken down, more readable version below. You can now add logging around this or easily add breakpoints:
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
this.getParameters();
if (!this.IsPostBack)
{
if ((this.paramTR != null) &&
(this.paramTR.ZevUser != null) &&
(this.paramTR.ZevUser.Active == 0))
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
string sessionId = Session["SessionId"] as string;
if (sessionId != null)
{
int session = int32.Parse(sessionId);
ZevUser user = ZevUser.GetById(session);
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
}
}
Why are you passing the session id to ZevUser.GetById()? I would expect this to take a user id, or for the method to be called something like ZevUser.GetBySessionId(). At the moment it's quite confusing.
This line is causing the issue:
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
This is because Session["SessionId"] can be null, and is null in this case.
If you are looking to get the SessionId that is set by ASP.net, then use this.Session.SessionID (source).
If you are storing a value in Session["SessionId"] that you are trying to retrieve, then do a null-check first:
if (Session["SessionId"] != null) { ...
You should consider testing the SessionId variable before using it by doing something like that :
if (!string.IsNullOrEmpty(Session["SessionId"].ToString()))
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
The best way to debug your exception is to enable debug when the exception is thrown.
For this, go to Debug>>Exceptions
and then enable first four checkboxes (maybe) and then try debugging the project. You will be halted at the position from where the exception will be thrown.

Categories