|
People have been making an assumption (very probably valid) that you want us to write your code for you. That would be doing you a disservice though as the question you ask is "How do I do this assignment????" and that's the question I'm going to answer, even though it's probably not the answer that you were wanting.
What you have here are a set of requirements. Some are explicitly stated and some require you to apply a little bit of problem solving. You start your task by working out what you already know. For instance, you have a vehicle speed and you know that it can store whole or floating point numbers (non-monetary). With a little bit of thought, you realise that the speed property is not going to be a whole number so it can't be a long, short or an int. This doesn't leave you with much in the way of data types so you need to do a little bit of research and find out which data types are available in C# that aren't monetary either.
That's how you solve the problem. By breaking big problems down into little problems. You have all the information you need in this question and the related book, so make use of them.
This space for rent
|
|
|
|
|
Pete O'Hanlon wrote: What you have here are a set of requirements Requirement rarely come in that form, unless we are reverse-engineering. What he has is an exact specification of the properties for the components that the teach desires.
Student does not need knowledge on why those properties exist, or why it would be preferred over the alternative. It is not an assignment, it's a joke.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Hi experts,
I have a WinForm app, with form that build Background Workers in code.
The trigger is a local timer which kill the current BGW if he finished and create it again.
I need in this specific time (between the kill and create - clear all the resources (mainly - memory).
The app uploading files (each above 100MB) using Arrays & Memory Streams.
without clear the memory - it grows with each file ( 3 files can easily get above 1G)
|
|
|
|
|
There are problems here.
1) If you kill a task, it's dead. It can't be asked to recycle it;s resourced after you kill it as the thread itself is terminated, which automatically recycles the stack. So you have no access to the variables that thread was using! To recycle, you need to tell the thread itself it's not needed and let it handle disposal as necessary before it terminates itself by returning from its startup method.
2) There is no specific Array.Dispose in .NET - which means you have no direct control over when the memory allocated to an array is released, even if you are in the task that created it.
The only way to do this is clumsy: tell the task to die via a semaphore so it can intelligently release what resources it has acquired; then when it is complete call GC.Collect to reclaim all unused memory.
Do note that this will not reduce the memory footprint of your overall application, as memory once allocated to a process is not released back to the OS once it is recycled by the CG.
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
As Griff explained, you can't have the GC collect "part" of the garbage. There's an easy way to cheat; instead of having the download-code in a BGW, put it inside a complete process (a separate executable). You could report progress easily by writing/reading stdout, and if you terminate the process, all resources for that process are cleaned up.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
I'm facing an issue , while populating data within datagridview control.
If datagridview's scroll bar is present, then it's showing a flickering and the scroll bar is not movable.
I have implemented solutions for handling double buffering, but could n't find any luck.
My working code:
<pre> public RxnDetailSelectionForm()
{
InitializeComponent();
this.ClientSize = Properties.Settings.Default.RxnImportFormSize;
this.groupBoxSelSectionType.Enabled = false;
this.groupBoxSelExptType.Enabled = false;
this.groupBoxSelExptType.Visible = false;
this.radioButtonSameSectionSameExpt.Checked = true;
this.dataGridView1.Focus();
PopulateData();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000;
return cp;
}
}
public void PopulateData()
{
this.dataGridView1.Rows.Clear();
DataTable dataTable = new DataTable("t");
BindingSource bindingSource = new BindingSource();
for (int i = 0; i < dataGridView1.ColumnCount; ++i)
{
dataTable.Columns.Add(new DataColumn(dataGridView1.Columns[i].Name));
dataGridView1.Columns[i].DataPropertyName = dataGridView1.Columns[i].Name;
}
dataTable.ReadXml("SampleData.xml");
bindingSource.DataSource = dataTable;
dataGridView1.DataSource = bindingSource;
this.dataGridView1.Rows[0].Selected = true;
}
private void RxnDetailSelectionForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.RxnImportFormSize = (sender as Form).ClientSize;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
|
|
|
|
|
You're using databinding; during the binding-process, the UI will stop responding for a very short time. All applications "flicker" like that when processing a lot, and it is not a problem.
If it is a problem to you and you want to eliminate it, then have your gridview virtualized. That's the "fastest" way to show a DGV and its contents.
How to: Implement Virtual Mode in the Windows Forms DataGridView Control | Microsoft Docs[^]
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Tried
this.dataGridView1.VirtualMode = true; , but did n't work.
|
|
|
|
|
That's correct. It requires a bit more than simply toggeling a boolean.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
|
Thanks, have tried it and didn't help.
|
|
|
|
|
I see the software to charge credit card swipe, samsung pay, ... I want to find out how the swipe card works and write code to get payment information in the software sales. how ? You can share the code for me with.
|
|
|
|
|
Start here: Magnetic stripe card - Wikipedia[^]
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Many magnetic stripe readers are keyboard emulators - they decode the data on the stripe and then fed it in to the keyboard buffer as if it has been typed.
=========================================================
I'm an optoholic - my glass is always half full of vodka.
=========================================================
|
|
|
|
|
Given that development recently in C# and even less on HTML. I a trying to use the webbrowser control from the GeckoWebBrowser Ver 45 32bit C# library to execute inserts on a website input.
I tried to use the version Gecko Ver 60 32bit but nothing. I can not pass on ASP.net I absolutely have to solve it by the end of the month. I ask for help and immensely thank you.
source with input name:
<input name="propNome" class="ui-widget-content ui-corner-all jq-lovpersone jq-lovpersone-field ui-autocomplete-input" role="textbox" aria-haspopup="true" aria-autocomplete="list" size="80" autocomplete="off">
my working code:<pre lang="cs"> if (!nomeproprietario)
{
foreach (GeckoHtmlElement hetxtnomeproprietario in webBrowser1.Document.GetElementsByName("propNome"))
{
hetxtnomeproprietario.SetAttribute("type", "text");
hetxtnomeproprietario.SetAttribute("value", "MARIO");
//hetxtnomeproprietario.InvokeMember("click");
//SendKeys.Send("{ENTER}");
nomeproprietario = true;
break;
}
} if instead I use this source with input id:
<input id="durataTrt" name="durataTrt" class="jq-text ui-widget-content ui-corner-all " value="" size="3" maxlength="3" type="text"> my code 1) is not working
if (!durata)
{
foreach (GeckoHtmlElement hetxtdurata in webBrowser1.Document.GetElementsByName("durataTrt"))
{
hetxtdurata.SetAttribute("type", "text");
hetxtdurata.SetAttribute("value", "10");
durata = true;
break;
}
}
I also tried with the .InnerHtml, .Value, .SettAttribute property but nothing
my code 2) is not working
var hetxtdurata1= new Gecko.DOM.GeckoInputElement(webBrowser1.Document.GetHtmlElementById("durataTrt").DomObject);
if (hetxtdurata1== null)
{
return;
}
else
{
hetxtdurata1.Value = "10";
}
I also tried with the .InnerHtml, .Value, SettAttribute property but nothing
my code 3) is not working
Gecko.GeckoHtmlElement hetxtdurata2= (Gecko.GeckoHtmlElement)webBrowser1.DomDocument.GetElementById("durataTrt");
if (hetxtdurata2== null)
{
return;
}
else
{
if (hetxtdurata2!= null)
{
hetxtdurata2.Click();
hetxtdurata2.SetAttribute("type", "text");
hetxtdurata2.SetAttribute("value", "10");
}
} I do not understand why with input name I have no problem while with input id instead.
[edit]Code blocks added - OriginalGriff[/edit]
Andrea Russo
modified 24-Oct-18 14:18pm.
|
|
|
|
|
hi ,
how can I setup automatic mail function which gets triggered by dateTimePicker?
I basicly want to send email when at time that dateTimePicker shows.
modified 13-Feb-19 21:02pm.
|
|
|
|
|
What have you tried ?
Have you created a TaskService, have you researched/tried using a Trigger ? Have you worked with the SmtpClient.SendMailAsync method ?
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
|
|
|
|
|
I will search for SmtpClient.SendMailAsync method and TaskService creation.thank you.
modified 13-Feb-19 21:02pm.
|
|
|
|
|
Two ways:
1) Have an application running which knows what time to send it, and which checks the time often enough to be accurate.
2) Use Scheduler to add a task that runs at a specific time. The task sends your email.
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
thank you. I will check Scheduler
modified 13-Feb-19 21:02pm.
|
|
|
|
|
You're welcome!
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I found the C# source file with the asynchronous class for sending large files via socket tcp between server and client. But my application is necessary that client send file for server.
I'm unable to change class AsynchronousClient.cs to receive file of server.
I need help adjusting the client class to send files.
Many thanks.
https://code.msdn.microsoft.com/windowsdesktop/Fixed-size-large-file-dfc3f45d
Client.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace Client
{
public partial class Client : Form
{
#region Constructor
public Client()
{
InitializeComponent();
}
#endregion
#region Button Event
private void btnConnect_Click(object sender, EventArgs e)
{
int port;
IPAddress ipAddress;
if (string.IsNullOrEmpty(tbxAddress.Text) || string.IsNullOrEmpty(tbxPort.Text))
{
MessageBox.Show(this,Properties.Resources.IsEmptyMsg);
return;
}
try
{
ipAddress = IPAddress.Parse(tbxAddress.Text);
}
catch
{
MessageBox.Show(this,Properties.Resources.InvalidAddressMsg);
return;
}
try
{
port = Convert.ToInt32(tbxPort.Text);
}
catch
{
MessageBox.Show(this,Properties.Resources.InvalidPortMsg);
return;
}
if (port < 0 || port > 65535)
{
MessageBox.Show(this, Properties.Resources.InvalidPortMsg);
return;
}
if (string.IsNullOrEmpty(tbxSavePath.Text))
{
MessageBox.Show(this, Properties.Resources.EmptyPath);
return;
}
AsynchronousClient.IpAddress = ipAddress;
AsynchronousClient.Port = port;
AsynchronousClient.FileSavePath = tbxSavePath.Text;
AsynchronousClient.Client = this;
Thread threadClient= new Thread(new ThreadStart(AsynchronousClient.StartClient));
threadClient.IsBackground = true;
threadClient.Start();
btnConnect.Enabled = false;
}
private void btnSavePath_Click(object sender, EventArgs e)
{
FolderBrowserDialog path = new FolderBrowserDialog();
path.ShowDialog();
this.tbxSavePath.Text = path.SelectedPath;
}
#endregion
#region Change the progressBar
public void SetProgressLength(int len)
{
progressBar.Minimum = 0;
progressBar.Maximum = len;
progressBar.Value = 0;
progressBar.Step = 1;
}
public void ProgressChanged()
{
progressBar.PerformStep();
}
#endregion
#region Functions
public void FileReceiveDone()
{
MessageBox.Show(this, Properties.Resources.FileReceivedDoneMsg);
}
public void ConnectDone()
{
MessageBox.Show(this,Properties.Resources.ConnectionMsg);
}
public void EnableConnectButton()
{
btnConnect.Enabled = true;
}
#endregion
}
}
AsynchonousClient.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Client
{
public static class AsynchronousClient
{
#region Members
private static string fileName;
private static string fileSavePath = "C:/";
private static long fileLen;
private static AutoResetEvent connectDone = new AutoResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
private static bool connected = false;
private delegate void ProgressChangeHandler();
private delegate void FileReceiveDoneHandler();
private delegate void ConnectDoneHandler();
private delegate void EnableConnectButtonHandler();
private delegate void SetProgressLengthHandler(int len);
#endregion
public static IDictionary<Socket, IPEndPoint> ClientsToSend = new Dictionary<Socket, IPEndPoint>();
public static string FileToSend { get; set; }
private const int c_bufferSize = 5242880;
private static int signal;
private static ManualResetEvent allDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private delegate void RemoveItemHandler(string ipAddress);
private delegate void CompleteSendHandler();
public static IList<Socket> Clients = new List<Socket>();
#region Properties
public static Client Client { get; set; }
public static IPAddress IpAddress { get; set; }
public static int Port { get; set; }
public static string FileSavePath
{
get
{
return fileSavePath;
}
set
{
fileSavePath = value.Replace("\\", "/");
}
}
#endregion
#region Functions
public static void StartClient()
{
connected = false;
if (IpAddress == null)
{
MessageBox.Show(Properties.Resources.InvalidAddressMsg);
return;
}
IPEndPoint remoteEP = new IPEndPoint(IpAddress, Port);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), clientSocket);
connectDone.WaitOne();
if (connected)
{
Receive(clientSocket);
receiveDone.WaitOne();
Client.BeginInvoke(new FileReceiveDoneHandler(Client.FileReceiveDone));
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
else
{
Thread.CurrentThread.Abort();
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket clientSocket = (Socket)ar.AsyncState;
clientSocket.EndConnect(ar);
}
catch
{
MessageBox.Show(Properties.Resources.InvalidConnectionMsg);
Client.BeginInvoke(new EnableConnectButtonHandler(Client.EnableConnectButton));
connectDone.Set();
return;
}
Client.BeginInvoke(new ConnectDoneHandler(Client.ConnectDone));
connected = true;
connectDone.Set();
}
private static void ReceiveFileInfo(Socket clientSocket)
{
byte[] fileNameLenByte = new byte[4];
try
{
clientSocket.Receive(fileNameLenByte);
}
catch
{
if (!clientSocket.Connected)
{
HandleDisconnectException();
}
}
int fileNameLen = BitConverter.ToInt32(fileNameLenByte, 0);
byte[] fileNameByte = new byte[fileNameLen];
try
{
clientSocket.Receive(fileNameByte);
}
catch
{
if (!clientSocket.Connected)
{
HandleDisconnectException();
}
}
fileName = Encoding.ASCII.GetString(fileNameByte, 0, fileNameLen);
fileSavePath = fileSavePath + "/" + fileName;
byte[] fileLenByte = new byte[8];
clientSocket.Receive(fileLenByte);
fileLen = BitConverter.ToInt64(fileLenByte, 0);
}
private static void Receive(Socket clientSocket)
{
StateObject state = new StateObject();
state.WorkSocket = clientSocket;
ReceiveFileInfo(clientSocket);
int progressLen = checked((int)(fileLen / StateObject.BufferSize + 1));
object[] length = new object[1];
length[0] = progressLen;
Client.BeginInvoke(new SetProgressLengthHandler(Client.SetProgressLength), length);
try
{
clientSocket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch
{
if (!clientSocket.Connected)
{
HandleDisconnectException();
}
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket clientSocket = state.WorkSocket;
BinaryWriter writer;
int bytesRead = clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
if (!File.Exists(fileSavePath))
{
writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Create));
}
else
{
writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Append));
}
writer.Write(state.Buffer, 0, bytesRead);
writer.Flush();
writer.Close();
Client.BeginInvoke(new ProgressChangeHandler(Client.ProgressChanged));
try
{
clientSocket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch
{
if (!clientSocket.Connected)
{
MessageBox.Show(Properties.Resources.DisconnectMsg);
}
}
}
else
{
receiveDone.Set();
}
}
#endregion
#region Private Functions
private static void HandleDisconnectException()
{
MessageBox.Show(Properties.Resources.DisconnectMsg);
Client.BeginInvoke(new EnableConnectButtonHandler(Client.EnableConnectButton));
Thread.CurrentThread.Abort();
}
#endregion
}
}
Program.cs
using System;
using System.Threading;
using System.Windows.Forms;
namespace Client
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Client());
}
public static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}
}
}
Server
Server.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace Server
{
public partial class Server : Form
{
private static bool HasStartup = false;
#region Constructor
public Server()
{
InitializeComponent();
}
#endregion
#region Button Event
private void btnStartup_Click(object sender, EventArgs e)
{
if (!HasStartup)
{
try
{
AsynchronousSocketListener.Port = tbxPort.Text;
}
catch(Exception ex)
{
MessageBox.Show(this,ex.Message);
return;
}
AsynchronousSocketListener.Server = this;
Thread listener = new Thread(new ThreadStart(AsynchronousSocketListener.StartListening));
listener.IsBackground = true;
listener.Start();
HasStartup = true;
}
MessageBox.Show(this,Properties.Resources.StartupMsg);
}
private void btnSelectFile_Click(object sender, EventArgs e)
{
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
tbxFile.Text = openFileDialog.FileName;
AsynchronousSocketListener.FileToSend = tbxFile.Text;
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if(lbxServer.SelectedItems.Count == 0)
{
MessageBox.Show(this,Properties.Resources.SelectClientMsg);
return;
}
if (string.IsNullOrEmpty(tbxFile.Text))
{
MessageBox.Show(this,Properties.Resources.EmptyFilePathMsg);
return;
}
if(AsynchronousSocketListener.Clients.Count == 0)
{
MessageBox.Show(this,Properties.Resources.ConnectionMsg);
return;
}
foreach (object item in lbxServer.SelectedItems)
{
foreach (Socket handler in AsynchronousSocketListener.Clients)
{
IPEndPoint ipEndPoint = (IPEndPoint)handler.RemoteEndPoint;
string address = ipEndPoint.ToString();
if (string.Equals(item.ToString(), address, StringComparison.OrdinalIgnoreCase))
{
AsynchronousSocketListener.ClientsToSend.Add(handler,ipEndPoint);
break;
}
}
}
Thread sendThread = new Thread(new ThreadStart(AsynchronousSocketListener.Send));
sendThread.IsBackground = true;
sendThread.Start();
btnSend.Enabled = false;
}
#endregion
#region ListBox item change functions
public void AddClient(IPEndPoint IpEndPoint)
{
lbxServer.BeginUpdate();
lbxServer.Items.Add(IpEndPoint.ToString());
lbxServer.EndUpdate();
}
public void CompleteSend()
{
while (lbxServer.SelectedIndices.Count > 0)
{
lbxServer.Items.RemoveAt(lbxServer.SelectedIndices[0]);
}
btnSend.Enabled = true;
}
public void RemoveItem(string ipAddress)
{
int index = 0;
bool flag = false;
foreach (object item in lbxServer.SelectedItems)
{
if (!string.Equals(item.ToString(), ipAddress, StringComparison.OrdinalIgnoreCase))
{
index++;
}
else
{
flag = true;
break;
}
}
if (flag)
{
lbxServer.Items.RemoveAt(index);
}
}
public void EnableSendButton()
{
btnSend.Enabled = true;
}
#endregion
}
}
AsynchronousSocketListener.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Server
{
public static class AsynchronousSocketListener
{
#region Constants
private const int c_clientSockets = 100;
private const int c_bufferSize = 5242880;
#endregion
#region Memebers
private static int port;
private static int signal;
private static ManualResetEvent allDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private delegate void AddClientHandler(IPEndPoint IpEndPoint);
private delegate void CompleteSendHandler();
private delegate void RemoveItemHandler(string ipAddress);
private delegate void EnableSendHandler();
#endregion
#region Properties
public static Server Server { get; set; }
public static string Port
{
set
{
try
{
port = Convert.ToInt32(value);
}
catch (FormatException)
{
throw new Exception(Properties.Resources.InvalidPortMsg);
}
catch (OverflowException ex)
{
throw new Exception(ex.Message);
}
if (port < 0 || port > 65535)
{
throw new Exception(Properties.Resources.InvalidPortMsg);
}
}
}
public static string FileToSend { get; set; }
public static IList<Socket> Clients = new List<Socket>();
public static IDictionary<Socket,IPEndPoint> ClientsToSend = new Dictionary<Socket,IPEndPoint>();
#endregion
#region Functions
public static void StartListening()
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
return;
}
listener.Listen(c_clientSockets);
while (true)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
allDone.WaitOne();
}
}
private static void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
IPEndPoint ipEndPoint = handler.RemoteEndPoint as IPEndPoint;
if ((ipEndPoint) != null)
{
Server.BeginInvoke(new AddClientHandler(Server.AddClient),ipEndPoint);
}
Clients.Add(handler);
allDone.Set();
}
public static void SendFileInfo()
{
string fileName = FileToSend.Replace("\\", "/");
IList<Socket> closedSockets = new List<Socket>();
IList<String> removedItems = new List<String>();
while (fileName.IndexOf("/") > -1)
{
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
FileInfo fileInfo = new FileInfo(FileToSend);
long fileLen = fileInfo.Length;
byte[] fileLenByte = BitConverter.GetBytes(fileLen);
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + 8];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileLenByte.CopyTo(clientData, 4 + fileNameByte.Length);
foreach (KeyValuePair<Socket, IPEndPoint> kvp in ClientsToSend)
{
Socket handler = kvp.Key;
IPEndPoint ipEndPoint = kvp.Value;
try
{
handler.Send(clientData);
}
catch
{
if (!handler.Connected)
{
closedSockets.Add(handler);
removedItems.Add(ipEndPoint.ToString());
}
}
}
RemoveClient(closedSockets);
RemoveClientItem(removedItems);
closedSockets.Clear();
removedItems.Clear();
}
public static void Send()
{
int readBytes = 0;
byte[] buffer = new byte[c_bufferSize];
IList<Socket> closedSockets = new List<Socket>();
IList<String> removedItems = new List<String>();
SendFileInfo();
using (FileStream stream = new FileStream(FileToSend, FileMode.Open))
{
do
{
sendDone.Reset();
signal = 0;
stream.Flush();
readBytes = stream.Read(buffer,0,c_bufferSize);
if (ClientsToSend.Count == 0)
{
sendDone.Set();
}
foreach (KeyValuePair<Socket,IPEndPoint> kvp in ClientsToSend)
{
Socket handler = kvp.Key;
IPEndPoint ipEndPoint = kvp.Value;
try
{
handler.BeginSend(buffer, 0, readBytes, SocketFlags.None, new AsyncCallback(SendCallback), handler);
}
catch
{
if (!handler.Connected)
{
closedSockets.Add(handler);
signal++;
removedItems.Add(ipEndPoint.ToString());
if (signal >= ClientsToSend.Count)
{
sendDone.Set();
}
}
}
}
sendDone.WaitOne();
RemoveClient(closedSockets);
RemoveClientItem(removedItems);
closedSockets.Clear();
removedItems.Clear();
}
while (readBytes > 0);
}
ClientDisconnect();
CompleteSendFile();
}
private static void SendCallback(IAsyncResult ar)
{
lock (Server)
{
Socket handler = null;
try
{
handler = (Socket)ar.AsyncState;
signal++;
int bytesSent = handler.EndSend(ar);
if (bytesSent == 0)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (ArgumentException argEx)
{
MessageBox.Show(argEx.Message);
}
catch (SocketException)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
finally
{
if (signal >= ClientsToSend.Count)
{
sendDone.Set();
}
}
}
}
private static void ClientDisconnect()
{
Clients.Clear();
ClientsToSend.Clear();
}
private static void CompleteSendFile()
{
Server.BeginInvoke(new CompleteSendHandler(Server.CompleteSend));
}
private static void RemoveClientItem(IList<String> ipAddressList)
{
foreach (string ipAddress in ipAddressList)
{
Server.BeginInvoke(new RemoveItemHandler(Server.RemoveItem), ipAddress);
}
if (ClientsToSend.Count == 0)
{
Server.BeginInvoke(new EnableSendHandler(Server.EnableSendButton));
}
}
private static void RemoveClient(IList<Socket> listSocket)
{
if (listSocket.Count > 0)
{
foreach (Socket socket in listSocket)
{
Clients.Remove(socket);
ClientsToSend.Remove(socket);
}
}
}
#endregion
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace Server
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Server());
}
}
}
modified 22-Oct-18 12:53pm.
|
|
|
|
|
Is there any error being raised during the compilation? Because it would be hard to check the entire code base and then suggest something.
It would be helpful to know the desired and provided behavior of the program.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
The issue is much the same as sending, and is controlled by a protocol which you design. The client sends a request for a file to the server. The server returns details of the file name size etc. The client then requests some data which the server returns. This process continues until the server signals "no more data".
|
|
|
|
|
I want to implement cheque printing in my ERP application. It is developed in C# with SQL Server as backend. Can anyone provide sample source code, or advice which classes or methods can be used
|
|
|
|
|