예제 #1
0
 private void FieldsInitialisation()
 {
     btCopyItems.Content = ClientUIPresenter.GetString("COPYTHIS");
     btCopyUsers.Content = ClientUIPresenter.GetString("COPYTHIS");
     lDesigned.Text      = ClientUIPresenter.GetString("DesignedandProgrammedby");
     ;
 }
예제 #2
0
        public MainWindow()
        {
            const string WINDOWS_FIREWALL_SERVICE = "MpsSvc";


            using (var sc = new ServiceController(WINDOWS_FIREWALL_SERVICE))
            {
                if ((sc.Status == ServiceControllerStatus.Running))
                {
                    Log.Instance.W(this, "Found working Windows Firewall Service");
                    MessageBoxResult result = MessageBox.Show(ClientUIPresenter.GetString("FoundworkingWindowsFirewallServiceWouldyouliketostopit")
                                                              , ClientUIPresenter.GetString("Question")
                                                              , MessageBoxButton.YesNo);
                    switch (result)
                    {
                    case MessageBoxResult.Yes:
                        if (ClientMaintaining.IsRunningAsLocalAdmin())
                        {
                            Log.Instance.W(this, ClientUIPresenter.GetString("Tryingtostop")
                                           );
                            try
                            {
                                sc.Stop();
                                ServiceHelper.ChangeStartMode(sc, ServiceStartMode.Disabled);
                                System.Windows.MessageBox.Show(
                                    ClientUIPresenter.GetString("WindowsFirewallServicehasbeenstopped")
                                    ,
                                    ClientUIPresenter.GetString("Success")
                                    , MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                            }
                            catch (Exception e)
                            {
                                Log.Instance.W(this, ClientUIPresenter.GetString("Errorwhilestoptrying")

                                               + e.Message);
                                System.Windows.MessageBox.Show(
                                    "Error while stop trying: " + e.Message,
                                    "Attention", MessageBoxButton.OK,
                                    MessageBoxImage.Warning);
                            }
                            //sc.sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
                            if (sc.Status == ServiceControllerStatus.Stopped)
                            {
                                Console.WriteLine("Service '{0}' has been stopped", sc.DisplayName);
                            }
                        }
                        else
                        {
                            System.Windows.MessageBox.Show(
                                ClientUIPresenter.GetString("TostoptheWindowsFirewallServiceyoumustRunthisappasAdministrator")
                                ,
                                ClientUIPresenter.GetString("Insufficientrightstostoptheservice")
                                , MessageBoxButton.OK,
                                MessageBoxImage.Warning);
                        }
                        break;

                    case MessageBoxResult.No:
                        System.Windows.MessageBox.Show(
                            ClientUIPresenter.GetString("Youmayencountersomeproblemswhensearchingforotherpeoplesservers")
                            ,
                            ClientUIPresenter.GetString("Attention")
                            , MessageBoxButton.OK,
                            MessageBoxImage.Warning);
                        break;
                    }
                }
            }

            settings.LocaleChanged += ChangeFormLocale;
            ClientMaintaining.ClientStateChanged += ClientEventsHandler;
            InitializeComponent();
            cbLanguage.ItemsSource = new List <string> {
                "ru-RU", "en-US", "ms-MY"
            };
            FillUpTextFields();
            ChatGrid.Width = 0;
            SetDefaultValues();

            ChatClientHandler.ChatMessageCame += (string s) =>
            {
                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    lbChatMessages.ItemsSource = new List <string>();
                    lbChatMessages.ItemsSource = ChatClientHandler.ChatBoxContainment;
                    lbChatMessages.ScrollIntoView(lbChatMessages.Items[lbChatMessages.Items.Count - 1]);
                }));
            };

            void SetDefaultValues()
            {
                tbLeaderName.Text = ClientMaintaining.IsRunningAsLocalAdmin() ? Miscelanious.GetComputerName() : string.Empty;
                tbPort.Text       = ClientMaintaining.IsRunningAsLocalAdmin() ? "666" : string.Empty;
                tbYourName.Text   = Miscelanious.GetComputerName();
            }

            void ChangeFormLocale(string locale)
            {
                FillUpTextFields();
            }

            void FillUpTextFields()
            {
                ClientUIPresenter presenter = new ClientUIPresenter(this);

                presenter.FillUpTextFields();
            }

            StartupManual manual = new StartupManual();

            if (!File.Exists(Path.Combine(Assembly.GetExecutingAssembly().Location
                                          .Replace(Assembly.GetExecutingAssembly().ManifestModule.Name, "") +
                                          "firstrun")))
            {
                manual.ShowDialog();
                File.Create(Path.Combine(Assembly.GetExecutingAssembly().Location
                                         .Replace(Assembly.GetExecutingAssembly().ManifestModule.Name, "") +
                                         "firstrun"));
            }


            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(2000);
            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed  += MonitoringStringAutoUpdating;
            aTimer.AutoReset = true;
            aTimer.Enabled   = true;
        }
예제 #3
0
        private async void BtHost_Click(object sender, RoutedEventArgs e)
        {
            LeaderServer.Leader.ServerDNSName = tbLeaderName.Text.Trim();
            LeaderServer.Leader.VisibleName   = tbYourName.Text.Trim();
            LeaderServer.Leader.ServerIP      = Miscelanious.ResolveIP(tbLeaderName.Text.Trim()).FirstOrDefault();


            if (ClientMaintaining.IsRunningAsLocalAdmin())
            {
                if (ServerMaintaining.host.State != CommunicationState.Opened &&
                    ServerMaintaining.host.State != CommunicationState.Opening)
                {
                    imgCircleArrows.RenderTransform = new RotateTransform();

                    IsScanningForServers = false;
                    ClientMaintaining.scan.ScanCancel();

                    bool ServerSuccessfullyStarted = false;

                    try
                    {
                        ServerSuccessfullyStarted =
                            await Task.Run(async() =>
                        {
                            ServerMaintaining.ServerStart();
                            return(true);
                        });
                    }
                    catch (InvalidOperationException exception)
                    {
                        System.Windows.MessageBox.Show(
                            ClientUIPresenter.GetString("ThehostnameandportarealreadyinuseWaitforalittle")
                            + exception.Message,
                            ClientUIPresenter.GetString("Error")
                            , MessageBoxButton.OK,
                            MessageBoxImage.Error);
                        ClientMaintaining.Disconnect();
                    }
                    catch (AddressAlreadyInUseException exception)
                    {
                        System.Windows.MessageBox.Show(
                            ClientUIPresenter.GetString("Thehostnameandportarealreadyinuse")
                            ,
                            ClientUIPresenter.GetString("Error")
                            , MessageBoxButton.OK,
                            MessageBoxImage.Error);
                        ClientMaintaining.Disconnect();
                    }

                    if (ServerSuccessfullyStarted)
                    {
                        ClientMaintaining.isSelfServer = true;
                        expander.IsExpanded            = false;
                        Expander_Collapsed(this, null);


                        LeaderServer.Leader.ServerState = ServerStates.DelivererSet;
                        //ServerStatus.Current.ServerState = ServerStates.DelivererSet;


                        GridContainerForUC.Children.Clear();
                        GridContainerForUC.Children.Add(new ucSelector());



                        Log.Instance.W(this, "Server is launched now trying to connect to ourselves");
                        ClientMaintaining.Join(tbYourName.Text, true);

                        //if (ClientMaintaining.GetConnectionStatus())
                        //{
                        //    ClientMaintaining.SendMessage("Hello to Everyone!");
                        //}
                    }
                }
                else
                {
                    string infoString = ClientUIPresenter.GetString("Yourserverisalreadystarted")
                    ;
                    if (LeaderServer.Leader.ServerDNSName != string.Empty)
                    {
                        infoString += Environment.NewLine + ClientUIPresenter.GetString("Itiscalled")
                                      + LeaderServer.Leader.VisibleName +
                                      Environment.NewLine + ClientUIPresenter.GetString("Theotherusersoughttolookfor")
                                      +
                                      LeaderServer.Leader.ServerDNSName;
                        foreach (var ip in NetworkComputers.ResolveIP(LeaderServer.Leader.ServerDNSName).Select(x => x.ToString()).Distinct())
                        {
                            infoString += Environment.NewLine + ClientUIPresenter.GetString("or")
                                          + ip;
                        }
                    }

                    System.Windows.MessageBox.Show(infoString
                                                   , "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            else
            {
                System.Windows.MessageBox.Show(ClientUIPresenter.GetString("TolaunchyourownserveryouneedtoRunthisappasAdministrator")
                                               ,
                                               ClientUIPresenter.GetString("Insufficientrightstolaunchaserver")
                                               , MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
예제 #4
0
        private void DisplayListOfElements(ClientState state)
        {
            List <Deliverer> ListDeliverers;

            switch (state)
            {
            case ClientState.DelivererSet:
            {
                ListDeliverers = SQLiteHelper.GetReader <Deliverer>("Deliverers");
                {
                    Pickableitems.Clear();

                    var r = new Regex($"(?:{currentSearch})+", RegexOptions.IgnoreCase);
                    foreach (var listDeliverer in ListDeliverers.Where(x => r.IsMatch(x.Name) || r.IsMatch(x.Description)))
                    {
                        Pickableitems.Add(new StoreItem(listDeliverer));
                    }
                }
                lbElementsToChoose.IsEnabled = true;
                btToStartToOrder.IsEnabled   = true;
                btToStartToOrder.Content     = ClientUIPresenter.GetString("Pickadeliverer")
                ;
                break;
            }

            case ClientState.DelivererWait:
            {
                Pickableitems.Clear();
                lbElementsToChoose.IsEnabled = false;
                ListDeliverers = SQLiteHelper.GetReader <Deliverer>("Deliverers");

                var r = new Regex($"(?:{currentSearch})+", RegexOptions.IgnoreCase);
                foreach (var listDeliverer in ListDeliverers.Where(x => r.IsMatch(x.Name) || r.IsMatch(x.Description)))
                {
                    Pickableitems.Add(new StoreItem(listDeliverer));
                }
            }

                LableOfPick.Text = "";
                //Pickableitems.Clear();

                btToStartToOrder.IsEnabled = false;
                btToStartToOrder.Content   = ClientUIPresenter.GetString("WaitingforLeader")
                ;
                break;


            case ClientState.OrderSet:
            {
                lbElementsToChoose.IsEnabled = true;
                LableOfPick.Text             = ClientUIPresenter.GetString("PICKORDERPOSITIONS")
                ;
                var deliverer = ClientMaintaining.CurrentDeliverer;
                if (deliverer != null)
                {
                    List <Item> ListItems = SQLiteHelper.GetReader <Item>("Items", "SELECT * FROM ",
                                                                          deliverer.ID);


                    Pickableitems.Clear();

                    var r = new Regex($"(?:{currentSearch})+", RegexOptions.IgnoreCase);
                    foreach (var listItem in ListItems.Where(x => r.IsMatch(x.Name) || r.IsMatch(x.Description)))
                    {
                        Pickableitems.Add(new Items(listItem));
                    }
                    btToStartToOrder.IsEnabled = true;
                    if (ClientMaintaining.isSelfServer)
                    {
                        btToStartToOrder.IsEnabled = true;

                        btToStartToOrder.Content = ClientUIPresenter.GetString("Starttocalculate");
                    }
                    else
                    {
                        btToStartToOrder.IsEnabled = true;
                        btToStartToOrder.Content   = ClientUIPresenter.GetString("Myorderisdone")
                        ;
                    }
                }

                break;
            }

            case ClientState.WaitingForCalculation:
            {
                Pickableitems.Clear();
                btToStartToOrder.IsEnabled = false;
                break;
            }

            //case ClientState.WaitingForCalculation:
            //{
            //    btToStartToOrder.IsEnabled = false;
            //    break;
            //}

            default:
                btToStartToOrder.IsEnabled = false;
                btToStartToOrder.Content   = ClientUIPresenter.GetString("WaitingforLeader");
                break;
            }
        }
예제 #5
0
 private void FieldsInitialise()
 {
     LableOfPick.Text = ClientUIPresenter.GetString("STORESLISTpickone");
     lSearch.Text     = ClientUIPresenter.GetString("Search");
     lDiscount.Text   = ClientUIPresenter.GetString("Discount");
 }
예제 #6
0
        private void BtToStartToOrder_Click(object sender, RoutedEventArgs e)
        {
            ServerStates state = 0;



            if (ClientMaintaining.isSelfServer)
            {
                state = LeaderServer.Leader.ServerState;
            }
            else
            {
                if (LeaderServer.CurrentServer != null)
                {
                    state = LeaderServer.CurrentServer.ServerState;
                }
            }

            if (state == ServerStates.OrdersSet)
            {
                if (ClientMaintaining.isSelfServer)
                {
                    if (ServerStatus
                        .users.Count > 1 &&
                        ServerStatus
                        .users.Count(x => x.ID != ClientMaintaining.ID && x.Ready == false) > 0)
                    {
                        MessageBoxResult result = MessageBox.Show(
                            ClientUIPresenter.GetString("NotallusersarereadytocalculatetheirordersContinueforcibly")

                            , ClientUIPresenter.GetString("Question"), MessageBoxButton.YesNo);
                        if (result == MessageBoxResult.Yes)
                        {
                            btToStartToOrder.IsEnabled      = false;
                            LeaderServer.Leader.ServerState = ServerStates.ReadyToCalculate;
                        }
                    }
                    else
                    {
                        btToStartToOrder.IsEnabled      = false;
                        LeaderServer.Leader.ServerState = ServerStates.ReadyToCalculate;
                    }
                }
                else
                {
                    if (ClientMaintaining.ClientReadiness)
                    {
                        ClientMaintaining.ClientReadiness = false;
                        btToStartToOrder.Content          = ClientUIPresenter.GetString("Myorderisdone")
                        ;
                    }
                    else
                    {
                        ClientMaintaining.ClientReadiness = true;
                        btToStartToOrder.Content          = ClientUIPresenter.GetString("Changemyorder")
                        ;
                    }
                }
            }
            if (state == ServerStates.DelivererSet &&
                ClientMaintaining.isSelfServer
                //&& LeaderServer.Leader.ServerState == ServerStates.DelivererSet
                && CurrentDeliverer != null)
            {
                //btToStartToOrder.IsEnabled = false;
                ServerStatus.Current.ServerDeliverer = CurrentDeliverer;
                LeaderServer.Leader.ServerState      = ServerStates.OrdersSet;
            }
            //switch (LeaderServer.Leader.ServerState)
        }
예제 #7
0
        //public static bool GetConnectionStatus()
        //{
        //    return isConnected;
        //}

        public static void Join(string Name, bool SelfServer = false)
        {
            //if (ClientStateChanged==null)
            if (!Subscribed)
            {
                ClientStateChanged += CurrentStateChanged;
                Subscribed          = true;
            }


            //if (bw.DoWork==null)
            //{
            //    bw.DoWork += Update;
            //}
            //bw.Dispose();
            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += RepetableUpdate;
            //bw.DoWork += Timer;
            ClientStateChanged?.Invoke(ClientState.Connecting);

            if (SelfServer)
            {
                client = new BookMyFood.ServiceChat.ServiceChatClient(
                    new System.ServiceModel.InstanceContext(new ChatClientHandler()));

                isSelfServer = true;
                //ClientStateChanged?.Invoke(ClientState.Connecting);
            }
            else
            {
                client = new BookMyFood.ServiceChat.ServiceChatClient(
                    new System.ServiceModel.InstanceContext(new ChatClientHandler())
                    , "WSDualHttpBinding_IServiceChat",
                    $"http://{LeaderServer.Leader.ServerIP}:{LeaderServer.Leader.Port}/Chat");
                isSelfServer = false;
                Log.Instance.W(client, $"Client Endpoint http://{LeaderServer.Leader.ServerIP}:{LeaderServer.Leader.Port}/");
                //Log.Instance.W(client, $"Client Endpoint net.tcp://{LeaderServer.Leader.ServerIP}:{LeaderServer.Leader.Port}/");
                //client.Endpoint.Address = new EndpointAddress($"net.tcp://{LeaderServer.Leader.ServerIP}:{LeaderServer.Leader.Port}/");
                //client
                //    = new ServiceChatClient(
                //    new InstanceContext(new ChatClientHandler()), "NetTcpBinding_IServiceChat",
                //    $"net.tcp://{LeaderServer.Leader.ServerIP}:{LeaderServer.Leader.Port}/");
                //ServiceChatClient<IServiceChat> cf =
                //    new ServiceChatClient<IServiceChat>(
                //        new Uri("http://localhost:8090/MyService/EmployeeService"));
                //IServiceChat client = cf.CreateChannel();
                //var d = client.GetEmployee(1);
            }


            try
            {
                Log.Instance.W(client, "Trying to connect ");
                ID = client.Connect(Name, isSelfServer);
                Log.Instance.W(client, "Connected ");

                isConnected      = true;
                FinalUsersStatus = new List <ServiceChat.ServerUser>();

                if (SelfServer)
                {
                    ClientStateChanged?.Invoke(ClientState.DelivererSet);
                }
                else
                {
                    ClientStateChanged?.Invoke(ClientState.DelivererWait);
                }
            }
            catch (EndpointNotFoundException exception)
            {
                isSelfServer = false;
                MessageBox((IntPtr)0, exception.Message, ClientUIPresenter.GetString("Timeout")
                           , 0);
            }
            catch (System.ServiceModel.Security.SecurityNegotiationException exception)
            {
                isSelfServer = false;
                MessageBox((IntPtr)0, ClientUIPresenter.GetString("Thedomainnameyouhaveusedisnotavailableinthisnetwork")
                           + Environment.NewLine + exception.Message +
                           Environment.NewLine + exception.InnerException.InnerException, ClientUIPresenter.GetString("NoDomainName")
                           , 0);
            }
            catch (Exception exception)
            {
                isSelfServer = false;
                MessageBox((IntPtr)0, ClientUIPresenter.GetString("Anerroroccuredwhiletryingtoconnect")
                           + Environment.NewLine + exception.Message, ClientUIPresenter.GetString("Commonerror")
                           , 0);
            }

            bw.RunWorkerAsync();
            //Update();
        }
예제 #8
0
        public static string GetMonitoringInfo()
        {
            string s = "";

            if (client == null)
            {
                s += ClientUIPresenter.GetString("Disconnected")
                ;
                return(s);
            }

            if (isConnected)
            {
                var leader = LeaderServer.Leader;
                if (leader != null)
                {
                    s += ClientUIPresenter.GetString("Connectedto")
                    ;
                    if (isSelfServer)
                    {
                        s += ClientUIPresenter.GetString("Myself")
                        ;
                        s += " | ";

                        switch (LeaderServer.Leader.ServerState)
                        {
                        case ServerStates.DelivererSet:
                            s += ClientUIPresenter.GetString("ServerStatusSelectingStore")
                            ;
                            break;

                        case ServerStates.OrdersSet:
                            s += ClientUIPresenter.GetString("ServerStatusPickinganitemstoorder")
                            ;
                            break;

                        case ServerStates.ReadyToCalculate:
                            s += ClientUIPresenter.GetString("ServerStatusGatheringparticipantsreadinessinfo")
                            ;
                            break;

                        case ServerStates.Verifying:
                            s += ClientUIPresenter.GetString("ServerStatusAnorderswerecalculated")
                            ;
                            break;
                        }
                        s += " | ";
                        int ready = ServerStatus.users.Count(x => x.Ready);
                        var all   = ServerStatus.users.Count;
                        s += ClientUIPresenter.GetString("Participantsreadiness")
                             + ready + ClientUIPresenter.GetString("outof")
                             + all;
                        s += " | ";
                    }
                    else
                    {
                        s += string.IsNullOrEmpty(leader.VisibleName) ? leader.VisibleName : leader.ServerDNSName;
                        s += " | ";

                        if (LeaderServer.CurrentServer != null)
                        {
                            switch (LeaderServer.CurrentServer.ServerState)
                            {
                            case ServerStates.DelivererSet:
                                s += ClientUIPresenter.GetString("ServerStatusSelectingStore");
                                break;

                            case ServerStates.OrdersSet:
                                s += ClientUIPresenter.GetString("ServerStatusPickinganitemstoorder");
                                break;

                            case ServerStates.ReadyToCalculate:
                                s += ClientUIPresenter.GetString("ServerStatusGatheringparticipantsreadinessinfo");
                                break;

                            case ServerStates.Verifying:
                                s += ClientUIPresenter.GetString("ServerStatusAnorderswerecalculated");
                                break;
                            }

                            s += " | ";
                        }
                    }



                    return(s);
                }
                else
                {
                    s += ClientUIPresenter.GetString("Disconnected");
                    return(s);
                }
            }

            else
            {
                s += ClientUIPresenter.GetString("Disconnected");
                return(s);
            }
        }
예제 #9
0
        public static async Task Update()
        {
            if (!currentlyUpdating)
            {
                currentlyUpdating = true;
                //1
                ServiceChat.ServerStatus serverInfo = null;
                if (isConnected)
                {
                    if (client != null)
                    {
                        {
                            try
                            {
                                serverInfo = await client.GetServerStatusAsync(ClientReadiness);
                            }
                            catch (Exception e)
                            {
                                Log.Instance.W(client ?? new object {}, "An error occurred while the client was trying to update its data");
                                Log.Instance.W(client ?? new object { }, e.Message);

                                return;
                            }
                        }
                    }
                }

                if (serverInfo != null && serverInfo.ServerDeliverer != null)
                {
                    //CurrentDeliverer.ID != serverInfo.ServerDeliverer.ID
                    CurrentDeliverer = serverInfo.ServerDeliverer;
                    //if (isSelfServer)
                    //{
                    //    //LeaderServer.CurrentServer.ServerState == ServerStates.DelivererSet
                    //    ClientStateChanged?.Invoke(ClientState.DelivererSet);
                    //}
                    //else
                    //{
                    //    ClientStateChanged?.Invoke(ClientState.DelivererWait);
                    //}
                }

                //2
                if (serverInfo != null)
                {
                    if (LeaderServer.CurrentServer == null)
                    {
                        LeaderServer.CurrentServer = new LeaderServer();
                    }
                    LeaderServer.CurrentServer.ServerState = (ServerStates)serverInfo.ServerState;



                    ClientUsersChanged?.Invoke(serverInfo.Users);
                }
                else
                {
                    //LeaderServer.CurrentServer = null;
                }


                //3
                //client.SendUser(ServerUser.Current);
                if (serverInfo != null)
                {
                    ServerUser.Current.ID = ID;

                    var CurrentUser = serverInfo.Users.FirstOrDefault(x => x.ID == ID);
                    if (CurrentUser == null || CurrentUser.MissionForClient == 1)
                    {
                        bw.CancelAsync();
                        Disconnect();

                        currentlyUpdating = false;
                        return;
                    }

                    CurrentDiscount = serverInfo.Discount;

                    if (ClientReadiness)
                    {
                        FinalUsersStatus = serverInfo.Users;
                    }

                    switch (serverInfo.ServerState)
                    {
                    case ServiceChat.ServerStates.DelivererSet:
                        if (isSelfServer)
                        {
                            //LeaderServer.CurrentServer.ServerState == ServerStates.DelivererSet
                            ClientStateChanged?.Invoke(ClientState.DelivererSet);
                        }
                        else
                        {
                            ClientStateChanged?.Invoke(ClientState.DelivererWait);
                        }
                        break;

                    case ServiceChat.ServerStates.OrdersSet:
                        ClientStateChanged?.Invoke(ClientState.OrderSet);
                        break;

                    case ServiceChat.ServerStates.ReadyToCalculate:

                        //if (FinalUsersStatus.Count <= serverInfo.Users.Count)
                        //    FinalUsersStatus = serverInfo.Users;
                        ClientReadiness = true;
                        //ClientStateChanged?.Invoke(ClientState.WaitingForCalculation);
                        //if (isSelfServer && ServerStatus.Current.Users.Count(x => !x.Ready) == 0
                        //                 && ServerStatus.Current.Users.Count(x => x.MissionForClient!=2) == 0)
                        //{
                        //    ServerStatus.Current.ServerState = ServerStates.Verifying;
                        //}
                        if (CurrentUser.MissionForClient == 2)
                        {
                            FinalUsersStatus             = serverInfo.Users;
                            CurrentUser.MissionForClient = 3;
                        }

                        if (isSelfServer &&
                            (ServerStatus.Current.Users.Count(x => x.MissionForClient == 4))
                            == ServerStatus.Current.Users.Count())
                        {
                            ServerStatus.Current.ServerState = ServerStates.Verifying;
                        }

                        break;

                    case ServiceChat.ServerStates.Verifying:
                        //if(FinalUsersStatus.Count<= serverInfo.Users.Count)
                        //FinalUsersStatus = serverInfo.Users;
                        //isConnected = false;
                        //FinalUsersStatus = serverInfo.Users;
                        ClientStateChanged?.Invoke(ClientState.Calculated);
                        if (CurrentUser.MissionForClient == 4)
                        {
                            CurrentUser.MissionForClient = 5;
                        }

                        //if (isSelfServer
                        //    && (ServerStatus.Current.Users.Count(x => x.MissionForClient == 6))
                        //        == ServerStatus.Current.Users.Count()
                        //)
                        //{
                        //    foreach (var user in ServerStatus.users)
                        //    {
                        //        user.MissionForClient = 7;
                        //        CurrentUser.MissionForClient = 7;
                        //        //ServerStatus.Current.ServerState = ServerStates.Verifying;
                        //    }
                        //}

                        if (CurrentUser.MissionForClient == 6)
                        {
                            await Task.Run(() => { Thread.Sleep(25000); });

                            await ClientMaintaining.Disconnect(true);

                            //FinalUsersStatus = serverInfo.Users;
                            //CurrentUser.MissionForClient = 3;
                        }

                        if (isSelfServer && CurrentUser.MissionForClient == 6)
                        {
                            await Task.Run(() => { Thread.Sleep(15000); });

                            await ServerFunction.ServerMaintaining.ServerStop();
                        }

                        //await Task.Run(() => { Thread.Sleep(10000); });
                        //await ClientMaintaining.Disconnect(true);
                        //if (isSelfServer
                        //&& (ServerStatus.Current.Users.Count(x => x.MissionForClient == 8)
                        //    == ServerStatus.Current.Users.Count())
                        //)
                        //{
                        //    await Task.Run(() => { Thread.Sleep(3000); });
                        //    await ServerFunction.ServerMaintaining.ServerStop();
                        //}
                        //return;
                        break;
                    }

                    ServerUser.Current.Name     = CurrentUser.Name;
                    ServerUser.Current.isLeader = isSelfServer;
                    ServerUser.Current.Ready    = ClientReadiness;

                    if (ServerUser.Current.Order == null || ServerUser.Current.Order.Items == null)
                    {
                        ServerUser.Current.Order = new UserOrder()
                        {
                            Items = new List <Item>()
                        }
                    }
                    ;

                    var s = ServerUser.Current;
                    var o = new List <ServiceChat.Item>();
                    if (s.Order.Items != null)
                    {
                        foreach (var i in s.Order.Items)
                        {
                            o.Add(new ServiceChat.Item()
                            {
                                ID          = i.ID,
                                Quantity    = i.Quantity,
                                Price       = i.Price,
                                Name        = i.Name,
                                Description = i.Description
                            });
                        }
                    }

                    try
                    {
                        var c = new ServiceChat.ServerUser()
                        {
                            ID               = s.ID,
                            isLeader         = s.isLeader,
                            Name             = s.Name,
                            Ready            = s.Ready,
                            MissionForClient = CurrentUser.MissionForClient,
                            Order            = new ServiceChat.UserOrder()
                            {
                                Items = o
                            }
                        };
                        await client.SendUserAsync(c);
                    }
                    catch (Exception e)
                    {
                        Log.Instance.W(client, ClientUIPresenter.GetString("ErrorappearedwhenyouvetriedtosenduserdataTryagain")
                                       + e.Message);
                        currentlyUpdating = false;
                    }
                }

                currentlyUpdating = false;
            }
        }
예제 #10
0
        private void FillItemsInformationFields()
        {
            FlowDocument myFlowDoc = new FlowDocument();
            var          users     = ClientFuncion.ClientMaintaining.FinalUsersStatus;

            List <BookMyFood.ServiceChat.Item> itemsUnfiltered = new List <Item>();

            foreach (var user in users)
            {
                if (user.Order != null && user.Order.Items.Count > 0)
                {
                    itemsUnfiltered.AddRange(user.Order.Items);
                }
            }



            decimal   sumDisc = 0;
            Paragraph Para    = new Paragraph();

            foreach (var id in itemsUnfiltered.OrderBy(x => x.ID).Select(x => x.ID).Distinct())
            {
                var item = itemsUnfiltered.FirstOrDefault(x => x.ID == id);
                if (item != null)
                {
                    int quantity = 0;
                    quantity = itemsUnfiltered.Where(x => x.ID == id).Select(x => x.Quantity).Sum();
                    //Para.Inlines.Add(
                    //    new Bold((new Run($"[{id:0000}] \"{item.Name}\""))))
                    //;
                    //Para.Inlines.Add(
                    //    ((new Run($"{quantity} x {item.Price:F2} = {(item.Price * quantity):F2}")))
                    //);

                    if (ClientMaintaining.CurrentDiscount != 0)
                    {
                        decimal pricedisc = (item.Price - ((item.Price / 100) * (decimal)ClientMaintaining.CurrentDiscount));
                        string  percent   = (ClientMaintaining.CurrentDiscount / 100).ToString("P",
                                                                                               CultureInfo.InvariantCulture);
                        sumDisc += pricedisc * quantity;

                        Para.Inlines.Add(
                            (new Run(
                                 $"[{id:0000}] ")));

                        Para.Inlines.Add(new Bold(new Run(item.Name)));
                        Para.Inlines.Add((new Run(
                                              $" {item.Price:F2} - {percent} ")));

                        Para.Inlines.Add(new Bold(new Run($"x {quantity}")));

                        Para.Inlines.Add((new Run(
                                              $" = {(pricedisc * quantity):F2}")
                                          ));
                    }
                    else
                    {
                        Para.Inlines.Add(
                            (new Run(
                                 $"[{id:0000}] ")));

                        Para.Inlines.Add(new Bold(new Run(item.Name)));
                        Para.Inlines.Add((new Run(
                                              $" {item.Price:F2} x ")));

                        Para.Inlines.Add(new Bold(new Run($"{quantity}")));

                        Para.Inlines.Add((new Run(
                                              $" = {(item.Price * quantity):F2}")
                                          ));
                    }

                    //    ;
                    //Para.Inlines.Add(
                    //    ((new Run($"{quantity} x {item.Price:F2} = {(item.Price * quantity):F2}")))
                    //);

                    Para.Inlines.Add(
                        new LineBreak()
                        );
                }
                //for
            }



            Para.Inlines.Add(
                new Underline((new Run(ClientUIPresenter.GetString("Sum")
                                       + $" = [{itemsUnfiltered.Select(x => x.Price * x.Quantity).Sum():F2}]")))
                );

            if (sumDisc > 0)
            {
                Para.Inlines.Add(
                    new LineBreak()
                    );
                Para.Inlines.Add(
                    new Underline((new Run(ClientUIPresenter.GetString("Sumdiscounted")
                                           + $" = [{sumDisc:F2}]")))
                    );
            }
            //itemsUnfiltered.AddRange( users.Where(x => x.Order != null && x.Order.Items.Count > 0).Select(x => x.Order.Items));
            //var distinctNames = itemsNames.Select(x=>x.)

            myFlowDoc.Blocks.Add(Para);
            rtbOrderItemsInfo.Document = myFlowDoc;
        }
예제 #11
0
        private void FillUsersInformationFields()
        {
            FlowDocument myFlowDoc = new FlowDocument();

            var       users        = ClientFuncion.ClientMaintaining.FinalUsersStatus;
            decimal   totalSum     = 0;
            decimal   totalSumDisc = 0;
            Paragraph Para         = new Paragraph();

            foreach (var user in users.OrderBy(x => x.ID))
            {
                decimal sumdisc = 0;
                Para.Inlines.Add(
                    new Bold((new Run($"[{user.Name}]")))
                    );
                Para.Inlines.Add(
                    new LineBreak()
                    );
                if (user.Order != null && user.Order.Items.Count > 0)
                {
                    foreach (var item in user.Order.Items)
                    {
                        Para.Inlines.Add(
                            new Run($"— [{item.ID:0000}] "));

                        Para.Inlines.Add((new Run($"\"{item.Name}\". {item.Price}")));
                        if (ClientMaintaining.CurrentDiscount != 0)
                        {
                            decimal pricedisc = (item.Price - ((item.Price / 100) * (decimal)ClientMaintaining.CurrentDiscount));
                            string  percent   = (ClientMaintaining.CurrentDiscount / 100).ToString("P",
                                                                                                   CultureInfo.InvariantCulture);
                            Para.Inlines.Add(
                                new Run($" - {percent:F2}"));
                            sumdisc += (pricedisc * item.Quantity);
                        }



                        Para.Inlines.Add(
                            new Run($" x {item.Quantity}"));
                        if (ClientMaintaining.CurrentDiscount != 0)
                        {
                            decimal pricedisc = (item.Price -
                                                 ((item.Price / 100) * (decimal)ClientMaintaining.CurrentDiscount));
                            Para.Inlines.Add((new Run(
                                                  $"  = {(pricedisc * item.Quantity):F2}"))
                                             );
                        }
                        else
                        {
                            Para.Inlines.Add((new Run(
                                                  $"  = {(item.Price * item.Quantity):F2}"))
                                             );
                        }

                        Para.Inlines.Add(
                            new LineBreak()
                            );
                    }
                    totalSumDisc += sumdisc;

                    decimal sum = user.Order.Items.Select(x => x.Price * x.Quantity).Sum();
                    totalSum += sum;
                    Para.Inlines.Add(
                        new Underline((new Run(ClientUIPresenter.GetString("Sum")
                                               + $" = [{sum:F2}]")))
                        );
                    Para.Inlines.Add(
                        new LineBreak()
                        );
                    if (sumdisc > 0)
                    {
                        Para.Inlines.Add(
                            new Underline((new Run(ClientUIPresenter.GetString("Sumdiscounted")
                                                   + $" = [{sumdisc:F2}]")))
                            );
                        Para.Inlines.Add(
                            new LineBreak()
                            );
                    }
                }
                //Bold myBold = new Bold(new Run($"[{user.Name}]"));

                //Para.Inlines.Add(
                //    new Separator()
                //);
                Para.Inlines.Add(
                    new LineBreak()
                    );

                //if (users.Count(x => x.Order != null) != 0 && user.Order.Items.Count > 0)
                //{
                //decimal sum = 0;
                //foreach (var user in users.Where(x => x.Order != null).Where(x => x.Order.Items.Any()))
                //{
                //    sum+= user.Order.Items.Select(x=>x.Price*x.Quantity)
                //}
                //}



                //myFlowDoc.Blocks.Add(Para);
            }

            if (totalSum > 0)
            {
                Para.Inlines.Add(
                    new Underline(
                        new Bold(
                            new Run(ClientUIPresenter.GetString("TOTALSUM")
                                    + $" = [{totalSum:F2}]"
                                    ))))
                ;
                Para.Inlines.Add(
                    new LineBreak()
                    );
            }

            if (totalSumDisc > 0)
            {
                Para.Inlines.Add(
                    new Underline((new Run(ClientUIPresenter.GetString("TOTALSUMDISCOUNTED")
                                           + $" = [{totalSumDisc:F2}]")))
                    );
                Para.Inlines.Add(
                    new LineBreak()
                    );
            }
            myFlowDoc.Blocks.Add(Para);

            rtbUsersOrdersInfo.Document = myFlowDoc;
        }