Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
M

Metal76

@Metal76
About
Posts
31
Topics
13
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Cannot use any DLL in Windows Service!
    M Metal76

    Final update: this is actually a known VS bug. http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=271421[^] I've discovered this by accident, skimming throug a ton of google results about $(TargetPath) usage.

    C# help testing debugging beta-testing question

  • Cannot use any DLL in Windows Service!
    M Metal76

    Update to the previous message: by carefully inspecting the installation logs, I noticed that by using $(TargetPath), VS was picking a copy of my service exe from the "obj/Debug" folder, and not from the "bin/Debug" folder, which contains the results of the compilation and all the assemblies that I'm referencing! I could not spot this earlier because I have a long path to the service exe directory, and I did not notice the fact that it contained "obj" instead of "bin"... For the moment, I have modified the external tool arguments as: $(BinDir)$(TargetName)$(TargetExt) which seems to work, even if I suspect there should be a more direct way to accomplish the same task. Regards, Andrea

    C# help testing debugging beta-testing question

  • Cannot use any DLL in Windows Service!
    M Metal76

    Hi Dhaim, I think I've found it! It is simply an installation issue. In order to install the service, I have configured an external tool in VS2008 with the following parameters: Title: Install Service Command: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe Arguments: $(TargetPath) Init.directory: $(TargetDir) The uninstall service is the same but adds /u. Now, launching this command actually installs the service (I have the familiar installutil log and I can start/stop the service as usual), but the service only works correctly if it does not include any dependency! As soon as I add an assembly, installing like this leads to the issue I noticed, for reasons that I'm not able to explain. If I simply open a VS prompt and install the service "manually" from the command line, everything is fine and the service works as expected. Thanks for your interest in my issue! Regards, Andrea

    C# help testing debugging beta-testing question

  • Cannot use any DLL in Windows Service!
    M Metal76

    Hi, it's actually a .NET assembly so there should not be any problem. It only implements the following code:

    namespace TimeLogger
    {
    public class RandomClass
    {
    public static int GetRandomNumber()
    {
    Random rand = new Random();

            return rand.Next();
        }
    }
    

    }

    And compiles it as a managed DLL (TestDll.dll). I add a reference to TestDll.dll in my simple service, I add a line which goes: int test = RandomClass.GetRandomNumber() and the service stops working as discussed in my previous message. What am I missing? Thanks, Andrea

    C# help testing debugging beta-testing question

  • Cannot use any DLL in Windows Service!
    M Metal76

    I'm experimenting with windows services, and I'm facing a strange issue. Consider the following code for a really simple, barebone windows service:

    public class TimeLoggerService : ServiceBase
    {
    public TimeLoggerService()
    {
    InitializeComponent();

        \_timer = new Timer(10000);
        \_timer.Elapsed += new ElapsedEventHandler(\_timer\_Elapsed);
    }
    
    protected override void OnStart(string\[\] args)
    {
        \_timer.Start();
    }
    
    protected override void OnStop()
    {
        \_timer.Stop();
    }
    
    protected void \_timer\_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Do stuff here
    }
    

    }

    I compile & install using installutil.exe, and everything works fine. The problem is: when I add a reference to any DLL in my code, the service stops working and I have a FileNotFoundException which tells me that it was impossible to load the DLL. Now: 1 - The service has a LocalSystem account 2 - The DLL is contained in the same folder as the service exe file (the bin/debug folder of my VS2008 project) 3 - This happens with any DLL: I've even written a "dummy" dll with a single method GetNumber() which returns an integer for testing purposes, and by simply adding a call to GetNumber() I have the aforementioned problem Do you have any suggestions about this issue? Regards, Andrea

    C# help testing debugging beta-testing question

  • Automatically update reference to DLL in VS2008
    M Metal76

    I'm developing an application whose components are split between several VS solutions. For example: - Solution A includes projectA1 and projectA2 generating projectA1.dll and projectA2.dll - Solution B includes projectB1 generating projectB1.dll - Solution C includes a project which uses all the DLLs above to generate an application app.exe When I add the DLLs as references to solution C, they are copied in the output folder for app.exe. However, if I change something in Solution A, the modified DLL is obviously not automatically copied to Solution C. Is there a way to maintain this kind of structure avoiding manual copies? Regards, Andrea

    Visual Studio visual-studio tutorial question announcement

  • Closing sockets in asynchronous TCP server
    M Metal76

    Hi Mark, at the moment my code implements a similar (but even simpler) approach: the EndXxx calls are wrapped in a try...catch block, only catching the SocketException and ObjectDisposed exception which seem to be the ones which get "normally" fired when I force the shutdown on the socket. Something like:

    try
    {
    ...
    // Starts receiving data
    _Socket.BeginReceive(_ReceiveBuffer,
    0,
    _ReceiveBuffer.Length,
    SocketFlags.None,
    new AsyncCallback(ClientReceiveCallback),
    null);
    ...

    }
    catch (SocketException sockExc)
    {
    // Process connection errors (e.g. connection closed by peer...)
    // by closing the socket
    SocketClose((SocketError)sockExc.ErrorCode);
    }
    catch (ObjectDisposedException objDispExc)
    {
    // Could fire during forced shutdown because
    // socket is disposed while reception is pending
    // No need to close the socket here
    }

    Do you think it could also be a valid approach? I feel a little uneasy to use exceptions to implement normal programming logic, but I could not find a "clean" way to forcibly shutdown sockets, even searching in CodeProject articles! Regards, Andrea

    C# sysadmin question announcement

  • Closing sockets in asynchronous TCP server
    M Metal76

    Hi Nick, before trying your suggestion, I was wondering: does using some kind of lock around socket I/O operations actually interfere with data exchange? That is: as well as BeginReceive/EndReceive, in my server I also transmit data with BeginSend/EndSend. Suppose I acquire a lock over the socket while reading, and at the same time I have a trasmission going on over the same socket. What happens? This is a situation I'm going to face in my code, which uses bidirectional full-duplex communications. Regards, Andrea

    C# sysadmin question announcement

  • Closing sockets in asynchronous TCP server
    M Metal76

    As usual you save my day Nick! I'm currently refactoring my server code for better maintainability, as soon as possible I'll try your suggestion and let you know. Thanks! Andrea

    C# sysadmin question announcement

  • Closing sockets in asynchronous TCP server
    M Metal76

    I'm developing an application in which multiple clients exchange data on a TCP link with a server using a custom protocol. I've chosen the asynchronous approach to implement the server: i.e. my application listens for incoming connection with BeginAccept, and accepts them with EndAccept, receives data with BeginReceive/EndReceive and so on. I also keep a list of connected client state information, so that the users of my class can read several info about the clients (IP address, connection state etc.) Now, I'm implementing several methods to forcibly disconnect a client, and to shutdown the whole server (disconnect all the clients and release server resources). Unfortunately, simply closeing the clients + server sockets does not work because the pending operations (EndAccept etc.) fail with various kind of exceptions (NullReference, ObjectDisposed etc.) Is there a correct way to forcibly shutdown connections? Regards, Andrea

    C# sysadmin question announcement

  • Async callback usage in TCP server application
    M Metal76

    Thanks Nick! As usual, very useful info. Bye, Andrea

    C# sysadmin question

  • Async callback usage in TCP server application
    M Metal76

    Hi Nick! By the way, I also considered the ReceiveAsync pattern you suggested in your last post, but as a newbie I found it more difficult to approach :-) I'll consider it for future enhancements.

    Nick Butler wrote:

    Just as a matter of style, I would put the calls to BeginAccept and BeginReceive in a private method each, just so you don't have two copies of each call.

    Do you mean something like the following?

    private void StartReceiving(ClientState clientState)
    {
    clientSocket.BeginReceive(clientState.Buffer,
    0,
    clientState.Buffer.Length,
    SocketFlags.None,
    new AsyncCallback(OnClientRead),
    clientState);
    }

    A couple of additional points (just to increase the amount of beer pints I already owe you): 1) Which is the correct way to gracefully shutdown the server app? I know for sure that I have to close all the client sockets; are there any other resources to shutdown in the async pattern I'm following? 2) I noticed that the ClientState instance I create inside OnClientConnect for each of the clients seems to be internally maintained by the async pattern, without any intervention on my side. That is: when OnClientRead fires from one of the clients, the input IAsyncResult state is the right ClientState instance associated with that client. So, it seems to me that keeping a clientList is only useful when I want to shutdown the server (so that I can dispose of each client socket) and if I want to offer to the users of my class the possibility to perform actions on connected clients (e.g. check state of client A, forcibly shutdown connection with client B etc.). Is this right? Thanks in advance and best regards, Andrea

    C# sysadmin question

  • Async callback usage in TCP server application
    M Metal76

    I'm developing an application in which multiple clients exchange data on a TCP link with a server using a custom protocol. I've chosen the asynchronous approach to implement the server. Below I've attached an excerpt of my code, showing the points discussed in my questions. I have several doubts about correct asynchronous callback usage, and I could not find anything in the docs: 1) Suppose you have several clients connected. Do all the callbacks (OnClientConnect, OnClientRead...) "live" in the same thread? That is, while I'm inside OnClientRead to serve one of the clients, can my code be interrupted by an OnClientRead from another client? I performed a simple investigation, and it seems that OnClientRead for different clients are called from the same thread. So, it seems that OnClientRead execution never gets interrupted. Am I right? Is this always true? If so, I think I can safely remove all the lock statements for clientList access. 2) Is it correct to always launch a new AsyncCallback every time? e.g. new AsyncCallback(OnClientRead) inside OnClientRead. Does this waste resources? Should I keep a different AsyncCallback for each client and reuse it? Regards, Andrea

    class ClientState
    {
    // Holds client state: I/O buffer, socket, IP endpoint etc...
    }

    class NetworkServer
    {
    // Holds list of client states
    private List clientList;
    private object lockObject = new object();

    // Start server node
    public void Start(int backlog)
    {
        clientList = new List();
    
       // Listen to incoming connections asynchronously
        serverSocket.Listen(backlog);
        serverSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);   
    }
    
    // Callback on client connection
    private void OnClientConnect(IAsyncResult state)
    {
        // Accepts incoming connection
        Socket clientSocket = serverSocket.EndAccept(state);
    
        // Create client state and fill it with state values    
        ClientState clientState = new ClientState();
        ...
    
        // Add to client list
        lock(lockObject)
        {
            clientList.Add(clientState);
        }
        
        // Start receiving from client
        clientSocket.BeginReceive(clientState.Buffer, 
                                  0,
    
    C# sysadmin question

  • Newbie threading questions (data exchange + shutdown)
    M Metal76

    Thanks Nick, great suggestion! I have to work with a console application and I thought an event-based solution would not fit, but now I think I'll reconsider the whole approach. Regards, Andrea

    C# question sysadmin help tutorial workspace

  • Newbie threading questions (data exchange + shutdown)
    M Metal76

    Hi Navaneeth, thanks for fast and really useful reply! I have an additional doubt regarding thread shutdown. At the moment, the HandleClient() is something like this:

    void HandleClient()
    {
    ...

    // Block until data is available from socket or client disconnected
    while ((recvMsgSize = clntSock.Receive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None)) > 0)
    {
    // Process received data
    ...
    }

    // Client disconnected, return from function --> terminate thread
    }

    So when shutting down the application I'd like to shutdown any active client connection and release any network resource. In order to use your solution (polling the canContinue flag) I think I should avoid blocking calls like the socket Receive() one. Am I right? And can you suggest a "graceful" way to shutdown alive connections? Thanks in advance and regards, Andrea

    C# question sysadmin help tutorial workspace

  • Newbie threading questions (data exchange + shutdown)
    M Metal76

    I'm writing a simple multi-threaded TCP socket server, in which a new thread is created for each incoming connection (I only have to handle few connection so this should be ok). It is something like this:

    static void Main(string[] args)
    {
    ...

    // Setup server socket
    TcpListener listener = new TcpListener(IPAddress.Any, servPort);
    listener.Start();
    
    while(true)
    {
      try
      {
          // Block waiting for connection
          Socket clntSock = listener.AcceptSocket();
    
          // Connection detected: launch worker thread
          MyProtocol protocol = new MyProtocol();
          Thread thread = new Thread(new ThreadStart(protocol.HandleClient));
          thread.Start();
      }
      catch (System.IO.IOException e)
      {
          // Perform error handling
          ...
      }
    }    
    

    }

    public class MyProtocol
    {
    public void HandleClient()
    {
    // Code to handle incoming data from client
    ...
    }
    }

    I have several newbie questions: 1) How can I access data living in the worker threads? I was thinking to use properties in MyProtocol class for this purpose, like:

    public class MyProtocol
    {
    // Value used inside HandleClient()
    public int Data
    {
    get { return _Data; }
    set { _Data = value; }
    }
    private int _Data;

    public void HandleClient() {...}
    

    }

    The main thread keeps a reference to the MyProtocol objects created, and uses the Data property to exchange data with the thread (with appropriate synchronization using lock to avoid race conditions). Is this ok? Is there any better approach? 2) Which is the correct way to shut down the connection threads? For example, if I want to close the server application, I think I should deal with terminating the connections in a correct manner. Best regards, Andrea

    C# question sysadmin help tutorial workspace

  • Asynchronous messaging with web service
    M Metal76

    Forgive me if this is a silly or badly formulated question but I'm a newbie in .NET programming. I need an easy way to exchange asynchronous messages between a Windows service (or client application) and a Web service. Up till now I've considered (but still not implemented and tested) the following approaches: - Using a TCP socket. Is there any standardized way in .NET to send/receive messages using this link? For example, using XML or SOAP as a standard encapsulation format for data. - Using MSMQ. Is this a valid approach for this kind of applications? I could not find many information. Do you have any suggestions and/or links to good reference material? Regards, Andrea

    .NET (Core and Framework) xml question csharp wcf oop

  • How to get rid of VS2005 unwanted automatical copy of source files to project directory?
    M Metal76

    Already found the answer by myself: in the "Add existing..." dialog, it is possible to add a class as a link instead of copying the file Regards

    Visual Studio visual-studio tutorial question

  • How to get rid of VS2005 unwanted automatical copy of source files to project directory?
    M Metal76

    I'm using VS2005 and I've noticed a strange behaviour. I have a folder SampleProgram containing a VS project (SampleProgram.csproj) and several source files. Moreover, I have another folder (let's call it FolderA) containing other source files. If I add the files inside FolderA to SampleProgram project, VS automatically copies the source files from FolderA to SampleProgram folder. Afterwards, the project works with the locally copied files, so that any modification is not propagated to FolderA. Is there any way to disable this behaviour? I'd like to directly reference the files in FolderA instead of working on local copies! Thanks in advance and best regards, Andrea

    Visual Studio visual-studio tutorial question

  • Newbie question: single/multiple method arguments
    M Metal76

    I think I've just found the answer by myself: void MyMethod(params int[]). It was a stupid question, indeed! Bye, Andrea

    C# question help csharp data-structures tutorial
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups