async Task Refresh()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                await CloudService.SyncOfflineCacheAsync();

                // get by batch (upgrade)
                var list = await CloudService.GetSharingSpacesAsParticipant();

                Items.ReplaceRange(list);
                hasMoreItems = true; // Reset for refresh
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[TaskList] Error loading items: {ex.Message}");
                await Application.Current.MainPage.DisplayAlert("Refresh problem", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
        private async Task GetCategoriesAsync()
        {
            if (Categories?.Count > 0)
            {
                return;
            }

            var result = await CloudService.GetCategories(CTSFactory.MakeCTS(20000).Token);

            if (result.IsRequestSuccessful)
            {
                var list = UnsplashCategory.GenerateListFromJson(result.JsonSrc);
                this.Categories = list;
                this.Categories.Insert(0, new UnsplashCategory()
                {
                    Title = "Featured",
                });
                this.Categories.Insert(0, new UnsplashCategory()
                {
                    Title = "New",
                });
                this.Categories.Insert(0, new UnsplashCategory()
                {
                    Title = "Random",
                });
                SelectedIndex = NEW_INDEX;
                await SerializerHelper.SerializerToJson <ObservableCollection <UnsplashCategory> >(list, CachedFileNames.CateListFileName, CacheUtil.GetCachedFileFolder());
            }
        }
Example #3
0
        /// <summary>
        /// 完成待办事项
        /// </summary>
        /// <param name="id">待办事项的ID</param>
        /// <returns></returns>
        private async Task CompleteTodo(ToDo todo)
        {
            IsLoading = Visibility.Visible;

            try
            {
                var item = todo;
                item.IsDone = !item.IsDone;

                await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(AllToDos, "myschedules.sch");

                if (App.CanSendRequest)
                {
                    var result = await CloudService.FinishToDoAsync(todo.ID, item.IsDone? "1" : "0");

                    if (result)
                    {
                        await CloudService.UpdateAllOrderAsync(ToDo.GetCurrentOrderString(AllToDos));
                    }
                }
                Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(AllToDos), MessengerTokens.UpdateTile);

                UpdateUndoneCount();
            }
            catch (Exception ex)
            {
                var task = Logger.LogAsync(ex);
            }
            finally
            {
                IsLoading = Visibility.Collapsed;
            }
        }
        /// <summary>
        /// 删除todo
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        /// 先从列表删除,然后把列表内容都序列化保存,接着:
        /// 1.如果已经登陆的,尝试发送请求;
        /// 2.离线模式,不用管
        private async Task DeleteToDo(ToDo todo)
        {
            try
            {
                var item = todo;

                DeletedToDos.Add(item);
                await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(DeletedToDos, SerializerFileNames.DeletedFileName);

                AllToDos.Remove(item);

                UpdateDisplayList(CateVM.Categories[SelectedCate].CateColorID);
                await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(AllToDos, SerializerFileNames.ToDoFileName);

                //登录过的
                if (App.CanSendRequest)
                {
                    var result = await CloudService.DeleteSchedule(todo.ID);

                    await CloudService.SetAllOrder(ToDo.GetCurrentOrderString(AllToDos));
                }

                Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(AllToDos), MessengerTokens.UpdateTile);

                UpdateUndoneCount();
            }
            catch (Exception e)
            {
                var task = ExceptionHelper.WriteRecordAsync(e, nameof(MainViewModel), nameof(DeleteToDo));
            }
        }
 public MainWindow()
 {
     InitializeComponent();
     _Service = CloudService.Create();
     _CloudServiceViewModel       = CloudServiceViewModel.Create(_Service);
     ServiceListBlock.DataContext = _CloudServiceViewModel;
 }
Example #6
0
        protected CloudService GenerateCloudServiceWithNetworkProfile(string resourceGroupName, string serviceName, string cspkgSasUri, string vnetName, string subnetName, string lbName, string lbFrontendName, Dictionary <string, RoleConfiguration> roleNameToPropertiesMapping, string publicIPAddressName)
        {
            CloudService cloudService = GenerateCloudService(serviceName, cspkgSasUri, vnetName, subnetName, roleNameToPropertiesMapping);

            cloudService.Properties.NetworkProfile = GenerateNrpCloudServiceNetworkProfile(publicIPAddressName, resourceGroupName, lbName, lbFrontendName);
            return(cloudService);
        }
        private async void Logout_Clicked(object sender, EventArgs e)
        {
            if (activityStack.IsVisible)
            {
                return;
            }

            messageLabel.Text           = "Terminating your session! Please wait!";
            activityStack.IsVisible     = true;
            activityIndicator.IsRunning = true;


            try
            {
                await CloudService.LogoutAsync();

                Application.Current.MainPage = new NavigationPage(new Views.EntryPage());
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Logout Failed", ex.Message, "OK");
            }
            finally
            {
                activityStack.IsVisible     = false;
                activityIndicator.IsRunning = false;
            }
        }
        async Task Refresh()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                await CloudService.SyncOfflineCacheAsync <Announcement>(overrideServerChanges : true);

                var table = await CloudService.GetTableAsync <Announcement>();

                var list = await table.ReadItemsOrderedAsync(0, 10, o => o.CreatedAt, descending : true);

                Items.ReplaceRange(list);
                hasMoreItems = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[AnnouncementsList] Error loading items: {ex.Message}");
            }
            finally
            {
                IsBusy = false;
            }
        }
        async Task ExecuteRefreshCommand()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                await CloudService.SyncOfflineCacheAsync();

                var table = await CloudService.GetTableAsync <Room>();

                var list = await table.ReadAllRoomsAsync();

                AllRooms.Clear();
                DisplayedRooms.Clear();
                foreach (var room in list)
                {
                    AllRooms.Add(room);
                    DisplayedRooms.Add(room);
                    SortRooms(DisplayedRooms, room);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[RoomListViewModel] Error loading items: {ex.Message}");
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #10
0
        /// <summary>
        /// 从服务器同步列表
        /// </summary>
        /// <returns></returns>
        public async Task <bool> GetLatestCates()
        {
            try
            {
                var result = await CloudService.GetCateInfoAsync();

                if (result == null)
                {
                    throw new ArgumentNullException();
                }

                var respJson  = JsonObject.Parse(result.JsonSrc);
                var isSuccess = JsonParser.GetBooleanFromJsonObj(respJson, "isSuccessed");
                if (!isSuccess)
                {
                    throw new ArgumentException();
                }

                var cateObj = JsonParser.GetStringFromJsonObj(respJson, "Cate_Info");
                var list    = GenerateList(cateObj.ToString());
                if (list == null)
                {
                    throw new ArgumentNullException();
                }

                Categories = list;
                await SerializerHelper.SerializerToJson <ObservableCollection <ToDoCategory> >(Categories, SerializerFileNames.CategoryFileName);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #11
0
        static void Main(string[] args)
        {
            WorkflowEngine  workflowEngine;
            Video           video;
            CloudService    cloudService;
            EncodingService encodingService;
            Message         message;
            Database        database;

            video        = new Video();
            cloudService = new CloudService();
            var videoUpload = new VideoUploadActivity(video, cloudService);

            encodingService = new EncodingService();
            var prepareForEncoding = new PrepareForEncodingActivity(video, encodingService);

            message = new Message();
            var sendEmail = new SendEmailActivity(video, message);

            database = new Database();
            var changeDatabase = new ChangeDatabaseActivity(video, database);

            workflowEngine = new WorkflowEngine();
            workflowEngine.RegisterActivity(videoUpload);
            workflowEngine.RegisterActivity(prepareForEncoding);
            workflowEngine.RegisterActivity(sendEmail);
            workflowEngine.RegisterActivity(changeDatabase);

            workflowEngine.Run();
        }
        private async Task <string> UploadToRealCloudAsync(MediaFile file)
        {
            var mediaStream = file.GetStream();

            string filename = Path.GetFileNameWithoutExtension(AlbumPath);

            // Get the SAS token from the backend
            var storageToken = await CloudService.GetUpSasTokenAsync(Settings.CurrentSharingSpace, filename);

            // Use the SAS token to upload the file
            var storageUri  = new Uri($"{storageToken.Uri}{storageToken.SasToken}");
            var blobStorage = new CloudBlockBlob(storageUri);

            // Compress
            byte[] img;
            using (var fileStream = System.IO.File.OpenRead(AlbumPath))
            {
                using (BinaryReader br = new BinaryReader(fileStream))
                {
                    img = br.ReadBytes((int)fileStream.Length);
                }
            }

            // Resize image (do not forget to add the iOS version of it)
            byte[] resizedImageArray = ImageResizer.ResizeImageAndroid(img, 720, 486);
            Stream resizedImage      = new MemoryStream(resizedImageArray);

            await blobStorage.UploadFromStreamAsync(resizedImage);

            // Set the content type of the current blob to image/jpeg
            blobStorage.Properties.ContentType = "image/jpeg";
            await blobStorage.SetPropertiesAsync();

            return(storageToken.Uri.ToString());
        }
Example #13
0
        async Task Delete()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                if (Item.Id != null)
                {
                    var table = await CloudService.GetTableAsync <Tag>();

                    await table.DeleteItemAsync(Item);

                    await CloudService.SyncOfflineCacheAsync();

                    MessagingCenter.Send <TagDetailViewModel>(this, "ItemsChanged");
                }
                await Application.Current.MainPage.Navigation.PopAsync();
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Delete Item Failed", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #14
0
        /// <summary>
        /// 更新排序
        /// </summary>
        /// <returns></returns>
        public async Task UpdateOrderAsync()
        {
            IsLoading = Visibility.Visible;
            await CloudService.UpdateAllOrderAsync(ToDo.GetCurrentOrderString(AllToDos));

            IsLoading = Visibility.Collapsed;
        }
Example #15
0
        async Task SaveAsync()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                var table = await CloudService.GetTableAsync <SharingSpace>();

                await table.UpsertItemAsync(CurrentSharingSpace);

                await CloudService.SyncOfflineCacheAsync();

                MessagingCenter.Send <EventDetailViewModel>(this, "ItemsChanged");
                await Application.Current.MainPage.Navigation.PopAsync();
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Save Item Failed", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #16
0
 /// <summary>
 /// 从离线模式注册/登录后,同步所有
 /// </summary>
 /// <returns></returns>
 private async Task AddAllOfflineToDos()
 {
     foreach (var sche in AllToDos)
     {
         var result = await CloudService.AddToDoAsync(sche.Content, sche.IsDone? "1" : "0", SelectedCate.ToString());
     }
 }
Example #17
0
        internal static bool CanAcceptSourceAndTarget(ModelElement sourceElement, ModelElement targetElement)
        {
            bool accept = true;

            if (targetElement is CloudService && !(targetElement is IoTCenter))
            {
                CloudService cloud = targetElement as CloudService;
                IoTCenter    iot;
                Endpoint     endp;
                //The IoTCenter that originates the connection is extracted
                if (sourceElement is IoTCenter)
                {
                    iot = sourceElement as IoTCenter;
                }
                else
                {
                    endp = sourceElement as Endpoint;
                    iot  = endp.IoTCenter;
                }
                foreach (Endpoint endpoint in cloud.ConnectedEndpoints)
                {
                    //If a connection between the obtained CloudService and IoTCenter already exists the connection is not allowed
                    if (endpoint.IoTCenter == iot && accept)
                    {
                        accept = false;
                    }
                }
            }
            else
            {
                accept = false;
            }
            return(accept);
        }
Example #18
0
        public async Task GetUserPlan()
        {
            CurrentUserPlans = new ObservableCollection <UserPlan>();

            var getResult = await CloudService.GetAllPlans(CTSFactory.MakeCTS().Token);

            getResult.ParseAPIResult();
            if (!getResult.IsSuccessful)
            {
                ToastService.SendToast("获得培养计划失败");
                return;
            }
            var json = getResult.JsonSrc;


            SelectedIndex = 0;

            if (CurrentUserPlans.Count == 0)
            {
                NoItemVisibility = Visibility.Visible;
            }
            else
            {
                NoItemVisibility = Visibility.Collapsed;
            }
        }
Example #19
0
        public void ShouldCreateOneCloudService()
        {
            var mockChannel = new MockRequestChannel();

            var cloudServiceToCreate = new CloudService {
                Name = cloudServiceName, Label = cloudServiceLabel
            };
            var cloudServiceToReturn = new CloudService
            {
                Name  = cloudServiceName,
                Label = cloudServiceLabel,
            };

            mockChannel.AddReturnObject(cloudServiceToReturn, new WebHeaderCollection {
                "x-ms-request-id:" + Guid.NewGuid()
            });

            Guid?jobOut;
            var  cloudServiceOperations = new CloudServiceOperations(new WebClientFactory(new Subscription(), mockChannel));
            var  createdCloudService    = cloudServiceOperations.Create(cloudServiceToCreate, out jobOut);

            Assert.IsNotNull(createdCloudService);
            Assert.IsInstanceOfType(createdCloudService, typeof(CloudService));
            Assert.AreEqual(cloudServiceToReturn.Name, createdCloudService.Name);
            Assert.AreEqual(cloudServiceToReturn.Label, createdCloudService.Label);

            var requestList = mockChannel.ClientRequests;

            Assert.AreEqual(1, requestList.Count);
            Assert.AreEqual(HttpMethod.Post.ToString(), requestList[0].Item1.Method);

            // Check the URI (for Azure consistency)
            Assert.AreEqual(baseURI, mockChannel.ClientRequests[0].Item1.Address.AbsolutePath.Substring(1));
        }
        async Task Refresh()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                await CloudService.SyncOfflineCacheAsync();

                var identity = await CloudService.GetIdentityAsync();

                if (identity != null)
                {
                    var name = identity.UserClaims.FirstOrDefault(c => c.Type.Equals("name")).Value;
                    Title = $"Tasks for {name}";
                }
                var table = await CloudService.GetTableAsync <TodoItem>();

                var list = await table.ReadItemsAsync(0, 20);

                Items.ReplaceRange(list);
                hasMoreItems = true; // Reset for refresh
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Items Not Loaded", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
        private async Task <GetClusterResult> GetCluster(string dnsName, string location)
        {
            var cloudServices = await this.ListCloudServices();

            Resource     clusterResource         = null;
            CloudService cloudServiceForResource = null;

            foreach (CloudService service in cloudServices)
            {
                clusterResource =
                    service.Resources.FirstOrDefault(
                        r =>
                        r.Type.Equals(ClustersResourceType, StringComparison.OrdinalIgnoreCase) &&
                        r.Name.Equals(dnsName, StringComparison.OrdinalIgnoreCase) &&
                        service.GeoRegion.Equals(location, StringComparison.OrdinalIgnoreCase));
                if (clusterResource != null)
                {
                    cloudServiceForResource = service;
                    break;
                }
            }

            if (clusterResource == null)
            {
                return(null);
            }

            var result = await this.GetClusterFromCloudServiceResource(cloudServiceForResource, clusterResource);

            return(result);
        }
Example #22
0
        async Task LogoutAsync()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                await CloudService.LogoutAsync();

                SetProperty(ref isUserLoggedIn, CloudService.IsUserLoggedIn(), "IsUserLoggedIn");
                MessagingCenter.Send(this, "RefreshLogin");
                NavigationService.Instance.MenuIsPresented = false;
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error al cerar sesión", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
        /// <summary>
        /// 完成待办事项
        /// </summary>
        /// <param name="id">待办事项的ID</param>
        /// <returns></returns>
        private async Task CompleteTodo(ToDo todo)
        {
            try
            {
                var item = todo;
                item.IsDone = !item.IsDone;

                await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(AllToDos, "myschedules.sch");

                if (App.CanSendRequest)
                {
                    var result = await CloudService.FinishSchedule(todo.ID, item.IsDone? "1" : "0");

                    if (result)
                    {
                        await CloudService.SetAllOrder(ToDo.GetCurrentOrderString(AllToDos));
                    }
                }
                Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(AllToDos), MessengerTokens.UpdateTile);

                UpdateUndoneCount();
            }
            catch (Exception ex)
            {
                var task = ExceptionHelper.WriteRecordAsync(ex, nameof(MainViewModel), nameof(CompleteTodo));
            }
        }
Example #24
0
        async Task ExecuteSaveCommand()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                if (Item.Id == null)
                {
                    await CloudService.InsertItemAsync(Item);
                }
                else
                {
                    await CloudService.UpdateItemAsync(Item);
                }
                MessagingCenter.Send <TaskDetailViewModel>(this, "ItemsChanged");
                await Application.Current.MainPage.Navigation.PopAsync();
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Save Item Failed", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #25
0
        public void Shutdown()
        {
            if (service != null)
            {
                lock (this)
                {
                    LogUtil.Info("Daemon Process shutdown...");

                    CloudService cloudService = service;

                    try
                    {
                        foreach (DaemonParticipant daemonParticipant in bubbleDaemons.Values)
                        {
                            daemonParticipant.Shutdown();
                        }

                        cloudService.Shutdown();
                    }
                    finally
                    {
                        // Removing process state info from database.
                        if (localProcessStateEntity != null)
                        {
                            entityContext.DeleteObject(localProcessStateEntity);
                            entityContext.SaveChanges();
                        }
                    }

                    service = null;
                    LogUtil.Info("Daemon Process shutdown done.");
                }
            }
        }
Example #26
0
        public AnnouncementEditViewModel(Announcement item = null)
        {
            if (item != null)
            {
                Item       = item;
                Title      = "Editar noticia";
                ImageUrl   = item.ImageUrl;
                IsEditMode = true;
            }
            else
            {
                Item       = new Announcement();
                Title      = "Nueva noticia";
                IsEditMode = false;
            }

            SaveCommand      = new Command(async() => await SaveAsync());
            DeleteCommand    = new Command(async() => await DeleteAsync());
            PickImageCommand = new Command(async() => await PickImageAsync());

            MessagingCenter.Subscribe <SettingsViewModel>(this, "RefreshLogin", (sender) =>
            {
                if (!(CloudService.IsUserLoggedIn() &&
                      CloudService.GetCurrentUser().UserId.Equals(Item.Author)))
                {
                    NavigationService.Instance.GoToHomePage();
                }
            });
        }
Example #27
0
        async Task ExecuteRefreshReservationsCommand()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                await CloudService.SyncOfflineCacheAsync();

                var reservationTable = await CloudService.GetTableAsync <Reservation>();

                var reservationList = await reservationTable.ReadAllReservationsAsync();

                ReservationsOfSelectedRoom.Clear();
                foreach (var reservation in reservationList)
                {
                    if (reservation.RoomName.Equals(SelectedRoom.Name))
                    {
                        ReservationsOfSelectedRoom.Add(reservation);
                        SortReservations(ReservationsOfSelectedRoom, reservation);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[Reservations] Error loading items: {ex.Message}");
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #28
0
 public async Task DeleteAsync()
 {
     Contract.Requires(Parent != null);
     var httpResponseMessage = await GetRestClient(Parent, "/" + Id).DeleteAsync();
     await Parent.Subscription.WaitForOperationCompletionAsync(httpResponseMessage);
     Parent = null;
 }
Example #29
0
        internal async Task CreateAsync(
            CloudService parent,
            Uri packageUrl,
            CreationOptions options = null,
            params ExtensionAssociation[] extensionAssociations)
        {
            Contract.Requires(parent != null);
            Contract.Requires(packageUrl != null);
            Contract.Requires(!string.IsNullOrWhiteSpace(Label));
            Contract.Requires(Configuration != null);

            if (options == null) options = new CreationOptions();
            var ns = XmlNamespaces.WindowsAzure;
            var content = new XElement(ns + "CreateDeployment",
                new XElement(ns + "Name", Name),
                new XElement(ns + "PackageUrl", packageUrl.ToString()),
                new XElement(ns + "Label", Label.ToBase64String()),
                new XElement(ns + "Configuration", Configuration.ToXml().ToString().ToBase64String()),
                new XElement(ns + "StartDeployment", options.StartDeployment),
                new XElement(ns + "TreatWarningsAsError", options.TreatWarningsAsError)
                );

            AddExtensionConfigurationXml(content, extensionAssociations);

            var response = await GetRestClient(parent).PostAsync(content);
            await parent.Subscription.WaitForOperationCompletionAsync(response);
            Parent = parent;
        }
        async Task Refresh()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;

            try
            {
                await CloudService.SyncOfflineCacheAsync();

                var table = await CloudService.GetTableAsync <Tag>();

                var list = await table.ReadItemsAsync(0, 20);

                Items.ReplaceRange(list);
                hasMoreItems = true; // Reset for refresh
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Items Not Loaded", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #31
0
        async Task ExecuteRefreshParkInfo()
        {
            try
            {
                var carParkTable = await CloudService.GetTableAsync <CarPark>();

                var park = await carParkTable.ReadAllParksAsync();

                ParkingSpaces = 100 - park.Count();

                ParkButtonText = "PARK NOW";
                var identity = await CloudService.GetIdentityAsync();

                foreach (var slot in park)
                {
                    if (slot.Park == identity.UserClaims.FirstOrDefault(c => c.Type.Equals("urn:microsoftaccount:name")).Value)
                    {
                        ParkButtonText = "LEAVE THE PARK";
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[CarParkViewModel] Error loading items: {ex.Message}");
            }
        }
Example #32
0
        public OrganizationEditViewModel(Organization item = null)
        {
            if (item != null)
            {
                Item       = item;
                Title      = "Editar organización";
                LogoUrl    = item.LogoUrl;
                IsEditMode = true;
            }
            else
            {
                Item       = new Organization();
                Title      = "Nueva organización";
                IsEditMode = false;
            }

            SaveCommand      = new Command(async() => await SaveAsync());
            DeleteCommand    = new Command(async() => await DeleteAsync());
            PickImageCommand = new Command(async() => await PickImageAsync());

            MessagingCenter.Subscribe <SettingsViewModel>(this, "RefreshLogin", (sender) =>
            {
                if (!(CloudService.IsUserLoggedIn() &&
                      CloudService.GetCurrentUser().UserId.Equals(Item.AdminUser)))
                {
                    NavigationService.Instance.GoToHomePage();
                }
            });
        }
Example #33
0
        internal Deployment(XElement element, CloudService parent)
            : this()
        {
            Contract.Requires(element != null);
            Contract.Requires(parent != null);

            Parent = parent;
            PopulateFromXml(element);
        }
Example #34
0
 public ServiceCertificate(XElement element, CloudService parent)
 {
     var ns = XmlNamespaces.WindowsAzure;
     Uri = new Uri((string)element.Element(ns + "CertificateUrl"));
     Thumbprint = (string)element.Element(ns + "Thumbprint");
     ThumbprintAlgorithm = (string)element.Element(ns + "ThumbprintAlgorithm");
     Certificate = new X509Certificate2(Convert.FromBase64String((string)element.Element(ns + "Data")));
     Parent = parent;
 }
Example #35
0
        internal async Task AddAsync(CloudService parent)
        {
            var ns = XmlNamespaces.WindowsAzure;

            var content = new XElement(ns + "Extension", BuildExtensionXml(ns).ToArray());

            var response = await GetRestClient(parent).PostAsync(content);
            await parent.Subscription.WaitForOperationCompletionAsync(response);
            Parent = parent;
        }
Example #36
0
        public Extension(XElement xml, CloudService parent)
        {
            Contract.Requires(parent != null);

            xml.HydrateObject(XmlNamespaces.WindowsAzure, this);

            PublicConfiguration = PublicConfiguration.FromBase64String();
            PrivateConfiguration = PrivateConfiguration.FromBase64String();
            
            Parent = parent;
        }
Example #37
0
 public CloudServiceTests()
 {
     CloudService = new CloudService("test-" + Guid.NewGuid().ToString("N"), TestLocation, LocationType.Region)
     {
         Description = "Test Description"
     };
     Debug.WriteLine("CloudServiceTests ctor - creating test service");
     TestConstants.Subscription.CreateCloudServiceAsync (CloudService).Wait();
     var cert = new X509Certificate2(@"..\..\CertKey.pfx", "1234", X509KeyStorageFlags.Exportable);
     var serviceCertificate = new ServiceCertificate(cert);
     CloudService.AddServiceCertificateAsync(serviceCertificate).Wait();
 }
Example #38
0
        internal async Task AddAsync(CloudService parent)
        {
            var ns = XmlNamespaces.WindowsAzure;
            var content = new XElement(ns + "CertificateFile",
                new XElement(ns + "Data", Convert.ToBase64String(Certificate.Export(X509ContentType.Pfx))),
                new XElement(ns + "CertificateFormat", "pfx"),
                new XElement(ns + "Password"));

            HttpResponseMessage response = await GetRestClient(parent).PostAsync(content);
            await parent.Subscription.WaitForOperationCompletionAsync(response);
            Parent = parent;
        }
Example #39
0
		public IEnumerable<Action> Schedule()
		{
			var services = _serviceProvider().ToArray();
			var currentServiceIndex = -1;
			var skippedConsecutively = 0;

			_isRunning = true;

			while (_isRunning)
			{
				currentServiceIndex = (currentServiceIndex + 1) % services.Length;
				_currentService = services[currentServiceIndex];

				var result = ServiceExecutionFeedback.DontCare;
				var isRunOnce = false;

				// 'more of the same pattern'
				// as long the service is active, keep triggering the same service
				// for at least 1min (in order to avoid a single service to monopolize CPU)
				var start = DateTimeOffset.UtcNow;
				
				while (DateTimeOffset.UtcNow.Subtract(start) < _moreOfTheSame && _isRunning && DemandsImmediateStart(result))
				{
					yield return () =>
						{
							var busyExecuteTimestamp = _countBusyExecute.Open();
							result = _schedule(_currentService);
							_countBusyExecute.Close(busyExecuteTimestamp);
						};
					isRunOnce |= WasSuccessfullyExecuted(result);
				}

				skippedConsecutively = isRunOnce ? 0 : skippedConsecutively + 1;
				if (skippedConsecutively >= services.Length && _isRunning)
				{
					// We are not using 'Thread.Sleep' because we want the worker
					// to terminate fast if 'Stop' is requested.

					var idleSleepTimestamp = _countIdleSleep.Open();
					lock (_sync)
					{
						Monitor.Wait(_sync, _idleSleep);
					}
					_countIdleSleep.Close(idleSleepTimestamp);

					skippedConsecutively = 0;
				}
			}

			_currentService = null;
		}
Example #40
0
		public IDisposable Monitor(CloudService service)
		{
			return new DisposableAction(() => { });
		}
Example #41
0
 public static CloudService CreateCloudService(string name)
 {
     CloudService cloudService = new CloudService();
     cloudService.Name = name;
     return cloudService;
 }
Example #42
0
 AzureRestClient GetRestClient(CloudService parent, string pathSuffix = null)
 {
     string servicePath = "services/hostedServices/" + parent.Name + "/certificates";
     if (pathSuffix != null) servicePath += pathSuffix;
     return parent.Subscription.GetCoreRestClient20120301(servicePath);
 }
Example #43
0
 public async Task DeleteAsync()
 {
     Contract.Requires(Parent != null);
     await Parent.Subscription.WaitForOperationCompletionAsync(await GetRestClient().DeleteAsync());
     Parent = null;
 }
Example #44
0
 AzureRestClient GetRestClient(CloudService cloudService, string pathSuffix = null)
 {
     string servicePath = "services/hostedservices/" + cloudService.Name + "/deploymentslots/" + Slot.ToString().ToLowerInvariant();
     if (!string.IsNullOrEmpty(pathSuffix)) servicePath += pathSuffix;
     return cloudService.Subscription.GetCoreRestClient20120301(servicePath);
 }
Example #45
0
 public async Task DeleteAsync()
 {
     Contract.Requires(Parent != null);
     await Parent.Subscription.WaitForOperationCompletionAsync(await GetRestClient("/" + ThumbprintAlgorithm + "-" + Thumbprint).DeleteAsync());
     Parent = null;
 }
 public WorkshopServiceBuilder WithAmazonServiceInstance(AwsService<Workshop> awsService)
 {
     _cloudService = awsService;
     return this;
 }
 public CustomAuthenticationServiceBuilder()
 {
     _cloudService = new AwsService<User>();
 }
Example #48
0
		public IDisposable Monitor(CloudService service)
		{
			var handle = OnStart(service);
			return new DisposableAction(() => OnStop(handle));
		}
 public WorkshopServiceBuilder WithAzureServiceInstance(AzureService<Workshop> azureService)
 {
     _cloudService = azureService;
     return this;
 }
Example #50
0
		RunningServiceHandle OnStart(CloudService service)
		{
			var process = Process.GetCurrentProcess();
			var handle = new RunningServiceHandle
				{
					Service = service,
					TotalProcessorTime = process.TotalProcessorTime,
					UserProcessorTime = process.UserProcessorTime,
					StartDate = DateTimeOffset.UtcNow
				};

			return handle;
		}
Example #51
0
 public static CloudService CreateCloudService(string name, global::System.Collections.ObjectModel.ObservableCollection<Microsoft.WindowsAzure.Commands.Utilities.WAPackIaaS.DataContract.UserAndRole> grantedToList)
 {
     CloudService cloudService = new CloudService();
     cloudService.Name = name;
     if ((grantedToList == null))
     {
         throw new global::System.ArgumentNullException("grantedToList");
     }
     cloudService.GrantedToList = grantedToList;
     return cloudService;
 }
        public CustomAuthenticationServiceBuilder WithAzureService(AzureService<User> azureService)
        {
            _cloudService = azureService;

            return this;
        }
 public WorkshopServices(CloudService<Workshop> cloudService)
 {
 }
 public WorkshopServiceBuilder()
 {
     _cloudService = new AzureService<Workshop>();
 }
Example #55
0
 private static AzureRestClient GetRestClient(
     CloudService parent,
     string pathSuffix = null)
 {
     var servicePath = "services/hostedServices/" + parent.Name + "/extensions";
     if (pathSuffix != null)
     {
         servicePath += pathSuffix;
     }
     return parent.Subscription.GetCoreRestClient20140601(servicePath);
 }
Example #56
0
 public Task CreateCloudServiceAsync(CloudService service) { return service.CreateAsync(this); }