Esempio n. 1
0
        void MinimizeWindow(object parameter)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
            {
                Log.DebugFormat("MinimizeWindow, {0}", DockPosition);

                ClearAnimations();

                Position position = new Position();
                switch (DockPosition.Selected)
                {
                case DockEdge.Left:
                    position.Top    = ActiveScreen.Bounds.Top;
                    position.Left   = ActiveScreen.Bounds.Left;
                    position.Width  = 1;
                    position.Height = ActiveScreen.Bounds.Height;
                    break;

                case DockEdge.Right:
                    position.Top    = ActiveScreen.Bounds.Top;
                    position.Left   = ActiveScreen.Bounds.Right;
                    position.Width  = 0;
                    position.Height = ActiveScreen.Bounds.Height;
                    break;

                case DockEdge.Top:
                    position.Top    = ActiveScreen.Bounds.Top;
                    position.Left   = ActiveScreen.Bounds.Left;
                    position.Width  = ActiveScreen.Bounds.Width;
                    position.Height = 0;
                    break;

                case DockEdge.Bottom:
                    position.Top    = ActiveScreen.Bounds.Bottom;
                    position.Left   = ActiveScreen.Bounds.Left;
                    position.Width  = ActiveScreen.Bounds.Width;
                    position.Height = 0;
                    break;
                }
                position.Bottom = position.Top + position.Height;
                position.Right  = position.Left + position.Width;

                _appbar.CorrectPosition(ref position);

                Log.DebugFormat("MinimizeWindow position {0}", position);

                _mainGrid.Width  = 0;
                _mainGrid.Height = 0;
                Width            = 0;
                Height           = 0;

                Left   = position.Left;
                Top    = position.Top;
                Width  = position.Width;
                Height = position.Height;

                switch (DockPosition.Selected)
                {
                case DockEdge.Left:
                    Canvas.SetLeft(_mainGrid, 0);
                    Canvas.SetTop(_mainGrid, 0);
                    break;

                case DockEdge.Right:
                    Canvas.SetLeft(_mainGrid, 0);
                    Canvas.SetTop(_mainGrid, 0);
                    break;

                case DockEdge.Top:
                    Canvas.SetLeft(_mainGrid, 0);
                    Canvas.SetTop(_mainGrid, 0);
                    break;

                case DockEdge.Bottom:
                    Canvas.SetLeft(_mainGrid, 0);
                    Canvas.SetTop(_mainGrid, 0);
                    break;
                }

                _mainGrid.Width  = position.Width;
                _mainGrid.Height = position.Height;

                SwitchOrientation();

                Log.DebugFormat("MinimzedWindow, MainGrid {0}", GetMainGridPosition());
            });
        }
Esempio n. 2
0
 private void HandleFileChangesFoundEvent(object sender, EventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(LoadMediaItems);
 }
Esempio n. 3
0
 private void Brick_OnLog(object sender, LogEventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(
         () => _log.Log(e.Message));
 }
        /// <summary>
        /// 上报订单,
        /// </summary>
        /// <param name="uploadDate">上报日期</param>
        private void UploadFolio(DateTime uploadDate)
        {
            try
            {
                _posSoapClient = new UploadService.posSoapClient();
                string tableDate = uploadDate.ToString("yyMMdd");
                //string tableDate = uploadDate.ToString("180101");


                var tenderCodeArray = AppConfig.Instance.TenderCode.Split(',');
                for (int i = 0; i < tenderCodeArray.Length; i++)
                {
                    tenderCodeArray[i] = "'" + tenderCodeArray[i] + "'";
                }
                string tenderCodes = string.Join(",", tenderCodeArray);

                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    Folios.Clear();
                });

                SuccessfulCount      = 0;
                FailuresCount        = 0;
                UploadButtonEnabled  = false;
                UploadTipsVisibility = true;

                Task.Factory.StartNew(() =>
                {
                    string queryFolioSql = "SELECT STARTTIM,SERIAL,AMT FROM FOLIO" + tableDate + " WHERE SERIAL IN(SELECT SERIAL FROM FOLIOPAYMENT" + tableDate + " WHERE PAYMENTDES IN (" + tenderCodes + ") GROUP BY SERIAL)";
                    var folios           = _interBaseHelper.ReadFolioData(queryFolioSql);

                    foreach (var folio in folios)
                    {
                        string strCallUserCode = AppConfig.Instance.CallUserCode;
                        string strCallPassword = AppConfig.Instance.CallPassword;
                        string strStoreCode    = AppConfig.Instance.StoreCode;
                        string strType         = "SA";
                        string strSalesDate    = folio.StartTim.ToString("yyyyMMdd");
                        string strSalesTime    = folio.StartTim.ToString("HHMMss");;
                        string strSalesDocNo   = folio.Serial;
                        string strVipCode      = "";
                        string strTenderCode   = GetStrTenderCodes(tableDate, folio.Serial);
                        string strRemark       = "";
                        string strItems        = GetStrItems(tableDate, folio.Serial);

                        string errorMessage;
                        var posResult = PostToServer(strCallUserCode,
                                                     strCallPassword,
                                                     strStoreCode,
                                                     strType,
                                                     strSalesDate,
                                                     strSalesTime,
                                                     strSalesDocNo,
                                                     strVipCode,
                                                     strTenderCode,
                                                     strRemark,
                                                     strItems,
                                                     out errorMessage);

                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            Folios.Add(new Folio
                            {
                                Serial        = folio.Serial,
                                Amt           = folio.Amt,
                                StartTim      = folio.StartTim,
                                UploadResult  = posResult ? "上报成功" : "上报失败," + errorMessage + ".",
                                UploadSuccess = posResult
                            });
                        });


                        if (posResult)
                        {
                            SuccessfulCount++;
                        }
                        else
                        {
                            FailuresCount++;
                        }
                    }
                }).ContinueWith(x => {
                    _logger.Info(string.Format("上报完毕,成功:{0},失败:{1}.", SuccessfulCount, FailuresCount));
                    UploadButtonEnabled = true;
                });
            }
            catch (Exception ex)
            {
                _logger.Info(ex, string.Format("上报错误,成功:{0},失败:{1}.", SuccessfulCount, FailuresCount));
                UploadButtonEnabled  = true;
                UploadTipsVisibility = false;
                _logger.Error(ex, ex.ToString());
                return;
            }
        }
        /// <summary>
        /// Load movies asynchronously
        /// </summary>
        public override async Task LoadMoviesAsync(bool reset = false)
        {
            await LoadingSemaphore.WaitAsync(CancellationLoadingMovies.Token);

            if (reset)
            {
                Movies.Clear();
                Page           = 0;
                VerticalScroll = 0d;
            }

            var watch = Stopwatch.StartNew();

            Page++;
            if (Page > 1 && Movies.Count == MaxNumberOfMovies)
            {
                Page--;
                LoadingSemaphore.Release();
                return;
            }

            StopLoadingMovies();
            Logger.Info(
                $"Loading page {Page}...");
            HasLoadingFailed = false;
            try
            {
                IsLoadingMovies = true;
                await Task.Run(async() =>
                {
                    var getMoviesWatcher = new Stopwatch();
                    getMoviesWatcher.Start();
                    var seen      = UserService.GetSeenMovies(Page);
                    var favorites = UserService.GetFavoritesMovies(Page);
                    var movies    = seen.allMovies.Union(favorites.allMovies).Distinct().ToList();
                    var result    = await MovieService
                                    .GetSimilarAsync(Page, Utils.Constants.MaxMoviesPerPage, movies,
                                                     CancellationLoadingMovies.Token).ConfigureAwait(false);
                    getMoviesWatcher.Stop();
                    var getMoviesEllapsedTime = getMoviesWatcher.ElapsedMilliseconds;
                    if (reset && getMoviesEllapsedTime < 500)
                    {
                        // Wait for VerticalOffset to reach 0 (animation lasts 500ms)
                        await Task.Delay(500 - (int)getMoviesEllapsedTime, CancellationLoadingMovies.Token).ConfigureAwait(false);
                    }

                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        Movies.AddRange(result.movies.Except(Movies, new MovieLightComparer()));
                        IsLoadingMovies       = false;
                        IsMovieFound          = Movies.Any();
                        CurrentNumberOfMovies = Movies.Count;
                        MaxNumberOfMovies     = result.nbMovies == 0 ? Movies.Count : result.nbMovies;
                        UserService.SyncMovieHistory(Movies);
                    });
                }, CancellationLoadingMovies.Token).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Page--;
                Logger.Error(
                    $"Error while loading page {Page}: {exception.Message}");
                HasLoadingFailed = true;
                Messenger.Default.Send(new ManageExceptionMessage(exception));
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Info(
                    $"Loaded page {Page} in {elapsedMs} milliseconds.");
                LoadingSemaphore.Release();
            }
        }
Esempio n. 6
0
 /// <summary>
 /// </summary>
 /// <param name="tooltipText"></param>
 /// <param name="timeoutInMilliseconds"></param>
 public void ShowBalloon(string tooltipText, int timeoutInMilliseconds)
 {
     ToolTipText = tooltipText;
     DispatcherHelper.CheckBeginInvokeOnUI(() => ViewCore.ShowCustomBalloon(timeoutInMilliseconds));
 }
Esempio n. 7
0
 private void OnAllowedFileExtensionsSet(OnAllowedFileExtensionsLoaded onAllowedFileExtensionsLoaded)
 {
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() => this.AllowedFileExtensions = (IList <string>)onAllowedFileExtensionsLoaded.FileExtensions.ToList <string>()));
 }
Esempio n. 8
0
 private void UpdateTimeUntilExamStart(int timeUntilExamStartInMinutes)
 {
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() => this.MinutesLeftUntilExamStart = (double)timeUntilExamStartInMinutes));
 }
Esempio n. 9
0
 private void OnExaminationUrlLoaded(OnExaminationUrlLoaded onExaminationUrlLoaded)
 {
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() => this.ClickablePathViewModel = new ClickablePathViewModel(onExaminationUrlLoaded.ExaminationUrl, (string)null)));
 }
Esempio n. 10
0
 protected void Ui(Action uiDelegate)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(uiDelegate);
 }
 protected virtual void UpdateUserInterface(Action action)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(action);
 }
Esempio n. 12
0
 /// <summary>
 /// Clears this instances log.
 /// </summary>
 public void Reset()
 {
     // this.logsb.Length = 0;
     DispatcherHelper.CheckBeginInvokeOnUI(() => this.mainWindow.ClearLogText());
 }
Esempio n. 13
0
 public void ResetErrorDisplay()
 {
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() => this.ShowFieldTextboxError = false));
 }
        /// <summary>
        /// 获取在线所有目录数据具体实现方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="retryCount"></param>
        private async void SetOnlineBookCatalogsData(string url, int retryCount = 3)
        {
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    return;
                }

                IsLoadingCatalogData = true;

                var i = 0;
                Tuple <List <BookCatalog>, string, string, string> value = null;
                while (i <= retryCount)
                {
                    value = await AnalisysSourceHelper.GetCatalogPageData(url, CurrentBook.BookId);

                    if (value != null)
                    {
                        break;
                    }
                    Debug.WriteLine($"加载目录失败,第{i + 1}次尝试");
                    i++;
                }

                if (value == null)
                {
                    Debug.WriteLine("加载目录失败,不再次尝试");
                    return;
                }

                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    if (value.Item1 != null)
                    {
                        if (CurrentBook == null)
                        {
                            return;
                        }

                        CurrentBook.CatalogList = new List <BookCatalog>();
                        foreach (var bookCatalog in value.Item1)
                        {
                            CurrentBook.CatalogList.Add(bookCatalog);
                        }

                        CatalogCount = CurrentBook.CatalogList.Count;
                        var temp     = CurrentBook.CatalogList.FirstOrDefault(p => p.CatalogUrl == CurrentCatalog.CatalogUrl);
                        if (temp != null)
                        {
                            CurrentCatalog = temp;
                            // PreLoadPreAndNextCatalog();
                        }
                    }
                    CurrentBook.Description = value.Item2;
                    CurrentBook.Cover       = value.Item3;
                    CurrentBook.AuthorName  = value.Item4;
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                IsLoadingCatalogData = false;
            }
        }
Esempio n. 15
0
File: UI.cs Progetto: rstoki/IL2CDR
 public static void Dispatch(Action action)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(action);
 }
Esempio n. 16
0
 public PinCodePopupView()
 {
     this.InitializeComponent();
     Messenger.Default.Register <OnAllowClosingPinCodePopup>((object)this, (Action <OnAllowClosingPinCodePopup>)(c => this._allowClosing = c.AllowClosing));
     Messenger.Default.Register <OnPinCodeLoginSuccessful>((object)this, (Action <OnPinCodeLoginSuccessful>)(c => DispatcherHelper.CheckBeginInvokeOnUI(new Action(((Window)this).Close))));
     Messenger.Default.Register <OnPinCodeLoginCancelled>((object)this, (Action <OnPinCodeLoginCancelled>)(c => DispatcherHelper.CheckBeginInvokeOnUI(new Action(((Window)this).Close))));
     Messenger.Default.Register <OnPinCodeLoginForceContinue>((object)this, (Action <OnPinCodeLoginForceContinue>)(c => DispatcherHelper.CheckBeginInvokeOnUI(new Action(((Window)this).Close))));
 }
Esempio n. 17
0
 public void ShowBalloon(string tooltipText)
 {
     ToolTipText = tooltipText;
     DispatcherHelper.CheckBeginInvokeOnUI(() => ViewCore.ShowCustomBalloon());
 }
        public void CsharpCall(int callbackType, int code, [MarshalAs(UnmanagedType.LPStr)] string msg1, [MarshalAs(UnmanagedType.LPStr)] string msg2)
        {
            try
            {
                Dictionary <string, string> settings = getPrintSettings(msg2);
                if (callbackType == 1 && code == 1)
                {
                    #region 用户上传文件
                    ThreadPool.QueueUserWorkItem((obj) =>
                    {
                        string FilePath     = "";
                        string copiesNum    = "";
                        string color        = "";
                        string documentName = "";
                        string pageCount1   = "";
                        //string newFileName = reName(settings["savedPath"]);
                        string newFileName = reName(settings["savedPath"], settings["document"]);
                        if (string.IsNullOrEmpty(newFileName))
                        {
                            return;
                        }

                        /*
                         * 这里用了委托
                         */
                        List <string> filePath = new List <string>();
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            //ModifyNameWindow modify_Window = new ModifyNameWindow(newFileName);
                            ModifyNameWindow modify_Window = new ModifyNameWindow(newFileName,
                                                                                  settings["copies"].ToString(), settings["color"]
                                                                                  , settings["document"], settings["pageCount"]);
                            //modify_Window.TransfEvent_New += frm_TransfEvent;
                            modify_Window.TransfEvent_New += frm_TransfEvent;
                            bool bo = (bool)modify_Window.ShowDialog();

                            //string filePath, string copies, string isColor, string documentName
                            //void frm_TransfEvent(string value)
                            void frm_TransfEvent(string filePath1, string copies, string isColor, string fileName, string pageCount)
                            {
                                FilePath     = filePath1;
                                copiesNum    = copies;
                                color        = isColor;
                                documentName = fileName;
                                pageCount1   = pageCount;
                            }
                            if (bo)
                            {
                                string iscolor = "0";
                                if (settings["color"] == "1")
                                {
                                    iscolor = "true";
                                }
                                else if (settings["color"] == "0")
                                {
                                    iscolor = "false";
                                }
                                #region // Old Pram
                                //NameValueCollection data = new NameValueCollection
                                //{
                                //   { "iscolor", iscolor },
                                //   { "copies", settings["copies"] },
                                //   { "endpage",settings["pageCount"]},
                                //   { "userid", AccountInfo.ID },
                                //   { "printType", "1" }
                                //};
                                #endregion
                                NameValueCollection dataUpload = new NameValueCollection
                                {
                                    { "sourceclient", "PC" }
                                };
                                var orderList  = new OrderList();
                                var account    = new Account();
                                var myDocument = new Bll.MyDocument();
                                string msg     = myDocument.DocTransCoding(AccountInfo.Token, new[] { FilePath }, dataUpload);
                                //string msg = myDocument.BusinessVirtualPrint(AccountInfo.Token, new[] { FilePath, FilePath }, data);
                                JObject jo = (JObject)JsonConvert.DeserializeObject(msg);
                                if (jo["code"].GetInt() == 200)
                                {
                                    string getPrintPrice = account.GetPrintPrice(AccountInfo.Token);
                                    JObject JoPrice      = (JObject)JsonConvert.DeserializeObject(getPrintPrice);
                                    if (JoPrice["code"].GetInt() == 200)
                                    {
                                        /*
                                         * 金额计算
                                         */

                                        double getpayMoney = settings["color"].GetBool()
                                            ? Convert.ToDouble(JoPrice["dataList"]["enterpriseColorPrice"]) : Convert.ToDouble(JoPrice["dataList"]["enterpriseBlackPrice"]);
                                        //double payMoney = jo["dataList"]["copies"].GetInt() * jo["dataList"]["totalPage"].GetInt() * getpayMoney;
                                        double payMoney = settings["copies"].GetInt() * jo["dataList"]["totalPage"].GetInt() * getpayMoney;

                                        //MessageBox.Show(settings["copies"] + payMoney);
                                        #region 双面打订单金额减半

                                        //settings["duplex"]=1是双面,
                                        if (settings["duplex"].GetBool())
                                        {
                                            //重新计算张数
                                            double ReSetTotalpage = Math.Ceiling(Convert.ToDouble(jo["dataList"]["totalPage"]) / 2);
                                            //重新计算金额
                                            payMoney = settings["copies"].GetInt() * ReSetTotalpage * getpayMoney;
                                        }

                                        #endregion

                                        string orderID  = jo["dataList"]["orderId"].ToString();
                                        string homePage = jo["dataList"]["filePageSection"].ToString().Split('-')[0];
                                        string endPage  = jo["dataList"]["filePageSection"].ToString().Split('-')[1];


                                        NameValueCollection dataPay = new NameValueCollection
                                        {
                                            { "orderid", orderID },
                                            { "paymode", "3" },
                                            { "homepage", homePage },
                                            { "endpage", endPage },
                                            { "iscolor", settings["color"] },
                                            { "printmode", settings["duplex"] },
                                            { "copies", settings["copies"] },
                                            { "amount", payMoney.ToString(CultureInfo.InvariantCulture) }
                                        };
                                        string temVal = orderList.OrderPay(AccountInfo.Token, dataPay);
                                        JObject JoPay = (JObject)JsonConvert.DeserializeObject(temVal);
                                        if (JoPay["code"].GetInt() == 200)
                                        {
                                            MessageBox.Show("您的订单已生成", "提示");
                                        }
                                        else
                                        {
                                            MessageBox.Show(JoPay["msg"].ToString(), "提示");
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("用户支付金额获取失败,已生成未支付订单", "提示");
                                    }
                                }
                                else
                                {
                                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                    {
                                        MessageBox.Show("订单生成失败2", "提示");
                                    });
                                }
                            }
                        });
                    });
                    #endregion
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Esempio n. 19
0
 public void HideBalloon()
 {
     DispatcherHelper.CheckBeginInvokeOnUI(() => ViewCore.CloseBalloon());
 }
 private void OnProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(() => Progress = e);
 }
Esempio n. 21
0
 private void RemoveMainDocumentClick()
 {
     Task.Factory.StartNew((Action)(() => this._handInFileMetadataStorageService.ClearMainDocument()));
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() => this.SelectedMainDocument = (HandInFileViewModel)null));
 }
Esempio n. 22
0
        /// <summary>
        /// Search movies asynchronously
        /// </summary>
        public override async Task LoadMoviesAsync(bool reset = false)
        {
            await LoadingSemaphore.WaitAsync();

            StopLoadingMovies();
            if (reset)
            {
                Movies.Clear();
                Page = 0;
            }

            var watch = Stopwatch.StartNew();

            Page++;
            if (Page > 1 && Movies.Count == MaxNumberOfMovies)
            {
                Page--;
                LoadingSemaphore.Release();
                return;
            }

            Logger.Info(
                $"Loading search page {Page} with criteria: {SearchFilter}");
            HasLoadingFailed = false;
            try
            {
                IsLoadingMovies = true;
                await Task.Run(async() =>
                {
                    var result =
                        await MovieService.SearchMoviesAsync(SearchFilter,
                                                             Page,
                                                             MaxMoviesPerPage,
                                                             Genre,
                                                             Rating,
                                                             CancellationLoadingMovies.Token).ConfigureAwait(false);

                    DispatcherHelper.CheckBeginInvokeOnUI(async() =>
                    {
                        Movies.AddRange(result.movies.Except(Movies, new MovieLightComparer()));
                        IsLoadingMovies       = false;
                        IsMovieFound          = Movies.Any();
                        CurrentNumberOfMovies = Movies.Count;
                        MaxNumberOfMovies     = result.nbMovies;
                        await UserService.SyncMovieHistoryAsync(Movies).ConfigureAwait(false);
                    });
                }).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Page--;
                Logger.Error(
                    $"Error while loading search page {Page} with criteria {SearchFilter}: {exception.Message}");
                HasLoadingFailed = true;
                Messenger.Default.Send(new ManageExceptionMessage(exception));
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Info(
                    $"Loaded search page {Page} with criteria {SearchFilter} in {elapsedMs} milliseconds.");
                LoadingSemaphore.Release();
            }
        }
 /// <summary>
 /// On pause player
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void OnPausedMedia(object sender, EventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(async() => await PauseMedia());
 }
Esempio n. 24
0
 protected virtual void OnSkipToPrevious()
 {
     DispatcherHelper.CheckBeginInvokeOnUI(() => SkipToPrevious?.Invoke(this, EventArgs.Empty));
 }
Esempio n. 25
0
 private void HandleAllItemsCompletedEvent(object sender, EventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(SortMediaItems);
 }
Esempio n. 26
0
        protected override void Connected()
        {
            base.Connected();

            DispatcherHelper.CheckBeginInvokeOnUI(() =>
            {
                BnetEvent b = new BnetEvent();
                b.EventId   = 0x19;
                b.Username  = string.Empty;
                b.Message   = "Connected to Battle.net.";

                Messenger.Default.Send <BnetEvent>(b, connectionToken);

                // Build 0x50
                BnetPacket bntPkt = new BnetPacket();
                bntPkt.InsertInt32(0x00);
                bntPkt.InsertInt32(0x49583836);

                if (botAccount.Product == BnetProduct.Starcraft)
                {
                    bntPkt.InsertBytes(System.Text.Encoding.UTF8.GetBytes("RATS"));
                }
                else if (botAccount.Product == BnetProduct.BroodWar)
                {
                    bntPkt.InsertBytes(System.Text.Encoding.UTF8.GetBytes("PXES"));
                }
                else if (botAccount.Product == BnetProduct.Warcraft2)
                {
                    bntPkt.InsertBytes(System.Text.Encoding.UTF8.GetBytes("NB2W"));
                }
                else if (botAccount.Product == BnetProduct.Diablo2)
                {
                    bntPkt.InsertBytes(System.Text.Encoding.UTF8.GetBytes("VD2D"));
                }
                else if (botAccount.Product == BnetProduct.Warcraft3)
                {
                    bntPkt.InsertBytes(System.Text.Encoding.UTF8.GetBytes("3RAW"));
                }

                if (ViewModelLocator.MainWindowViewModelStatic.AccountsModel.VersionBytes.ContainsKey(botAccount.Product))
                {
                    bntPkt.InsertInt32(ViewModelLocator.MainWindowViewModelStatic.AccountsModel.VersionBytes[botAccount.Product]);
                }
                else
                {
                    // Insert 0x00 just so that we don't have an invalid packet structure .. but we know we'll need to reconnect.
                    if (botAccount.Product == BnetProduct.Starcraft || botAccount.Product == BnetProduct.BroodWar)
                    {
                        bntPkt.InsertInt32(0xD3);
                    }
                    else if (botAccount.Product == BnetProduct.Diablo2 || botAccount.Product == BnetProduct.LordOfDest)
                    {
                        bntPkt.InsertInt32(0x0D);
                    }
                    else if (botAccount.Product == BnetProduct.Warcraft2)
                    {
                        bntPkt.InsertInt32(0x4F);
                    }
                    else if (botAccount.Product == BnetProduct.Warcraft3 || botAccount.Product == BnetProduct.FrozenThrone)
                    {
                        bntPkt.InsertInt32(0x13);
                    }
                }

                bntPkt.InsertInt32(0x00);
                bntPkt.InsertInt32(0x00);
                bntPkt.InsertInt32(0x00);
                bntPkt.InsertInt32(0x00);
                bntPkt.InsertInt32(0x00);
                bntPkt.InsertString("USA");
                bntPkt.InsertString("United States");

                using (DataBuffer sendProtocolBuffer = new DataBuffer())
                {
                    sendProtocolBuffer.InsertByte(0x01);     // Protocol ID
                    sendProtocolBuffer.InsertBytes(bntPkt.GetBuffer(0x50));

                    Send(sendProtocolBuffer.GetBuffer());
                    bntPkt.Dispose();
                }

                Receive(4, null);
            });
        }
Esempio n. 27
0
 private void Brick_OnConnect(object sender, ConnectedEventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(
         () => IsConnected = e.State);
 }
Esempio n. 28
0
        /// <summary>
        /// Load movies asynchronously
        /// </summary>
        public override async Task LoadMoviesAsync(bool reset = false)
        {
            await LoadingSemaphore.WaitAsync();

            StopLoadingMovies();
            if (reset)
            {
                Movies.Clear();
                Page = 0;
            }

            var watch = Stopwatch.StartNew();

            Page++;
            if (Page > 1 && Movies.Count == MaxNumberOfMovies)
            {
                Page--;
                LoadingSemaphore.Release();
                return;
            }

            Logger.Info(
                $"Loading movies seen page {Page}...");
            HasLoadingFailed = false;
            try
            {
                IsLoadingMovies = true;
                var imdbIds =
                    await UserService.GetSeenMovies(Page);

                if (!_needSync)
                {
                    var movies = new List <MovieJson>();
                    await imdbIds.movies.ParallelForEachAsync(async imdbId =>
                    {
                        var movie = await MovieService.GetMovieAsync(imdbId);
                        if (movie != null)
                        {
                            movie.IsFavorite = true;
                            movies.Add(movie);
                        }
                    });

                    var updatedMovies = movies.OrderBy(a => a.Title)
                                        .Where(a => (Genre != null
                                        ? a.Genres.Any(
                                                         genre => genre.ToLowerInvariant() ==
                                                         Genre.EnglishName.ToLowerInvariant())
                                        : a.Genres.TrueForAll(b => true)) && a.Rating >= Rating);
                    Movies.AddRange(updatedMovies.Except(Movies.ToList(), new MovieComparer()));
                }
                else
                {
                    var moviesToDelete = Movies.Select(a => a.ImdbCode).Except(imdbIds.allMovies);
                    var moviesToAdd    = imdbIds.allMovies.Except(Movies.Select(a => a.ImdbCode));
                    foreach (var movie in moviesToDelete.ToList())
                    {
                        Movies.Remove(Movies.FirstOrDefault(a => a.ImdbCode == movie));
                    }

                    var movies = moviesToAdd.ToList();
                    await movies.ParallelForEachAsync(async imdbId =>
                    {
                        var movie = await MovieService.GetMovieAsync(imdbId);
                        if ((Genre != null
                                    ? movie.Genres.Any(
                                 genre => genre.ToLowerInvariant() ==
                                 Genre.EnglishName.ToLowerInvariant())
                                    : movie.Genres.TrueForAll(b => true)) && movie.Rating >= Rating)
                        {
                            DispatcherHelper.CheckBeginInvokeOnUI(() =>
                            {
                                Movies.Add(movie);
                            });
                        }
                    });
                }

                IsLoadingMovies       = false;
                IsMovieFound          = Movies.Any();
                CurrentNumberOfMovies = Movies.Count;
                MaxNumberOfMovies     = imdbIds.nbMovies;
                await UserService.SyncMovieHistoryAsync(Movies);
            }
            catch (Exception exception)
            {
                Page--;
                Logger.Error(
                    $"Error while loading movies seen page {Page}: {exception.Message}");
                HasLoadingFailed = true;
                Messenger.Default.Send(new ManageExceptionMessage(exception));
            }
            finally
            {
                Movies.Sort((a, b) => String.Compare(a.Title, b.Title, StringComparison.Ordinal));
                _needSync = false;
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Info(
                    $"Loaded movies seen page {Page} in {elapsedMs} milliseconds.");
                LoadingSemaphore.Release();
            }
        }
        /// <summary>,
        /// delete a MSBuildLogsExtended.DataSourceEntities.Build.
        /// </summary>
        protected override void Delete()
        {
            #region Asyncronized wcf method call

            string             viewName = ViewName_Delete;
            Framework.UIAction uiAction = Framework.UIAction.Delete;

            Messenger.Default.Send <Framework.UIActionStatusMessage>(new Framework.UIActionStatusMessage(EntityName, viewName, uiAction, Framework.UIActionStatus.Starting));

            MSBuildLogsExtended.WcfContracts.IBuildServiceAsyn _Instance = MSBuildLogsExtended.WcfContracts.WcfServiceResolverAsyn.ResolveWcfServiceBuild();

            AsyncCallback asyncCallback = delegate(IAsyncResult result)
            {
#if WINDOWS_PHONE
                DispatcherHelper.Initialize();
#endif
                try
                {
                    DispatcherHelper.CheckBeginInvokeOnUI((Action) delegate()
                    {
                        var responseMessage = _Instance.EndDeleteEntity(result);

                        this.Search();

                        Messenger.Default.Send <Framework.UIActionStatusMessage>(new Framework.UIActionStatusMessage(EntityName, viewName, uiAction, Framework.UIActionStatus.Success));
                    });
                }
                catch (Exception ex)
                {
                    DispatcherHelper.CheckBeginInvokeOnUI((Action) delegate()
                    {
                        Messenger.Default.Send <Framework.UIActionStatusMessage>(new Framework.UIActionStatusMessage(EntityName, viewName, uiAction, Framework.UIActionStatus.Failed, ex.Message));
                    });
                }
            };

            try
            {
#if WINDOWS_PHONE
                AssignSelectedValueFromSelectedItemToEntity(this.m_CurrentInEditingDefault);
#endif

                MSBuildLogsExtended.CommonBLLEntities.BuildRequestMessageBuiltIn _Request = new MSBuildLogsExtended.CommonBLLEntities.BuildRequestMessageBuiltIn()
                {
                    Critieria = new MSBuildLogsExtended.DataSourceEntities.BuildCollection(),
                    BusinessLogicLayerRequestID    = Guid.NewGuid().ToString(),
                    BusinessLogicLayerRequestTypes = Framework.CommonBLLEntities.BusinessLogicLayerRequestTypes.Delete,
                };
                _Request.Critieria.Add(MSBuildLogsExtended.EntityContracts.IBuildHelper.Clone <MSBuildLogsExtended.DataSourceEntities.Build.Default, MSBuildLogsExtended.DataSourceEntities.Build>(this.m_CurrentDefault));
                _Instance.BeginDeleteEntity(_Request, asyncCallback, null);
            }
            catch (Exception ex)
            {
                Messenger.Default.Send <Framework.UIActionStatusMessage>(new Framework.UIActionStatusMessage(EntityName, viewName, uiAction, Framework.UIActionStatus.Failed, ex.Message));
            }

            #endregion Asyncronized wcf method call

            #region Syncronized wcf method call -- not in use/WPF only

            /*
             * MSBuildLogsExtended.CommonBLLIoC.IoCBuild.DeleteEntity(this.m_CurrentDefault);//
             * this.m_EntityCollectionDefault.Remove(this.m_CurrentDefault);
             */

            #endregion Syncronized wcf method call -- not in use/WPF only
        }
Esempio n. 30
0
        void OnSettingChanged(SettingChangedMessage message)
        {
            switch (message.Name)
            {
            case "IconRows":
                int  iconRows = (int)message.Value;
                bool slideIn  = iconRows < IconRows;

                ClearAnimations();

                IconRows = iconRows;

                /*
                 * Position position = CalculateSlideOutPosition();
                 * //Position position = slideIn ? CalculateSlideInPosition() : CalculateSlideOutPosition();
                 * //Position position = new Position();
                 *
                 * if (_appbar.ReserveScreen)
                 * {
                 *  Width = 0;
                 *  Height = 0;
                 *
                 *  _appbar.Resize(ref position);
                 * }
                 *
                 * if (slideIn)
                 *  _actionQueue.QueueAction(SlideOut);
                 * else
                 *  _actionQueue.QueueAction(SlideOut);
                 */

                if (_appbar.ReserveScreen)
                {
                    Position position = CalculateSlideOutPosition();

                    Width  = 0;
                    Height = 0;

                    _appbar.Resize(ref position);
                }

                _actionQueue.QueueAction(SlideOut);
                break;

            case "ActiveScreen":
                ActiveScreen         = Helper.GetScreenFromName((string)message.Value);
                _appbar.ActiveScreen = ActiveScreen;

                _actionQueue.QueueAction(SlideInMinimize);
                _actionQueue.QueueAction(MinimizeWindow);
                _actionQueue.QueueAction(SlideOut);
                break;

            case "DockPosition":
                DockPosition oldValue = DockPosition;
                DockPosition newValue = (DockPosition)message.Value;

                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    Log.DebugFormat("ChangeDockPosition, {0} to {1}", oldValue, newValue);

                    DockPosition = newValue;
                    _appbar.Dock(DockPosition);

                    _actionQueue.QueueAction(SlideInMinimize, oldValue);
                    _actionQueue.QueueAction(MinimizeWindow);
                    _actionQueue.QueueAction(SlideOut);
                });
                break;

            case "AutoHide":
                AutoHide = (bool)message.Value;
                break;

            case "AutoHideDelay":
                // TODO: I'm not even saving it in the dependancy property, maybe I
                // should remove the  dependancy property?
                _appbar.AutoHideDelay = (int)message.Value;
                break;

            case "PopupDelay":
                // TODO: I'm not even saving it in the dependancy property, maybe I
                // should remove the  dependancy property?
                _appbar.PopupDelay = (int)message.Value;
                break;

            case "ReserveScreen":
                _appbar.ReserveScreen = (bool)message.Value;
                if (_appbar.ReserveScreen)
                {
                    _actionQueue.QueueAction(MinimizeWindow);
                    _actionQueue.QueueAction((parameter) =>
                    {
                        _appbar.Reserve();
                        //HandleFullScreenRdpApps();
                    });
                    _actionQueue.QueueAction(SlideOut);
                }
                else
                {
                    _actionQueue.QueueAction(SlideInMinimize);
                    _actionQueue.QueueAction((parameter) => _appbar.Unreserve());
                    _actionQueue.QueueAction(SlideOut);
                }
                break;
            }
        }