Example #1
0
 public async Task PostAsync_InvalidBaseEndpoint_ThrowsArgumentException()
 {
     var httpCommunication = new HttpCommunication();
     await Assert.ThrowsExceptionAsync <ArgumentException>(
         async() =>
         await httpCommunication.PostAsync("invalid uri", "", new Dictionary <string, string>(), new byte[0]));
 }
        /// <summary>
        /// 创建通讯模块
        /// </summary>
        /// <param name="communicationType">通讯方式</param>
        /// <returns></returns>
        public static ICommunication CreateCommunication(CommunicationType communicationType)
        {
            ICommunication communication = null;

            switch (communicationType)
            {
            case CommunicationType.C8962:
                communication = new C8962Communication();
                break;

            case CommunicationType.socketClient:
                communication = new SocketTcpClientCommunication();
                break;

            case CommunicationType.Http:
                communication = new HttpCommunication();
                break;

            case CommunicationType.HongDian:
                throw new NotImplementedException("CommunicationType.HongDian 通讯方式暂时未实现");

            //break;
            case CommunicationType.MAS:
                throw new NotImplementedException("CommunicationType.MAS 通讯方式暂时未实现");
            //break;

            default:
                throw new NotImplementedException("未知通讯方式");
                //break;
            }
            return(communication);
        }
        /*  Timer elapsed definitions  */
        private void Timer_loopRegister_Elapsed(object sender, EventArgs e)
        {
            if (ProgramData.LoginSuccess)
            {
                if (radio_register.Checked)
                {
                    string opcode = ProgramData.ReadyToSelectCoursesList[ProgramData.CurrentSelectCourseIdx].ToString();

                    HttpCommunication.AddRegister(opcode, out string msg);

                    if (ProgramData.CurrentSelectCourseIdx + 1 == ProgramData.ReadyToSelectCoursesList.Count)
                    {
                        _timerLoopRegister.Stop();

                        btn_readySelCoursesList.Enabled = true;
                        radio_register.Enabled          = radio_selection.Enabled = true;
                        checkBox_OnSchedule.Enabled     = true;
                        group_TimePicker.Enabled        = checkBox_OnSchedule.Checked;

                        btn_StartReg.Enabled = true;
                    }
                    else
                    {
                        ProgramData.CurrentSelectCourseIdx += 1;
                    }

                    AddLog(msg);
                }
            }
        }
Example #4
0
 public async Task PostAsync_NullData_ThrowsArgumentNullException()
 {
     var httpCommunication = new HttpCommunication();
     await Assert.ThrowsExceptionAsync <ArgumentNullException>(
         async() =>
         await httpCommunication.PostAsync("http://localhost", "", new Dictionary <string, string>(), null));
 }
        private void timer_tryToLogin_Elapsed(object sender, EventArgs e)
        {
            Debug.Print(DateTime.Now.ToLongTimeString() + " - Trying to login");

            if (!HttpCommunication.Init(out ProgramData.SecureRandom))
            {
                if (CMode.Equals(ConnectionMode.Unknown))
                {
                    CMode = ConnectionMode.Offline;
                    radio_register.Enabled  = radio_selection.Enabled = true;
                    radio_selection.Checked = true;
                }
                else if (CMode.Equals(ConnectionMode.Offline))
                {
                    slb_LoginAs.Text = "嘗試連接到伺服器(離線模式)";
                }
            }
            else
            {
                slb_LoginAs.Text = "伺服器連線成功,嘗試登入使用者";
                CMode            = ConnectionMode.Online;
            }

            if (CMode.Equals(ConnectionMode.Online))
            {
                ProgramData.EncryptPw =
                    Crypto.GetEncrypt(ProgramData.LoginPw, ProgramData.LoginId, ProgramData.SecureRandom);
                if (!HttpCommunication.Login(ProgramData.LoginId, ProgramData.EncryptPw, out string msg))
                {
                    AddLog(msg);
                    ProgramData.LoginSuccess = false;
                    slb_LoginAs.Text         = "登入失敗";

                    loginToolStripMenuItem.Visible       = true;
                    cancelLoginToolStripMenuItem.Visible = false;
                }
                else
                {
                    AddLog(msg);
                    slb_LoginAs.Text         = "登入為 " + ProgramData.LoginId;
                    ProgramData.LoginSuccess = true;

                    loginToolStripMenuItem.Visible       = false;
                    cancelLoginToolStripMenuItem.Visible = false;

                    logoutToolStripMenuItem.Visible       = true;
                    myCourseToolStripMenuItem.Visible     = true;
                    searchCourseToolStripMenuItem.Visible = true;

                    if (!_timerLoopSelect.Enabled)
                    {
                        radio_register.Enabled = radio_selection.Enabled = true;
                        radio_register.Checked = true;
                    }
                }

                _timerTryToLogin.Stop();
            }
        }
Example #6
0
        public ActionResult Display()
        {
            HttpCommunication <Category> obj = new HttpCommunication <Category>("http://localhost:1309/api/");

            obj.ServiceAddress = "Products";
            var result = obj.GetRecords();

            ViewBag.res = result;
            return(View());
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            //  To control whether send query or not
            ProgramData.AcceptToConnect = false;
            ProgramData.LoginSuccess    = false;

            CMode = ConnectionMode.Unknown;

            slb_LoginAs.Visible = true;
            slb_LoginAs.Text    = "尚未登入";

            //  Try to check connection
            if (!HttpCommunication.CheckServerConnect())
            {
                AddLog("無法建立與選課伺服器的連接,請檢查連線。");
                loginToolStripMenuItem.Enabled = false;
            }

            //  Default visible
            btn_StartReg.Visible = true;
            btn_StartSel.Visible = btn_Cancel.Visible = false;

            //  Default enabled
            btn_StartReg.Enabled            = false;
            radio_register.Enabled          = radio_selection.Enabled = false;
            btn_readySelCoursesList.Enabled = true;
            btn_readyDelCoursesList.Enabled = false;
            checkBox_OnSchedule.Enabled     = false;
            group_TimePicker.Enabled        = false;

            //  Default checked
            checkBox_OnHook.Checked = true;

            //  Default value
            ProgramData.CurrentNetworkTime  = DateTime.Now;
            dateTimePicker_OnSchedule.Value = ProgramData.CurrentNetworkTime;

            //  Time timers start
            _timerSyncNetworkTime.Start();
            _timerCurrentTime.Start();

            //  Keep connection alive timer start
            _timerKeepConnectAlive.Start();

            //  MainForm closing event (do logout)
            FormClosing += Main_FormClosing;

            //  For Debugger
            Debug.Print("Main(UI) thread : " + Thread.CurrentThread.ManagedThreadId);
        }
        private void Timer_loopSelect_Elapsed(object sender, EventArgs e)
        {
            if (ProgramData.LoginSuccess)
            {
                if (radio_selection.Checked)
                {
                    string opcode = ProgramData.ReadyToSelectCoursesList[ProgramData.CurrentSelectCourseIdx].ToString();

                    if (HttpCommunication.AddSelection(opcode, out string msg))
                    {
                        ProgramData.ReadyToSelectCoursesList.Remove(ProgramData.CurrentSelectCourseIdx);
                        ProgramData.CurrentSelectCourseIdx -= 1;
                    }

                    if (ProgramData.ReadyToSelectCoursesList.Count == 0)
                    {
                        _timerLoopSelect.Stop();
                        AddLog("全部加選完畢。");

                        btn_readySelCoursesList.Enabled = true;
                        radio_register.Enabled          = radio_selection.Enabled = true;
                        checkBox_OnSchedule.Enabled     = true;
                        group_TimePicker.Enabled        = checkBox_OnSchedule.Checked;

                        btn_Cancel.Visible   = false;
                        btn_StartSel.Visible = true;
                    }
                    else if (ProgramData.CurrentSelectCourseIdx + 1 == ProgramData.ReadyToSelectCoursesList.Count)
                    {
                        ProgramData.CurrentSelectCourseIdx = 0; //  If reach end of list, return to start of list
                    }
                    else
                    {
                        ProgramData.CurrentSelectCourseIdx += 1; //  Default, retrieve list one by one
                    }

                    if (msg.Contains("未知")) //  If lost connect
                    {
                        AddLog("等待登入成功後將自動進行嘗試加選。");
                        LostConnect();
                    }
                    else
                    {
                        AddLog(msg); //  Normal status
                    }
                }
            }
        }
Example #9
0
 private void CourseStudentListForm_Load(object sender, EventArgs e)
 {
     LastSearchIndex = -1;
     if (HttpCommunication.GetCourseStudents(OpCode, out dynamic datas, out string msg))
     {
         listView_Students.Items.Clear();
         if (datas != null)
         {
             foreach (var data in datas)
             {
                 listView_Students.Items.Add(new ListViewItem(new string[] { data.idcode }));
             }
         }
     }
     statusLabel.Text = msg;
 }
        private void RefreshAppendList()
        {
            if (HttpCommunication.GetAllMyCoursesAppend(ProgramData.LoginId, out dynamic datas, out string msg))
            {
                listView_Appends.Items.Clear();
                if (datas != null)
                {
                    foreach (var data in datas)
                    {
                        listView_Appends.Items.Add(new ListViewItem(new string[] { data.ord, data.op_type, data.op_code, data.cname, data.teacher }));
                    }
                }
            }

            statusLabel.Text      = msg;
            btn_delAppend.Enabled = false;
        }
 private void timer_keepConnectAlive_Elapsed(object sender, EventArgs e)
 {
     if (ProgramData.LoginSuccess)
     {
         //  If action not finish yet, do not block network source.
         if (!(_timerLoopRegister.Enabled || _timerLoopSelect.Enabled))
         {
             if (!HttpCommunication.GetAllMyCourses(ProgramData.LoginId, out _, out _))
             {
                 AddLog("已由伺服器端離線。");
                 LostConnect();
             }
             else
             {
                 Debug.Print(DateTime.Now.ToLongTimeString() + " - Keep connection alive.");
             }
         }
     }
 }
        private void timer_loopDelete_Elapsed(object sender, EventArgs e)
        {
            if (ProgramData.LoginSuccess)
            {
                if (checkBox_DelCourseFirst.Checked)
                {
                    string opCode = ProgramData.ReadyToDeleteCoursesList[ProgramData.CurrentDeleteCourseIdx].ToString();

                    HttpCommunication.DeleteSelection(opCode, out string msg);

                    if (ProgramData.CurrentDeleteCourseIdx + 1 == ProgramData.ReadyToDeleteCoursesList.Count)
                    {
                        _timerLoopDelete.Stop();
                    }
                    else
                    {
                        ProgramData.CurrentDeleteCourseIdx += 1;
                    }

                    AddLog(msg);
                }
            }
        }
        private void btn_delAppend_Click(object sender, EventArgs e)
        {
            string seletedItemString = listView_Appends.SelectedItems[0].SubItems[3].Text + "(" + listView_Appends.SelectedItems[0].SubItems[1].Text + ")";
            string opcode            = listView_Appends.SelectedItems[0].SubItems[2].Text;
            string msg = null;

            if (MessageBox.Show(
                    "您確定要取消遞補 [" + seletedItemString + "] 嗎",
                    "確認取消遞補",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                if (HttpCommunication.DeleteAppend(opcode, out msg))
                {
                    MessageBox.Show(msg, "取消遞補成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(msg, "取消遞補失敗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

            RefreshAppendList();
        }
        private void btn_delSelection_Click(object sender, EventArgs e)
        {
            string seletedItemString = listView_Courses.SelectedItems[0].SubItems[2].Text + "(" + listView_Courses.SelectedItems[0].SubItems[1].Text + ")";
            string opcode            = listView_Courses.SelectedItems[0].SubItems[1].Text;
            string msg = null;

            if (MessageBox.Show(
                    "您確定要退選 [" + seletedItemString + "] 嗎",
                    "確認退選",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                if (HttpCommunication.DeleteSelection(opcode, out msg))
                {
                    MessageBox.Show(msg, "退選成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(msg, "退選失敗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

            RefreshCourseList();
        }
        public async Task <IEnumerable <int> > GetBestStoriesIdsAsync()
        {
            var url = $"https://hacker-news.firebaseio.com/{apiVersion}/beststories.json";

            return(await HttpCommunication.GetAsync <IEnumerable <int> >(url));
        }
        public async Task <Story> GetStoryDetailAsync(int id)
        {
            var url = $"https://hacker-news.firebaseio.com/{apiVersion}/item/{id}.json";

            return(await HttpCommunication.GetAsync <Story>(url));
        }
Example #17
0
        /// <exception cref="ArgParserException"><c>--socket_ip</c> passed without specifying <c>--socket_port</c> or vice-versa</exception>
        public void ParseArguments(string[] args, Func <byte[]> takeScreenshotCallback)
        {
            for (int i = 0; i < args.Length; i++)
            {
                // For some reason sometimes visual studio will pass this to us on the commandline. it makes no sense.
                if (args[i] == ">")
                {
                    i++;
                    var stdout = args[i];
                    Console.SetOut(new StreamWriter(stdout));
                    continue;
                }

                var arg = args[i].ToLower();
                if (arg.StartsWith("--load-slot="))
                {
                    cmdLoadSlot = arg.Substring(arg.IndexOf('=') + 1);
                }

                if (arg.StartsWith("--load-state="))
                {
                    cmdLoadState = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                if (arg.StartsWith("--config="))
                {
                    cmdConfigFile = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--movie="))
                {
                    cmdMovie = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--dump-type="))
                {
                    cmdDumpType = arg.Substring(arg.IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--dump-frames="))
                {
                    string   list  = arg.Substring(arg.IndexOf('=') + 1);
                    string[] items = list.Split(',');
                    _currAviWriterFrameList = new HashSet <int>();
                    foreach (string item in items)
                    {
                        _currAviWriterFrameList.Add(int.Parse(item));
                    }

                    // automatically set dump length to maximum frame
                    _autoDumpLength = _currAviWriterFrameList.OrderBy(x => x).Last();
                }
                else if (arg.StartsWith("--version"))
                {
                    printVersion = true;
                }
                else if (arg.StartsWith("--dump-name="))
                {
                    cmdDumpName = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--dump-length="))
                {
                    int.TryParse(arg.Substring(arg.IndexOf('=') + 1), out _autoDumpLength);
                }
                else if (arg.StartsWith("--dump-close"))
                {
                    _autoCloseOnDump = true;
                }
                else if (arg.StartsWith("--chromeless"))
                {
                    _chromeless = true;
                }
                else if (arg.StartsWith("--fullscreen"))
                {
                    startFullscreen = true;
                }
                else if (arg.StartsWith("--lua="))
                {
                    luaScript  = args[i].Substring(args[i].IndexOf('=') + 1);
                    luaConsole = true;
                }
                else if (arg.StartsWith("--luaconsole"))
                {
                    luaConsole = true;
                }
                else if (arg.StartsWith("--socket_port="))
                {
                    int.TryParse(arg.Substring(arg.IndexOf('=') + 1), out socket_port);
                }
                else if (arg.StartsWith("--socket_ip="))
                {
                    socket_ip = arg.Substring(arg.IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--mmf="))
                {
                    mmf_filename = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--url_get="))
                {
                    URL_get = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--url_post="))
                {
                    URL_post = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                else if (arg.StartsWith("--audiosync="))
                {
                    audiosync = arg.Substring(arg.IndexOf('=') + 1) == "true";
                }
                else if (arg.StartsWith("--open-ext-tool-dll="))
                {
                    // the first ext. tool from ExternalToolManager.ToolStripMenu which satisfies both of these will be opened:
                    // - available (no load errors, correct system/rom, etc.)
                    // - dll path matches given string; or dll filename matches given string with or without `.dll`
                    openExtToolDll = args[i].Substring(20);
                }
                else if (arg.StartsWith("--network_debug="))
                {
                    networkDebug = arg.Substring(arg.IndexOf('=') + 1) == "true";
                }
                else if (arg.StartsWith("--network_debug_rom="))
                {
                    networkRomPath = args[i].Substring(args[i].IndexOf('=') + 1);
                }
                else
                {
                    cmdRom = args[i];
                }
            }

            httpCommunication = URL_get == null && URL_post == null
                                ? null // don't bother
                                : new HttpCommunication(takeScreenshotCallback, URL_get, URL_post);
            memoryMappedFiles = mmf_filename == null
                                ? null // don't bother
                                : new MemoryMappedFiles(takeScreenshotCallback, mmf_filename);
            if (socket_ip == null && socket_port <= 0)
            {
                socketServer = null;                 // don't bother
            }
            else if (socket_ip == null || socket_port <= 0)
            {
                throw new ArgParserException("Socket server needs both --socket_ip and --socket_port. Socket server was not started");
            }
            else
            {
                socketServer = new SocketServer(takeScreenshotCallback, socket_ip, socket_port);
            }
        }