Click here to Skip to main content
15,914,225 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi guys following is the windows form code I am using.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Deployment;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using System.Windows.Forms;
namespace FORMBROADCASTER
{
    public partial class Form1 : Form
    {        
        BackGroundProcess obj = new BackGroundProcess();
       
        public Form1()
        {
            InitializeComponent();            
        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {               
                this.obj.backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //backgroundWorker1.WorkerSupportsCancellation = true;
            try
            {
                if (obj.backgroundWorker1.IsBusy)
                {
                    obj.backgroundWorker1.CancelAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Error");
            }
        }                
    }
}


Now from the above form I am creating the Object of the following Class

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace FORMBROADCASTER
{
    class BackGroundProcess
    {
        public BackgroundWorker backgroundWorker1 ;
        public static long iRecPack = 0;
        public static long i7201 = 0;
        public static long i7202 = 0;
        public static long i7208 = 0;
        public static long i6541 = 0;
        public static long i7207 = 0;
        public static long iOther = 0;
        int n;
        public static long iSentPack = 0;
        public static market_Indices[] mIndices;
        public static UdpClient sendBrod = new UdpClient("192.168.201.24", 7864);
        public static UdpClient sendBrod1 = new UdpClient("192.168.201.24", 7865);
        UdpClient peer ;
        IPAddress multicastaddress ;
        IPEndPoint ep ;
        public BackGroundProcess()
        {
            backgroundWorker1 = new BackgroundWorker();
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            peer = new UdpClient(34074);
            multicastaddress = IPAddress.Parse("233.1.2.5");
            ep = null;
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //Form1 form12 = new Form1();
            
            peer.JoinMulticastGroup(multicastaddress);
            //Thread oThread = new Thread(new ThreadStart(VISIONNSEMARKETWATCH.Program.processByte()));
            int j = 0;
            Stopwatch stopwatch = new Stopwatch();
            //TextWriter tw = new StreamWriter("c:\\data.txt");
            //if (!backgroundWorker1.IsBusy)
            //{
                while (!backgroundWorker1.CancellationPending)
                {
                    try
                    {
                        //System.Windows.Forms.Application.DoEvents();
                        ep = new IPEndPoint(IPAddress.Any, 34074);
                        stopwatch.Start();
                        byte[] data = peer.Receive(ref ep);
                        stopwatch.Stop();
                        MWProperties[] mwproc = new MWProperties[2];
                        int i = processByte(ref data, ref mwproc);
                        j++;
                    }                    
                    finally
                    {
                        //System.GC.Collect();
                    }
                    stopwatch.Reset();                    
                }
            //}
            //else
            //{
            //    //MessageBox.Show("You can't start another thread");
            //}
            peer = null;
            //tw.Close();
        }
        public static void TwidleBytes(Byte[] b, int fStart, int fSize)
        {
            Array.Reverse(b, fStart - 1, fSize);
        }
        public int processByte(ref byte[] byt, ref MWProperties[] newprop)
        {
            #region "Variable Declaration"
            byte[] Ibyt = new byte[byt.Length];
            int iLineCount = 0;
            String _Detail;
            String _Summary = "";//"Token,MarketType,FillPrice,FillVolume,OpenInterest,DayHiOI,DayLoOI"; 
            IntPtr p;
            Byte[] bytDecompressed;
            BcastCmpPacket Bcp = new BcastCmpPacket();
            BcastPackData Bpd = new BcastPackData();
            #endregion
            try
            {
                //Mapping the BroadCast Data to Packet Structure According Para 3.6 of Document & fetching the cPackData
                Array.Copy(byt, Ibyt, byt.Length);
                TwidleBytes(byt, 1, 2);
                TwidleBytes(byt, 3, 2);
                p = Marshal.AllocHGlobal(Marshal.SizeOf(Bpd));
                Marshal.Copy(byt, 0, p, byt.Length);
                Bpd = (BcastPackData)Marshal.PtrToStructure(p, Bpd.GetType());
                Marshal.FreeHGlobal(p);
                byt = Bpd.cPackData;
                TwidleBytes(byt, 1, 2);

                // Mapping the cPackData to COMPRESSION_BROADCAST_DATA 
                Bpd = new BcastPackData();
                p = Marshal.AllocHGlobal(Marshal.SizeOf(Bcp));
                Marshal.Copy(byt, 0, p, byt.Length);
                Bcp = (BcastCmpPacket)Marshal.PtrToStructure(p, Bcp.GetType());
                //Console.WriteLine(Bcp.iCompLen);
                // If in COMPRESSION_BROADCAST_DATA CompressionLen is not equle to 0
                if (Bcp.iCompLen > 0)
                {
                    //Steps to decompree the Data
                    Console.WriteLine(p.ToString());
                    Marshal.FreeHGlobal(p);
                    bytDecompressed = new Byte[Bcp.iCompLen];
                    byt = new Byte[Bcp.iCompLen];
                    Array.Copy(Bcp.cCompData, byt, Bcp.iCompLen);
                    int length = LatestLZO.lzo11_decomp(ref byt, out bytDecompressed);
                    //bytDecompressed = new LZOCompressor().Decompress(byt);
                    //Fetching the Message Header
                    Bcp = new BcastCmpPacket();
                    byt = new Byte[56];
                    Array.Copy(bytDecompressed, 8, byt, 0, 56);
                    //Fethcing the Transaction Code from Message_Header
                    my_Message_Header Mh = new my_Message_Header();
                    TwidleBytes(byt, 9, 4);
                    TwidleBytes(byt, 37, 2);
                    TwidleBytes(byt, 39, 2);
                    p = Marshal.AllocHGlobal(Marshal.SizeOf(Mh));
                    Marshal.Copy(byt, 0, p, byt.Length);
                    Mh = (my_Message_Header)Marshal.PtrToStructure(p, Mh.GetType());
                    Marshal.FreeHGlobal(p);
                    int StartIndex = 48;
                    int i = Int16.Parse(bytDecompressed[49].ToString());
                    Bcast_Header Bh = new Bcast_Header();
                    if (Mh.TransactionCode == 7208)
                    {
                        i7208++;
                        newprop = new MWProperties[i];

                        for (int n = 0; n < i; n++)
                        {
                            //double Value = 0.0;
                            //_Detail = "";
                            byt = new Byte[212];
                            Array.Copy(bytDecompressed, 50 + (n * 212), byt, 0, 212);
                            sendBrod.Send(byt, byt.Length);
                            //byt = null;                           
                        }
                        return 7208;
                    }
                }
                else
                {
                    bytDecompressed = new byte[506];
                    Array.Copy(Bcp.cCompData, bytDecompressed, bytDecompressed.Length);
                    Bcp = new BcastCmpPacket();
                    byt = new Byte[56];
                    Array.Copy(bytDecompressed, 8, byt, 0, 56);
                    my_Message_Header Mh = new my_Message_Header();
                    Marshal.FreeHGlobal(p);
                    TwidleBytes(byt, 9, 4);
                    TwidleBytes(byt, 37, 2);
                    TwidleBytes(byt, 39, 2);
                    p = Marshal.AllocHGlobal(Marshal.SizeOf(Mh));
                    Marshal.Copy(byt, 0, p, byt.Length);
                    Mh = (my_Message_Header)Marshal.PtrToStructure(p, Mh.GetType());
                    Marshal.FreeHGlobal(p);
                    int StartIndex = 48;
                    int i = Int16.Parse(bytDecompressed[49].ToString());
                    Bcast_Header Bh = new Bcast_Header();
                    if (Mh.TransactionCode == 7207)
                    {
                        i7207++;
                        mIndices = new market_Indices[i];
                        for (int m = 0; m < i; m++)
                        {
                            mIndices[m] = new market_Indices();
                            Ticker_7207 indices = new Ticker_7207();
                            byte[] indbyte = new byte[72];
                            Array.Copy(bytDecompressed, 50 + (m * 72), indbyte, 0, 72);
                            //Array.Reverse(indbyte, 21, indbyte.Length - 21);
                            sendBrod1.Send(indbyte, indbyte.Length);
                            //indbyte = null;                            
                        }
                        return 7207;
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Exception is : " + ex.Message);
                //sendBrod.Close();
                //sendBrod = null;
            }
            finally
            {
                //System.GC.Collect();
            }
            return 0;
        }

Now I want that when I click the button in form, backgroundWorker process should start. then Inside
C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
I am receiving the broadcast packets from the multicast Ip address.


Then I make a call to the function
C#
public int processByte(ref byte[] byt, ref MWProperties[] newprop)
which processes this bytes and sends it as broadcast packet.

But my application is not behaving properly some time when I click button1 it want start. Sometime it hangs after running some times. Some time it gives me the error
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

And all this things happens mostly in Run mode means when I press ctr + f5. & In debug mode application runs perfactly
Posted
Updated 28-Jul-11 23:06pm
v4
Comments
kkprocks123 29-Jul-11 5:08am    
One more thing is when I click the button2 it hangs that time as well

"In debug mode application runs perfactly"
I bet it doesn't.

You have a number of places there where you are using try blocks with either no catch, or discarded catches. How do you know you app is working, if you are ignoring the exceptions?

Handle the catches - at least log the errors. You may well find that one of the exceptions is causing the serious problem later on.
 
Share this answer
 
Comments
kkprocks123 29-Jul-11 5:49am    
OriginalGriff
After your suggestion I made a changes In application
public void maintainlog(string s)
{
TextWriter tw = new StreamWriter("c:\\data.txt");
tw.WriteLine(s);
tw.Close();
}
I added this code to application and call this function in each catch statement but I still the result is nothing
Sergey Alexandrovich Kryukov 2-Aug-11 5:22am    
I don't see how you failed the advice. It rather looks like you completely ignored it.
--SA
Sergey Alexandrovich Kryukov 2-Aug-11 5:21am    
I agree, the biggest failure here is blocking exception propagation. Nothing good can be expected with such "coding style". Not handling exceptions would be better than that. My 5 for the advice.
--SA
hi kkprocks123,

Your example is a great resourse for me. After successful decompression I tried to map my_Message_Header, as per structure avaiable in doc which is 40 byte in size. so I changed your code where my_Message_Header is 56 to 40 and position of bytes to be twidled for
my_Message_Header as per doc available.Doing so I am not getting meaningful data.I got Transaction Code which is not in doc. Could you help me here?

av_m222@Yahoo.com
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900