public void Start(UpdateClient update, QuestionRepository repository)
 {
     IPHostEntry ipHost = Dns.GetHostEntry("localhost");
     IPAddress ipAddr = ipHost.AddressList[0];
     IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, Properties.Settings.Default.Port);
     _sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         _sListener.Bind(ipEndPoint);
         _sListener.Listen(_clientCount);
         do
         {
             Socket handler = _sListener.Accept();
             _clientList.Add(new FakeClient(handler, update, _students, repository));
             update?.DynamicInvoke(_clientList[_clientList.Count - 1]);
             new Thread(()=>
             {
                 var client = _clientList[_clientList.Count - 1];
                 client.ReceiveMessage();
                 if (client.Mark == 0)
                 {
                     _clientList.Remove(client);
                     _connectedClient--;
                 }
             }) { IsBackground = true }.Start();
             _connectedClient++;
         } while (_connectedClient < _clientCount);
     }
     catch { throw; }
 }
Example #2
0
        public ICommandResult Handle(UpdateClient command)
        {
            command.Validate();
            if (command.Invalid)
            {
                return(new GenericResult(ERROR_MESSAGE, false, command.Notifications));
            }


            var client = _repository.GetById(command.Id);

            if (client == null)
            {
                return(new GenericResult(SUCESS_MESSAGE, true, "Não possui cliente na base"));
            }

            client.UpdateClient(command);

            _repository.Update(client);

            return(new GenericResult(SUCESS_MESSAGE, true, client));
        }
Example #3
0
        public static void CanUpdate(AppClients clients, UpdateClient command, Roles roles)
        {
            Guard.NotNull(command, nameof(command));

            var client = GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot update client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e(Not.Defined("Client id"), nameof(command.Id));
                }

                if (string.IsNullOrWhiteSpace(command.Name) && command.Role == null)
                {
                    e(Not.DefinedOr("name", "role"), nameof(command.Name), nameof(command.Role));
                }

                if (command.Role != null && !roles.ContainsKey(command.Role))
                {
                    e(Not.Valid("role"), nameof(command.Role));
                }

                if (client == null)
                {
                    return;
                }

                if (!string.IsNullOrWhiteSpace(command.Name) && string.Equals(client.Name, command.Name))
                {
                    e(Not.New("Client", "name"), nameof(command.Name));
                }

                if (command.Role == client.Role)
                {
                    e(Not.New("Client", "role"), nameof(command.Role));
                }
            });
        }
Example #4
0
        public static void CanUpdate(AppClients clients, UpdateClient command)
        {
            Guard.NotNull(command, nameof(command));

            var client = GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot update client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e("Client id is required.", nameof(command.Id));
                }

                if (string.IsNullOrWhiteSpace(command.Name) && command.Permission == null)
                {
                    e("Either name or permission must be defined.", nameof(command.Name), nameof(command.Permission));
                }

                if (command.Permission.HasValue && !command.Permission.Value.IsEnumValue())
                {
                    e("Permission is not valid.", nameof(command.Permission));
                }

                if (client == null)
                {
                    return;
                }

                if (!string.IsNullOrWhiteSpace(command.Name) && string.Equals(client.Name, command.Name))
                {
                    e("Client has already this name.", nameof(command.Name));
                }

                if (command.Permission == client.Permission)
                {
                    e("Client has already this permission.", nameof(command.Permission));
                }
            });
        }
Example #5
0
        public async Task UpdateClient_should_create_events_and_update_client()
        {
            var command = new UpdateClient {
                Id = clientId, Name = clientNewName, Role = Role.Developer
            };

            await ExecuteCreateAsync();
            await ExecuteAttachClientAsync();

            var result = await PublishIdempotentAsync(command);

            result.ShouldBeEquivalent(sut.Snapshot);

            Assert.Equal(clientNewName, sut.Snapshot.Clients[clientId].Name);

            LastEvents
            .ShouldHaveSameEvents(
                CreateEvent(new AppClientUpdated {
                Id = clientId, Name = clientNewName, Role = Role.Developer
            })
                );
        }
Example #6
0
        public static void CanUpdate(AppClients clients, UpdateClient command, Roles roles)
        {
            Guard.NotNull(command, nameof(command));

            var client = GetClientOrThrow(clients, command.Id);

            Validate.It(() => "Cannot update client.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Id))
                {
                    e("Client id is required.", nameof(command.Id));
                }

                if (string.IsNullOrWhiteSpace(command.Name) && command.Role == null)
                {
                    e("Either name or role must be defined.", nameof(command.Name), nameof(command.Role));
                }

                if (command.Role != null && !roles.ContainsKey(command.Role))
                {
                    e("Role is not valid.", nameof(command.Role));
                }

                if (client == null)
                {
                    return;
                }

                if (!string.IsNullOrWhiteSpace(command.Name) && string.Equals(client.Name, command.Name))
                {
                    e("Client has already this name.", nameof(command.Name));
                }

                if (command.Role == client.Role)
                {
                    e("Client has already this role.", nameof(command.Role));
                }
            });
        }
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     phone   = phoneBox.Text;
     name    = nameBox.Text;
     email   = emailBox.Text;
     address = addressBox.Text;
     if (birthBox.SelectedDate != null && phone.All(char.IsDigit))
     {
         IClient  cl   = Factory.Instance.GClient();
         DateTime date = birthBox.SelectedDate ?? DateTime.Now;
         cl.AddClient(name, date, email, phone, address);
         UpdateClient?.Invoke();
         MessageBox.Show("You successfully added new client");
         phoneBox.Text   = null;
         nameBox.Text    = null;
         emailBox.Text   = null;
         addressBox.Text = null;
         birthBox.Text   = null;
     }
     else
     {
         MessageBox.Show("Invalid input data");
     }
 }
Example #8
0
        public FormErrorReport(ErrorReport report, INetworkStatusMonitor networkStatusMonitor, UpdateClient updateClient)
        {
            InitializeComponent();

            _report = report;
            _networkStatusMonitor = networkStatusMonitor;
            _updateClient         = updateClient;

            var editorControl = new TextEditorControl();

            _editor = editorControl.Editor;

            textBoxTitle.Text = _report.Title;
            _editor.Text      = _report.Body;

            _editor.Options.ShowWhiteSpace  = false;
            _editor.Options.ShowLineNumbers = false;

            _editor.TextChanged += EditorOnTextChanged;
            _editor.SetSyntax(StandardSyntaxType.Markdown);

            editorControl.Dock = DockStyle.Fill;
            editorPanel.Controls.Add(editorControl);
        }
Example #9
0
        private void StartReading()
        {
            Task.Factory.StartNew(() =>
            {
                _serialPort.ReceivedBytesThreshold = 250;
                _serialPort.DataReceived          += _serialPort_DataReceived;

                var buffer = new List <byte>();

                while (true)
                {
                    _readEvent.WaitOne(15000);
                    _readEvent.Reset();

                    try
                    {
                        var readBuffer = new byte[_serialPort.BytesToRead];

                        _serialPort.Read(readBuffer, 0, readBuffer.Length);
                        buffer.AddRange(readBuffer);

                        Debug.WriteLine($"Received {buffer.Count}");

                        if (buffer.Count > 200)
                        {
                            UpdateClient?.Invoke(buffer.ToArray());
                            buffer = new List <byte>();
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
Example #10
0
        private async void UpdateButton_Click(object sender, RoutedEventArgs e)
        {
            var dataContext = (MainWindowModel)DataContext;

            dataContext.UpdateStatus = UpdateStatus.Updating;

            var updates = await Task.Run(async() =>
            {
                return(await UpdateClient.Check());
            });

            var result = await Task.Run(async() =>
            {
                return(await UpdateClient.Update(updates));
            });

            switch (result)
            {
            case UpdateClient.UpdateResult.SuccessAndRestart:
                Close();
                return;

            case UpdateClient.UpdateResult.Failure:
                dataContext.UpdatedResultMessage = $"アップデートに失敗しました。";
                break;

            case UpdateClient.UpdateResult.Success:
                dataContext.UpdatedResultMessage = "アップデートが完了しました。";
                break;

            default:
                break;
            }

            dataContext.UpdateStatus = UpdateStatus.Updated;
        }
Example #11
0
 public UpdateInfo(int pid, string fileName, UpdateClient updateClient)
 {
     Pid      = pid;
     FileName = fileName;
     Client   = updateClient;
 }
Example #12
0
    private bool updateAgentInformation()
    {
        Console.WriteLine("Sending server client information");
        jsonClass jsC = new jsonClass {
            debugFlag = debugFlag, connectURL = connectURL
        };

        setOS();


        List <string> deviceList;
        string        CPUModel = "";

        deviceList = new List <string> {
        };

        if (osID == 1)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Description FROM Win32_VideoController"); //Prep object to query windows GPUs

            //Get Devices (Windows)
            foreach (ManagementObject mo in searcher.Get())
            {
                deviceList.Add(mo.Properties["Description"].Value.ToString().Trim());
            }

            //Get CPU (Windows)
            searcher = new ManagementObjectSearcher("SELECT Name from Win32_Processor"); //Prep object to query windows CPUs
            foreach (ManagementObject mo in searcher.Get())
            {
                deviceList.Add(mo.Properties["Name"].Value.ToString().Trim());
            }
        }
        else if (osID == 0)
        {
            //Get GPU Devices (Linux) use lspci to query GPU
            ProcessStartInfo pinfo = new ProcessStartInfo();
            pinfo.FileName               = "lspci";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardOutput = true;
            Process lspci = new Process();
            lspci.StartInfo = pinfo;
            lspci.Start();
            List <string> searchList = new List <string>(new string[] { "VGA compatible controller: ", "3D controller: " });


            while (!lspci.HasExited)
            {
                while (!lspci.StandardOutput.EndOfStream)
                {
                    string stdOut = lspci.StandardOutput.ReadLine();
                    foreach (string searchItem in searchList)
                    {
                        int pozi = stdOut.IndexOf(searchItem);
                        if (pozi != -1)
                        {
                            deviceList.Add(stdOut.Substring(pozi + searchItem.Length));
                        }
                    }
                }
            }

            //Get CPU (Linux) use lscpu to query CPU
            pinfo.FileName               = "lscpu";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardOutput = true;
            lspci.StartInfo              = pinfo;
            lspci.Start();
            string searchString = "Model Name: ";
            while (!lspci.HasExited)
            {
                while (!lspci.StandardOutput.EndOfStream)
                {
                    string stdOut = lspci.StandardOutput.ReadLine();
                    int    pos    = stdOut.IndexOf(searchString);
                    if (pos != -1)
                    {
                        deviceList.Add(stdOut.Substring(pos + searchString.Length));
                    }
                }
            }
        }
        else if (osID == 2)
        {
            //Get Machine Name (Mac)
            ProcessStartInfo pinfo = new ProcessStartInfo();
            pinfo.FileName               = "scutil";
            pinfo.Arguments              = " --get ComputerName";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardError  = true;
            pinfo.RedirectStandardOutput = true;


            //Get Devices (Mac)
            pinfo.FileName  = "system_profiler";
            pinfo.Arguments = " -detaillevel mini";
            Process getDevices = new Process();
            getDevices.StartInfo = pinfo;

            Console.WriteLine("Please wait while devices are being enumerated...");
            getDevices.Start();
            Boolean triggerRead = false;

            string searchID = "Chipset Model: ";

            while (!getDevices.StandardOutput.EndOfStream)
            {
                string stdOut = getDevices.StandardOutput.ReadLine().TrimEnd();

                if (triggerRead == true)
                {
                    if (stdOut.Contains("Total Number of Cores:")) //Just incase we go past
                    {
                        break;
                    }
                    if (stdOut.Contains("Hardware:"))
                    {
                        searchID = "Processor Name: ";
                    }
                    int pos = stdOut.IndexOf(searchID);

                    if (pos != -1)
                    {
                        if (searchID == "Chipset Model: ")
                        {
                            deviceList.Add(stdOut.Substring(pos + searchID.Length));
                        }
                        else if (searchID == "Processor Name: ")
                        {
                            CPUModel = stdOut.Substring(pos + searchID.Length);
                            searchID = "Processor Speed: ";
                        }
                        else if (searchID == "Processor Speed: ")
                        {
                            CPUModel = CPUModel + " @ " + stdOut.Substring(pos + searchID.Length);
                            deviceList.Add(CPUModel);
                            break;
                        }
                    }
                }
                else if (triggerRead == false)
                {
                    if (stdOut.Contains("Graphics/Displays:"))
                    {
                        triggerRead = true;
                    }
                }
            }
        }

        String guid = Guid.NewGuid().ToString(); //Generate GUID

        UpdateClient update = new UpdateClient
        {
            action  = "updateInformation",
            token   = tokenID,
            uid     = guid,
            os      = osID,
            devices = deviceList
        };

        string jsonString = jsC.toJson(update);
        string ret        = jsC.jsonSend(jsonString);

        if (jsC.isJsonSuccess(ret))
        {
            return(true);
        }
        return(false);
    }
Example #13
0
 public UpdateEngine(string packageListKey)
 {
     updater = new UpdateClient(packageListKey, System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\");//System.Windows.Forms.Application.StartupPath + "\\");
 }
        void obradi()
        {
            try
            {
                int operacija = 0;
                while (operacija != (int)Operacije.Kraj)
                {
                    TransferKlasa transfer = formater.Deserialize(tok) as TransferKlasa;
                    switch (transfer.Operacija)
                    {
                    case Operacije.Login:
                        FindAgent fa = new FindAgent();
                        transfer.Rezultat = fa.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.AddClient:
                        AddClient ac = new AddClient();
                        transfer.Rezultat = ac.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.GetListClients:
                        GetLIstClients glc = new GetLIstClients();
                        transfer.Rezultat = glc.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.SearchClients:
                        SearchClients sc = new SearchClients();
                        transfer.Rezultat = sc.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.SelectClient:
                        SelectClient scl = new SelectClient();
                        transfer.Rezultat = scl.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.UpdateClient:
                        UpdateClient uc = new UpdateClient();
                        transfer.Rezultat = uc.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.AddPolicy:
                        AddPolicy ap = new AddPolicy();
                        transfer.Rezultat = ap.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.UpdatePolicy:
                        UpdatePolicy up = new UpdatePolicy();
                        transfer.Rezultat = up.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.DeletePolicy:
                        DeletePolicy dp = new DeletePolicy();
                        transfer.Rezultat = dp.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.SearchPolicy:
                        SearchPolicy sp = new SearchPolicy();
                        transfer.Rezultat = sp.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.SelectPolicy:
                        SelectPolicy spo = new SelectPolicy();
                        transfer.Rezultat = spo.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.GetListInsTypes:
                        GetListInsuranceTypes git = new GetListInsuranceTypes();
                        transfer.Rezultat = git.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.DeleteClient:
                        DeleteClient dc = new DeleteClient();
                        transfer.Rezultat = dc.IzvrsiSO(transfer.TransferObjekat as OpstiDomenskiObjekat);
                        formater.Serialize(tok, transfer);
                        break;

                    case Operacije.Kraj:
                        operacija = 1;
                        Server.listaTokova.Remove(tok);
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception)
            {
                Server.listaTokova.Remove(tok);
            }
        }
Example #15
0
 public void UpdateClient(UpdateClient command)
 {
     RaiseEvent(SimpleMapper.Map(command, new AppClientUpdated()));
 }
Example #16
0
 async Task<IEnumerable<PackageManifest>> GetAvailableUpdates()
 {
     var updateClient = new UpdateClient(null, DashConfiguration.PackageUpdateServiceLocation);
     var currentVersion = GetCurrentVersion();
     return (await updateClient.GetAvailableManifestsAsync(UpdateClient.Components.DashServer))
         .Where(manifest => manifest.Version > currentVersion)
         .ToList();
 }
Example #17
0
        public void TestUpdater()
        {
            using (UpdateService<TestUpdateServer> service =
                new UpdateService<TestUpdateServer>(51315, "Updater"))
            {
                service.Connect();

                using (UpdateClient<IUpdateServer> client =
                    new UpdateClient<IUpdateServer>(new IPAddress(new byte[] { 127, 0, 0, 1 }), 51315, "Updater"))
                {
                    client.Connect();

                    Assert.IsTrue(client.ServiceObject.CheckForUpdate(new Version(1, 0)), "Version check failed!");
                    Assert.IsFalse(client.ServiceObject.CheckForUpdate(new Version(2, 0)), "Version check not failed!");
                    Assert.IsFalse(client.ServiceObject.CheckForUpdate(new Version(3, 0)), "Version check not failed!");

                    using (IFileLoader loader = new StreamFileLoader(new MemoryStream()))
                    {
                        client.ServiceObject.DownloadUpdate(loader);
                    }

                    client.Disconnect();
                }

                service.Disconnect();
            }
        }
Example #18
0
 public RegisteredClient Update(UpdateClient updateRegister)
 {
     return(this._clientManager.Update(updateRegister));
 }
Example #19
0
        //comon events
        private async void windowLoaded(object sender, RoutedEventArgs e)
        {
            if (CanWork)
            {
                CreateIcon();

                var list = await LoadLanguages();

                list.Add(new LanguageObject()
                {
                    LanguageIso = "en", LanguageName = "English"
                });
                cbLanguage.ItemsSource = list;
                var selectedLang = from lang in list where lang.LanguageIso == settings.GetValue("LanguageIso", "en") select lang;
                cbLanguage.SelectedItem      = selectedLang.FirstOrDefault();
                cbLanguage.SelectionChanged += CbLanguageSelectionChanged;


                if (settings.GetValue("AutomaticDetection", false))
                {
                    location = new PCLocation();
                    cbAutomaticLocation.IsChecked = settings.GetValue <bool>("AutomaticDetection");
                    cbCuntry.IsEnabled            = false;
                    cbCity.IsEnabled = false;
                }
                else
                {
                    cbCuntry.IsEnabled   = true;
                    cbCuntry.ItemsSource = weather.geonames.geonames;
                    var selectedContry = from contry in weather.geonames.geonames where contry.geonameId == settings.GetValue("GeonameID", 6252001) select contry;
                    cbCuntry.SelectedItem      = selectedContry.FirstOrDefault();
                    cbCuntry.SelectionChanged += CbCuntrySelectionChanged;

                    cbCity.IsEnabled = true;
                    var cityList = await LoadCity((cbCuntry.SelectedItem as Geoname).countryCode);

                    cbCity.ItemsSource = cityList;
                    var selectedCity = from city in cityList where city.geonameId == settings.GetValue("CityGeonameID", 5128581) select city;
                    cbCity.SelectedItem      = selectedCity.FirstOrDefault();
                    cbCity.SelectionChanged += CbCitySelectionChanged;
                }
                cbAutomaticLocation.Click += CbAutomaticLocationClick;


                cbThemperature.SelectedIndex     = settings.GetValue("Celsium", 0);
                cbThemperature.SelectionChanged += CbThemperatureSelectionChanged;

                cbIcon.IsChecked = settings.GetValue("LoadIcon", true);
                cbIcon.Click    += CbIconClick;

                cbCondition.IsChecked = settings.GetValue("ShowCondition", true);
                cbCondition.Click    += CbConditionClick;

                cbThemperatureShow.IsChecked = settings.GetValue("ShowThemperatue", true);
                cbThemperatureShow.Click    += CbThemperatureShowClick;

                cbLocationShow.IsChecked = settings.GetValue("ShowLocation", true);
                cbLocationShow.Click    += CbLocationShowClick;

                cbShowInetMessage.IsChecked = settings.GetValue("ShowInetDis", false);
                cbShowInetMessage.Click    += CbShowInetMessageClick;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if ((string)key.GetValue("Weather Widget") == null)
                {
                    cbStartUP.IsChecked = false;
                }
                else
                {
                    cbStartUP.IsChecked = true;
                }
                cbStartUP.Click += CbStartUPClick;

                colorPicker.SelectedColor         = settings.GetValue("TextColor", new WeatherColor(255, 255, 255, 255)).GetColor();
                colorPicker.SelectedColorChanged += colorPickerSelectionColorChanged;

                colorPickerBackground.SelectedColor         = settings.GetValue("BackgroundColor", new WeatherColor(0, 255, 255, 255)).GetColor();
                colorPickerBackground.SelectedColorChanged += ColorPickerBackgroundSelectedColorChanged;

                colorPickerBorder.SelectedColor         = settings.GetValue("BorderColor", new WeatherColor(0, 255, 255, 255)).GetColor();
                colorPickerBorder.SelectedColorChanged += ColorPickerBorderSelectedColorChanged;

                var th = settings.GetValue("WidgetBorder", new WidgetBorder(1, 1, 1, 1)).GetBorder();
                tbBorderLeft.Text   = th.Left.ToString();
                tbBorderRight.Text  = th.Right.ToString();
                tbBorderTop.Text    = th.Top.ToString();
                tbBorderBottom.Text = th.Bottom.ToString();

                tbBorderLeft.TextChanged   += TbBorderTextChanged;
                tbBorderRight.TextChanged  += TbBorderTextChanged;
                tbBorderTop.TextChanged    += TbBorderTextChanged;
                tbBorderBottom.TextChanged += TbBorderTextChanged;

                widget.SetWidgetBorder();
                widget.SetWidgetTextColor();
                widget.SetWidgetBackgroundColor();
                widget.SetWidgetBorderColor();
                UpdateWidget();
                widget.ShowWidget(true);

                Update             = new UpdateClient("https://ogycode.github.io/WeatherWidget/update.json");
                Update.NewVersion += UpdateNewVersion;
                var assembly = Assembly.GetExecutingAssembly();
                var version  = assembly.GetName().Version;
                Update.Check(new Verloka.HelperLib.Update.Version(version.Major, version.Minor, version.MajorRevision, version.MinorRevision));
            }
        }
Example #20
0
 Task <OneOf <Success, NotFound> > IRequestHandler <UpdateClient, OneOf <Success, NotFound> > .Handle(UpdateClient request, CancellationToken cancellationToken)
 {
     return(this.apartmentRepository.Update(request.Client, cancellationToken));
 }
 public GenericResult UpdateClient(
     [FromBody] UpdateClient updateClient,
     [FromServices] ClientHandler handler)
 {
     return((GenericResult)handler.Handle(updateClient));
 }
Example #22
0
        public void CanUpdate_should_throw_execption_if_client_id_is_null()
        {
            var command = new UpdateClient();

            Assert.Throws <ValidationException>(() => GuardAppClients.CanUpdate(clients, command));
        }
Example #23
0
 public UpdateEngine(string packageListKey)
 {
     updater = new UpdateClient(packageListKey, System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\");//System.Windows.Forms.Application.StartupPath + "\\");
 }
Example #24
0
        public async Task<IHttpActionResult> Update(UpdateVersion version)
        {
            return await DoActionAsync("UpdateController.Update", async (serviceClient) =>
            {
                var updateClient = new UpdateClient(null, DashConfiguration.PackageUpdateServiceLocation);
                var updateManifest = await updateClient.GetUpdateVersionAsync(UpdateClient.Components.DashServer, version.Version);
                if (updateManifest == null)
                {
                    return NotFound();
                }
                var package = updateManifest.GetPackage(UpdateClient.GetPackageFlavorLabel(AzureService.GetServiceFlavor()));
                if (package == null)
                {
                    return NotFound();
                }
                var servicePackage = package.FindFileByExtension(".cspkg");
                var serviceConfig = package.FindFileByExtension(".cscfg");
                if (servicePackage == null || serviceConfig == null)
                {
                    return NotFound();
                }
                var operationId = DashTrace.CorrelationId.ToString();
                try
                {
                    var operationStatus = await UpdateConfigStatus.GetConfigUpdateStatus(operationId);
                    await operationStatus.UpdateStatus(UpdateConfigStatus.States.PreServiceUpdate, "Begin software upgrade to version [{0}]. Operation Id: [{1}]", version.Version, operationId);
                    // Do a couple of things up-front to ensure that we can upgrade & then kick the upgrade off & don't wait for it to complete.
                    // Make sure reverse-DNS is configured
                    var updateResponse = await serviceClient.UpdateService(new HostedServiceUpdateParameters
                    {
                        ReverseDnsFqdn = String.Format("{0}.cloudapp.net.", serviceClient.ServiceName),
                    });
                    // Copy current config to config for new version
                    var currentConfig = await serviceClient.GetDeploymentConfiguration();
                    var currentSettings = AzureServiceConfiguration.GetSettingsProjected(currentConfig);
                    var newConfigDoc = XDocument.Load(
                        await updateClient.DownloadPackageFileAsync(UpdateClient.Components.DashServer, updateManifest, package, serviceConfig.Name));
                    var newSettings = AzureServiceConfiguration.GetSettings(newConfigDoc);
                    // Keep the same number of instances
                    var ns = AzureServiceConfiguration.Namespace;
                    AzureServiceConfiguration.GetInstances(newConfigDoc).Value = AzureServiceConfiguration.GetInstances(currentConfig).Value;
                    foreach (var currentSetting in currentSettings)
                    {
                        var newSetting = AzureServiceConfiguration.GetSetting(newSettings, currentSetting.Item1);
                        if (newSetting != null)
                        {
                            newSetting.SetAttributeValue("value", currentSetting.Item2);
                        }
                    }
                    // Certificates (if there are any)
                    var currentCerts = AzureServiceConfiguration.GetCertificates(currentConfig);
                    if (currentCerts != null)
                    {
                        var newCerts = AzureServiceConfiguration.GetCertificates(newConfigDoc);
                        newCerts.RemoveNodes();
                        foreach (var currentCert in currentCerts.Elements())
                        {
                            var newCert = new XElement(ns + "Certificate");
                            foreach (var currentAttrib in currentCert.Attributes())
                            {
                                newCert.SetAttributeValue(currentAttrib.Name, currentAttrib.Value);
                            }
                            newCerts.Add(newCert);
                        }
                    }
                    // Send the update to the service
                    Uri packageUri;
                    if (!String.IsNullOrWhiteSpace(servicePackage.SasUri))
                    {
                        packageUri = new Uri(servicePackage.SasUri);
                    }
                    else
                    {
                        packageUri = await updateClient.GetPackageFileSasUriAsync(UpdateClient.Components.DashServer, updateManifest, package, servicePackage.Name);
                    }
                    await operationStatus.UpdateStatus(UpdateConfigStatus.States.PreServiceUpdate, "Service upgrade using package [{0}].", packageUri.ToString());
                    var upgradeResponse = await serviceClient.UpgradeDeployment(new DeploymentUpgradeParameters
                    {
                        Label = String.Format("Dash.ManagementAPI-{0:o}", DateTime.UtcNow),
                        PackageUri = packageUri,
                        Configuration = newConfigDoc.ToString(),
                        Mode = DeploymentUpgradeMode.Auto,
                    });
                    operationStatus.CloudServiceUpdateOperationId = upgradeResponse.RequestId;
                    await operationStatus.UpdateStatus(UpdateConfigStatus.States.UpdatingService, "Service upgrade in progress.");
                    await EnqueueServiceOperationUpdate(serviceClient, operationId);
                    // Manually fire up the async worker 
                    var queueTask = ProcessOperationMessageLoop(operationId, null, null, GetMessageDelay(), null);

                    return Content(upgradeResponse.StatusCode, new OperationResult 
                    { 
                        OperationId = operationId, 
                    });
                }
                catch (CloudException ex)
                {
                    return Content(ex.Response.StatusCode, new OperationResult
                    {
                        OperationId = operationId,
                        ErrorCode = ex.ErrorCode,
                        ErrorMessage = ex.ErrorMessage,
                    });
                }
                catch (Exception ex)
                {
                    return InternalServerError(ex);
                }
            });
        }
 private void UpdateClient(UpdateClient command)
 {
     Raise(command, new AppClientUpdated());
 }
 protected Task On(UpdateClient command, CommandContext context)
 {
     return(handler.UpdateAsync <AppDomainObject>(context, a => a.UpdateClient(command)));
 }