Exemple #1
0
 public TicketsInfo SessionStart(TicketsInfo ticketsInfo)
 {
     try
     {
         using (var authentication = new SendReceive(new TcpClient(_host, _port)))
         {
             try
             {
                 authentication.SendData(ticketsInfo);
             }
             catch (Exception ex)
             {
                 authentication?.Dispose();
             }
             ticketsInfo = (TicketsInfo)authentication.ReceiveData();
         }
     }
     catch (SocketException ex)
     {
     }
     finally
     {
     }
     return(ticketsInfo);
 }
Exemple #2
0
        public string SessionStart(MessageData messageData)
        {
            string answer = "";

            try
            {
                using (var authentication = new SendReceive(new TcpClient(_host, _port)))
                {
                    try
                    {
                        authentication.SendData(messageData);
                    }
                    catch (Exception ex)
                    {
                        authentication?.Dispose();
                    }
                    answer = authentication.ReceiveData().ToString();
                }
            }
            catch (SocketException ex)
            {
            }
            finally
            {
            }
            return(answer);
        }
Exemple #3
0
 public DepartmentsData SessionStart(DepartmentsData departmentsData)
 {
     try
     {
         using (var authentication = new SendReceive(new TcpClient(_host, _port)))
         {
             try
             {
                 authentication.SendData(departmentsData);
             }
             catch (Exception ex)
             {
                 authentication?.Dispose();
             }
             departmentsData = (DepartmentsData)authentication.ReceiveData();
         }
     }
     catch (SocketException ex)
     {
     }
     finally
     {
     }
     return(departmentsData);
 }
Exemple #4
0
 public Authentication SessionStart(Authentication authenticationData)
 {
     try
     {
         using (var authentication = new SendReceive(new TcpClient(_host, _port)))
         {
             try
             {
                 authentication.SendData(authenticationData);
             }
             catch (Exception ex)
             {
                 authentication?.Dispose();
             }
             authenticationData = (Authentication)authentication.ReceiveData();
         }
     }
     catch (SocketException ex)
     {
     }
     finally
     {
     }
     return(authenticationData);
 }
Exemple #5
0
        private SMSLineNumber[] GetLines(string userName, string password)
        {
            var message     = string.Empty;
            var sendReceive = new SendReceive();
            var result      = sendReceive.GetSMSLines(userName, password, ref message);

            if (!string.IsNullOrWhiteSpace(message))
            {
                throw new Exception(message);
            }
            return(result);
        }
Exemple #6
0
        public void Send_Receive_Thread(object o)
        {
            SendReceive m_sr = (SendReceive)o;

            if (BACKGROUND_CONNECT)
            {
                if (!sr.Connect(Globs.marantz_host))
                {
                    string err = sr.Errors;
                    return;
                }
            }
            m_sr.Init_Sender();
            m_sr.Run_Receiver();
        }
Exemple #7
0
        public async Task Sender_Without_a_Server_returns_Endpoint_not_found_Exception(object configuration)
        {
            // Arrange
            var config = (SocketConfiguration)configuration;

            config.TimeOut = TimeSpan.FromMilliseconds(50);
            using var sut  = new SendReceive(config);
            // no server this time around

            // Act
            var xtResult = await sut.SendAsync <Message>(new Message());

            // Assert
            Assert.False(xtResult.IsSuccess);
        }
Exemple #8
0
        public async Task Sends_With_Server_TimeOut_return_no_success(object configuration)
        {
            // Arrange
            var config = (SocketConfiguration)configuration;

            config.TimeOut = TimeSpan.FromSeconds(1);
            using var sut  = new SendReceive(config);
            // is a timeout
            sut.SetupReceiver <Message>(m => Thread.Sleep(1500));

            // Act
            var xtResult = await sut.SendAsync(new Message());

            // Assert
            Assert.False(xtResult.IsSuccess);
        }
Exemple #9
0
        public async Task SendReceive_works()
        {
            // Arrange
            var config = new ConfigurationTestData().GetSocketConfigInProc;

            using var sut = new SendReceive(config);
            int result = -1;

            sut.SetupReceiver <Message>(m => result = m.Number);

            // Act
            await sut.SendAsync(new Message { Number = 42 });

            // Assert
            Assert.Equal(42, result);
        }
Exemple #10
0
        public void DoLowerJob(Socket sock)
        {
            Comm.ReceiveInput(ref NetC);
            lock (LockObj) NetC.IsDoneLoadingInput = true;

            bool hasResultTo = true;

            while (NetC.HasSeedFrom || hasResultTo)
            {
                bool ynSeed = UnitSeed - Comm.GetCount(NetC.SiBef) > 0;
                SendReceive.SendPrimitive(sock, ynSeed);

                if (ynSeed)
                {
                    bool ynSeed2 = SendReceive.ReceivePrimitive <bool>(sock);

                    if (ynSeed2)
                    {
                        SeedIndex     siTemp   = default(SeedIndex);
                        SeedContainer sConTemp = default(SeedContainer);
                        Comm.ReceiveSeed(ref siTemp, ref sConTemp);
                        lock (LockObj) Comm.PutSeed(siTemp, sConTemp, ref NetC);
                    }
                }

                bool ynResult = Comm.GetCount(NetC.SiAft) > UnitSeed ||
                                (!NetC.HasSeedFrom && Comm.GetCount(NetC.SiAft) > 0);
                SendReceive.SendPrimitive(sock, ynResult);

                if (ynResult)
                {
                    SeedIndex       siTemp   = default(SeedIndex);
                    ResultContainer rConTemp = default(ResultContainer);
                    lock (LockObj) Comm.PullResult(ref NetC, ref siTemp, ref rConTemp);
                    ResultContainer rConMerged = default(ResultContainer);
                    Comm.MergeResult(rConTemp, ref rConMerged);
                    Comm.SendResult(siTemp, rConMerged);
                }

                lock (LockObj) NetC.HasSeedFrom = SendReceive.ReceivePrimitive <bool>(sock);
                hasResultTo = Comm.GetCount(NetC.SiBef) > 0 ||
                              Comm.GetCount(NetC.SiAllo) > 0 ||
                              Comm.GetCount(NetC.SiAft) > 0;
                SendReceive.SendPrimitive(sock, hasResultTo);
            }
        }
Exemple #11
0
        public async Task Exception_propagation_when_server_response_Throws_to_Requester()
        {
            var ipc = new ConfigurationTestData().GetSocketConfigInProc;

            using var sut = new SendReceive(ipc);
            sut.SetupReceiver <Message>(r =>
            {
                throw new ArgumentException("this is a unit test proving the exception propagation works");
            });

            // Act
            var result = await sut.SendAsync <Message>(new Message());

            // Assert
            Assert.False(result.IsSuccess);
            Assert.NotNull(result.Exception);
            Assert.Contains("ArgumentException", result.Exception.Message);
            Assert.StartsWith("Server failed with" + Environment.NewLine + "ArgumentException", result.Exception.Message);
        }
Exemple #12
0
        public void DoUpperJob(Socket sock)
        {
            while (!NetC.IsDoneLoadingInput)
            {
            }
            Comm.SendInput(NetC);

            bool hasSeedTo     = true;
            bool hasResultFrom = true;

            while (hasSeedTo || hasResultFrom)
            {
                bool ynSeed = SendReceive.ReceivePrimitive <bool>(sock);
                if (ynSeed)
                {
                    SeedIndex     siTemp   = default(SeedIndex);
                    SeedContainer sConTemp = default(SeedContainer);
                    lock (LockObj) Comm.PullSeed(ref NetC, ref siTemp, ref sConTemp);

                    bool ynSeed2 = Comm.GetCount(siTemp) > 0;
                    SendReceive.SendPrimitive(sock, ynSeed2);
                    if (ynSeed2)
                    {
                        Comm.SendSeed(ref siTemp, ref sConTemp);
                    }
                }

                bool ynResult = SendReceive.ReceivePrimitive <bool>(sock);
                if (ynResult)
                {
                    SeedIndex       siTemp   = default(SeedIndex);
                    ResultContainer rConTemp = default(ResultContainer);
                    Comm.ReceiveResult(ref siTemp, ref rConTemp);
                    lock (LockObj) Comm.PutResult(siTemp, rConTemp, ref NetC);
                }

                hasSeedTo = (NetC.HasSeedFrom || Comm.GetCount(NetC.SiBef) > 0);
                SendReceive.SendPrimitive(sock, hasSeedTo);
                hasResultFrom = SendReceive.ReceivePrimitive <bool>(sock);
            }
        }
Exemple #13
0
        public long[] SendSms(long[] phoneNos, string[] message, ref string response)
        {
            MessageValidation(phoneNos, message);

            long[] result;
            int    smsLineId     = 0;
            var    messagesCount = message.Count();
            var    numbersCount  = phoneNos.Count();

            var details = new List <WebServiceSmsSend>();

            for (int i = 0; i < numbersCount; i++)
            {
                details.Add(new WebServiceSmsSend
                {
                    IsFlash     = false,
                    MessageBody = messagesCount > 1 ? message[i] : message[0],
                    MobileNo    = phoneNos[i]
                });
            }
            var userName = AppSettings.SmsUserName;
            var password = AppSettings.SmsPassword;
            var smsLines = GetLines(userName, password);

            if (smsLines != null && smsLines.Count() > 0)
            {
                smsLineId = smsLines[0].ID;
            }
            else
            {
                throw new Exception("هیچ خطی برای ارسال پیام یافت نشد.");
            }
            var sendReceive = new SendReceive();

            result = sendReceive.SendMessage(userName, password, details.ToArray(), smsLineId, DateTime.Now, ref response);
            if (!string.IsNullOrWhiteSpace(response))
            {
                throw new Exception(response);
            }
            return(result);
        }
Exemple #14
0
        public async Task AsyncSendAndReceive()
        {
            // Arrange
            var ipc = new ConfigurationTestData().GetSocketConfigInProc;

            using var sut = new SendReceive(ipc);
            var result = -1;

            sut.SetupReceiverAsync <Message>(r =>
            {
                result = r.Number;
                return(Task.CompletedTask);
            });

            // Act
            var xtResult = await sut.SendAsync(new Message { Number = 2 });

            // Assert
            Assert.True(xtResult.IsSuccess);
            Assert.Equal(2, result);
        }
        public void ExecuteExternalDllFunction()
        {
            int dll = 0;

            try
            {
                dll = LoadLibrary(@"somemodule.dll");
                IntPtr address = GetProcAddress(dll, "SendReceive");

                uint   deviceIndex = 0;
                Buffer pReq        = new Buffer()
                {
                    length = 0, pData = new StringBuilder()
                };
                Buffer pResp = new Buffer()
                {
                    length = 0, pData = new StringBuilder()
                };
                uint pReceivedLen = 0;
                uint pStatus      = 0;

                if (address != IntPtr.Zero)
                {
                    SendReceive sendReceive = (SendReceive)Marshal.GetDelegateForFunctionPointer(address, typeof(SendReceive));

                    IntPtr ret = sendReceive(deviceIndex, ref pReq, ref pResp, pReceivedLen, pStatus);
                }
            }
            catch (Exception Ex)
            {
                //handle exception...
            }
            finally
            {
                if (dll > 0)
                {
                    FreeLibrary(dll);
                }
            }
        }
Exemple #16
0
        public void incommingData(TcpClient tcpClient, string str)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                try
                {
                    if (str != "")
                    {
                        var splitmessage = str.Split('@');

                        var cmd  = splitmessage[0];
                        var data = splitmessage[1];

                        switch (cmd)
                        {
                        case "judge":
                            lock (currentCompetition.judges)
                            {
                                var judge = SendReceive.deserializer <Judge>(data);
                                var j     = currentCompetition.judges.First(x => x.id == judge.id);
                                if (j.occupied)
                                {
                                    Server.sendData("occupied", currentCompetition.judges, tcpClient);
                                    logger.Error("Judge occupied and denied by server");
                                }
                                else
                                {
                                    j.occupied = true;
                                    clientsHashtable.Add(tcpClient, j.judgeSeat);
                                    Server.sendData("ok", j.id.ToString(), tcpClient);
                                    logger.Info("Judge selection ok " + j.name);
                                    if (currentCompetition.judges.All(x => x.occupied))
                                    {
                                        if (currentCompetition.currentJump.scores.All(x => x.points == -1))
                                        {
                                            Server.sendDataToAll("jump", currentCompetition.currentJump);
                                        }
                                        else
                                        {
                                            Server.sendData("jump", currentCompetition.currentJump, tcpClient);
                                        }
                                    }
                                }
                            }
                            break;

                        case "score":
                            lock (currentCompetition)
                            {
                                var score = SendReceive.deserializer <Score>(data);
                                currentCompetition.currentJump.scores[score.judgeSeat].points    = score.points;
                                currentCompetition.currentJump.scores[score.judgeSeat].judgeSeat = score.judgeSeat;
                                currentCompetition.currentJump.scores[score.judgeSeat].judgeId   = score.judgeId;
                                logger.Info("Judge id: " + score.judgeId + " On seat: " + score.judgeSeat +
                                            " Sent score: " + score.points);

                                if (currentCompetition.currentJump.scores.TrueForAll(x => x.points != -1))
                                {
                                    currentCompetition.currentJump.calculateJumpScore();
                                    currentCompetition.currentContestant.calculateTotalScore();

                                    if (_autoGotoNext)
                                    {
                                        gotoNextJump(currentCompetition);
                                        logger.Info("Auto Going to next jump");
                                    }
                                }
                            }
                            break;
                        }
                    }
                    else
                    {
                        Server.removeClient(tcpClient);
                    }
                }
                catch (Exception e)
                {
                    logger.Error("Error in function IncomingData: " + e.Message);
                    logger.Info(str);
                }
            });
        }
Exemple #17
0
        private static void GetConnection(SendReceive sendReceive)
        {
            try
            {
                var    receiveData = sendReceive.ReceiveData();
                string className   = receiveData.GetType().Name;
                switch (className)
                {
                case "Authentication":    //авторизация
                {
                    var authenticationData = (Authentication)receiveData;
                    var result             = IsTrueData(authenticationData);
                    sendReceive.SendData(result);
                }
                break;

                case "TicketsInfo":
                {
                    var tickets = (TicketsInfo)receiveData;
                    foreach (var item in GetData.GetTickets())
                    {
                        List <string> nameCitizen = new List <string>();
                        foreach (var citizen in item.Citizens)
                        {
                            nameCitizen.Add(citizen.Family);
                        }
                        TicketInfo ticket = new TicketInfo
                        {
                            Id            = item.Id,
                            Criterion     = item.Criterion,
                            DepartmentId  = item.DepartmentId.GetValueOrDefault(),
                            Status        = item.Status,
                            Message       = item.Message,
                            Type          = item.Type,
                            CreatDateTime = item.CreatDateTime,
                            CloseDateTime = item.CloseDateTime.GetValueOrDefault(),
                            Citizens      = nameCitizen
                        };
                        tickets.Tickets.Add(ticket);
                    }
                    sendReceive.SendData(tickets);
                }
                break;

                case "DepartmentsData":
                {
                    var departments = (DepartmentsData)receiveData;
                    foreach (var item in GetData.GetDepartments())
                    {
                        DepartmentData departmentData = new DepartmentData
                        {
                            Id   = item.Id,
                            Name = item.Name
                        };
                        departments.departmentsData.Add(departmentData);
                    }
                    sendReceive.SendData(departments);
                }
                break;

                case "MessageData":
                {
                    var message = (MessageData)receiveData;
                    SendingData.SendTicket(message.Message, message.Criterion, 0, message.Type, message.DepartmentId, message.IdCitizen);
                    sendReceive.SendData("Готово");
                }
                break;

                default:
                {
                }
                break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Чтото не так");
            }
            finally
            {
                sendReceive.Dispose();
            }
        }
Exemple #18
0
        private void Form1_Load(object sender, EventArgs e)
        {
            if (Globs.NO_SEND)
            {
                this.chkSEND.Checked = false;
            }
            else
            {
                this.chkSEND.Checked = true;
            }
            if (System.IO.File.Exists(Globs.json_file3))
            {
                Load_Tree(Globs.json_file3);
            }
            else if (System.IO.File.Exists(Globs.json_file2))
            {
                Load_Tree(Globs.json_file2);
            }
            else
            {
                Load_Tree(Globs.json_file);
            }

            ShowSliderLevelLegend(this.txtScrollLegend);

            this.d    = new Dispatcher(); // Dispatcher handles events
            this.d.ui = this;

            this.d.MessageSender       += AddToSendList;
            this.d.MessageReceiver     += AddToReceiveList;
            this.d.SendRefresher       += RefreshSendList;
            this.d.SendClearer         += ClearSendList;
            this.d.ConnectNotifier     += Connected;
            this.d.SliderSetter        += SetSliderLevel;
            this.d.ResizeHandler       += SetSliderLevel;
            this.d.ParameterShower     += ShowParameterValues;
            this.d.ReceiveProcessor    += ProcessReceivedMessage;
            this.d.MarantzLevelUpdater += UpdateMarantzLevels;
            this.d.ThumbResizer        += ResizeAllThumbs;

            this.c = new Controller(this.d);

            this.d.queue = this.c;

            this.rz = new Resizer(this.d);

            this.sr           = new SendReceive(this.d); // Connection manages connection to remote host
            this.d.connection = this.sr;

            if (!BACKGROUND_CONNECT)
            {
                if (!sr.Connect(Globs.marantz_host))
                {
                    string err = sr.Errors;
                    return;
                }
            }
            this.send_receive_thread = new System.Threading.Thread(Send_Receive_Thread);

            LevelController      lc;
            MultiLevelController mlc;

            LevelController.Orient vert  = LevelController.Orient.vert;
            LevelController.Orient horiz = LevelController.Orient.horiz;

            // FL = Front-Left
            // FR = Front-Right
            // C  = Center
            // SW = Sub-Woofer
            // SL = Surround-Left
            // SR = Surround-Right
            // SBL = Surround-Back-Left  -> Front-Lower-Half-Left
            // SBR = Surround-Back-Right -> Front-Lower-Half-Right
            // FHL = Front-Height-Left
            // FHR = Front-Height-Right
            // FWL = Front-Width-Left
            // FWR = Front-Width-Right

            lc = LevelControllerFactory.New("Main Volume", "MV", horiz, (ScrollBar)this.zMasterVolume, this.txtMasterVolume, this.d);
            this.levctrls.Add("zMasterVolume", lc);
            lc = LevelControllerFactory.New("Front Left harder|softer", "CVFL", vert, null, this.txtFrontLeft, this.d);
            this.levctrls.Add("zFrontLeft", lc);
            lc = LevelControllerFactory.New("Front Right harder|softer", "CVFR", vert, null, this.txtFrontRight, this.d);
            this.levctrls.Add("zFrontRight", lc);
            lc = LevelControllerFactory.New("Back Left Surround Speaker harder|softer", "CVSL", vert, (ScrollBar)this.zBackLeft, this.txtBackLeft, this.d);
            this.levctrls.Add("zBackLeft", lc);
            lc = LevelControllerFactory.New("Back Right Surround Speaker harder|softer", "CVSR", vert, (ScrollBar)this.zBackRight, this.txtBackRight, this.d);
            this.levctrls.Add("zBackRight", lc);
            lc = LevelControllerFactory.New("Front Left Lower-Half harder|softer", "CVSBL", vert, (ScrollBar)this.zBassLeft, this.txtBassLeft, this.d);
            this.levctrls.Add("zBassLeft", lc);
            lc = LevelControllerFactory.New("Front Right Lower-Half harder|softer", "CVSBR", vert, (ScrollBar)this.zBassRight, this.txtBassRight, this.d);
            this.levctrls.Add("zBassRight", lc);
            lc = LevelControllerFactory.New("Center-Speaker harder|softer", "CVC", vert, (ScrollBar)this.zCenterVolume, this.txtCenterVolume, this.d);
            this.levctrls.Add("zCenterVolume", lc);

            lc = LevelControllerFactory.New("Test Balance Control", "-", horiz, (ScrollBar)this.sbSlider, this.txtSlider, this.d);
            this.levctrls.Add("sbSlider", lc);

            int n = 0;

            mlc = new MultiLevelController("Master L|R Balance",
                                           new string[] { "CVFL", "CVSBL" },  /* left top */
                                           new string[] { "CVFR", "CVSBR" },  /* right top */
                                           new string[] { "CVSL" },           /* left bottom */
                                           new string[] { "CVSR" },           /* right bottom */
                                           horiz, (ScrollBar)this.zMasterBalance, this.txtMasterBalance, this.d);
            foreach (LevelController tlc in mlc.level_controllers())
            {
                this.levctrls.Add(String.Format("L|R {0}", n++), lc);
            }
            this.levctrls.Add("zMasterBalance", mlc);
            this.balance_ctrls.Add("zMasterBalance", mlc);

            //                                                   Back Commands                    Front Commands
            mlc = new MultiLevelController("Front|Back Balance",
                                           new string[] { "CVFL", "CVSBL", "CVC" },  /* left top */
                                           new string[] { "CVFR", "CVSBR", "CVC" },  /* right top */
                                           new string[] { "CVSL" },                  /* left bottom */
                                           new string[] { "CVSR" },                  /* right bottom */
                                           vert, (ScrollBar)this.zBalanceFrontRear, this.txtBalanceFrontRear, this.d);
            foreach (LevelController tlc in mlc.level_controllers())
            {
                this.levctrls.Add(String.Format("F|B {0}", n++), lc);
            }
            this.levctrls.Add("zBalanceFrontRear", mlc);
            this.balance_ctrls.Add("zBalanceFrontRear", mlc);

            //                                                     Left Commands            Right Commands
            mlc = new MultiLevelController("Surround L|R Balance", new string[] { "CVSL" }, new string[] { "CVSR" },
                                           new string[] { }, new string[] { },
                                           horiz, (ScrollBar)this.zRearBalance, this.txtRearBalance, this.d);
            foreach (LevelController tlc in mlc.level_controllers())
            {
                this.levctrls.Add(String.Format("Surr L|R {0}", n++), lc);
            }
            this.levctrls.Add("zRearBalance", mlc);
            this.balance_ctrls.Add("zRearBalance", mlc);

            foreach (string levctrl in this.levctrls.Keys)
            {
                LevelController tlc = this.levctrls[levctrl];
                tlc.balance_controlers = this.balance_ctrls;
            }

            this.d.ResizeAllThumbs();  // need to manually trigger resize so thumbs are the correct size

            this.send_receive_thread.Start(this.sr);

            mlc.test_balance();

            //this.d.Start_Session();  // tell ReceiveThread to expect output from Receiver

            //if (!pr.Go()) {
            //    String errs = pr.Errors;
            //    if (errs == "")
            //        errs = "Unknown Processor Error";
            //    ui.Add_to_Received(errs);
            //}
        }
Exemple #19
0
 ///<inheritdoc/>
 internal Socket(SocketConfiguration config)
 {
     _rqRep       = new RqRep(config);
     _pubSub      = new PubSub(config);
     _sendReceive = new SendReceive(config);
 }