Ejemplo n.º 1
0
        public Object start(TransferObject to)
        {
            Object resultObject = null;

            String calleeClass  = to.getCalleeClass();
            String calleeMethod = to.getCalleeMethod();

            StateObject stateObject = new StateObject();

            stateObject.transferObject = to;

            try {
                if (Connect(stateObject))
                {
                    Send(stateObject);

                    resultObject = Receive(stateObject);
                }
            } catch (Exception e) {
                Logging.LogError("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]");
                Logging.LogError(e.ToString());
            } finally {
                Close(stateObject);
            }

            return(resultObject);
        }
Ejemplo n.º 2
0
        /**
         * Dispatch request to a appointed socket connection.
         * @param to TransferObject
         * @return Object
         */
        public static object execute(TransferObject to)
        {
            Object retObject = null;

            if (connectionList == null)
            {
                initialize();
            }

            String connectionName = to.getConnectionName();

            foreach (SocketConnection connection in connectionList)
            {
                if (connection.getName().Equals(connectionName))
                {
                    if (to.isAsynchronous())
                    {
                        ExecuteDelegate executeDelegate = delegate(SocketConnection socketConnection, TransferObject transferObject) {
                            return(socketConnection.execute(transferObject));
                        };
                        IAsyncResult asyncResult = executeDelegate.BeginInvoke(connection, to, null, null);
                        Future       future      = new Future(executeDelegate, asyncResult);
                        retObject = future;
                    }
                    else
                    {
                        retObject = connection.execute(to);
                    }
                }
            }

            return(retObject);
        }
Ejemplo n.º 3
0
        public static byte[] transferObjectToByteArray(TransferObject to)
        {
            // out
            byte[] toByteArray = to.getByteData();
            byte[] sendData    = null;
            // if compress flag is true
            if (to.isCompress())
            {
                sendData = TransferUtil.getOutputByCompress(toByteArray);
            }
            else
            {
                sendData = TransferUtil.getOutputByNormal(toByteArray);
            }

            //set long connection flag
            if (to.isLongConnection())
            {
                sendData[0] |= TransferObject.LONGCONNECTION_FLAG;
            }

            //set new version flag
            if (to.isNewVersion())
            {
                sendData[0] |= TransferObject.NEWVERSION_FLAG;
            }

            byte[] newData = new byte[sendData.Length + TatalaFlag.Length];
            Array.Copy(TatalaFlag, 0, newData, 0, TatalaFlag.Length);
            Array.Copy(sendData, 0, newData, TatalaFlag.Length, sendData.Length);
            sendData = newData;

            return(sendData);
        }
Ejemplo n.º 4
0
        public static void NonblockingProcess <T>(T[] list, Action <T> actionHandler, int threadCount, Action <List <ParallelProcessError> > callback = null)
        {
            if (actionHandler == null)
            {
                throw new ArgumentNullException("funcHandler");
            }
            if (threadCount <= 0)
            {
                throw new ArgumentException("Error with the threadcount '" + threadCount + "'. The thread count must be larger than 0.", "threadCount");
            }
            if (list == null || list.Length <= 0)
            {
                if (callback != null)
                {
                    callback(new List <ParallelProcessError>(0));
                }
                return;
            }
            TransferObject <T> obj = new TransferObject <T>()
            {
                Context          = ContextManager.Current,
                ActionHandler    = actionHandler,
                Queue            = CreateQueue(list),
                ExceptionArray   = new Exception[list.Length],
                AliveThreadCount = threadCount,
                Blocking         = false,
                Callback         = callback
            };

            for (int i = 0; i < threadCount; i++)
            {
                Task.Factory.StartNew(c => ProcessTask <T>((TransferObject <T>)c), obj);
            }
        }
Ejemplo n.º 5
0
        public static TransferObject byteArrayToTransferObject(byte[] byteArray)
        {
            //TransferObject to = new TransferObject();
            int receiveLength = byteArray.Length;

            byte[] toByteArray = new byte[receiveLength - 1];
            Array.Copy(byteArray, 1, toByteArray, 0, receiveLength - 1);
            byte flagbyte = byteArray[0];

            TransferObject to = null;

            //check if new version of transfer object
            if (TransferUtil.isNewVersion(flagbyte))
            {
                to = new NewTransferObject();
            }
            else
            {
                to = new StandardTransferObject();
            }

            if (TransferUtil.isCompress(flagbyte))
            {
                toByteArray = TransferUtil.getInputByCompress(toByteArray);
            }
            else
            {
                toByteArray = TransferUtil.getInputByNormal(toByteArray);
            }
            to.setByteData(toByteArray);

            return(to);
        }
Ejemplo n.º 6
0
        public Object execute(TransferObject to)
        {
            Object resultObject = null;

            resultObject = SocketController.execute(to);

            return(resultObject);
        }
Ejemplo n.º 7
0
        private void Send(StateObject stateObject)
        {
            TransferObject to     = stateObject.transferObject;
            Socket         client = stateObject.workSocket;

            byte[] sendData = TransferUtil.transferObjectToByteArray(to);

            client.Send(sendData);
        }
Ejemplo n.º 8
0
        public async Task <ActionResult <ValidationResult> > PostStockTax(StockTaxObject stockTaxObject)
        {
            try
            {
                // Call Bank service
                var tax = stockTaxObject.Price * stockTaxObject.Amount * _taxInfo.TaxRate;

                var url            = _services.BankService.BaseAddress + "api/transfer";
                var stateAccount   = Guid.Parse("7bedb953-4e7e-45f9-91de-ffc0175be744");
                var transferObject = new TransferObject {
                    Amount = tax, FromAccountId = stockTaxObject.Buyer, ReservationId = stockTaxObject.ReservationId, ToAccountId = stateAccount
                };

                var validationResult = await Policy.Handle <FlurlHttpException>()
                                       .WaitAndRetryAsync(new[]
                {
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(3)
                }).ExecuteAsync(() => url.WithTimeout(10).PutJsonAsync(transferObject).ReceiveJson <ValidationResult>());

                if (!validationResult.Valid)
                {
                    _logger.LogWarning("Failed to Tax Trade, with error {ErrorMessage}", validationResult.ErrorMessage);
                }

                // Store in own database
                var taxHistory = new TaxHistory
                {
                    Amount  = stockTaxObject.Amount,
                    Buyer   = stockTaxObject.Buyer,
                    Price   = stockTaxObject.Price,
                    Seller  = stockTaxObject.Seller,
                    StockId = stockTaxObject.StockId,
                    TaxRate = _taxInfo.TaxRate,
                    Tax     = tax
                };
                TaxPaid.Inc(tax);
                await _context.TaxHistories.AddAsync(taxHistory);

                await _context.SaveChangesAsync();

                _rabbitMqClient.SendMessage(new HistoryMessage {
                    Event = "PaidTax", EventMessage = $"Paid ${tax} tax for buying shares", User = stockTaxObject.Buyer, Timestamp = DateTime.UtcNow
                });

                _logger.LogInformation("Exacted {Tax} in taxes from from {User}", tax, stockTaxObject.Buyer);
                _logger.LogInformation("Logged TaxInfo to database {TaxHistory}", taxHistory);
                return(validationResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Failed to do stuff");
                Console.WriteLine(e);
                throw;
            }
        }
Ejemplo n.º 9
0
        public static Object execute(TransferObject to)
        {
            Object retObj = null;

            //for csharp client, server target is Socket.
            target = new SocketServerTarget();
            retObj = target.execute(to);
            return(retObj);
        }
Ejemplo n.º 10
0
        public async Task SendHandshakeInfo(TransferObject transfferObject)
        {
            var user = _users.FirstOrDefault(x => x.Value.UserName == transfferObject.Receiver);

            if (user.Value != null)
            {
                string connectionId = user.Key;

                await Clients.Client(connectionId).ReceiveSendHandshakeInfo(transfferObject);
            }
        }
Ejemplo n.º 11
0
        private async Task MakeTransferHelper(Guid senderId, Guid receiverId, Guid reservationId)
        {
            var transferObject = new TransferObject()
            {
                FromAccountId = senderId, ToAccountId = receiverId, Amount = 5.00, ReservationId = reservationId
            };
            var transferContent = new StringContent(JsonConvert.SerializeObject(transferObject), Encoding.UTF8, "application/json");
            var httpResponse    = await _client.PutAsync("/api/transfer", transferContent);

            httpResponse.EnsureSuccessStatusCode();
        }
Ejemplo n.º 12
0
        public static TransferObject Start(ActivityBuilder activityBuilder)
        {
            TransferObject = new TransferObject();
            var rootActivity = activityBuilder.Implementation;

            _logger.Trace("Converting root activity to traversal object.");
            var traversalObject = FromGenericWWFObject.ToBaseTraversalObject(rootActivity);

            TraverseActivities(traversalObject, 0);

            return(TransferObject);
        }
Ejemplo n.º 13
0
        public async Task <ActionResult <ValidationResult> > PutTransfer(TransferObject transferObject)
        {
            try
            {
                var fromAccount = await _context.Accounts.FirstOrDefaultAsync(x => x.OwnerId == transferObject.FromAccountId);

                if (fromAccount == null)
                {
                    _logger.LogWarning($"FromAccountId {transferObject.FromAccountId} does not exist");
                    return(new ValidationResult {
                        Valid = false, ErrorMessage = $"FromAccountId {transferObject.FromAccountId} does not exist"
                    });
                }
                var toAccount = await _context.Accounts.FirstOrDefaultAsync(x => x.OwnerId == transferObject.ToAccountId);

                if (toAccount == null)
                {
                    _logger.LogWarning($"ToAccountId {transferObject.ToAccountId} does not exist");
                    return(new ValidationResult {
                        Valid = false, ErrorMessage = $"ToAccountId {transferObject.ToAccountId} does not exist"
                    });
                }
                var reservation = await _context.Reservations.FirstOrDefaultAsync(r => r.OwnerAccount == fromAccount && r.Id == transferObject.ReservationId);

                if (reservation == null)
                {
                    _logger.LogWarning($"Reservation {transferObject.ReservationId} does not exist");
                    return(new ValidationResult {
                        Valid = false, ErrorMessage = $"Reservation {transferObject.ReservationId} does not exist"
                    });
                }

                reservation.Amount -= transferObject.Amount;
                toAccount.Balance  += transferObject.Amount;
                _context.Transfers.Add(new Transfer {
                    Amount = transferObject.Amount, From = fromAccount, To = toAccount
                });
                TotalTransfers.Inc();
                TotalMoneyTransferred.Inc(transferObject.Amount);
                await _context.SaveChangesAsync();

                _logger.LogInformation("Successfully transferred {Amount} from {@Sender} to {@Receiver}", transferObject.Amount, fromAccount, toAccount);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Failed to transfer");
                throw;
            }

            return(new ValidationResult {
                Valid = true, ErrorMessage = ""
            });
        }
Ejemplo n.º 14
0
        private void Send(StateObject stateObject)
        {
            TransferObject to     = stateObject.transferObject;
            Socket         socket = stateObject.workSocket;

            byte[] sendData = TransferUtil.transferObjectToByteArray(to);

            //socket.Send(sendData);

            // Begin sending the data to the remote device.
            socket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
        }
Ejemplo n.º 15
0
        public override Object execute(TransferObject baseto)
        {
            StandardTransferObject to = (StandardTransferObject)baseto;
            String calleeMethod       = to.getCalleeMethod();

            if (calleeMethod.Equals("receiveMessage"))
            {
                String message = to.getString("message");
                ChatRoomClient.getInstance().receiveMessage(message);
            }

            return(null);
        }
Ejemplo n.º 16
0
        public void Read(string filename, List <ITransferObject> transferObjects)
        {
            if (!FileSystem.FileExists(filename))
            {
                return;
            }
            string json = FileSystem.ReadAllText(filename);
            OpenApiStringReader reader   = new OpenApiStringReader();
            OpenApiDocument     document = reader.Read(json, out OpenApiDiagnostic diagnostic);

            diagnostic.Errors?.ForEach(error => Logger.Error(error.Message));
            transferObjects.Add(TransferObject.Create(document));
        }
Ejemplo n.º 17
0
        private static void ConnectCallback(IAsyncResult ar)
        {
            var client = ar.AsyncState as Socket;

            client.EndConnect(ar);
            //string mess = "Hello Everyone!";

            TransferObject data = new TransferObject();

            data.Buffer = new byte[TransferObject.size];
            data.socket = client;

            client.BeginSend(Encoding.UTF8.GetBytes(messagenumber), 0, messagenumber.Length, SocketFlags.None, SendCallback, data);
        }
Ejemplo n.º 18
0
        public ActionResult AddTransfer([FromBody] JsonElement json)
        {
            string          authHeader = this.HttpContext.Request.Headers["Authorization"];
            TokenModel      tokenModel = new TokenModel();
            ClaimsPrincipal auth       = tokenModel.GetPrincipal(authHeader);

            if (auth.Identity.IsAuthenticated)
            {
                new ClickTracker("AddTransfer", false, true, json.GetRawText(), auth.Identity.Name);
                TransferObject obj            = JsonConvert.DeserializeObject <TransferObject>(json.GetRawText());
                ManualCashFlow manualCashFlow = new ManualCashFlow();
                return(Ok(manualCashFlow.AddTransfer(obj)));
            }
            return(Ok(""));
        }
        private static void ConnectCallback(IAsyncResult ar)
        {
            var client = ar.AsyncState as Socket;

            client.EndConnect(ar);

            TransferObject data = new TransferObject();

            data.Buffer = new byte[TransferObject.size];
            data.socket = client;

            var message = toserver;

            client.BeginSend(Encoding.UTF8.GetBytes(message), 0, message.Length, SocketFlags.None, SendCallback, data);
        }
Ejemplo n.º 20
0
        public static Object byteArrayToReturnObject(byte[] byteArray)
        {
            byte[] toByteArray = new byte[byteArray.Length - 1];
            Array.Copy(byteArray, 1, toByteArray, 0, byteArray.Length - 1);

            if (TransferUtil.isCompress(byteArray[0]))
            {
                toByteArray = TransferUtil.getInputByCompress(toByteArray);
            }
            else
            {
                toByteArray = TransferUtil.getInputByNormal(toByteArray);
            }

            return(TransferObject.convertReturnByteArray(toByteArray));
        }
Ejemplo n.º 21
0
        public Employee Login(Employee employee)
        {
            try
            {
                var transfer = new TransferObject
                {
                    TransferObj = employee,
                    Operation   = Operation.Login
                };
                _formatter.Serialize(_networkStream, transfer);

                transfer = _formatter.Deserialize(_networkStream) as TransferObject;
                var error = false;
                try
                {
                    var result = (int)transfer.TransferObj;
                    if (result == -1)
                    {
                        MessageBox.Show("User is already logged in!");
                        error = true;
                    }
                }
                catch
                {
                }
                var emp = transfer?.TransferObj as Employee;
                if (emp != null)
                {
                    MessageBox.Show("Login successfull.");
                }
                else
                {
                    if (!error)
                    {
                        MessageBox.Show("Wrong username or password", "Error!");
                    }
                }
                return(emp);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error establishing connection!");
                throw;
            }
        }
Ejemplo n.º 22
0
        public Object execute(TransferObject to)
        {
            String calleeClass  = to.getCalleeClass();
            String calleeMethod = to.getCalleeMethod();

            Object retobj = null;

            try {
                Type       type     = Type.GetType(calleeClass);
                Object     instance = Activator.CreateInstance(type);
                MethodInfo method   = type.GetMethod(calleeMethod);
                retobj = method.Invoke(instance, new object[] { to });
            } catch (Exception e) {
                Logging.LogError(e.ToString());
            }

            return(retobj);
        }
Ejemplo n.º 23
0
        internal List <AutoType> GetAllAutoTypes()
        {
            try
            {
                var transfer = new TransferObject {
                    Operation = Operation.GetAutoTypes
                };
                _formatter.Serialize(_networkStream, transfer);

                transfer = _formatter.Deserialize(_networkStream) as TransferObject;
                return(transfer?.TransferObj as List <AutoType>);
            }
            catch (Exception)
            {
                MessageBox.Show("Error establishing connection!");
                throw;
            }
        }
Ejemplo n.º 24
0
        public override Object execute(TransferObject baseto)
        {
            NewTransferObject to           = (NewTransferObject)baseto;
            string            calleeMethod = to.getCalleeMethod();

            if (calleeMethod.Equals("receiveMessage"))
            {
                int    playerId = to.getInt();
                string message  = to.getString();
                NetworkManager.Instance.ReceiveMessage(playerId, message);
            }
            else if (calleeMethod.Equals("addPlayer"))
            {
                int     playerId            = to.getInt();
                string  playerName          = to.getString();
                int     playerLevel         = to.getInt();
                int     equipedWeaponTypeId = to.getInt();
                float[] position            = to.getFloatArray();
                NetworkManager.Instance.AddPlayer(playerId, playerName, playerLevel, equipedWeaponTypeId, position);
            }
            else if (calleeMethod.Equals("receiveMovement"))
            {
                int     playerId = to.getInt();
                float[] target   = to.getFloatArray();
                NetworkManager.Instance.ReceiveMovement(playerId, target);
            }
            else if (calleeMethod.Equals("receivePlayerInfos"))
            {
                to.getInt(); //ignore userId
                int[]    playerIds            = to.getIntArray();
                string[] playerNames          = to.getStringArray();
                int[]    playerLevels         = to.getIntArray();
                int[]    equipedWeaponTypeIds = to.getIntArray();
                float[]  playerPositions      = to.getFloatArray();
                NetworkManager.Instance.ReceivePlayerInfos(playerIds, playerNames, playerLevels, equipedWeaponTypeIds, playerPositions);
            }
            else if (calleeMethod.Equals("removePlayer"))
            {
                int playerId = to.getInt();
                NetworkManager.Instance.RemovePlayer(playerId);
            }

            return(null);
        }
Ejemplo n.º 25
0
        private void ReadFromUrl(CookieConfiguration configuration, List <ITransferObject> list)
        {
            Logger.Trace($"Read cookies from {configuration.Url}");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(configuration.Url);

            request.CookieContainer = new CookieContainer();
            request.Credentials     = CredentialCache.DefaultCredentials;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Logger.Trace($"{response.Cookies.Count} cookies found");
                foreach (Cookie cookie in response.Cookies)
                {
                    if (cookie.Name == configuration.Name)
                    {
                        list.Add(TransferObject.Create(cookie));
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public static ParallelProcessResult <R> Process <T, R>(T[] list, Func <T, R> funcHandler, int threadCount)
        {
            if (funcHandler == null)
            {
                throw new ArgumentNullException("funcHandler");
            }
            if (threadCount <= 0)
            {
                throw new ArgumentException("Error with the threadcount '" + threadCount + "'. The thread count must be larger than 0.", "threadCount");
            }
            if (list == null)
            {
                return(null);
            }
            if (list.Length <= 0)
            {
                return(new ParallelProcessResult <R>(new R[0], new List <ParallelProcessError>(0)));
            }
            TransferObject <T, R> obj = new TransferObject <T, R>()
            {
                Context          = ContextManager.Current,
                FuncHandler      = funcHandler,
                Queue            = CreateQueue(list),
                ResultList       = new R[list.Length],
                ExceptionArray   = new Exception[list.Length],
                AliveThreadCount = threadCount,
                Blocking         = true,
                Callback         = null
            };

            Task[] tasks = new Task[threadCount - 1];
            for (int i = 0; i < threadCount - 1; i++)
            {
                tasks[i] = Task.Factory.StartNew(c => ProcessTask <T, R>((TransferObject <T, R>)c), obj);
            }
            ProcessTask <T, R>(obj);
            if (tasks.Length > 0)
            {
                Task.WaitAll(tasks);
            }
            return(new ParallelProcessResult <R>(obj.ResultList, BuildErrorInfoList(obj.ExceptionArray)));
        }
Ejemplo n.º 27
0
        public List <Invoice> FindInvoices(string criteria)
        {
            try
            {
                var transfer = new TransferObject
                {
                    TransferObj = criteria,
                    Operation   = Operation.FindInvoice
                };
                _formatter.Serialize(_networkStream, transfer);

                transfer = _formatter.Deserialize(_networkStream) as TransferObject;
                return(transfer?.TransferObj as List <Invoice>);
            }
            catch (Exception)
            {
                MessageBox.Show("Error establishing connection!");
                throw;
            }
        }
Ejemplo n.º 28
0
        private void execute(TransferObject to)
        {
            String calleeClassName = to.getCalleeClass();

            //Check default proxy, don't need reflection.
            if (calleeClassName.Equals(TransferObject.DEFAULT_PROXY))
            {
                if (serverCallProxy != null)
                {
                    serverCallProxy.execute(to);
                }
            }
            else
            {
                String     calleeMethod = to.getCalleeMethod();
                Type       type         = Type.GetType(calleeClassName);
                Object     instance     = Activator.CreateInstance(type);
                MethodInfo method       = type.GetMethod(calleeMethod);
                method.Invoke(instance, new object[] { to });
            }
        }
Ejemplo n.º 29
0
        public bool Logout(Employee employee)
        {
            try
            {
                var transfer = new TransferObject
                {
                    TransferObj = employee,
                    Operation   = Operation.Logout
                };
                _formatter.Serialize(_networkStream, transfer);

                transfer = _formatter.Deserialize(_networkStream) as TransferObject;
                var result = (bool)transfer?.TransferObj;
                return(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error establishing connection!");
                throw;
            }
        }
Ejemplo n.º 30
0
        public void Read(string url)
        {
            HttpWebRequest request = WebRequest.CreateHttp(url);

            request.CookieContainer = new CookieContainer();
            transferObjects.OfType <TransferObject <Cookie> >().ForEach(x => request.CookieContainer.Add(x.Value));
            WebResponse response = request.GetResponse();

            string json;

            using (Stream responseStream = response.GetResponseStream())
                using (StreamReader streamReader = new StreamReader(responseStream))
                {
                    json = streamReader.ReadToEnd();
                }
            OpenApiStringReader reader   = new OpenApiStringReader();
            OpenApiDocument     document = reader.Read(json, out OpenApiDiagnostic diagnostic);

            diagnostic.Errors?.ForEach(error => Logger.Error(error.Message));

            transferObjects.Add(TransferObject.Create(document));
        }