c# - Serializing the path of the running application -


good day,

i have client application sends server lists of application client opens. particulary sends file path, file name , hostname. problem sent data should serialize , deserialize when received in server. new c# have little idea of serialization.

this client side

private list<int> listedprocesses = new list<int>();         private void senddata()         {             string processid = "";             string processname = "";             string processpath = "";             string processfilename = "";             string processmachinename = "";              listbox1.beginupdate();             try             {                    piis = getallprocessinfos();                 (int = 0; < piis.count; i++)                 {                     try                     {                         if (!listedprocesses.contains(piis[i].id)) //placed on list avoid redundancy                         {                             listedprocesses.add(piis[i].id);                             processid = piis[i].id.tostring();                             processname = piis[i].name.tostring();                             processpath = piis[i].path.tostring();                             processfilename = piis[i].filename.tostring();                             processmachinename = piis[i].machinename.tostring();                             output.text += "\n\nsent data : \n\t" + processfilename + "\n\t" + processmachinename + "\n\t" + processid + "\n\t" + processname + "\n\t" + processpath + "\n";                         }                      }                     catch (exception ex)                     {                         wait.abort();                         output.text += "error..... " + ex.stacktrace;                      }                      networkstream ns = tcpclnt.getstream();                     string data = "";                     data = "--++" + "  " + processfilename + " " + processmachinename + " " + processid + " " + processpath;                     if (ns.canwrite)                     {                         byte[] bf = new asciiencoding().getbytes(data);                         ns.write(bf, 0, bf.length);                         ns.flush();                     }                 }             }                         {                 listbox1.endupdate();             }          }          private void cmd_dis_click(object sender, eventargs e)         {             if (wait != null)             {                 wait.abort();                 //read.close(2000);             }              ipaddress ipclient = dns.gethostbyname(dns.gethostname()).addresslist[0];             string ipclnt = "+@@+" + ipclient.tostring();             networkstream ns = tcpclnt.getstream();             if (ns.canwrite)             {                 byte[] bf = new asciiencoding().getbytes(ipclnt);                 ns.write(bf, 0, bf.length);                 ns.flush();             }              tcpclnt.close();            // read.close();             application.exit();         }          private void listbox1_selectedindexchanged(object sender, eventargs e)         {             processinfoitem pii = piis.firstordefault(x => x.id == (int)(sender listbox).selectedvalue);             if (pii != null)             {                 string hostname = system.net.dns.gethostname();                  textbox4.text = listbox1.selectedvalue.tostring();                 textbox5.text = (pii.filename);                 textbox6.text = (pii.path);                 textbox7.text = (pii.machinename);             }         }          private list<processinfoitem> piis = new list<processinfoitem>();         private void form1_load(object sender, eventargs e)         {             piis = getallprocessinfos();             listbox1.displaymember = "name";             listbox1.valuemember = "id";             listbox1.datasource = piis;          }         private list<processinfoitem> getallprocessinfos()         {              list<processinfoitem> result = new list<processinfoitem>();             process currentprocess = process.getcurrentprocess();             process[] processes = process.getprocesses();             foreach (process p in processes)             {                 if (!string.isnullorempty(p.mainwindowtitle))                 {                     //processinfoitem pii = new processinfoitem(p.id, p.mainmodule.modulename, p.mainmodule.filename, p.mainwindowtitle);                     processinfoitem pii = new processinfoitem(p.id, p.mainmodule.modulename, p.mainwindowtitle, p.mainmodule.filename, environment.machinename);                     result.add(pii);                 }             }             return result;         }         public class processinfoitem         {             public int id { get; set; }             public string name { get; set; }             public string filename { get; set; }             public string path { get; set; }             public string machinename { get; set; }             public processinfoitem(int id, string name, string filename, string path, string machinename)             {                 this.id = id;                 this.name = name;                 this.filename = filename;                 this.path = path;                 this.machinename = machinename;             }         } 

and here server needs deserialize

  private void recievedata()         {             networkstream nstream = tcpclient.getstream();             asciiencoding ascii = null;             while (!stoprecieving)             {                 if (nstream.canread)                 {                     byte[] buffer = new byte[1024];                     nstream.read(buffer, 0, buffer.length);                     ascii = new asciiencoding();                     recvdt = ascii.getstring(buffer);                     /*received message checks if has +@@+ ip disconnected*/                     bool f = false;                     f = recvdt.contains("+@@+");                     if (f)                     {                         string d = "+@@+";                         recvdt = recvdt.trimstart(d.tochararray());                         clientdis();                         stoprecieving = true;                     }                      //else if (recvdt.contains("^^"))                     //{                     //    new transmit_file().transfer_file(file, ipselected);                     //}                     /* ++-- shutsdown/restrt/logoff/abort*/                     else if (recvdt.contains("++--"))                     {                         string d = "++--";                         recvdt = recvdt.trimstart(d.tochararray());                         this.invoke(new rcvdata(addtooutput));                         clientdis();                     }                      /*--++ normal msg*/                     else if (recvdt.contains("--++"))                     {                          string d = "--++";                         recvdt = recvdt.trimstart(d.tochararray());                         this.invoke(new rcvdata(addtooutput));                      }                 }                 thread.sleep(1000);             }          }   public void addtooutput()         {             if (recvdt != null && recvdt != "")             {                 output.text += "\n received data : " + recvdt;                 recvdt = null;                }          } 

thank you.

you can use wcf communication between client , server application.

you can create service , host in application receive data other application , consume service in other application send data , show response.

here example of doing in simple way. in sample have created 2 applications. application2 sends data application1 automatically once in each 10 secconds , application1 sends response application2 , application2 show response.

to run sample codes follow steps:

  1. create soloution 2 console applications, application1 , application2
  2. add system.servicemodel reference both projects.
  3. paste below codes in program.cs of each project.
  4. right click on solution , in properties, make solution multi startup projects , set action of each project 'start'
  5. press ctrl+f5 run projects
  6. in application1 window see service running message.
  7. application2 send datetime.now application 2 every 10 secconds , receive respone application 2 , display it application1 window.

application1 program.cs

using system; using system.servicemodel;  namespace application1 {     [servicecontract]     public interface iechoservice     {         [operationcontract]         string echo(string value);     }      public class echoservice : iechoservice     {         public string echo(string value)         {             return string.format("you send me data'{0}'", value);         }     }      class program     {         static void main(string[] args)         {             using (servicehost host = new servicehost(typeof(echoservice), new uri[] { new uri("http://localhost:8000") }))             {                 host.addserviceendpoint(typeof(iechoservice), new basichttpbinding(), "echo");                 host.open();                 console.writeline("service running...");                 console.writeline("press enter exit if want close service.");                 console.readline();                 host.close();             }         }     } } 

application2 program.cs

using system; using system.servicemodel; using system.servicemodel.channels;  namespace application2 {     [servicecontract]     public interface iechoservice     {         [operationcontract]         string echo(string value);     }      class program     {         static void main(string[] args)         {             //in real implementation, use server ip instead of localhost             channelfactory<iechoservice> factory = new channelfactory<iechoservice>(new basichttpbinding(), new endpointaddress("http://localhost:8000/echo"));             iechoservice proxy = factory.createchannel();             int processedseccond = 0;             while (true)             {                 var datetime = datetime.now;                 if (datetime.second % 10 == 0 && datetime.second!=processedseccond)                 {                     processedseccond = datetime.second;                     string data= datetime.tostring(); //or console readline manual data entry                     console.writeline("recieved response: " + proxy.echo(str));                 }             }         }     } } 

result

enter image description here

it's simple. can change codes desire.

an example of passing complex data service:

[datacontract] public class mymessageclass {     [datamember]     public string myvalue1 {get;set;}      [datamember]     public string myvalue2 {get;set;} } 

then can update interface , inplementation of service , use without need serialize , deserialize anything, things done wcf behind scene.

pleae note can use wcf services both windows forms applications , console applications , can continue develop project same way doing. change need add service application run on server , consume service in application run on client. not related logic of application all. , samples provided in console application sake of simplicity.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -