The brackets are a horrible habit I've picked up from Java OpenGL programming. I hate it, and I hate that I do it.

I didn't know about lock - I'll use it. I've transitioned from Java to C# without bothering to read up on language specs.

Thanks again.

I found the threading issue - turns out it really needs to stay that way, so I just make any thread that wants to send or read a packet check and see if a packet is being handled at that moment. If it is, it'll sleep and try again until it goes through.

Code if anyone needs to do something similar:

        public void SendPacket(Packet P)
        {
            while (IsPacketBeingSent)
            {
                Thread.Sleep(5);
            }

            IsPacketBeingSent = true;
            {
                using (MemoryStream MS = new MemoryStream())
                {
                    //Console.WriteLine("SEND START");
                    BinaryFormatter BF = new BinaryFormatter();
                    BF.Serialize(MS, P);

                    byte[] Payload = MS.ToArray();
                    int PayloadSize = Payload.Length;
                    int SentSize = 0;

                    SentSize += SocketMain.Send(BitConverter.GetBytes(PayloadSize));
                    //Console.WriteLine("\tSocket.Send (PayloadSize): " + SentSize);

                    SentSize = 0;

                    SentSize += SocketMain.Send(Payload);
                    //Console.WriteLine("\tSocket.Send (Payload): " + SentSize);

                    //Console.WriteLine("\tSent payload:" + P.GetType().ToString() + "," + SentSize + " | " + Utility.GetMD5Hash(Payload));
                }
            }
            IsPacketBeingSent = false;
        }

        public void ReadPacket()
        {
            while (IsPacketBeingRead)
            {
                Thread.Sleep(5);
            }

            IsPacketBeingRead = true;
            {
                //Console.WriteLine("READ START");
                byte[] BufferArray = new byte[131072];
                int BytesReceived = 0;

                while (BytesReceived < sizeof(int))
                {
                    BytesReceived += SocketMain.Receive(BufferArray, BytesReceived, sizeof(int) - BytesReceived, SocketFlags.None);
                    //Console.WriteLine("\tSocket.Receive (PayloadSize): " + BytesReceived);
                }

                int PayloadSize = BitConverter.ToInt32(BufferArray, 0);
                //Console.WriteLine("\tReceived payload size: " + PayloadSize);
                BytesReceived = 0;

                while (BytesReceived < PayloadSize)
                {
                    BytesReceived += SocketMain.Receive(BufferArray, BytesReceived, PayloadSize - BytesReceived, SocketFlags.None);
                    //Console.WriteLine("\tSocket.Receive (Payload): " + BytesReceived);
                }

                byte[] Payload = BufferArray.Take(PayloadSize).ToArray();

                //Console.WriteLine("\tReceived payload:" + PayloadSize.ToString() + " | " + Utility.GetMD5Hash(Payload));
                using (MemoryStream MS = new MemoryStream(Payload))
                {
                    BinaryFormatter BF = new BinaryFormatter();

                    try
                    {
                        HandlePacket((Packet)BF.Deserialize(MS));
                    }

                    catch (SerializationException ...

Thanks for offering, but I've got it sorted out now. Thanks for all of your help.

I think I've found the issue after looking at console output with these changes:

public void SendPacket(Packet P)
        {
            using (MemoryStream MS = new MemoryStream())
            {
                Console.WriteLine("SEND START");
                BinaryFormatter BF = new BinaryFormatter();
                BF.Serialize(MS, P);

                byte[] Payload = MS.ToArray();
                int PayloadSize = Payload.Length;
                int SentSize = 0;

                SentSize += SocketMain.Send(BitConverter.GetBytes(PayloadSize));
                Console.WriteLine("\tSocket.Send (PayloadSize): " + SentSize);

                SentSize = 0;

                SentSize += SocketMain.Send(Payload);
                Console.WriteLine("\tSocket.Send (Payload): " + SentSize);

                Console.WriteLine("\tSent payload:" + P.GetType().ToString() + "," + SentSize + " | " + Utility.GetMD5Hash(Payload));
            }
        }

        public void ReadPacket()
        {
            Console.WriteLine("READ START");
            byte[] BufferArray = new byte[131072];
            int BytesReceived = 0;

            while (BytesReceived < sizeof(int))
            {
                BytesReceived += SocketMain.Receive(BufferArray, BytesReceived, sizeof(int) - BytesReceived, SocketFlags.None);
                Console.WriteLine("\tSocket.Receive (PayloadSize): " + BytesReceived);
            }

            int PayloadSize = BitConverter.ToInt32(BufferArray, 0);
            Console.WriteLine("\tReceived payload size: " + PayloadSize);
            BytesReceived = 0;

            while (BytesReceived < PayloadSize)
            {
                BytesReceived += SocketMain.Receive(BufferArray, BytesReceived, PayloadSize - BytesReceived, SocketFlags.None);
                Console.WriteLine("\tSocket.Receive (Payload): " + BytesReceived);
            }

            byte[] Payload = BufferArray.Take(PayloadSize).ToArray();

            Console.WriteLine("\tReceived payload:" + PayloadSize.ToString() + " | " + Utility.GetMD5Hash(Payload));
            using (MemoryStream MS = new MemoryStream(Payload))
            {
                BinaryFormatter BF = new BinaryFormatter();

                try
                {
                    HandlePacket((Packet)BF.Deserialize(MS));
                }

                catch (SerializationException E)
                {
                    Console.WriteLine("------------------ STOP ------------------");
                    SendPacket(new Packet6StopError());
                    Console.WriteLine("------------------ STOP ------------------");
                    throw E;
                }
            }
        }

It looks like I've got packets sending from somewhere else (no idea where) at the same time as other packets. Several times on the console I can see:

SEND START
SEND START
    Socket.Send (PayloadSize): 4
    Socket.Send (Payload): 38398
    Socket.Send (PayloadSize): 4
    Socket.Send (Payload): 18710
  [...]

When the crash happens on my end, I noticed ...

Yes, it does. In my most recent try, one of the smallest packets (always 194 bytes) caused the issue. I seemingly received all data, but MD5 hashes were different.

I've tried to handle the exception and just keep going. One packet screwing up out of 100 is tolerable in the application. But since I send the size before the payload, one failed packet causes all of the others to be read incorrectly. I end up reading an absurd payload size like 9557463 or even -594831. If there is a way around this, I'd gladly take it.

Also, I noticed that Socket.Send returns an int which I assume is bytes that were sent. Does Socket.Send actually send that much data each time or does it work the same way as Socket.Recieve?

Thanks! Didn't know that. It works for a short period of time now, but it still ends up crashing with the same sort of exception on the same Packet when testing over my local network. Testing by connecting to myself, though, works great, finally.

These Packets are anywhere from 16kb to around 100kb, by the way.

I've changed ReadPacket() to the following. Is this what you meant?:

        public void ReadPacket()
        {
            byte[] BufferArray = new byte[131072];
            SocketMain.Receive(BufferArray, sizeof(int), SocketFlags.None);

            int PayloadSize = BitConverter.ToInt32(BufferArray, 0);
            int BytesReceived = 0;

            while (BytesReceived < PayloadSize)
            {
                BytesReceived += SocketMain.Receive(BufferArray, BytesReceived, PayloadSize - BytesReceived, SocketFlags.None);
            }

            byte[] Payload = BufferArray.Take(PayloadSize).ToArray();

            Console.WriteLine("Received:" + PayloadSize.ToString() + " | " + Utility.GetMD5Hash(Payload));
            using (MemoryStream MS = new MemoryStream(Payload))
            {
                BinaryFormatter BF = new BinaryFormatter();
                HandlePacket((Packet)BF.Deserialize(MS));
            }
        }

Any ideas where to go next or is my logic wrong?

I'm trying to send data back and forth between two computers using a Socket (TCP). The data is in the form of serialized Packet objects.

At an early point in the application, it must send 25 or so Packets of the same type to the other side. See Case 1 in HandlePacket(). After a few Packets of this type are sent (2 to 5, it's random), the other side crashes with a SerializationException: "Binary stream '0' does not contain a valid BinaryHeader."

I've confirmed that I am always reading the same amount of data from the socket that was sent from the other computer, and I've also confirmed with an MD5 hash that, when the exception is thrown, the data received is not the same actual data that was sent.

Keep in mind that some packets of the type that is failing to deserialize actually do make it through and are processed correctly. I can't figure out why this is happening.

Also, Packets are typically responded to as soon as they are received, so the Send and Read methods usually run on the same thread. Here's my code to send and receive Packets, can anyone see anything wrong?

        public void SendPacket(Packet P)
        {
            using (MemoryStream MS = new MemoryStream())
            {
                BinaryFormatter BF = new BinaryFormatter();
                BF.Serialize(MS, P);

                byte[] Payload = MS.ToArray();
                int PayloadSize = Payload.Length;

                SocketMain.Send(BitConverter.GetBytes(PayloadSize));
                SocketMain.Send(Payload);

                Console.WriteLine("Sent:" + P.GetType().ToString() + ", " + Payload.Length + " | " + Utility.GetMD5Hash(Payload));
            }
        }

        public void ReadPacket()
        {
            byte[] BufferArray = ...

There's another operating system called "Cosmos" that is written in C#, although I think it just converts the C# to Assembly and compiles that. I'm not exactly sure how the thing works at all. :D Maybe it's something worth looking at?

Solved. Thanks for your help everyone.

I've been wondering this for awhile... On your line 3 why should I use "using" before making the FileStream?

I haven't attempted yet, but just wondering. ;)

Not really understanding what you mean...You can have as many if statements as you want wherever you want pretty much.

Here's my dilema. My client program is going to request a certain file from my server program, so the server program needs to send the size of the file it requests and then the file itself by using a Socket all in one go. My client will then read the size of the data, read the file to a buffer, and write the buffer to a file. Essentially it's just downloading something from the computer my server program is running on.

As the files get larger I'm running in to memory issues. Here's how I send something from the server, with an old attempt at using FileStreams to use less memory. I was using MemoryStreams.

[ICODE]Send(File.ReadAllBytes(@"C:\largevideo.avi"));[/ICODE]

[CODE] public void Send(object Data)
{
FileStream SerializeStream = new FileStream(Properties.Settings.Default.TempPath + "serialstrm.TEMP", FileMode.Create); //Create a file to hold serialized data
BinaryFormatter BF = new BinaryFormatter();

        BF.Serialize(SerializeStream, Data); //serialize the data to the file

        //first 8 bytes = size of data
        byte[] Payload      = new byte[8 + SerializeStream.Length]; 

        //stupidity right here :P
        byte[] ByteData     = Data as byte[]; 

        //length of data in byte format 
        byte[] LengthOfData = BitConverter.GetBytes(ByteData.Length); 

        //copy length of data to Payload starting at offset 0
        Buffer.BlockCopy(LengthOfData, 0, Payload, 0, LengthOfData.Length); 
        //copy the byte data to Payload starting at offset 8
        Buffer.BlockCopy(ByteData, 0, Payload, 8, ByteData.Length); 

        MasterSocket.Send(Payload);
    }[/CODE]

I can't figure out how I can send this to the client without reading the entire file into memory first. I know that using File.ReadAllBytes() is going to put that into the memory. What ...

Antivirus programs search a virus executable for a known piece of code or some other sort of signature that uniquely identifies it. Exactly how a virus is identified depends upon how the antivirus was made. The "signatures" or "definitions" you download just about every day is a database containing these identifications.

A virus isn't [I]known[/I] and removable until it has already been released, hit some computers, and either submitted to or caught by Antivirus companies who add an ID for the virus to their database and release an update. To combat new viruses that are unknown, what's called a heuristic scan may be performed.

A heuristic scan picks apart an executable and searches for patterns commonly found in viruses, such as disabling parts of Windows, raising a fake error when something is opened, etc. Most viruses (in this case I am talking about extremely common 'rouge antiviruses') are just cheap copies of earlier ones. Several are identical to one another other than a slightly different GUI, name, and possibly hiding techniques. You can see how this actually works well! If a program is flagged by heuristics it is usually flagged as "Suspicious" as the antivirus doesn't really know if it is a threat or not.

Anyway, It depends on exactly what you are doing in the background. If you're accessing the internet in any way, it'll probably respond by asking the user to allow the program through the firewall. (assuming the antivirus has one, it SHOULD if it's worth anything) ...

The program that uses this function is receiving files of multiple types and sizes from another PC. It has been working well but when the files' size exceeds about 100MB I run out of memory. I need to modify the receiving code so that it saves the incomplete file to the hard drive instead of the memory as it is being read from the stream. Kind of like how Firefox downloads things if you watch it. It makes a .PART file and it increases in size until it's done downloading.

I'm not sure how to do this with the code I have...Any help is appreciated.

Here's the code:
[CODE] public object Receive()
{
MemoryStream MS;
BinaryFormatter BF = new BinaryFormatter();

        byte[] Buffer = new byte[8];                        //First 8 bytes are the size of the data
        NetStream.Read(Buffer, 0, 8);                       //Read them
        Buffer = new byte[BitConverter.ToInt32(Buffer, 0)]; //Set the buffer accordingly

        int BytesRecieved = 0;

        while (BytesRecieved != Buffer.Length)
        {
            try
            {
                BytesRecieved = BytesRecieved + NetStream.Read(Buffer, BytesRecieved, 1024); //Read a kilobyte to the buffer at a time
            }

            catch (ArgumentOutOfRangeException) //There's less than 1 KB left to read
            {
                BytesRecieved = BytesRecieved + NetStream.Read(Buffer, BytesRecieved, Buffer.Length - BytesRecieved);
            }
        }

        MS = new MemoryStream(Buffer);
        return BF.Deserialize(MS);
    }[/CODE]

I'm not really understanding what you mean but I'm guessing it's waiting too long. To make it go faster you'll need to change line 12 to a lower value. The value is in milliseconds and you can get that simply multiplying the number of seconds you want by 1000. If you want 2 seconds type 2000, 5 seconds 5000, 0.5 seconds 500, etc.

What I got from that was to assign the context menu to the control on right click.
That made it a little better but created a new problem. The menu isn't thrown to the top left of the screen anymore, instead it shows up under the File button on the first click. It also shows up wherever I click in the ListView. I need it to show up only when an item is right clicked.

The ChrW() function "returns a character associated with the specified character code."

[URL="http://msdn.microsoft.com/en-us/library/60ecse8t%28v=vs.80%29.aspx"]Here's[/URL] a list of character codes. DEC 59 is a ';'. :)

EDIT: I am sorry, I've never even heard of ZedGraph.

Did that work?

What are your requirements?

Erm..that code above is already in C#.

Its taking a string called ligne, splitting it at char 59 (that's a semicolon), and assigning valeur as index zero of the split.

C# equivalent of that

[CODE]string valeur = ligne.Split(';')[0];[/CODE]

samueal commented: Good one. +4

Use code tags please. :)

[CODE]static void Main(string[] args)
{
string[,] fp = readFilePaths();
OleDbConnection con = new OleDbConnection();
OleDbDataAdapter da;
DataSet ds = new DataSet();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Documents and Settings/kyalanur/Desktop/Nav tool/PCGDataManager.mdb;User ID=;Password=;";
string sq = "SELECT * FROM History";
con.Open();
da = new OleDbDataAdapter(sq, con);
da.Fill(ds, "History");

        for (int i = 0; i < 284; i++)
        {
            if (true)
            {
                //Enter into the dtabase
                DataRow dr = ds.Tables["History"].NewRow();
                dr[0] = DateTime.Today.Date.ToString();
                dr[0] = fp[i, 2];
                dr[2] = generateFilePath(fp[i, 0], fp[i, 1]);
                dr[3] = " ";
                dr[4] = " ";
                dr[5] = fp[i, 3];
                ds.Tables["History"].Rows.Add(dr);
                //OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
                //da.UpdateCommand = cb.GetUpdateCommand();
                da.Update(ds, "History");
            }
            else
            {

            }
        }
    } [/CODE]

I know absolutely nothing about databases so I'm pulling whatever I say straight from Google. :D

Lines 26 and 27 are commented out. Why? That is similar to what was suggested [URL="http://forums.asp.net/t/1239458.aspx"]here.[/URL]

The attached program has a small bug when you right click on an item. The first time you right click any item it'll throw the context menu (it's the same menu under File) all the way up to the top left of the screen, but the second time you right click it'll appear in the right spot. It only does this once. Why would it be doing this? How can I fix it? :?:

Here is the code that runs when you right click.
[CODE]private void FileBrowser_MouseClick(object sender, MouseEventArgs e)
{
FileBrowser.Update();

        if (e.Button == MouseButtons.Right)
        {
            //Show it relative to the FileBrowser at the location of the mouse
            FileContextMenu.Show(FileBrowser, e.Location);
        }
    }[/CODE]

You'll need to keep track of how many it sends and tell it to stop and wait a specified amount of time when that number reaches 400.

Here's an example. I do not know how long you might want it to wait, I assumed 30 seconds.

[CODE] int SentEmails = 0;

        if (SentEmails != 400)  //This code will run if you have not yet sent 400 emails
        {
            //Your code to send an email
            SentEmails++; //Add one to SentEmails
        }

        else //SentEmails equals 400.
        {
            SentEmails = 0;                         //Set it back to zero so we can do it all over again
            System.Threading.Thread.Sleep(30000);    //Wait thirty seconds. (The amount is in milliseconds)
        }[/CODE]

I am sorry but I'm not seeing how that code is supposed to work. It doesn't appear that you're storing the times a number is repeated anywhere.

Try this. It's not the best answer but certainly simpler than what you have above.

[LIST]
[*]Create Key/Value dictionary

[*] Walk through your array, add a key for each number and increment the value each time that element is repeated.

[*] Walk through the dictionary keys, and return the key with the highest value.
[/LIST]

If that doesn't make sense I'll be glad to help.

Your gmail address and password, yes.

Try incorporating what is in the web.config into the code itself. This worked for me.

[CODE] MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");

        message.From = new MailAddress("testing@gmail.com");
        message.To.Add("alex@hotmail.com");
        message.To.Add("alex2@hotmail.com");
        message.Subject = "Test Mail";
        message.Body = "This is for testing SMTP mail from GMAIL";

        smtpClient.Port = 587;
        smtpClient.Credentials = new System.Net.NetworkCredential("Address", "Password");
        smtpClient.EnableSsl = true;

        smtpClient.Send(message);[/CODE]

Would this work for you? This will open the specified website in the user's default browser.

[CODE]System.Diagnostics.Process.Start("http://www.daniweb.com/");[/CODE]

Please use code tags next time. :)

[CODE] int P = 0;
int[,] numbers = {{1, 2, 0, 6 },
{5, 6, 7, 0 },
{9, 3, 6, 2 },
{6, 4, 8, 1}};
int[] A = new int[16];

        foreach (int n in numbers)
        {
            A[P] = n;
            P++;
        }

        P = -1;

        for (int x = 0; x < A.Length; x++)
        {
            for (int y = 0; y < A.Length; y++)
            {
                if (A[x] == A[y])
                {
                    if (x != y)
                    {
                        if (A[x] > P) P = A[x];
                    }
                }
            }
        }

        if (P == -1) Console.WriteLine("There's No repeated number ");
        else Console.WriteLine("The most repeated number is {0}", P);[/CODE]

Could you comment your code? It is a little hard to understand and it might help you solve the problem.

You can't convert a file's byte code to a string and then back to bytes. It will not contain the same data. That's why your copy is smaller than the original; data is lost. I can't explain exactly why this happens but it just does.

I can't think of anything right now that would work with how you have this set up. You have to write the raw data to file without converting it. But I'll try to think of or find something that will work for you. I don't want you to have to rewrite it! I know how that feels. :D

In the meantime could I see your code for 'socketRecv()'?