|
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
|
|
|
|
|
What framework are you using for this ERP solution of yours? In .NET framework printing APIs differ from framework to framework, you will find one thing for Windows Forms, and entirely different thing for WPF.
As for the cheque printing, you need to utilize a third-party solution if you do not wish to write the code for it yourself, as I doubt Microsoft has provided any in-built solution for cheque printing. It requires you to print text, on specific areas of the paper (cheque). That will be complex. However the normal PrintDocument class might be able to help you out, and you can then decide where you want to print, what information.
PrintDocument Class (System.Drawing.Printing) | Microsoft Docs
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Hi
I use this code to read the barcode from A4 size paper.
It works correctly.
But it takes more than 23 seconds to read one sheet of paper.
The program, which was designed to accomplish hundreds of papers in record time, which means the failure of the main objective of the production of this program.
Is there a solution for being more experienced than me.
Thanks in advance for anyone who answered my inquiry.
int i = 0;
ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
try
{
decoded = "";
String[] barcodes = BarcodeScanner.Scan(jpegPaths[frame], BarcodeType.All);
barcode = new string[barcodes.Length];
foreach (string element in barcodes)
{
if (element != "")
barcode[i] = element;
i += 1;
}
|
|
|
|
|
Your code isn't doing any of the heavy lifting of scanning a page for barcodes. That's entire up to the ZXing library.
You're only option is to use a different library that has better performance. It's going to be up to you to test these libraries out to see if they are up to your requirements.
Google for "C# barcode scanning library".
|
|
|
|
|
Yes, your words are true and I apologize for being a beginner programmer
Is there a barcode library faster?
|
|
|
|
|
This is where YOU do the research. I already told you what to Google for to find libraries. It's up to you to try them out.
|
|
|
|
|
I have the following setup:
Client: AngularJS Web App
Server: ASP.NET Web API
In the server I use the IdentityFramework3 to authenticate users on my AngularJS Client that has the (oidc-token-manager) configured.
Currently I'm setting the AbsoluteRefreshTokenLifetime to 48 hours for my Client MyAngularJsApp like so:
new Client
{
Enabled = true,
ClientId = MyAngularJsApp.Id,
ClientUri = MyAngularJsApp.Uri,
ClientName = MyAngularJsApp.Name,
Flow = Flows.Implicit,
AllowAccessToAllScopes = true,
IdentityTokenLifetime = 300,
AccessTokenLifetime = 3600,
RefreshTokenExpiration = TokenExpiration.Absolute,
RefreshTokenUsage = TokenUsage.ReUse,
AbsoluteRefreshTokenLifetime = TimeSpan.FromDays(2).Seconds,
RequireConsent = false,
RedirectUris = new List<string>
{
MyAngularJsApp.Uri + "/assets/idSrv/callback.html",
MyAngularJsApp.Uri + "/assets/idSrv/silentrefreshframe.html"
},
PostLogoutRedirectUris = new List<string>
{
MyAngularJsApp.Uri + "/index.html"
}
} There is one specific user that will log into my client that I want to set his Refresh Token to last 100 days so that the user does not have to Authenticate in 100 days, the reason I need this specific user to have 100 days without needing to log in is because this user will be used to display a specific part of the app on a big monitor, it'll remain static for 100 days
AbsoluteRefreshTokenLifetime = TimeSpan.FromDays(100).Seconds How do I make it so that only this user has this refresh token lifetime?
[Edit]Reformatted the question so that it wasn't all inside one pre block.
modified 18-Oct-18 2:49am.
|
|
|
|
|
Hi!! I've made an application with WinForm C#. How can I change it to application Sercvice. Thanks
|
|
|
|
|
Depends.
Services and Apps are very different beasties: services do not have a UI, WinForms apps do.
What is your app doing, and why do you want it as a service?
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!
|
|
|
|
|
App which get CPU Temperature and Windows config.
|
|
|
|
|
Please, stop trying to type the absolute bare minimum, or we will be here all day!
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with. And the better the information you give us, the better help we can give you.
So what does this app do with the info?
What should the service do with it?
What problems are you having in converting it?
What help do you need?
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!
|
|
|
|
|
ok ok... So, I've build an apps to get my computer Configuration and its Temperature.
My question is : How to convert windows application to windows service c# ?.. thanks
|
|
|
|
|
So, the "all day" option it is then ...
Just saying the same thing over again in bigger letters doesn't make it more informative - it makes it more annoying, but does not increase the overall level of information. And annoying the people you want help from probably isn't the best way to go in life.
Read what I said again:
Quote: Please, stop trying to type the absolute bare minimum, or we will be here all day!
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with. And the better the information you give us, the better help we can give you.
So what does this app do with the info?
What should the service do with it?
What problems are you having in converting it?
What help do you need?
So what does the app do with the info?
1) Store it in a database?
2) Etch it on stone tablets and pass it down the mountain?
3) Strap it to the legs of pigeons and send it to your auntie?
4) Display it to the user in a neat and tidy way so he can understand what is going on in his computer?
5) Something else entirely?
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!
|
|
|
|
|
wrote: How to convert windows application to windows service c# I will answer the narrowest part of your question. Unless you're running on an old version of Windows, you cannot convert a UI based application into a windows service. A service is expected to have no user interface.
What you can do is extract the core logic that relates to the none UI part and host that as a DLL inside a service. If you need to communicate with a forms or WPF application you need to set up some form of communications protocol between the two. TCP is a popular choice.
This space for rent
|
|
|
|
|
Services don't have a UI, so turning your app into a service isn't possible or feasible.
Usually, people start out writing a service, and make it compilable as a command line app to test is without having to continually install/uninstall a service (not to mention avoiding the slightly more tedious nature of debugging a Windows service).
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
I need help with breaking my algorithm into modules. The reason why is because the following code at the moment is essentially duplicated three times for each calculate button on my GUI Windows Forms Application. I was wondering if I break it down in to sub-routines this can be done? Can anyone help me with this?
public void park1()
{
string allotedTime = txtTimeLimit1.Text;
string startTime = txtEntryTime1.Text;
string endTime = txtExitTime1.Text;
if (String.IsNullOrEmpty(allotedTime) || String.IsNullOrEmpty(startTime) || String.IsNullOrEmpty(endTime))
{
MessageBox.Show("Enter all time values");
}
else
{
TimeSpan alloted = TimeSpan.Parse(allotedTime);
DateTime start = DateTime.Parse(startTime);
DateTime end = DateTime.Parse(endTime);
if (start > end)
end = end.AddDays(1);
TimeSpan duration = end.Subtract(start);
//If the start time is greater than end that means the diff is above 12 hours
//So subtracting the hours from a day to get the number of hours used if (TimeSpan.Compare(alloted, duration) == -1)
if (TimeSpan.Compare(alloted, duration) == -1)
{
overTime1++;
}
completeTime1++;
lblOverTime1.Text = "" + overTime1;
int percentage = (overTime1 * 100) / completeTime1;
lblOverTimePercentage1.Text = "" + percentage;
if (percentage > 50)
{
warnWarden();
}
}
}
|
|
|
|
|
Start by creating a seperate class (seperate from your GUI class) and pass the necessary data for the algortihm via or the constructor or via properties (or both).
The GUI should handle data validation input. Perhaps make the calculation buttons only available if the data is valid.
When the algorithm is finished it returns the result to the GUI who can display it.
Small pseudocode example.
function calculate(){
int n1, n2;
bool parse1 = int.TryParse(txt1.Text, out n1);
bool parse2 = int.TryParse(txt2.Text, out n2);
if(parse1 && parse2){
Calculator calc = new Calculator();
txt_sum.Text = calc.Add(n1, n2);
txt_substract.Text = calc.Substract(n1, n2);
}
}
function Add(int n1, int n2){
return n1 + n2;
}
function Substract(int n1, int n2){
return n1 - n2;
}
Of course this is a very quick and dirty pseudo code example, you'll need to work the rest out from there.
PS: If you want to do it properly move the calculations to some form of a business layer instead of just a seperate class.
Hope this helps.
|
|
|
|
|
Hey, I am also a programmer, so for that, I have some different thought, before taking any modulator you just take some class or integer and after you step by step you will do the code. For further about it
epson error code 0xf1 just visit with it.
|
|
|
|
|
0) Set the Tag property on each calc button to an appropriate (unique) integer index value, such as 1, 2, 3. etc
1) Set each calc button to use the same Click event handler
2) In the one-and-only Click event handler do something like this:
private void Calc_Click(object sender,...)
{
switch (Convert.ToInt32((Button)sender.Tag))
{
case 1 : MyCalcRoutine(1, txtTimeLimit1, txtEntryTime1, txtExitTime1); break;
case 2 : MyCalcRoutine(2, txtTimeLimit2, txtEntryTime2, txtExitTime2); break;
case 3 : MyCalcRoutine(3, txtTimeLimit3, txtEntryTime3, txtExitTime3); break;
}
}
And finally, your generic calculation routine.
private void MyCalcRoutine(int index, TextBox timeLimit, TextBox entryTime, TextBox exitTime)
{
string allotedTime = timeLimit.Text;
string startTime = entryTime.Text;
string endTime = exitTime;
if (String.IsNullOrEmpty(allotedTime) || String.IsNullOrEmpty(startTime) || String.IsNullOrEmpty(endTime))
{
MessageBox.Show("Enter all time values");
}
else
{
TimeSpan alloted = TimeSpan.Parse(allotedTime);
DateTime start = DateTime.Parse(startTime);
DateTime end = DateTime.Parse(endTime);
if (start > end)
{
end = end.AddDays(1);
}
TimeSpan duration = end.Subtract(start);
if (TimeSpan.Compare(alloted, duration) == -1)
{
overTime1++;
}
completeTime1++;
lblOverTime1.Text = "" + overTime1;
int percentage = (overTime1 * 100) / completeTime1;
lblOverTimePercentage1.Text = "" + percentage;
if (percentage > 50)
{
warnWarden();
}
}
}
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
I'm not sure how far you got with breaking this down into a single algorithm, but here's what I got so far.
public class UIForm
{
public class TimeSet
{
private TextBox _txtAllottedTime;
private TextBox _txtStartTime;
private TextBox _txtEndTime;
public TimeSet(TextBox txtAllottedTime, TextBox txtStartTime, TextBox txtEndTime)
{
_txtAllottedTime = txtAllottedTime;
_txtStartTime = txtStartTime;
_txtEndTime = txtEndTime;
}
private string AllottedTime =>
_txtAllottedTime.Text;
private string StartTime =>
_txtStartTime.Text;
private string EndTime =>
_txtEndTime.Text;
public bool TextWasEnteredByUser =>
string.IsNullOrEmpty(AllottedTime) ||
string.IsNullOrEmpty(StartTime) ||
string.IsNullOrEmpty(EndTime);
}
public List<TimeSet> TimeSets
{
new TimeSet(txtTimeLimit1, txtEntryTime1, txtExitTime1),
new TimeSet(txtTimeLimit2, txtEntryTime2, txtExitTime2),
new TimeSet(txtTimeLimit3, txtEntryTime3, txtExitTime3)
};
public void park1()
{
park(TimeSets[0]);
}
public void park2()
{
park(TimeSets[1]);
}
public void park3()
{
park(TimeSets[2]);
}
public void park(TimeSet timeSet)
{
if (!timeSet.TextWasEnteredByUser)
{
MessageBox.Show("Enter all time values");
}
else
{
TimeSpan alloted = TimeSpan.Parse(timeSet.AllottedTime);
DateTime start = DateTime.Parse(timeSet.StartTime);
DateTime end = DateTime.Parse(timeSet.EndTime);
if (start > end)
end = end.AddDays(1);
TimeSpan duration = end.Subtract(start);
if (TimeSpan.Compare(alloted, duration) == -1)
{
overTime1++;
}
completeTime1++;
lblOverTime1.Text = "" + overTime1;
int percentage = (overTime1 * 100) / completeTime1;
lblOverTimePercentage1.Text = "" + percentage;
if (percentage > 50)
{
warnWarden();
}
}
}
}
I had to do some guessing, and as a forewarning, I obviously couldn't compile this code. However, what I am attempting to show you is that I created a subclass (one which should be in a separate file at this point), and this is handling one park# case at a time. I can initialize each TimeSet in a List<TimeSet> , and access a single instance of a TimeSet in a given park# call. This gives me the arguments I need. I then just call a single method, park , with all of the parameters I need in one object at the beginning.
Also, due to this cleanup, I can clean up that if statement to ask the object passed in one question, instead of calling string.IsNullOrEmpty() multiple times in one line. This makes the code a bit more readable.
You can continue on refactoring, because I do see there were a few other controls that you could add to the class, and frankly the rest of the else block could potentially be in this new class, cleaning up your UIForm code.
I would need a bit more context in order to be more thorough, but hopefully you see what I'm trying to do. Good luck.
|
|
|
|
|