public async Task InsertAsync(User user)
        {
            using (var db = LocalConnection.GetConnection())
            {
                // Insert User
                var tb_user = new TB_USER()
                {
                    FIRIST_NAME = user.FirstName,
                    LAST_NAME   = user.LastName,
                    EMAIL       = user.Email,
                    PASSWORD    = user.Password,
                    CREATE_DATE = DateTime.Now,
                    IS_ACTIVE   = true,
                    UPDATE_DATE = DateTime.Now
                };
                db.TB_USER.Add(tb_user);

                // Insert phones
                user.Phones.ForEach(p =>
                {
                    db.TB_PHONE.Add(new TB_PHONE()
                    {
                        NUMBER       = (int)p.Number,
                        AREA_CODE    = (int)p.Area_code,
                        COUNTRY_CODE = p.Country_code,
                        CREATE_DATE  = DateTime.Now,
                        USER_ID      = tb_user.ID
                    });
                });

                await db.SaveChangesAsync();
            }
        }
        public LocalGetResourceContents(LocalConnection conn)
        {
            this.Parent = conn;
            var fact = new MgdServiceFactory();

            _resSvc = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
        }
        public void Invoke(string connectionName, string data = "", string methodName = "Invoke")
        {
            // wait for ack!

            #region rx
            if (rx == null)
            {
                rx = new LocalConnection();


                var client = new DynamicContainer {
                    Subject = new object()
                };

                Action <string> Invoke = ack_data =>
                {
                    // http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_4.html

                    if (yield != null)
                    {
                        yield(ack_data);
                    }

                    //content.r.Fill = Brushes.Green;
                };

                // http://stackoverflow.com/questions/6834455/as3-localconnection-errors
                client["Invoke"] = Invoke.ToFunction();
                rx.allowDomain("*");
                rx.allowInsecureDomain("*");
                rx.status += delegate
                { };

                rx.client = client.Subject;

                // ArgumentError: Error #2082: Connect failed because the object is already connected.
                // Error #2044: Unhandled StatusEvent:. level=error, code=

                // If the string for connectionName begins with an underscore (for example, _connectionName), Flash Player
                // does not add a prefix to the string. This means the receiving and sending LocalConnection objects will
                // use identical strings for connectionName. If the receiving object uses LocalConnection.allowDomain() to specify that connections from any domain will be accepted, you can move the SWF file with the receiving LocalConnection object to another domain without altering any sending LocalConnection objects.
                rx.connect(connectionName + "_ack");

                //content.MouseLeftButtonUp +=
                //    delegate
                //    {
            }
            #endregion


            #region tx
            tx.status +=
                delegate
            {
            };
            tx.allowDomain("*");
            tx.allowInsecureDomain("*");
            tx.send(connectionName, methodName, data);
            #endregion
        }
Exemple #4
0
        public DbAttack GetAttackById(Guid id)
        {
            var command = new MySqlCommand($"SELECT * FROM Attack WHERE Id = {id}");
            var data    = ExecuteSingleDataQuery <DbAttack>(command);

            LocalConnection.InsertOrReplace(data);
            return(null);
        }
Exemple #5
0
 public LocalRuntimeMap(LocalConnection conn, MgdMap map, bool suppressErrors)
     : base(conn)
 {
     _impl = map;
     _conn = conn;
     InitializeLayersAndGroups(suppressErrors);
     _disableChangeTracking = false;
 }
Exemple #6
0
 private void ListenForConnections()
 {
     if (LocalConnection.ConnectionWaiting)
     {
         LocalConnection.AcceptConnection();
         AddClient(new LocalClient(this));
     }
 }
Exemple #7
0
 /// <summary>
 /// Gets an endpoint connected to this server.
 /// Disposing the endpoint also disposes the server.
 /// </summary>
 /// <typeparam name="TPacketData">The packet type.</typeparam>
 /// <returns>The new endpoint.</returns>
 public Endpoint <TPacketData> GetLocalEndpoint <TPacketData>()
 {
     lock (_mutex)
     {
         var connection = new LocalConnection <TPacketData>(this);
         _connections.Add(connection);
         return(connection);
     }
 }
 public void Test()
 {
     Guid            gameId       = Guid.Parse("59c2bb37-eaad-4f5c-8760-ed00aa349a85");
     var             localAttacks = LocalConnection;
     string          query        = $"SELECT * FROM Attack WHERE GameId = ?";
     SQLiteCommand   command      = LocalConnection.CreateCommand(query, gameId);
     var             test         = command.CommandText;
     List <DbAttack> result       = command.ExecuteQuery <DbAttack>();
 }
Exemple #9
0
 public override void CheckForPackets()
 {
     while (LocalConnection.ServerToClientPending())
     {
         Stream str = LocalConnection.ReadServerToClientPacket();
         ReadPacket(str);
         LocalConnection.EndReadingServerToClientPacket();
     }
 }
Exemple #10
0
        public static void InternalInvoke(Action <string> yield)
        {
            #region rx
            if (rx == null)
            {
                rx = new LocalConnection();
                var r = new Random();

                ii = r.Next();


                var client = new DynamicContainer {
                    Subject = new object()
                };

                Action <string> Invoke = data =>
                {
                    //if (yield == null)
                    //    return;

                    // http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_4.html
                    //Diagnostics("InternalInvoke yield");

                    yield(data);
                    //yield = null;

                    //content.r.Fill = Brushes.Green;
                };

                // http://stackoverflow.com/questions/6834455/as3-localconnection-errors
                client["Invoke"] = Invoke.ToFunction();
                rx.allowDomain("*");
                rx.allowInsecureDomain("*");
                rx.status += delegate
                { };

                rx.client = client.Subject;

                // ArgumentError: Error #2082: Connect failed because the object is already connected.
                // Error #2044: Unhandled StatusEvent:. level=error, code=

                // If the string for connectionName begins with an underscore (for example, _connectionName), Flash Player
                // does not add a prefix to the string. This means the receiving and sending LocalConnection objects will
                // use identical strings for connectionName. If the receiving object uses LocalConnection.allowDomain() to specify that connections from any domain will be accepted, you can move the SWF file with the receiving LocalConnection object to another domain without altering any sending LocalConnection objects.
                rx.connect("_Invoke" + ii);

                //content.MouseLeftButtonUp +=
                //    delegate
                //    {
            }
            #endregion

            Diagnostics("NavigateTo");
            new Uri("http://young-beach-4377.herokuapp.com/#c" + ii).NavigateTo();
            //};
        }
 public virtual Connection Connect()
 {
     var localConnection = new LocalConnection();
     var remoteConnection = new LocalConnection(localConnection);
     lock (server)
     {
         server.connections.Add(remoteConnection);
     }
     return localConnection;
 }
        public async Task DeleteByEmailAsync(string email)
        {
            using (var db = LocalConnection.GetConnection())
            {
                var usr = await db.TB_USER.Where(u => u.EMAIL == email).FirstOrDefaultAsync();

                db.TB_TOKEN_AUTHENTICATION
                .RemoveRange(usr.TB_TOKEN_AUTHENTICATION);
                await db.SaveChangesAsync();
            }
        }
Exemple #13
0
        public virtual Connection Connect()
        {
            var localConnection  = new LocalConnection();
            var remoteConnection = new LocalConnection(localConnection);

            lock (server)
            {
                server.connections.Add(remoteConnection);
            }
            return(localConnection);
        }
        private void SaveToLocalDb <T>(T[] data)
        {
            if (data.Length == 0)
            {
                return;
            }

            foreach (T item in data)
            {
                LocalConnection.InsertOrReplace(item);
            }
        }
Exemple #15
0
        public void runLocalWorkflow()
        {
            string          dbname = "localcsharpdatabase";
            LocalConnection conn   = new LocalConnection(dbname);

            new DelveClient(conn);

            conn.CreateDatabase(true);

            conn.LoadCSV(
                rel: "edge_csv",
                schema: new CSVFileSchema("Int64", "Int64"),
                syntax: new CSVFileSyntax(header: new List <string>()
            {
                "src", "dest"
            }, delim: "|"),
                //path: "~/workspace/data/wiki-Vote2.txt"
                data: @"
                    30|31
                    33|30
                    32|31
                    34|35
                    35|32
                "
                );

            conn.Query(
                srcStr: @"
                    def vertex(id) = exists(pos: edge_csv(pos, :src, id) or edge_csv(pos, :dest, id))
                    def edge(a, b) = exists(pos: edge_csv(pos, :src, a) and edge_csv(pos, :dest, b))
                ",
                persist: new List <string>()
            {
                "vertex", "edge"
            },
                output: "edge"
                );
            // Jaccard Similarity Query
            string queryString = @"
                def uedge(a, b) = edge(a, b) or edge(b, a)
                def tmp(a, b, x) = uedge(x,a) and uedge(x,b) and a > b
                def jaccard_similarity(a,b,v) = (count[x : tmp(a,b,x)] / count[x: (uedge(a, x) or uedge(b, x)) and tmp(a,b,_)])(v)

                def result = jaccard_similarity
            ";

            var queryResult = conn.Query(
                srcStr: queryString,
                output: "result"
                );

            Console.WriteLine("==> Jaccard Similarity: " + JObject.FromObject(queryResult).ToString());
        }
 public async Task InsertToken(UserToken token)
 {
     using (var db = LocalConnection.GetConnection())
     {
         db.TB_TOKEN_AUTHENTICATION.Add(new TB_TOKEN_AUTHENTICATION {
             IS_VALID    = true,
             TOKEN       = token.Token,
             USER_ID     = token.UserId,
             CREATE_DATE = DateTime.Now,
             UPDATE_DATE = DateTime.Now
         });
         await db.SaveChangesAsync();
     }
 }
        public async Task UpdateTokenAsync(UserToken token)
        {
            using (var db = LocalConnection.GetConnection())
            {
                var tk = await db.TB_TOKEN_AUTHENTICATION.Where(t => t.TOKEN == token.Token).FirstOrDefaultAsync();

                if (tk != null)
                {
                    tk.IS_VALID    = token.IsValid;
                    tk.UPDATE_DATE = tk.UPDATE_DATE;
                    await db.SaveChangesAsync();
                }
            }
        }
Exemple #18
0
 private void buttonHistory_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         LocalConnection   localCon = new LocalConnection();
         DietHistoryWindow dietWin  = new DietHistoryWindow();
         localCon.InitializeConnection();
         dietWin.ShowDialog();
         LogWriter.LogWrite("Opened the macros calculator window.");
     }
     catch (Exception g)
     {
         MessageBox.Show(g.Message);
         LogWriter.LogWrite(g.ToString());
     }
 }
        public async Task <User> SearchByIdAsync(int userId)
        {
            using (var db = LocalConnection.GetConnection())
            {
                TB_USER user = await db.TB_USER.Where(u => u.ID == userId).FirstOrDefaultAsync();

                return(new User()
                {
                    UserId = user.ID,
                    Email = user.EMAIL,
                    Created_at = user.CREATE_DATE,
                    FirstName = user.FIRIST_NAME,
                    LastName = user.LAST_NAME
                });
            }
        }
Exemple #20
0
        protected override bool AttemptConnection()
        {
            LocalConnection.EstablishConnection();

            DateTime start = DateTime.Now;

            while (LocalConnection.ConnectionWaiting)
            {
                if ((DateTime.Now - start).TotalSeconds > 5.0)
                {
                    return(false);
                }

                Thread.Sleep(100);
            }

            return(true);
        }
Exemple #21
0
        public async Task <IEnumerable <Phone> > SearchByUserIdAsync(int userId)
        {
            using (var db = LocalConnection.GetConnection())
            {
                var phones = await db.TB_PHONE.Where(p => p.USER_ID == userId).ToListAsync();

                List <Phone> result = new List <Phone>();
                phones.ForEach(p =>
                {
                    result.Add(new Phone()
                    {
                        Number       = p.NUMBER,
                        Area_code    = p.AREA_CODE,
                        Country_code = p.COUNTRY_CODE
                    });
                });
                return(result);
            }
        }
Exemple #22
0
        public async Task InsertPhonesAsync(Phone[] phones, int userId)
        {
            using (var db = LocalConnection.GetConnection())
            {
                foreach (var phone in phones)
                {
                    db.TB_PHONE.Add(new TB_PHONE()
                    {
                        NUMBER       = (int)phone.Number,
                        AREA_CODE    = (int)phone.Area_code,
                        COUNTRY_CODE = phone.Country_code,
                        USER_ID      = userId,
                        CREATE_DATE  = DateTime.Now,
                        UPDATE_DATE  = DateTime.Now
                    });
                }

                await db.SaveChangesAsync();
            }
        }
        public async Task <IEnumerable <UserToken> > SearchTokensByLoginAsync(string login)
        {
            using (var db = LocalConnection.GetConnection())
            {
                var t = await db.TB_TOKEN_AUTHENTICATION.Where(x => x.TB_USER.EMAIL == login).ToListAsync();

                List <UserToken> tks = new List <UserToken>();
                t.ForEach(tk =>
                {
                    tks.Add(new UserToken()
                    {
                        UserId     = tk.USER_ID,
                        CreateDate = tk.CREATE_DATE,
                        Email      = tk.TB_USER.EMAIL,
                        IsValid    = tk.IS_VALID,
                        ModifyDate = tk.UPDATE_DATE,
                        Token      = tk.TOKEN
                    });
                });
                return(tks);
            }
        }
        public async Task <UserCredentials> SearchAsync(string login)
        {
            using (var db = LocalConnection.GetConnection())
            {
                TB_USER user = await db.TB_USER.Where(u => u.EMAIL == login).FirstOrDefaultAsync();

                if (user != null)
                {
                    return(new UserCredentials()
                    {
                        Id = user.ID,
                        IsActive = user.IS_ACTIVE,
                        Email = user.EMAIL,
                        Password = user.PASSWORD
                    });
                }
                else
                {
                    return(null);
                }
            }
        }
        public async Task <User> SearchByEmailAsync(string userEmail)
        {
            using (var db = LocalConnection.GetConnection())
            {
                TB_USER user = await db.TB_USER.Where(u => u.EMAIL == userEmail).FirstOrDefaultAsync();

                if (user != null)
                {
                    return(new User()
                    {
                        UserId = user.ID,
                        Email = user.EMAIL,
                        Created_at = user.CREATE_DATE,
                        FirstName = user.FIRIST_NAME,
                        LastName = user.LAST_NAME
                    });
                }
                else
                {
                    return(null);
                }
            }
        }
        public async Task <UserToken> SearchByTokenAsync(string token)
        {
            using (var db = LocalConnection.GetConnection())
            {
                var t = await db.TB_TOKEN_AUTHENTICATION.Where(x => x.TOKEN == token).FirstOrDefaultAsync();

                if (t != null)
                {
                    return(new UserToken()
                    {
                        UserId = t.USER_ID,
                        CreateDate = t.CREATE_DATE,
                        Email = t.TB_USER.EMAIL,
                        IsValid = t.IS_VALID,
                        ModifyDate = t.UPDATE_DATE,
                        Token = t.TOKEN
                    });
                }
                else
                {
                    return(null);
                }
            }
        }
Exemple #27
0
        /**
         * Gets the next message in the queue, optionally blocking until a message is available
         */
        private Int32 GetMessage_1_0(Int32 ConnectionHandle,Hashtable InParameters,ref Hashtable OutParameters)
        {
            StartTiming("GetMessage_1_0-Internal",true);

            Int32        ErrorCode   = Constants.INVALID;
            AgentMessage NextMessage = null;

            // Unpack the input parameters
            Int32 Timeout = ( Int32 )InParameters["Timeout"];

            // First, validate the connection requesting the message by making sure it
            // exists and is local
            Connection Recipient;

            if ((Connections.TryGetValue(ConnectionHandle,out Recipient)) &&
                (Recipient is LocalConnection))
            {
                // This should only ever be called by local connections since remote
                // connections have a direct messaging link between Agents
                LocalConnection ConnectionMessageSentTo = Recipient as LocalConnection;

                StopTiming();

                // If no message is available, wait for one for the specified amount of time
                bool Signaled = ConnectionMessageSentTo.MessageAvailableWait(Timeout);

                StartTiming("GetMessage-Internal",true);

                // If the semaphore was signaled, then check the queue and get the next message
                if (Signaled)
                {
                    // Thread-safe queue usage
                    lock (ConnectionMessageSentTo.MessageQueue)
                    {
                        // Check to see if we actually have any messages to dequeue (standard case)
                        if (ConnectionMessageSentTo.MessageQueue.Count > 0)
                        {
                            // Dequeue and process the message
                            NextMessage = ConnectionMessageSentTo.MessageQueue.Dequeue();

                            OutParameters            = new Hashtable();
                            OutParameters["Version"] = ESwarmVersionValue.VER_1_0;
                            OutParameters["Message"] = NextMessage;

                            string NewLogMessage = String.Format("Step 3 of 4 for message: ({0:X8} -> {1:X8}), {2}, Message Count {3} (Local Connection)",
                                                                 NextMessage.To,
                                                                 NextMessage.From,
                                                                 NextMessage.Type,
                                                                 ConnectionMessageSentTo.MessageQueue.Count);

                            Log(EVerbosityLevel.SuperVerbose,ELogColour.Green,NewLogMessage);
                            ErrorCode = Constants.SUCCESS;
                        }
                        else
                        {
                            // If the semaphore was signaled and the message queue is empty, which
                            // is only true after CloseConnection is called, we're done
                            ErrorCode = Constants.ERROR_CONNECTION_DISCONNECTED;
                        }
                    }
                }
                else
                {
                    // Otherwise, the timeout period has elapsed; this is still considered a
                    // success only without a message to send back
                    Log(EVerbosityLevel.Verbose,ELogColour.Green,String.Format("[GetMessage] Message available timeout expired, safely returning to {0:X8} with no message",ConnectionHandle));
                    ErrorCode = Constants.SUCCESS;
                }
            }
            else
            {
                string LogMessage = String.Format("[GetMessage] Either connection doesn't exist or is not a local connection: {0:X8}",ConnectionHandle);
                Log(EVerbosityLevel.Informative,ELogColour.Red,LogMessage);
                ErrorCode = Constants.ERROR_CONNECTION_NOT_FOUND;
            }

            // Determine if we have a message to send back
            if (NextMessage != null)
            {
                string NewLogMessage = String.Format("Step 4 of 4 for message: ({0:X8} -> {1:X8}), {2}, Delivered (Local Connection)",
                                                     NextMessage.To,
                                                     NextMessage.From,
                                                     NextMessage.Type);
                Log(EVerbosityLevel.SuperVerbose,ELogColour.Green,NewLogMessage);
            }
            else if (Timeout == -1)
            {
                if ((Recipient != null) &&
                    (Recipient.CurrentState == ConnectionState.DISCONNECTED))
                {
                    Log(EVerbosityLevel.Informative,ELogColour.Green,String.Format("[GetMessage] Safely returning to {0:X8} with no message",ConnectionHandle));
                }
                else
                {
                    Log(EVerbosityLevel.Informative,ELogColour.Orange,String.Format("[GetMessage] Returning to {0:X8} with no message, possibly in error",ConnectionHandle));
                }
            }

            StopTiming();
            return(ErrorCode);
        }
Exemple #28
0
        /**
         * Takes messages off the internal message queue and handles them by either
         * sending responses, forwarding the message on, or processing it internally
         */
        private void ProcessMessagesThreadProc()
        {
            // A response message queue used to send messages back to the one which sent it
            Queue <AgentMessage> ResponseMessageQueue = new Queue <AgentMessage>();

            while (AgentHasShutDown == false)
            {
                StartTiming("ProcessMessage-Internal", true);

                lock ( MessageQueueLock )
                {
                    // Swap the SM and PM message queue to keep things moving at full speed
                    Queue <AgentMessage> Temp = MessageQueuePM;
                    MessageQueuePM = MessageQueueSM;
                    MessageQueueSM = Temp;
                }

                // Process all messages currently in the queue
                while (MessageQueuePM.Count > 0)
                {
                    Debug.Assert(ResponseMessageQueue.Count == 0);

                    // Get and process the next message
                    AgentMessage NextMessage = MessageQueuePM.Dequeue();
                    Debug.Assert(NextMessage != null);

                    bool bMessageHandled = false;
                    switch (NextMessage.Type)
                    {
                    case EMessageType.SIGNAL:
                    {
                        if (NextMessage is DisconnectionSignalMessage)
                        {
                            // Mark the connection as inactive
                            DisconnectionSignalMessage DisconnectMessage = NextMessage as DisconnectionSignalMessage;
                            Log(EVerbosityLevel.Informative,ELogColour.Green,String.Format("[CloseConnection] Connection disconnected {0:X8}",DisconnectMessage.ConnectionToDisconnect.Handle));
                            DisconnectMessage.ConnectionToDisconnect.CurrentState     = ConnectionState.DISCONNECTED;
                            DisconnectMessage.ConnectionToDisconnect.DisconnectedTime = DateTime.UtcNow;
                        }

                        // Signal the message and move on
                        AgentSignalMessage SignalMessage = NextMessage as AgentSignalMessage;
                        SignalMessage.ResetEvent.Set();
                        bMessageHandled = true;
                    }
                    break;

                    case EMessageType.TIMING:
                    {
                        Connection FromConnection;
                        if ((Connections.TryGetValue(NextMessage.From,out FromConnection)))
                        {
                            Connection ToConnection;
                            if ((Connections.TryGetValue(NextMessage.To,out ToConnection)) &&
                                (ToConnection is LocalConnection))
                            {
                                // Handle message
                                AgentTimingMessage TimingMessage = NextMessage as AgentTimingMessage;
                                AgentApplication.UpdateMachineState(MachineNameFromConnection(FromConnection),TimingMessage.ThreadNum,TimingMessage.State);
                                bMessageHandled = true;
                            }
                        }
                    }
                    break;

                    case EMessageType.TASK_REQUEST:
                    {
                        // Look up the requesting connection
                        Debug.Assert(NextMessage.From != Constants.INVALID);
                        Connection RequestingConnection;
                        if (Connections.TryGetValue(NextMessage.From,out RequestingConnection))
                        {
                            // Look up the specified Job
                            AgentJob JobToAskForTasks = RequestingConnection.Job;
                            if (JobToAskForTasks != null)
                            {
                                // If we get a valid response back, add it to the queue
                                AgentTaskRequestResponse Response = JobToAskForTasks.GetNextTask(RequestingConnection);
                                if (Response != null)
                                {
                                    ResponseMessageQueue.Enqueue(Response);

                                    // Specifications and releases are always handled here, but
                                    // reservations are special in that we will send a reservation
                                    // back to local connections but we'll need to make sure the
                                    // message continues on to remote connections.
                                    if ((Response.ResponseType == ETaskRequestResponseType.SPECIFICATION) ||
                                        (Response.ResponseType == ETaskRequestResponseType.RELEASE) ||
                                        ((Response.ResponseType == ETaskRequestResponseType.RESERVATION) &&
                                         (JobToAskForTasks.Owner is LocalConnection)))
                                    {
                                        bMessageHandled = true;
                                    }
                                }
                            }
                            else
                            {
                                // Unable to find the Job, just send back a release message
                                Log(EVerbosityLevel.Verbose,ELogColour.Orange,"[ProcessMessage] Unable to find Job for Task Request; may have been closed");
                                //ResponseMessageQueue.Enqueue( new AgentTaskRequestResponse( RequestingConnection.Job.JobGuid,
                                //															ETaskRequestResponseType.RELEASE ) );
                                bMessageHandled = true;
                            }
                        }
                        else
                        {
                            // Unable to find the connection, swallow the request
                            Log(EVerbosityLevel.Verbose,ELogColour.Orange,"[ProcessMessage] Unable to find owning Connection for Task Request");
                            bMessageHandled = true;
                        }
                    }
                    break;

                    case EMessageType.TASK_STATE:
                    {
                        // Look up the sending connection
                        Debug.Assert(NextMessage.From != Constants.INVALID);
                        Connection SendingConnection;
                        if ((Connections.TryGetValue(NextMessage.From,out SendingConnection)) &&
                            (SendingConnection.Job != null))
                        {
                            // Look up the specified Job
                            AgentJob UpdatedJob;
                            if (ActiveJobs.TryGetValue(SendingConnection.Job.JobGuid,out UpdatedJob))
                            {
                                AgentTaskState UpdatedTaskState = NextMessage as AgentTaskState;
                                UpdatedJob.UpdateTaskState(UpdatedTaskState);

                                if (UpdatedJob.Owner is LocalConnection)
                                {
                                    // If the Task state change is of a type potentially interesting to
                                    // the Instigator, return it
                                    switch (UpdatedTaskState.TaskState)
                                    {
                                    case EJobTaskState.TASK_STATE_INVALID:
                                    case EJobTaskState.TASK_STATE_COMPLETE_SUCCESS:
                                    case EJobTaskState.TASK_STATE_COMPLETE_FAILURE:
                                        // For these message types, allow the message to continue on
                                        break;

                                    default:
                                        // Nothing to do otherwise, mark the message as handled
                                        bMessageHandled = true;
                                        break;
                                    }
                                }
                                else
                                {
                                    // Always send messages on for remote connections
                                }
                            }
                            else
                            {
                                // Unable to find the Job, swallow the request
                                Log(EVerbosityLevel.Verbose,ELogColour.Orange,"[ProcessMessage] Unable to find Job for Task Request");
                                bMessageHandled = true;
                            }
                        }
                        else
                        {
                            // Unable to find the connection, swallow the request
                            Log(EVerbosityLevel.Verbose,ELogColour.Orange,"[ProcessMessage] Unable to find owning Connection for Task Request");
                            bMessageHandled = true;
                        }
                    }
                    break;
                    }

                    // If the message was not handled completely, send it on
                    if (bMessageHandled == false)
                    {
                        // Look up who the message is being sent to and make sure they're
                        // still active and if not, ignore the message
                        Connection Recipient;
                        Debug.Assert(NextMessage.To != Constants.INVALID);
                        if (Connections.TryGetValue(NextMessage.To,out Recipient))
                        {
                            if (Recipient is LocalConnection)
                            {
                                // If the recipient is local, place it in the proper queue
                                // and signal that a message is ready
                                LocalConnection LocalRecipient = Recipient as LocalConnection;
                                lock (LocalRecipient.MessageQueue)
                                {
                                    LocalRecipient.MessageQueue.Enqueue(NextMessage);

                                    string NewLogMessage = String.Format("Step 2 of 4 for message: ({0:X8} -> {1:X8}), {2}, Message Count {3} (Local Connection)",
                                                                         NextMessage.To,
                                                                         NextMessage.From,
                                                                         NextMessage.Type,
                                                                         LocalRecipient.MessageQueue.Count);

                                    Log(EVerbosityLevel.SuperVerbose,ELogColour.Green,NewLogMessage);

                                    LocalRecipient.MessageAvailableSignal();
                                }
                            }
                            else
                            {
                                Debug.Assert(Recipient is RemoteConnection);

                                // If the recipient is remote, send the message via SendMessage
                                // unless the message is a Task being sent back, which is sent
                                // via the dedicated Task API
                                RemoteConnection RemoteRecipient = Recipient as RemoteConnection;
                                if (NextMessage is AgentTaskSpecification)
                                {
                                    // All new Tasks are sent via the dedicated Task API
                                    AgentTaskSpecification TaskSpecification = NextMessage as AgentTaskSpecification;

                                    Hashtable RemoteInParameters = new Hashtable();
                                    RemoteInParameters["Version"]       = ESwarmVersionValue.VER_1_0;
                                    RemoteInParameters["Specification"] = TaskSpecification;
                                    Hashtable RemoteOutParameters = null;

                                    Int32 Error = RemoteRecipient.Interface.AddTask(RemoteRecipient.Handle,RemoteInParameters,ref RemoteOutParameters);
                                    if (Error >= 0)
                                    {
                                        // Perhaps we should be sending an accept message back?
                                    }
                                    else
                                    {
                                        AgentTaskState UpdateMessage;
                                        if (Error == Constants.ERROR_CONNECTION_DISCONNECTED)
                                        {
                                            // Special case of the connection dropping while we're adding the
                                            // task, say it's been killed to requeue
                                            UpdateMessage = new AgentTaskState(TaskSpecification.JobGuid,
                                                                               TaskSpecification.TaskGuid,
                                                                               EJobTaskState.TASK_STATE_KILLED);
                                        }
                                        else
                                        {
                                            // All other error cases will be rejections
                                            UpdateMessage = new AgentTaskState(TaskSpecification.JobGuid,
                                                                               TaskSpecification.TaskGuid,
                                                                               EJobTaskState.TASK_STATE_REJECTED);
                                        }
                                        AgentJob Job;
                                        if (ActiveJobs.TryGetValue(TaskSpecification.JobGuid,out Job))
                                        {
                                            Job.UpdateTaskState(UpdateMessage);
                                        }
                                    }
                                }
                                else
                                {
                                    // All standard messages are sent via the SendMessage API
                                    Hashtable RemoteInParameters = new Hashtable();
                                    RemoteInParameters["Version"] = ESwarmVersionValue.VER_1_0;
                                    RemoteInParameters["Message"] = NextMessage;
                                    Hashtable RemoteOutParameters = null;

                                    RemoteRecipient.Interface.SendMessage(NextMessage.To,RemoteInParameters,ref RemoteOutParameters);
                                }

                                string NewLogMessage = String.Format("Step 2 of 2 for message: ({0:X8} -> {1:X8}), {2}, (Remote Connection)",
                                                                     NextMessage.To,
                                                                     NextMessage.From,
                                                                     NextMessage.Type);

                                Log(EVerbosityLevel.SuperVerbose,ELogColour.Green,NewLogMessage);
                            }
                        }
                        else
                        {
                            Log(EVerbosityLevel.Informative,ELogColour.Orange,"ProcessMessage: Message sent to invalid connection, ignoring: " + NextMessage.Type.ToString());
                        }
                    }

                    // If there are any responses to the message, send them
                    if (ResponseMessageQueue.Count > 0)
                    {
                        foreach (AgentMessage NextResponse in ResponseMessageQueue)
                        {
                            // For each one of the messages, set the routing fields properly
                            NextResponse.To   = NextMessage.From;
                            NextResponse.From = NextMessage.To;

                            // And then queue the message back up immediately
                            MessageQueuePM.Enqueue(NextResponse);
                        }
                        ResponseMessageQueue.Clear();
                    }
                }

                StopTiming();

                // Wait for a message to become available and once unlocked, swap the queues
                // and check for messages to process. Set a timeout, so we'll wake up every
                // now and then to check for a quit signal at least
                MessageQueueReady.WaitOne(500);
            }
        }
Exemple #29
0
 /// <summary>
 /// Connects two LocalConnections, ensuring that each of them has the
 /// other one as the endpoint.
 /// </summary>
 /// <param name="first">The first connection to connect</param>
 /// <param name="second">The second connection to connect</param>
 public static void Connect(LocalConnection first, LocalConnection second)
 {
     first.Endpoint = second;
     second.Endpoint = first;
 }
 public LocalGetResourceContents(LocalConnection conn)
 {
     this.Parent = conn;
     var fact = new MgdServiceFactory();
     _resSvc = (MgResourceService)fact.CreateService(MgServiceType.ResourceService);
 }
 public static void remove_asyncError(LocalConnection that, Action <AsyncErrorEvent> value)
 {
     CommonExtensions.RemoveDelegate(that, value, AsyncErrorEvent.ASYNC_ERROR);
 }
 public static void remove_securityError(LocalConnection that, Action <SecurityErrorEvent> value)
 {
     CommonExtensions.RemoveDelegate(that, value, SecurityErrorEvent.SECURITY_ERROR);
 }
 public static void remove_status(LocalConnection that, Action <StatusEvent> value)
 {
     CommonExtensions.RemoveDelegate(that, value, StatusEvent.STATUS);
 }