WildBamaBoy 19 Junior Poster

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.

WildBamaBoy 19 Junior Poster

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));
                    } …
WildBamaBoy 19 Junior Poster

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

WildBamaBoy 19 Junior Poster

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 …

WildBamaBoy 19 Junior Poster

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?

WildBamaBoy 19 Junior Poster

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?

WildBamaBoy 19 Junior Poster

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[] …
WildBamaBoy 19 Junior Poster

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?

WildBamaBoy 19 Junior Poster

Solved. Thanks for your help everyone.

WildBamaBoy 19 Junior Poster

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. ;)

WildBamaBoy 19 Junior Poster

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

WildBamaBoy 19 Junior Poster

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. Send(File.ReadAllBytes(@"C:\largevideo.avi"));

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);
        }

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 …

WildBamaBoy 19 Junior Poster

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 known 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 …

WildBamaBoy 19 Junior Poster

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:

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);
        }
WildBamaBoy 19 Junior Poster

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.

WildBamaBoy 19 Junior Poster

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.

WildBamaBoy 19 Junior Poster

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

Here's a list of character codes. DEC 59 is a ';'. :)

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

WildBamaBoy 19 Junior Poster

Did that work?

WildBamaBoy 19 Junior Poster

What are your requirements?

WildBamaBoy 19 Junior Poster

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

WildBamaBoy 19 Junior Poster

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

string valeur = ligne.Split(';')[0];
samueal commented: Good one. +4
WildBamaBoy 19 Junior Poster

Use code tags please. :)

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
                {

                }
            }
        }

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 here.

WildBamaBoy 19 Junior Poster

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.

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);
            }
        }
WildBamaBoy 19 Junior Poster

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.

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)
            }
WildBamaBoy 19 Junior Poster

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.

  • 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.

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

WildBamaBoy 19 Junior Poster

Your gmail address and password, yes.

WildBamaBoy 19 Junior Poster

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

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);
WildBamaBoy 19 Junior Poster

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

System.Diagnostics.Process.Start("http://www.daniweb.com/");
WildBamaBoy 19 Junior Poster

Please use code tags next time. :)

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);

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

WildBamaBoy 19 Junior Poster

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()'?

WildBamaBoy 19 Junior Poster

I'm also working on something similar to this. I believe your problem is that you're writing a string representation of the data to the file. .txt files contain only text and nothing else. Right click a .txt file and open it with Notepad. It's just text. Now right click an .exe file and open it with Notepad. It's a bunch of garbage. That's the file's raw byte code.

Converting that to a string and writing it to a file is not going to work. You're going to have to write the raw byte code to a file with no changes to it after you receive it.

Use File.WriteAllBytes(Destination, data)

WildBamaBoy 19 Junior Poster

Server code

public static object Receive()
        {
            MemoryStream MS;

            byte[] Buffer = new byte[1024];
            int BytesRecieved = Sock.Receive(Buffer);

            MS = new MemoryStream(Buffer);

            return new BinaryFormatter().Deserialize(MS);
        }

        public static void Send(object Data)
        {
            MemoryStream MS = new MemoryStream();
            BinaryFormatter BF = new BinaryFormatter();

            BF.Serialize(MS, Data);

            byte[] Payload = new byte[8 + MS.ToArray().Length];
            byte[] ByteData = MS.ToArray();
            byte[] LengthOfData = BitConverter.GetBytes(ByteData.Length);

            Buffer.BlockCopy(LengthOfData, 0, Payload, 0, LengthOfData.Length);
            Buffer.BlockCopy(ByteData, 0, Payload, 8, ByteData.Length);

            Sock.Send(Payload);

            Log("Sent payload of " + (Payload.Length - 8) + " bytes.");
        }

Client code

public object Receive()
        {
            DataReceivedLabel.Text = "0";
            DataSizeLabel.Text = "0 bytes";

            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

            DataSizeLabel.Text = Buffer.Length + " bytes";

            int BytesRecieved = 0;

            while (BytesRecieved != Buffer.Length)
            {
                try
                {
                    BytesRecieved = BytesRecieved + NetStream.Read(Buffer, BytesRecieved, 100); //Read 100 bytes to the buffer at a time
                    DataReceivedLabel.Text = BytesRecieved.ToString();                          //Set the amount received
                }

                catch (ArgumentOutOfRangeException)                                             //There's less than 100 bytes left to read
                {
                    int Remainder = Buffer.Length - Convert.ToInt32(DataReceivedLabel.Text);    //Get the bytes left to read and finish.

                    BytesRecieved = BytesRecieved + NetStream.Read(Buffer, BytesRecieved, Remainder);
                    DataReceivedLabel.Text = BytesRecieved.ToString();
                }
            }

            MS = new MemoryStream(Buffer);
            return BF.Deserialize(MS);
        }

        public void Send(object Data)
        {
            MemoryStream MS = new MemoryStream();
            BinaryFormatter BF = new BinaryFormatter();

            BF.Serialize(MS, Data);

            NetStream.Write(MS.ToArray(), 0, MS.ToArray().Length);
        }

Compare to above. The 'garbage' was the adding the bytes that were …

WildBamaBoy 19 Junior Poster

Uhh apparently it works now. :S
I actually read what the code was doing and noticed there was garbage left over from how the program used to work. Removed that and it appears to run fine.

WildBamaBoy 19 Junior Poster

I tried with the client and server running on two different computers and it actually started working. I increased the amount of data sent until it finally crashed. It crashed when the size of the data was 24110 bytes, receiving only 8752.

EDIT: It only works SOMETIMES. :?:

WildBamaBoy 19 Junior Poster

This will do it.

for (int I = 1; I <= 4; I++)
            {
                this.Controls["label" + I].Text = "Some text";
            }
WildBamaBoy 19 Junior Poster

Try increasing the size to 1048576 and see if it works.

WildBamaBoy 19 Junior Poster

Your buffer needs to be 1048576 if you want to get up to a megabyte. Warning though, reading cuts off when the buffer is full so if your image turns out to be bigger than a megabyte you're not going to have the full image and it will throw an exception like it is now.

WildBamaBoy 19 Junior Poster

You reached 380 points, so you achieved position 11591 of 658357 on the ranking list


You type 501 characters per minute
You have 90 correct words and
you have 1 wrong words

The highest wpm I remember getting was on some baby-ish typing program in our school's computer app class. 110 wpm :)

WildBamaBoy 19 Junior Poster
jackhicks121 commented: I have https://serverorbit.com/466440-s21-hp-8gb-667mhz-pc2-5300-ecc-ddr2-sdram-184-pin-reg-ram-deal/. Will it work or suggest me what should I do +0
WildBamaBoy 19 Junior Poster

Gah. It's so weird! I did what you suggested. I can send a password to the server and get a response, but when trying to get bigger amounts of data everything goes crazy. The data I am sending to the client is 6306 bytes exactly. If I step through all of the code line by line it works great. However if I run the program normally the client throws a Serialization Exception.

The exception says "End of Stream encountered before parsing was completed."

EDIT: Putting a breakpoint on the moment when my client deserializes the data showed that it only received 4372 of the 6306 bytes it was supposed to be getting. The server shows that it sends all of it, too. :'( Why would I not be receiving some data when I don't step through it line by line?

EDIT2: This is the new code for the server.

public static object Receive()
        {
            MemoryStream MS;
            BinaryFormatter BF = new BinaryFormatter();

            //Receive the size of the data.
            List<byte> ReceivedBytes = new List<byte>();

            byte[] Buffer = new byte[1024];
            int BytesRecieved = Sock.Receive(Buffer);

            for (int i = 0; i < BytesRecieved; i++)
            {
                ReceivedBytes.Add(Buffer[i]);
            }

            MS = new MemoryStream(ReceivedBytes.ToArray());

            return BF.Deserialize(MS);
        }

        public static void Send(object Data)
        {
            MemoryStream MS = new MemoryStream();
            BinaryFormatter BF = new BinaryFormatter();

            BF.Serialize(MS, Data);

            byte[] Payload = new byte[8 + MS.ToArray().Length];
            byte[] ByteData = MS.ToArray();
            byte[] LengthOfData = BitConverter.GetBytes(ByteData.Length);

            System.Buffer.BlockCopy(LengthOfData, 0, Payload, 0, LengthOfData.Length);
            System.Buffer.BlockCopy(ByteData, 0, Payload, 8, ByteData.Length);

            Sock.Send(Payload);
        }

and …

WildBamaBoy 19 Junior Poster

A. It's really strange...sometimes the sending and receiving works once, and sometimes not at all. An exception is never thrown, the client just seems to indefinitely be waiting for data when the server has already sent it.

B. That sounds like it would work well....I'll give it a shot.

WildBamaBoy 19 Junior Poster

In my client/server program, whenever I need to get data from one or the other it requires a buffer to temporarily store the data. The problem is that I don't know how much data I am going to be getting. I could be receiving a few lines of text or a 100mb file.

I've tried:

1. Getting the Length of the NetworkStream.
Not supported. It would be great if it worked! :'(

2. Reading NetworkStream with a StreamReader and getting the length
The length stops at 8 kilobytes.

3. Increasing the size of the buffer as needed
Data became corrupted.

4. Sending the size of the data and then the actual data
The client gets one thing from the server and doesn't receive anything after that.

I'm completely out of ideas now. Can anyone help me with this?

Here's the sending and receiving code for my server with the attempt and number 4 included.

public static object Receive()
        {
            MemoryStream MS;
            BinaryFormatter BF = new BinaryFormatter();

            //Receive the size of the data.
            int DataSize = 0;
            byte[] SizeBuffer = new byte[1024];
            int k = Sock.Receive(SizeBuffer);

            DataSize = BitConverter.ToInt32(SizeBuffer, 0);

            // Set the size of the buffer and get the actual data
            List<byte> ReceivedBytes = new List<byte>();
            byte[] DataBuffer = new byte[DataSize];

            k = Sock.Receive(DataBuffer);

            for (int i = 0; i < k; i++)
            {
                ReceivedBytes.Add(DataBuffer[i]);
            }

            MS = new MemoryStream(ReceivedBytes.ToArray());

            return BF.Deserialize(MS);
        }

        public static void Send(object Data) …
WildBamaBoy 19 Junior Poster

I don't believe you're going to be able to easily get the path of a file just by having its file name. That's what Search does. The first thing that popped up in my head was to create a dictionary. Make the key be the file's name and make the value the full path to the file.

You'll need to add to the dictionary while you have the file's FileInfo by using its Name (just the file's name) and FullName (the full path to it) properties. Then in that second foreach you'll need to look up the path from the dictionary.

Here's your code edited to do the above. I can not test it right now.

Your first block.

public Dictionary<string, string> FileDict = new Dictionary<string, string>(); //make a new dictionary, with its key being a string and value being a string

        private void button1_Click(object sender, EventArgs e)
        {
            DirectoryInfo di = new DirectoryInfo(dDir);

            FileInfo[] vpkFiles = di.GetFiles("*.vpk");
            foreach (FileInfo fi in vpkFiles)
            {
                FileDict.Add(fi.Name, fi.FullName); //assign key as the file's name, and value as the full path to it.
                checkedListBox1.Items.Add(fi.Name);
            }
        }

Second block.

foreach (object itemChecked in checkedListBox1.CheckedItems)
            {
                string P = FileDict[itemChecked.ToString()]; //lookup the value of the current item
                DirectoryInfo di = new DirectoryInfo(P);
                FileInfo[] maps = di.MoveTo(dDir); //MoveTo doesn't return FileInfo[] :)
            }
WildBamaBoy 19 Junior Poster

Exactly what I needed. Thank you.

WildBamaBoy 19 Junior Poster

If you look at a bunch of files with the Details view, file types known to Windows have a greater description of the file in the Type column. For example, .exe is an Application, .txt is a Text Document, and .cpp is C++ Source. If they are not known, Windows just shows the extension plus the word 'file'. I need to get this extra description just as it would appear in Windows. Is there any way to get it from Windows programatically or would I have to manually create some kind of database? (I'd really rather not)

I can see all of the known file extensions and their descriptions by going to Folder Options and File Types, but I don't see an obvious way to get that description.

WildBamaBoy 19 Junior Poster

When you make a new 'A' and tell it to Show(), you should see another method called ShowDialog(). This is exactly what you want as execution will not continue until that dialog is closed.

Here's an example. Assuming the form you want to call is named SubmitForm.

SubmitForm A = new SubmitForm();
A.ShowDialog();
MessageBox.Show("The submit form closed."); //This will not show until the form closes.

If you want the Submmit button to actually close the form. Then put this at the end of your code for it.

this.DialogResult = DialogResult.OK;

All forms shown as 'dialogs' return a DialogResult to the caller. They will close once their DialogResult has been assigned, which is what that code does. You can get its DialogResult by changing line 2 of the above to:

DialogResult SubmitResult = A.ShowDialog();

Now you'd just have to check the value with an IF statement. You don't have to do that though. ;)

WildBamaBoy 19 Junior Poster

Try this. I don't understand the problem fully but this is what I use to get the computer's 'external' IP that you can connect to it from, especially if it is behind a router.

string IP = new WebClient().DownloadString("http://automation.whatismyip.com/n09230945.asp");
WildBamaBoy 19 Junior Poster

There's an infinite recursion going on. Here's what is happening.

Line 127: You make a BattleshipBoard object called 'b' giving it the value of a new BattleshipBoard class. It's going to go through and assign any variables you tell it to and make its methods available to the object you assign it to.

Line 10: You create a new Player object called 'p' with the value of a new Player class. It will assign values and make the methods available to 'p'.

Line 48: Inside the Player class, you create another new BattleshipBoard.

The program will now go back to BattleshipBoard, which creates a new player, which creates a new BattleshipBoard, which creates a new player, and so on.

ddanbe commented: Nice observation and explanation! +14
WildBamaBoy 19 Junior Poster

Figured it all out!

WildBamaBoy 19 Junior Poster

Thank you! That's the kind of post I was looking for. :)

I don't seem to have something called 'netcat'. It says 'not recognized as an internal or external command blah blah blah'. I'm on XP SP3 if that matters. Either way, it seems that I can successfully connect the two programs because when a connection is established I show the IP address of the other computer (RemoteEndpoint?). The only time I try to send data is when I send the screenshot so it's probably something with how I use the socket. I'll work with that awhile.

Random.Next() says 'returns a random number within the specified range'. I believe that most of the random ports have been very very high numbers. I've changed that to 2000 and 3000 as I didn't know about reserved ports. Maybe I need to check if the port can be used first or something? Can I do that?

Fantastic explanation by the way. Maybe a stupid question but do I need to send the file's name or can I just receive the raw file data and write it to a file with a name of my own choosing?