I have written an asynchronous server using .Net socket, and when this server is overloaded (receiving a lot of data, file for example), all the packets are not received by the server.
If I increase the length of buffer, I receive more data but not all the packets.
Is anybody have a solution to my problem?
The code of my server is :
class ServerFile
{
#region Delegate
private delegate void Method(ConnectionInfoFile Infos, Object Content);
#endregion
#region Fields
private Int32 Port;
private Socket ServerSocket = null;
private List<ConnectionInfoFile> Connections = new List<ConnectionInfoFile>();
private Dictionary<Command, Method> Map = new Dictionary<Command, Method>();
#endregion
#region Constructor
public ServerFile(Int32 Port)
{
this.Port = Port;
this.Map[Command.Server_User_Login] = this.Login;
}
#endregion
#region Methods - Login
private void Login(ConnectionInfoFile Client, Object Content)
{
Client.Id = (Int32)Content;
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - The client is now authentified as '" + Client.Id + "'.");
}
#endregion
#region Methods - Receive
private void ReceiveCallback(IAsyncResult Result)
{
ConnectionInfoFile Connection = (ConnectionInfoFile)Result.AsyncState;
try
{
Int32 BytesRead = Connection.Socket.EndReceive(Result);
if (BytesRead != 0)
{
Byte[] Message = (new MemoryStream(Connection.AsyncBuffer, 0, BytesRead)).ToArray();
Connection.Append(Message);
Packet Packet;
while ((Packet = Connection.TryParseBuffer()) != null)
{
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - Command received : " + Packet.Command.ToString());
if (Packet.Recipient == 0)
{
if (this.Map.ContainsKey(Packet.Command))
this.Map[Packet.Command](Connection, Packet.Content);
}
else
{
foreach (ConnectionInfoFile Item in this.Connections)
{
if (Item.Id == Packet.Recipient)
{
Byte[] Buffer = Packet.Serialize(Connection.Id, Packet.Command, Packet.Content);
this.Send(Item, Buffer);
}
}
}
}
Connection.Socket.BeginReceive(Connection.AsyncBuffer, 0, Connection.AsyncBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), Connection);
}
else
this.CloseConnection(Connection);
}
catch (SocketException E)
{
CloseConnection(Connection);
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - Receive socket exception : " + E.SocketErrorCode);
}
catch (Exception E)
{
CloseConnection(Connection);
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - Receive exception : "+ E.Message);
}
}
#endregion
#region Methods - CloseConnection
private void CloseConnection(ConnectionInfoFile Connection)
{
Connection.Socket.Close();
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - The user " + Connection.Id + " has been disconnected !");
lock (this.Connections)
{
this.Connections.Remove(Connection);
}
}
#endregion
#region Methods - Send
protected void Send(IConnectionInfo Connection, Byte[] Buffer)
{
Connection.Socket.BeginSend(Buffer, 0, Buffer.Length, 0, new AsyncCallback(SendCallback), Connection);
}
private static void SendCallback(IAsyncResult Result)
{
try
{
IConnectionInfo Connection = (IConnectionInfo)Result.AsyncState;
Int32 BytesSent = Connection.Socket.EndSend(Result);
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + typeof(ServerFile).Name.Insert(6, " ") + " - Sent " + BytesSent + " bytes " + Connection.Id.ToString() + ".");
}
catch (Exception E)
{
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + typeof(ServerFile).GetType().Name.Insert(6, " ") + " - Exception : " + E.ToString());
}
}
#endregion
#region Methods - Stop
public void Stop()
{
this.ServerSocket.Close();
this.ServerSocket = null;
}
#endregion
#region Methods - Start
public void Start()
{
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - Start listening on port " + this.Port + "...");
this.ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.ServerSocket.Bind(new IPEndPoint(IPAddress.Any, this.Port));
this.ServerSocket.Listen((Int32)SocketOptionName.MaxConnections);
for (Int32 i = 0; i < 5; i++)
this.ServerSocket.BeginAccept(new AsyncCallback(this.AcceptCallback), this.ServerSocket);
}
#endregion
#region Methods - Accept
private void AcceptCallback(IAsyncResult Result)
{
ConnectionInfoFile Connection = new ConnectionInfoFile();
Socket Socket = (Socket)Result.AsyncState;
try
{
Connection.Socket = Socket.EndAccept(Result);
Connection.ConnectionDate = DateTime.Now;
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - A new client has been registered");
lock (this.Connections)
{
this.Connections.Add(Connection);
}
Connection.Socket.BeginReceive(Connection.AsyncBuffer, 0, Connection.AsyncBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), Connection);
}
catch (SocketException E)
{
this.CloseConnection(Connection);
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - Accept socket exception: " + E.SocketErrorCode);
}
catch (Exception E)
{
this.CloseConnection(Connection);
Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] - " + this.GetType().Name.Insert(6, " ") + " - Accept exception: " + E.Message);
}
Socket.BeginAccept(new AsyncCallback(AcceptCallback), Result.AsyncState);
}
#endregion
}
Sorry for my English and thanks a lot.
NeoKript
Related
I am calling following method inside thread. inside method i have written logs which writes some variable values in notepad file.
Problem : Sometime last log of method do not log anything. ie last line not exucuting sometime. i am not able to understand problem. please guide me if there are issue somewhere.
This is web application hosted in iis server.
Function :
public bool ResetEmployeeAssignedCoursesByRole()
{
bool bReturn = false;
DbTransactionHelper dbTransactionHelper = new DbTransactionHelper();
dbTransactionHelper.BeginTransaction();
try
{
// this line execuete fine
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Started " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
StringBuilder sbQueryEmployeeCourse = new StringBuilder();
sbQueryEmployeeCourse.Append(" set #roleID = " + roleID + "; ");
sbQueryEmployeeCourse.Append(" set #courseID = " + courseID + "; ");
sbQueryEmployeeCourse.Append(" set #inActiveReason = " + inActiveReason + "; ");
sbQueryEmployeeCourse.Append(" set #lastRecordUpdateSource = " + lastRecordUpdateSource + "; ");
sbQueryEmployeeCourse.Append(" call sp_Reset_EmpAssignedCoursesByRole (#roleID, #courseID, #inActiveReason, #lastRecordUpdateSource); ");
DataTable dtEmployeeCourse = dbTransactionHelper.GetDataTable(BusinessUtility.GetString(sbQueryEmployeeCourse), CommandType.Text, null
);
dbTransactionHelper.CommitTransaction();
bReturn = true;
// this line not execuete sometime.
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
}
catch (Exception ex)
{
ErrorLog.createRoleLog("Add Role ID " + BusinessUtility.GetString(roleID));
dbTransactionHelper.RollBackTransaction();
ErrorLog.createRoleLog("Add Course ID " + BusinessUtility.GetString(courseID));
ErrorLog.createRoleLog(ex.ToString());
}
return bReturn;
}
Calls method like below :
Thread t = new Thread(ResetEmployeeAssignedCoursesByRole);
t.Start();
FUNCTION createRoleLog :
public static void createRoleLog(string errorMessage, int empHdrID = 0)
{
try
{
//string path = BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogsDiractory")) + "Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string path = BusinessUtility.GetString(ErrorLog.ErrorLogPath) + "RoleLog" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogError")).ToString().ToUpper() == "TRUE")
{
if (!File.Exists(path))
{
StreamWriter sw = File.CreateText(path);
sw.Close();
}
//using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
//{
// sw.WriteLine("-------- " + DateTime.Now + " --------");
// sw.WriteLine(errorMessage);
// sw.WriteLine("------------------------");
// sw.Close();
//}
if (!IsFileLocked(new FileInfo(path)))
{
using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (System.IO.StreamWriter sw = new StreamWriter(stream))
{
if (empHdrID != 0)
{
sw.WriteLine("-------- [empHdrID: " + empHdrID + "] " + DateTime.Now + " --------");
}
else
{
sw.WriteLine("-------- " + DateTime.Now + " --------");
}
sw.WriteLine(errorMessage);
sw.WriteLine("------------------------");
sw.Close();
}
}
}
else
{
}
}
}
catch (Exception ex)
{
//throw ex;
}
}
Last line of function which not execution sometime is :
** this line not execuete sometime.**
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
I'm trying to develop a sms sending system using asp.net mvc 4 where I'm using HUAWEI USB 3G modem to send sms. Problem is, when I receive sms, most often the text are coming like this,
AT+CMGF=1 AT+CMGS="+8801671234567" Name: Sample Name Amount1: 1000.....
Here are my codes,
public ActionResult SendSms(int RentId=0)
{
AmountInfo BillTable = db.AmountInfoes.Find(RentId);
var GetName = db.AmountInfoes.Where(a => a.serial.Equals(BillTable.serial)).FirstOrDefault();
string getName = GetName.name;
int getAmount1 = GetName.amount1;
int getAmount2 = GetName.amount2;
int getAmount3 = GetName.amount3;
int getAmount4 = GetName.amount4;
int getAmount5 = GetName.amount5;
int getAmount6 = GetName.amount6;
string getNumber = GetName.phone;
try
{
SP.PortName = "COM8";
SP.Close();
SP.Open();
string ph_no;
string the_no = getNumber;
string txt_msg = "Name: " + getName + " Amount1: " + getAmount1 + " Amount2: " + getAmount2 + " Amount3: " + getAmount3 + " Amount4: " + getAmount4 + " Amount5: " + getAmount5 + " Amount6: " + getAmount6;
ph_no = Char.ConvertFromUtf32(34) + the_no + char.ConvertFromUtf32(34);
SP.Write("AT+CMGF=1" + Char.ConvertFromUtf32(13));
SP.Write("AT+CMGS=" + ph_no + Char.ConvertFromUtf32(13));
SP.Write(txt_msg + Char.ConvertFromUtf32(26) + Char.ConvertFromUtf32(13));
SP.Close();
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("RentManager");
}
Is there something wrong in my code? How can I fix this problem where AT commands will not appear in my sms? Need this help badly. Thanks.
Following Code snippet is sending PIN to another Self Hosted WCF service inside Windows Service which further then makes a call to SMPP server. But that only happens when i am in debug mode. In normal mode it does not work.
$
ChannelFactory<IServiceWCF> pipeFactory =
new ChannelFactory<IServiceWCF>(
new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/MyService/PipeForMyService"));
pipeProxy = pipeFactory.CreateChannel();
pipeProxy.Connect();
pipeProxy.SendPin(pin);
ServiceWCF
$
public class ServiceWCF : IServiceWCF
{
PINComposer pinComposer = new PINComposer();
public bool SendPin(string pin)
{
Library.WriteErrorLog("Call Hits. Pin is " + pin);
PINComposer pinComposer = new PINComposer();
pinComposer.Connect();
pinComposer._client.SendSpeedLimit = 0;
DataCodings coding = (DataCodings)Enum.Parse(typeof(DataCodings), "Default");
byte srcTon = byte.Parse("0");
byte srcNpi = byte.Parse("0");
string srcAdr = "2378";
byte dstTon = byte.Parse("1");
byte dstNpi = byte.Parse("1");
string dstAdr = "03347823422";
IList<SubmitSmResp> resp = pinComposer._client.Submit(SMS.ForSubmit()
.From(srcAdr, srcTon, srcNpi)
.To(dstAdr, dstTon, dstNpi)
.Coding(coding)
.Text(pin + " " + "is your pin code")
.ExpireIn(TimeSpan.FromDays(2))
.DeliveryReceipt()
);
Library.WriteErrorLog("SMS Sent");
return true;
}
public bool Connect()
{
pinComposer.Connect();
return true;
}
}
PINComposer.CS
$
class PINComposer
{
public readonly SmppClient _client;
private readonly MessageComposer _messageComposer = new MessageComposer();
public PINComposer()
{
_client = new SmppClient();
_client.Timeout = 60000;
_client.NeedEnquireLink = true;
_client.EnquireInterval = 20;
_client.RaiseEventsInMainThread = true;
_client.evConnected += new Inetlab.SMPP.Common.ConnectedEventHandler(client_evConnected);
_client.evDisconnected += new Inetlab.SMPP.Common.DisconnectedEventHandler(client_evDisconnected);
_client.evBindComplete += new Inetlab.SMPP.Common.BindRespEventHandler(client_evBindComplete);
_client.evDeliverSm += new Inetlab.SMPP.Common.DeliverSmEventHandler(client_evDeliverSm);
_client.evEnquireLink += new Inetlab.SMPP.Common.EnquireLinkEventHandler(client_evEnquireLink);
_client.evGenericNack += new Inetlab.SMPP.Common.GenericNackEventHandler(client_evGenericNack);
_client.evUnBind += new Inetlab.SMPP.Common.UnBindEventHandler(client_evUnBind);
_client.evDataSm += new Inetlab.SMPP.Common.DataSmEventHandler(client_evDataSm);
_client.evSubmitComplete += new Inetlab.SMPP.Common.SubmitSmRespEventHandler(client_evSubmitComplete);
_client.evQueryComplete += new Inetlab.SMPP.Common.QuerySmRespEventHandler(client_evQueryComplete);
_messageComposer.evFullMessageReceived += OnFullMessageReceived;
_messageComposer.evFullMessageTimedout += OnFullMessageTimedout;
}
public void Connect()
{
if (_client.Status == ConnectionStatus.Closed)
{
_client.AddrNpi = Convert.ToByte(0);
_client.AddrTon = Convert.ToByte(0);
_client.EnabledSslProtocols = SslProtocols.None;
_client.ConnectAsync("172.16.53.39", 2775);
}
}
void client_evConnected(object sender, bool bSuccess)
{
if (bSuccess)
{
_client.BindAsync("radius", "rad12", ConnectionMode.Transceiver);
Library.WriteErrorLog("SMPP Service has been connected to server...");
}
}
private void client_evEnquireLink(object sender, EnquireLink data)
{
Library.WriteErrorLog("Link with server is alive...");
}
private void client_evGenericNack(object sender, GenericNack data)
{
Library.WriteErrorLog("GenericNack received with status " + data.Status.ToString());
}
private void client_evUnBind(object sender, UnBind data)
{
Library.WriteErrorLog("UnBind request received");
}
void client_evSubmitComplete(object sender, SubmitSmResp data)
{
Library.WriteErrorLog("SubmitSmResp received." + " Status: " + data.Status + ", Message Id: " + data.MessageId + ", Sequence: " + data.Sequence);
}
void client_evQueryComplete(object sender, QuerySmResp data)
{
Library.WriteErrorLog("QuerySmResp received." + " Status: " + data.Status + ", Message Id: " + data.MessageId + ", Sequence: " + data.Sequence + ", Message State: " + data.MessageState);
}
private void client_evDeliverSm(object sender, DeliverSm data)
{
try
{
//Check if we received Delivery Receipt
if (data.MessageType == MessageTypes.SMSCDeliveryReceipt)
{
//Get MessageId of delivered message
string messageId = data.Receipt.MessageId;
MessageState deliveryStatus = data.Receipt.State;
}
else
{
// Receive incoming message and try to concatenate all parts
if (data.Concatenation != null)
{
_messageComposer.AddMessage(data);
Library.WriteErrorLog(
string.Format(
"DeliverSm part received : Sequence : {0} SourceAddr : {1} Concatenation ( {2} )" +
" Coding : {3} Text : {4}",
data.Sequence, data.SourceAddr, data.Concatenation, data.DataCoding, data.MessageText));
}
else
{
Library.WriteErrorLog("DeliverSm received : "
+ " Sequence : " + data.Sequence
+ " SourceAddr : " + data.SourceAddr
+ " Coding : " + data.DataCoding
+ " MessageText : " + data.MessageText);
}
}
}
catch (Exception ex)
{
data.Response.Status = CommandStatus.ESME_RX_T_APPN;
Library.WriteErrorLog("Failed to process DeliverSm" + ex);
}
}
private void client_evDataSm(object sender, DataSm data)
{
string messageText = data.Client.GetMessageText(data);
Library.WriteErrorLog("DataSm received :"
+ " Sequence: " + data.Sequence
+ ", SourceAddr: " + data.SourceAddr
+ ", DestAddr: " + data.DestAddr
+ ", Coding: " + data.DataCoding
+ ", Text: " + messageText);
}
void client_evDisconnected(object sender)
{
Library.WriteErrorLog("SmppClient disconnected");
}
private void OnFullMessageTimedout(object sender, MessageEventHandlerArgs args)
{
Library.WriteErrorLog(string.Format("Incomplete message received from {0}", args.Parts[0].SourceAddr));
}
private void OnFullMessageReceived(object sender, MessageEventHandlerArgs args)
{
Library.WriteErrorLog(string.Format("Full message received from {0}: {1}", args.Parts[0].SourceAddr, args.Text));
}
void client_evBindComplete(object sender, Inetlab.SMPP.PDU.BindResp data)
{
switch (data.Status)
{
case CommandStatus.ESME_ROK:
Library.WriteErrorLog("SmppClient bound");
Library.WriteErrorLog("Bind result : system is " + data.SystemId + " with status " + data.Status.ToString());
break;
default:
Library.WriteErrorLog("Bad status returned during Bind : " + data.Command.ToString() + " with status " + data.Status.ToString());
break;
}
}
}
How are you launching the various projects and in which order ?
If I recall correctly, the "Auto hosting" provided by the WCF development tools only works in debug, and in release you have to deploy "properly".
This documentation my help out : Using the WCF Development Tools
I'm using the BusyIndicator in my program, the purpose is to show a busy indicator on the view, while the viewModel is loading data from the database.
*Note: before I added the backgroundworker everything worked perfectly.
My program is build in this way:
I have a view that contains:
<NetworkUI:NetworkView
x:Name="networkControl"
NodesSource="{Binding Network.Nodes}"
ConnectionsSource="{Binding Path=Network.Connections}"
MouseDown="networkControl_MouseDown"
MouseUp="networkControl_MouseUp"
MouseMove="networkControl_MouseMove"
/>
Where Network.Nodes and Network.Connections are my problem (I need to see them and I don't)
They are binded to the viewModel called mainWindowViewModel, the main method for getting data from Database called ShowSystem:
public void ShowSystem(bool update)
{
List<String> interfacesForFlow = new List<String>();
#region CreateNetworkClasses
MethodInfo getInterfacesWithGuidToFlow = dbType.GetMethod("getInterfacesWithGuidToFlow");
#endregion
MainNet = Common.Model.Network.getNetwork();
Debug.WriteLine("MainNet.Systems.Count = " + MainNet.Systems.Count);
if (MainNet.Systems.Count == 0)
update = true;
List<String> systemNames = new List<string>();
if (update)
{
if(MainNet.Systems.Count > 0)
MainNet.Systems.Clear();
if (this.Network.Nodes.Count > 0)
{
this.Network.Nodes.Clear();
this.Network.Connections.Clear();
}
try
{
systemNames = (List<String>)getAllSystemMethod.Invoke(sqlDB, null);
Debug.WriteLine("Success getAllSystemMethod");
}
catch (Exception ex)
{
logger.addMessage("Error in getAllSystemMethod: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getAllSystemMethod: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
#region CreateSystems
foreach (var sysName in systemNames)
{
#region Intializating
ObservableCollection<Common.Model.Enum> enums = new ObservableCollection<Common.Model.Enum>();
ObservableCollection<Common.Model.Struct> structs = new ObservableCollection<Common.Model.Struct>();
ObservableCollection<Common.Model.Interface> interfaces = new ObservableCollection<Common.Model.Interface>();
//List<Model.Enum> enums = new List<Model.Enum>();
//List<Model.Struct> structs = new List<Model.Struct>();
//List<Model.Interface> interfaces = new List<Model.Interface>();
int systemId = -1;
Object[] getSystemIdParams = new Object[1];
getSystemIdParams[0] = sysName;
try
{
systemId = (int)getSystemId.Invoke(sqlDB, getSystemIdParams);
Debug.WriteLine("Success getSystemId systemId = " + systemId);
}
catch (Exception ex)
{
logger.addMessage("Error in getSystemId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSystemId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
List<int> sysEnumsIds = new List<int>();
List<int> sysStructsIds = new List<int>();
List<int> sysInterfacesIds = new List<int>();
Object[] getSysEnumsIdParams = new Object[1];
getSysEnumsIdParams[0] = systemId;
try
{
sysEnumsIds = (List<int>)getSysEnumsId.Invoke(sqlDB, getSysEnumsIdParams); //return List<int> all system Enums ids
if (sysEnumsIds.Count > 0)
Debug.WriteLine("Success getSysEnumsId first count is " + sysEnumsIds.Count);
else
Debug.WriteLine("success getSysEnumsId but no ids found");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysEnumsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysEnumsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSysStructsIdParams = new Object[1];
getSysStructsIdParams[0] = systemId;
try
{
sysStructsIds = (List<int>)getSysStructsId.Invoke(sqlDB, getSysStructsIdParams);
if (sysStructsIds.Count > 0)
Debug.WriteLine("success getSysStructsId count = " + sysStructsIds.Count);
else
Debug.WriteLine("success getSysStructsId but no ids found");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysStructsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysStructsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSysInterfacesIdParams = new Object[1];
getSysInterfacesIdParams[0] = systemId;
try
{
sysInterfacesIds = (List<int>)getSysInterfacesId.Invoke(sqlDB, getSysInterfacesIdParams);
if (sysInterfacesIds.Count > 0)
Debug.WriteLine("Success getSysInterfacesId count = " + sysInterfacesIds.Count);
else
Debug.WriteLine("success getSysInterfacesId but no ids found");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysInterfacesId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysInterfacesId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
#endregion
#region GetInterfaces
foreach (var #interface in sysInterfacesIds) //get interface
{
ObservableCollection<Common.Model.Message> messages = new ObservableCollection<Common.Model.Message>();
ObservableCollection<Common.Model.Definition> definitions = new ObservableCollection<Common.Model.Definition>();
ObservableCollection<Common.Model.Include> includes = new ObservableCollection<Common.Model.Include>();
List<int> includesIds = new List<int>();
List<int> definitionsIds = new List<int>();
List<int> messagesIds = new List<int>();
#region getIncludes
Object[] getIncludesIdsParams = new object[1];
getIncludesIdsParams[0] = #interface;
try
{
includesIds = (List<int>)getIncludesIds.Invoke(sqlDB, getIncludesIdsParams);
Debug.WriteLine("Success getIncludesIds " + includesIds.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getIncludesIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getIncludesIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
foreach (var id in includesIds)
{
Object[] getIncludeParams = new object[1];
getIncludeParams[0] = id;
string includeName = "";
try
{
includeName = (string)getInclude.Invoke(sqlDB, getIncludeParams);
Debug.WriteLine("Success get include name = " + includeName);
}
catch (Exception ex)
{
logger.addMessage("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
}
includes.Add(new Common.Model.Include(includeName));
}
#endregion
#region getdefinitions
Object[] getdefinitionsIdsParams = new object[1];
getdefinitionsIdsParams[0] = #interface;
try
{
definitionsIds = (List<int>)getDefinitionsIds.Invoke(sqlDB, getdefinitionsIdsParams);
Debug.WriteLine("Success getDefinitionsIds " + definitionsIds.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getDefinitionsIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getDefinitionsIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
foreach (var id in definitionsIds)
{
List<Object> definition = new List<object>();
Object[] getDefinitionParams = new object[1];
getDefinitionParams[0] = id;
string includeName = "";
try
{
definition = (List<Object>)getDefinition.Invoke(sqlDB, getDefinitionParams);
Debug.WriteLine("Success getDefinisions " + definition[0]);
}
catch (Exception ex)
{
logger.addMessage("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
}
definitions.Add(new Common.Model.Definition(Convert.ToString(definition[0]), Convert.ToInt32(definition[1])));
}
#endregion
Object[] getInterfaceFromIdParam = new Object[1];
getInterfaceFromIdParam[0] = #interface;
List<Object> tempInterface = new List<object>();
try
{
tempInterface = (List<Object>)getInterfaceFromId.Invoke(sqlDB, getInterfaceFromIdParam);
Debug.WriteLine("Success getInterfaceFromId " + tempInterface.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getInterfaceFromId : " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInterfaceFromId : " + ex.Message + " Inner: " + ex.InnerException.Message);
}
interfaces.Add(new Common.Model.Interface(messages, definitions, includes, Convert.ToString(tempInterface[0]), Convert.ToString(tempInterface[1]), Convert.ToInt32(tempInterface[2]), Convert.ToInt32(tempInterface[3]), Convert.ToBoolean(tempInterface[4])));
Debug.WriteLine("Success adding new interface: " + interfaces.Last().Name);
}
#endregion
#region InputOutputNumber
List<int> inputs = new List<int>();
List<int> outputs = new List<int>();
int inputCount = 0;
int outputCount = 0;
Object[] getSysInputNumParams = new Object[1];
getSysInputNumParams[0] = systemId;
try
{
inputs = (List<int>)getSysInputs.Invoke(sqlDB, getSysInputNumParams);
if (inputs != null)
{
inputCount = inputs.Count;
Debug.WriteLine("Success getSysInputNum inputs = " + inputCount);
}
else
Debug.WriteLine("Success getSysInputNum inputs = 0");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysInputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysInputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSysOutputNumParams = new Object[1];
getSysOutputNumParams[0] = systemId;
try
{
outputs = (List<int>)getSysOutputs.Invoke(sqlDB, getSysOutputNumParams);
if (outputs != null)
{
outputCount = outputs.Count;
Debug.WriteLine("Success getSysOutputNum outputs = " + outputCount);
}
else
Debug.WriteLine("Success getSysOutputNum outputs = 0");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysOutputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysOutputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
#endregion
Common.Model.System system = null;
try
{
system = new Common.Model.System(interfaces, enums, structs, sysName, inputCount, outputCount, inputs, outputs);
Debug.WriteLine("Success adding new system");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new system: " + ex.Message);
Debug.WriteLine("Error in creating new system: " + ex.Message);
}
MainNet.Systems.Add(system);
Debug.WriteLine("Done! you now have a new system with: " + interfaces.Count + " interfaces And " + enums.Count + " Enums and " + structs.Count + " Structs, The name is: " + sysName + " numOfInput: " + inputCount + " numOfOutput: " + outputCount);
#endregion
}
#endregion
}
#region addNodesToUi
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
try
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
Debug.WriteLine("Success creating new nodeViewModel");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new nodeViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in creating new nodeViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
}
int width = 0;
int height = 0;
foreach (var system in MainNet.Systems)
{
Debug.WriteLine("inside Foreach in system: " + system.Name + " interface " + system.Interfaces.Count + " structs " + system.Structs.Count);
if (nodes == null)
Debug.WriteLine("FUUUCCKKKK!");
try
{
Debug.WriteLine("Before add node");
try
{
Debug.WriteLine("trying to add: " + system.Name + " " + system.InputNum + " " + system.OutputNum + " " + system.Interfaces.Count + " " + system.Enums.Count + " " + system.Structs.Count);
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => nodes.Add(CreateNode(system.Name, new Point(width, height), false, system.InputNum, system.OutputNum, system.Interfaces, system.Enums, system.Structs, update))));
}
catch (Exception ex)
{
logger.addMessage("Error adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Debug.WriteLine("Success adding new node to list");
}
catch (Exception ex)
{
logger.addMessage("Error in adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
}
width += 150;
if (width >= 700)
{
width = 0;
height += 100;
}
}
if (MainWindow.IsFlow)
{
Object[] getInterfacesWithGuidToFlowParam = new Object[1];
getInterfacesWithGuidToFlowParam[0] = MainWindow.GuidToFlow;
try
{
interfacesForFlow = (List<String>)getInterfacesWithGuidToFlow.Invoke(sqlDB, getInterfacesWithGuidToFlowParam);
Debug.WriteLine("Success getInterfacesWithGuidToFlow " + interfacesForFlow.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getInterfacesWithGuidToFlow : " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInterfacesWithGuidToFlow : " + ex.Message + " Inner: " + ex.InnerException.Message);
}
}
foreach (var system in MainNet.Systems)
{
if (system.OutputNum > 0) //this system has an output connector
{
int i = 0;
foreach (var outId in system.Outputs) //loop throw all systems ids that current system is connected to
{
Debug.WriteLine("out id = " + outId);
ConnectionViewModel connection = null;
try
{
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection = new ConnectionViewModel()));
Debug.Write("Success creating new ConnectionViewModel");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new ConnectionViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in creating new ConnectionViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSystemNameParams = new Object[1];
getSystemNameParams[0] = outId;
string destSystemName = "";
try
{
destSystemName = (String)getSystemName.Invoke(sqlDB, getSystemNameParams);
}
catch (Exception ex)
{
logger.addMessage("Error in getSystemName: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSystemName: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
NodeViewModel sourceItem = null;
NodeViewModel destItem = null;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => sourceItem = nodes.Find(x => x.Name == system.Name)));
//int sourceId = nodes.FindIndex(sourceItem);
Debug.Write("Success creating new sourceItem");
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => destItem = nodes.Find(x => x.Name == destSystemName)));
Debug.Write("Success creating new destItem");
try
{
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => destItem.InputSystems.Add(sourceItem.Name)));
}
catch (Exception ex)
{
logger.addMessage("Error adding input system: " + ex.Message);
Debug.Write("Error adding input system: " + ex.Message);
}
try
{
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => sourceItem.OutputSystems.Add(destItem.Name)));
}
catch (Exception ex)
{
logger.addMessage("Error adding OutputSystems: " + ex.Message);
Debug.Write("Error adding OutputSystems: " + ex.Message);
}
Debug.Write("Success bah");
//int destId = nodes.FindIndex(destItem);
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.SourceConnector = sourceItem.OutputConnectors[i++]));
Debug.Write("Success bah");
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.DestConnector = destItem.InputConnectors[destItem.InputConnectors.Count - 1]));
Debug.Write("Success bah");
// Add the connection to the view-model.
//
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.Type = ConnectionViewModel.ConnectorType.REGULAR));
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => this.Network.Connections.Add(connection)));
//Debug.Write("Success bah");
if (MainWindow.IsFlow)
{
Debug.WriteLine("inside IsFlow!");
foreach (var #interface in interfacesForFlow)
{
String[] systems = #interface.Split('_');
Debug.WriteLine("Flow from: " + systems[0] + " To " + systems[1]);
if(systems[0].Equals(sourceItem.Name) && systems[1].Equals(destItem.Name))
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.Type = ConnectionViewModel.ConnectorType.FLOW));
}
}
}
}
}
#endregion
}
And this method is being called from the backgroundWorker DoWork method, these all the backgroundWorker references:
public MainWindowViewModel()
{
//
// Create a network, the root of the view-model.
//
Network = new NetworkViewModel();
nodes = new List<NodeViewModel>();
//ShowSystem(false);
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync(false);
//create networkt according to classes created
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => this.IsBusy = false));
this.IsBusy = false;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => OnPropertyChanged("Network")));
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
this.BusyContent = "Please Wait...";
this.IsBusy = true;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ShowSystem((bool)e.Argument)));
}
You have not implemented your BackgroundWorker correctly, despite me already providing you with a link to see how it should be implemented in the comments:
Progress Bar update from Background worker stalling
You're not even calling your ShowSystem method from the BackgroundWorker, so how do you expect to get any data?:
void bw_DoWork(object sender, DoWorkEventArgs e)
{
//You should only update UI properties from here using Dispatcher.CurrentDispatcher
this.BusyContent = "Please Wait...";
this.IsBusy = true;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => OnPropertyChanged("Network")));
//This runs on the background thread so this is where you do long running process
ShowSystem(false);
}
You clearly haven't learned how to use a BackgroundWorker yet, so that is what you should be doing, rather than coming here and asking duplicate questions. I already gave you a link to one example of the correct implementation of a BackgroundWorker and you can find another in the BackgroundWorker Class page on MSDN.
I trust that will be enough to get you going again.
Do the UI work in the UI thread, using the dispatcher. See here for more information. So basically, anything that has something to do with a UI control needs to be dispatched to the UI thread.
You have to invoke method in main thread from doWork which is running in separate thread in order to update UI.
I'd suggest to have a look at http://msdn.microsoft.com/en-us/library/dd460693(v=vs.110).aspx which is available in .NET4 and above. (Have a look at Task specifically)
I have a code for serial communication, with this code im sending values from textboxes to an device or when im testing to another PC. But when I press my "Program" button I get this error.
System.NullReferenceException was unhandled
Object reference not set to an instance of an object.
And i can catch the exception with an try catch but then i wont send my values to the device connected to my port.
This is my code:
public partial class MainForm : Form
{
private Settings _settings;
private SettingsIniFile _settingsIniFile = new SettingsIniFile();
private StringList _baudratelist = new StringList();
private StringList _systemPorts = new StringList();
private StringList _comportList = new StringList();
private Timer _comtimer = new Timer();
private ComPort _comport;
public MainForm()
{
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
//var portname = GetCurrentComPort();
}
private String GetCurrentComPort()
{
int index = _comPortComboBox.SelectedIndex;
if (index < 0)
return null;
return _comportList[index];
}
private void OnComtimerOnTick(object sender, EventArgs args)
{
foreach (var item in SerialPort.GetPortNames())
{
if (!_systemPorts.Contains(item))
{
_comtimer.Stop();
_systemPorts.Add(item);
LoadComportName();
//MessageBox.Show("The new device is connected to" + item);
_comtimer.Start();
}
}
}
private void LoadSettings(bool defaults)
{
SettingsIniFile iniFile = new SettingsIniFile();
_settings = iniFile.LoadSettings(defaults);
}
private void SaveSettings()
{
SaveTextBoxes();
_settingsIniFile.Save(_settings);
}
private void LoadTextBoxes()
{
//ACR
_startRemovalTextBox.Text = _settings.AcrStartRemoval11;
_removalTimeTextBox.Text = _settings.AcrRemovalTime12;
_removalDelayTextBox.Text = _settings.AcrRemovalDelay13;
//CLEANING
_durCleaningTextbox.Text = _settings.CleanDurCleaning21;
_timeValveOnTextbox.Text = _settings.CleanTimeValveOn22;
_timeValveOffTextBox.Text = _settings.CleanTimeValveOff23;
//CALIBRATE
_contentLeftTextBox.Text = _settings.CalibrateContentLeft31;
_calibrateLeftTextBox.Text = _settings.CalibrateCalibrateLeft33;
_contentRightTextBox.Text = _settings.CalibrateContentRight32;
_calibrateRightTextBox.Text = _settings.CalibrateCalibrateRight34;
//CONDUCTIVITY
_factorLeftTextBox.Text = _settings.ConductFactorLeft41;
_offsetLeftTextBox.Text = _settings.ConductOffsetleft42;
_factorRightTextBox.Text = _settings.ConductFactorRight43;
_offsetRightTextBox.Text = _settings.ConductOffsetRight44;
_levelLeftTextBox.Text = _settings.ConductLevelLeft45;
_levelRightTextBox.Text = _settings.ConductLevelRight46;
//GENERAL
_typeOfValveTextBox.Text = _settings.GeneralTypeOfValve51;
_indicatorTextBox.Text = _settings.GeneralIndicator52;
_inverseOutputTextBox.Text = _settings.GeneralInverseOutput53;
_restartTimeTextBox.Text = _settings.GeneralRestartTime54;
_waterTimeTextBox.Text = _settings.GeneralWaterTime55;
_gateDelayTextbox.Text = _settings.GeneralGateDelay56;
//PULSATION
_pulsationTextBox.Text = _settings.PulsationPulsationPm61;
_ratioFrontTextBox.Text = _settings.PulsationSrRatioFront62;
_ratioBackTextBox.Text = _settings.PulsationSrRatioBack63;
_stimulationTextBox.Text = _settings.PulsationStimulationPm64;
_stimFrontTextBox.Text = _settings.PulsationSrStimFront65;
_stimBackTextBox.Text = _settings.PulsationSrStimBack66;
_stimulationDurTextBox.Text = _settings.PulsationStimulationDur67;
//return _settings;
}
private void SaveTextBoxes()
{
//ACR
_settings.AcrStartRemoval11 = _startRemovalTextBox.Text;
_settings.AcrRemovalTime12 = _removalTimeTextBox.Text;
_settings.AcrRemovalDelay13 = _removalDelayTextBox.Text;
//CLEANING
_settings.CleanDurCleaning21 = _durCleaningTextbox.Text;
_settings.CleanTimeValveOn22 = _timeValveOnTextbox.Text;
_settings.CleanTimeValveOff23 = _timeValveOffTextBox.Text;
//CALIBRATE
_settings.CalibrateContentLeft31 = _contentLeftTextBox.Text;
_settings.CalibrateCalibrateLeft33 = _calibrateLeftTextBox.Text;
_settings.CalibrateContentRight32 = _contentRightTextBox.Text;
_settings.CalibrateCalibrateRight34 = _calibrateRightTextBox.Text;
//CONDUCTIVITY
_settings.ConductFactorLeft41 = _factorLeftTextBox.Text;
_settings.ConductOffsetleft42 = _offsetLeftTextBox.Text;
_settings.ConductFactorRight43 = _factorRightTextBox.Text;
_settings.ConductOffsetRight44 = _offsetRightTextBox.Text;
_settings.ConductLevelLeft45 = _levelLeftTextBox.Text;
_settings.ConductLevelRight46 = _levelRightTextBox.Text;
//GENERAL
_settings.GeneralTypeOfValve51 = _typeOfValveTextBox.Text;
_settings.GeneralIndicator52 = _indicatorTextBox.Text;
_settings.GeneralInverseOutput53 = _inverseOutputTextBox.Text;
_settings.GeneralRestartTime54 = _restartTimeTextBox.Text;
_settings.GeneralWaterTime55 = _waterTimeTextBox.Text;
_settings.GeneralGateDelay56 = _gateDelayTextbox.Text;
//PULSATION
_settings.PulsationPulsationPm61 = _pulsationTextBox.Text;
_settings.PulsationSrRatioFront62 = _ratioFrontTextBox.Text;
_settings.PulsationSrRatioBack63 = _ratioBackTextBox.Text;
_settings.PulsationStimulationPm64 = _stimulationTextBox.Text;
_settings.PulsationSrStimFront65 = _stimFrontTextBox.Text;
_settings.PulsationSrStimBack66 = _stimBackTextBox.Text;
_settings.PulsationStimulationDur67 = _stimulationDurTextBox.Text;
}
private void DefaultSettingButtonClick(object sender, System.EventArgs e)
{
LoadSettings(true);
LoadTextBoxes();
SaveSettings();
LoadComportName();
}
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void LoadComportName()
{
var availablePorts = _systemPorts;
_comPortComboBox.DataSource = null;
if (availablePorts != null && availablePorts.Any())
{
_comPortComboBox.DataSource = availablePorts;
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void SetBaudrate()
{
_baudratelist.Add("4600");
_baudratelist.Add("9600");
_baudratelist.Add("19200");
}
private void SendMessageTest()
{
var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
+ _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
_removalDelayTextBox.Text + "\r\n";
var Cleaningcontent ="["+ _cleaningNamelLabel.Text+"]" +"\r\n"+_cleaningIdLabel21.Text+
_durCleaningTextbox.Text + "\r\n"+ _cleaningLabelId22.Text+
_timeValveOnTextbox.Text + "\r\n"+ _cleaningLabelId23.Text+_timeValveOffTextBox.Text+"\r\n";
var Calibratecontent = "[" +_calibrateNameLabel.Text+ "]"+"\r\n"+_calibrateIDLabel31.Text+_contentLeftTextBox.Text+
"\r\n"+ _calibrateIDLabel32.Text+_calibrateLeftTextBox.Text+"\r\n"+_calibrateIDLabel33.Text+_contentRightTextBox.Text+
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
try
{
_comport.WriteBytes(array);
}
catch(Exception exc)
{
MessageBox.Show("Error {1}: "+ exc);
}
try
{
_comport.ReadBytes(array, array.Length, 1000);
}
catch(Exception exc)
{
MessageBox.Show("Error {2}" + exc);
}
//string result = Encoding.ASCII.GetString(array);
//MessageBox.Show(result);
}
}
This is my code for the communication:
namespace Communication
{
public class ComPort
{
private readonly SerialPort _serialPort;
public ComPort(string portname, int baudRate)
{
_serialPort = new SerialPort();
_serialPort.PortName = portname; <-----
_serialPort.BaudRate = baudRate;
_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.Handshake = Handshake.None;
// _serialPort.WriteBufferSize = 1;
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
_serialPort.Open();
_serialPort.ReadTimeout = 20000;
_serialPort.WriteTimeout = 20000;
}
public void Clear()
{
while (ReadByte() != -1)
continue;
}
private byte[] _array = new byte[] {0};
public void WriteByte(byte value)
{
_array[0] = value;
_serialPort.Write(_array, 0, 1);
// _serialPort.BaseStream.WriteByte(value);
_serialPort.BaseStream.Flush();
}
public void WriteBytes(byte[] array)
{
_serialPort.Write(array, 0, array.Length);
}
public void WriteBytes(byte[] array, int index, int length )
{
_serialPort.Write(array, index, length);
}
private int _readTimeOut = -1;
public int ReadByte(int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
return _serialPort.ReadByte();
// _serialPort.Read(array, 0, 1);
// return array[0];
}
catch (TimeoutException)
{
return -1;
}
}
public int ReadBytes(byte[] array, int length, int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
int bytesRead = 0;
while ( bytesRead < length )
bytesRead += _serialPort.Read(array, bytesRead, length - bytesRead);
// _serialPort.Read(array, 0, 1);
// return array[0];
return bytesRead;
}
catch (TimeoutException)
{
return -1;
}
}
/// <summary>
/// sends string followed by CR - LF
/// </summary>
/// <param name="line"></param>
public void WriteLine(String line)
{
WriteBytes(StringToBytes(line + "\r\n"));
}
public static byte[] StringToBytes(string input)
{
return Encoding.ASCII.GetBytes(input);
}
public void Close()
{
try
{
_serialPort.DtrEnable = false;
_serialPort.RtsEnable = false;
_serialPort.Close();
}
catch(IOException)
{
}
}
public bool Dtr
{
get { return _serialPort.DtrEnable; }
set { _serialPort.DtrEnable = value; }
}
public bool Rts
{
get { return _serialPort.RtsEnable; }
set { _serialPort.RtsEnable = value; }
}
}
}
Can someone explain to me what the problem is?
Thanks in advance
Possible anwser:
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
_comport = new ComPort("COM6", 9600);
But when i do this another error comes around the corner:
Value cannot be null.
Parameter name: PortName
This comes in the second piece of code where the arrow is.
Probably there is not comport selected at startup, so the _comport never gets created, you should check if the comport is created before you use is: if (_comport != null) ...
Update:
I think you should create a button instead of default connecting on a combobox selection change.
public void buttonConnect_Click(object sender, EventArgs e)
{
// check if the comport is created, else show a message and return,
TryDisconnect();
var portname = GetCurrentComPort();
if (portname == null)
return;
try
{
_comport = new ComPort(portname, 9600);
}
catch(Exception exception)
{
// try to create a better message here :-)
MessageBox.Show("Something went wrong....");
}
}
public void buttonDisconnect_Click(object sender, EventArgs e)
{
TryDisconnect();
}
public void TryDisconnect()
{
if( _comport != null)
{
_comport.Dispose();
_comport = null;
}
}
Also for this:
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
// check the _comPort instance first, if not assigned, leave a message..
if(_comPort == null)
{
MessageBox.Show("The comport is not initialized");
return;
}
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
I got a tip for you, try to separate the markup/construction of the message, here how you could do.
I did not change all the code, only some examples:
I would create a struct/class to hold all information
public struct AcrContentInfo
{
public string AcrName;
public string AcrId11;
public string StartRemoval;
public string AcrId12;
public string RemovalTime;
public string AcrId13;
public string RemovalDelay;
// markup the information:
public override string ToString()
{
return string.Format(
"[{0}]\r\n{1}{2}\r\n{3}{4}\r\n{5}{6}\r\n",
AcrName,
AcrId11, StartRemoval,
AcrId12, RemovalTime,
AcrId13, RemovalDelay);
}
}
private void SendMessageTest()
{
// Instead of:
//var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
// + _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
// _removalDelayTextBox.Text + "\r\n";
// I would use this instead, this way it wil be easier to maintain different versions.
// The code using the struct isn't responsible for markup
// Create the struct and fillin the fields.
AcrContentInfo acrContentInfo = new AcrContentInfo
{
AcrName = _acrNameLabel.Text,
AcrId11 = _acrIdLabel11.Text,
StartRemoval = _startRemovalTextBox.Text,
AcrId12 = _acrIdLabel12.Text,
RemovalTime = _removalTimeTextBox.Text,
AcrId13 = _acrIdLabel13.Text,
RemovalDelay = _removalDelayTextBox.Text
};
// if there is a new version of the protocol, you can create something like this
// AcrContentInfoV2 acrContentInfo = new AcrContentInfoV2
// call the tostring, (create a markup)
var Acrcontent = acrContentInfo.ToString();
// --- old code ---
var Cleaningcontent = "[" + _cleaningNamelLabel.Text + "]" + "\r\n" + _cleaningIdLabel21.Text +
_durCleaningTextbox.Text + "\r\n" + _cleaningLabelId22.Text +
_timeValveOnTextbox.Text + "\r\n" + _cleaningLabelId23.Text + _timeValveOffTextBox.Text + "\r\n";
var Calibratecontent = "[" + _calibrateNameLabel.Text + "]" + "\r\n" + _calibrateIDLabel31.Text + _contentLeftTextBox.Text +
"\r\n" + _calibrateIDLabel32.Text + _calibrateLeftTextBox.Text + "\r\n" + _calibrateIDLabel33.Text + _contentRightTextBox.Text +
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
// instad of:
//byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
// I always try not to make very long lines of code.
// A stringbuilder is much more efficient building strings.
// I would:
StringBuilder sb = new StringBuilder();
sb.AppendLine("2");
sb.AppendLine("Acrcontent");
sb.AppendLine("Cleaningcontent");
sb.AppendLine("Calibratecontent");
sb.AppendLine("Conductcontent");
sb.AppendLine("Generalcontent");
sb.AppendLine("Pulsationcontent");
sb.AppendLine("3");
// why make the comport class responsible for the encoding type. _ComPort.StringToBytes_
byte[] array = Encoding.UTF8.GetBytes(sb.ToString());
try
{
_comport.WriteBytes(array);
// only read when write was succeed?
_comport.ReadBytes(array, array.Length, 1000);
}
catch (Exception exc)
{
MessageBox.Show("Error {1}: " + exc);
}
}
These are only my ideas, and meant to be constructive. (other point of view) Happy codeing..
You have to instantiate _comport before calling a method or accessing a property on it.
maybe in
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
portname is null then _comport not instantiated. you can trace it and check that if it has a value or not.
Yes assign a value to _comport like
_comport=null;