Example #1
1
		private async void LaunchUriForResult_Click(object sender, RoutedEventArgs e)
		{
			var protocol = "win10demo2://";
			var packageFamilyName = "0df93276-6bbb-46fa-96b7-ec223e226505_cb1hhkscw5m06";
			var status = await Launcher.QueryUriSupportAsync(new Uri(protocol), LaunchQuerySupportType.UriForResults, packageFamilyName);
			if (status == LaunchQuerySupportStatus.Available)
			{
				var options = new LauncherOptions
				{
					TargetApplicationPackageFamilyName = packageFamilyName
				};
				var values = new ValueSet();
				values.Add("TwitterId", "danvy");
				var result = await Launcher.LaunchUriForResultsAsync(new Uri(protocol), options, values);
				if (result.Status == LaunchUriStatus.Success)
				{
					var authorized = result.Result["Authorized"] as string;
					if (authorized == true.ToString())
					{
						var dialog = new MessageDialog("You are authorized :)");
						await dialog.ShowAsync();
					}
				}
			}
		}
Example #2
0
		private async void CallService_Click(object sender, RoutedEventArgs e)
		{
			var connection = new AppServiceConnection();
			connection.PackageFamilyName = "0df93276-6bbb-46fa-96b7-ec223e226505_cb1hhkscw5m06"; // Windows.ApplicationModel.Package.Current.Id.FamilyName;
			connection.AppServiceName = "CalculatorService";
			var status = await connection.OpenAsync();
			if (status != AppServiceConnectionStatus.Success)
			{
				var dialog = new MessageDialog("Sorry, I can't connect to the service right now :S");
				await dialog.ShowAsync();
				return;
			}
			var message = new ValueSet();
			message.Add("service", OperatorCombo.Items[OperatorCombo.SelectedIndex]);
			message.Add("a", Convert.ToInt32(ValueABox.Text));
			message.Add("b", Convert.ToInt32(ValueBBox.Text));
			AppServiceResponse response = await connection.SendMessageAsync(message);
			if (response.Status == AppServiceResponseStatus.Success)
			{
				if (response.Message.ContainsKey("result"))
				{
					ResultBlock.Text = response.Message["result"] as string;
				}
			}
			else
			{
				var dialog = new MessageDialog(string.Format("Opps, I just get an error :S ({0})", response.Status));
				await dialog.ShowAsync();
			}
		}
Example #3
0
		private async void CallService_Click(object sender, RoutedEventArgs e)
		{
			var connection = new AppServiceConnection();
			connection.PackageFamilyName = "041cdcf9-8ef3-40e4-85e2-8f3de5e06155_ncrzdc1cmma1g"; // Windows.ApplicationModel.Package.Current.Id.FamilyName;
			connection.AppServiceName = "CalculatorService";
			var status = await connection.OpenAsync();
			if (status != AppServiceConnectionStatus.Success)
			{
				var dialog = new MessageDialog("Sorry, I can't connect to the service right now :S");
				await dialog.ShowAsync();
				return;
			}
			var message = new ValueSet();
			message.Add("service", (OperatorCombo.SelectedValue as ComboBoxItem).Content);
			message.Add("a", Convert.ToInt32(ValueABox.Text));
			message.Add("b", Convert.ToInt32(ValueBBox.Text));
			AppServiceResponse response = await connection.SendMessageAsync(message);
			if (response.Status == AppServiceResponseStatus.Success)
			{
				if (response.Message.ContainsKey("result"))
				{
					ResultBlock.Text = response.Message["result"].ToString();
				}
			}
			else
			{
				var dialog = new MessageDialog(string.Format("Opps, I just get an error :S ({0})", response.Status));
				await dialog.ShowAsync();
			}
		}
Example #4
0
        private async void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var message = args.Request.Message;
            string command = message["Command"] as string;

            switch (command)
            {
                case "CalcSum":
                    {
                        var messageDeferral = args.GetDeferral();

                        int value1 = (int)message["Value1"];
                        int value2 = (int)message["Value2"];

                        //Set a result to return to the caller 
                        int result = value1 + value2;
                        var returnMessage = new ValueSet();
                        returnMessage.Add("Result", result);
                        var responseStatus = await args.Request.SendResponseAsync(returnMessage);

                        messageDeferral.Complete();
                        break;
                    }

                case "Quit":
                    {
                        //Service was asked to quit. Give us service deferral 
                        //so platform can terminate the background task 
                        _serviceDeferral.Complete();
                        break;
                    }
            }
        }
        private async void InitializeAppSvc()
        {
            string WebServerStatus = "PoolWebServer failed to start. AppServiceConnectionStatus was not successful.";

            // Initialize the AppServiceConnection
            appServiceConnection = new AppServiceConnection();
            appServiceConnection.PackageFamilyName = "PoolWebServer_hz258y3tkez3a";
            appServiceConnection.AppServiceName = "App2AppComService";

            // Send a initialize request 
            var res = await appServiceConnection.OpenAsync();
            if (res == AppServiceConnectionStatus.Success)
            {
                var message = new ValueSet();
                message.Add("Command", "Initialize");
                var response = await appServiceConnection.SendMessageAsync(message);
                if (response.Status != AppServiceResponseStatus.Success)
                {
                    WebServerStatus = "PoolWebServer failed to start.";
                    throw new Exception("Failed to send message");
                }
                appServiceConnection.RequestReceived += OnMessageReceived;
                WebServerStatus = "PoolWebServer started.";
            }

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                txtWebServerStatus.Text = WebServerStatus;
            });
        }
        private async void pickerBtb_Click(object sender, RoutedEventArgs e)
        {
            //Set a result to return to the caller
            var returnMessage = new ValueSet();
            server = new HttpServer(8080);
            server.StartServer();
            returnMessage.Add("Status", "Success");

            // var myPictures = await StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
            var picker = new Windows.Storage.Pickers.FileOpenPicker();
            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file
                Log("Picked photo: " + file.Path, "Success");
                server.FilePath = file.Path;
            }
            else
            {
                Log("Operation cancelled.", "Error");
            }
        }
 private ValueSet AddBook(string book)
 {
     BooksRepository.Instance.AddBook(book.ToBook());
     var result = new ValueSet();
     result.Add("result", "ok");
     return result;
 }
        private async Task NotifyClientsOfPerimeterState()
        {
            var _sensorCurrentValue = _sensorPin.Read();
            var messages = new ValueSet(); //name value pair

            if (_sensorCurrentValue == GpioPinValue.High)
            {
                //send perimeter breached
                messages.Add("Perimeter Notification", "Breached");
            }
            else
            {
                //send perimeter secure
                messages.Add("Perimeter Notification", "Secure");
            }

            //send message to the client
            var response = await _connection.SendMessageAsync(messages);

            if (response.Status == AppServiceResponseStatus.Success)
            {
                var result = response.Message["Response"];
                //optionally log result from client
            }
        }
        private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            // if you are doing anything awaitable, you need to get a deferral
            var requestDeferral = args.GetDeferral();
            var returnMessage = new ValueSet();
            try
            {
                //obtain and react to the command passed in by the client
                var message = args.Request.Message["Request"] as string;
                switch (message)
                {
                    case "Turn LED On":
                        _ledPin.Write(GpioPinValue.High);
                        break;
                    case "Turn LED Off":
                        _ledPin.Write(GpioPinValue.Low);
                        break;
                }
                returnMessage.Add("Response", "OK");
            }
            catch (Exception ex)
            {
                returnMessage.Add("Response", "Failed: " + ex.Message);
            }

            await args.Request.SendResponseAsync(returnMessage);
 
            //let the OS know that the action is complete
            requestDeferral.Complete();
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            Loading.IsActive = true;
            AppServiceConnection connection = new AppServiceConnection();
            connection.PackageFamilyName = Package.Current.Id.FamilyName;
            connection.AppServiceName = "FeedParser";

            var status = await connection.OpenAsync();

            if (status == AppServiceConnectionStatus.Success)
            {
                ValueSet data = new ValueSet();
                data.Add("FeedUrl", "http://blog.qmatteoq.com/feed/");

                var response = await connection.SendMessageAsync(data);
                if (response.Status == AppServiceResponseStatus.Success)
                {
                    string items = response.Message["FeedItems"].ToString();
                    var result = JsonConvert.DeserializeObject<List<FeedItem>>(items);
                    News.ItemsSource = result;
                }
            }

            Loading.IsActive = false;
        }
Example #11
0
 private async void SendMessageToServer(string message)
 {
     var command = new ValueSet();
     command.Add("Command", "Bridge");
     command.Add("SendToServer", message);
     var response = await _appServiceConnection.SendMessageAsync(command);
 }
Example #12
0
        private async void InitializeService()
        {
            _appServiceConnection = new AppServiceConnection
            {
                PackageFamilyName = "ConnectionService-uwp_5gyrq6psz227t",
                AppServiceName = "App2AppComService"
            };

            // Send a initialize request 
            var res = await _appServiceConnection.OpenAsync();
            if (res == AppServiceConnectionStatus.Success)
            {
                var message = new ValueSet {{"Command", "Connect"}};

                var response = await _appServiceConnection.SendMessageAsync(message);
                if (response.Status == AppServiceResponseStatus.Success)
                {
                    InitializeSerialBridge();
                    //InitializeBluetoothBridge();
                    _appServiceConnection.RequestReceived += _serialBridge.OnCommandRecived;
                    //_appServiceConnection.RequestReceived += _bluetoothBridge.OnCommandRecived;
                    //_appServiceConnection.RequestReceived += _appServiceConnection_RequestReceived;
                    
                }
            }
        }
Example #13
0
        public static async Task RegisterApplicationTrigger(Type backgroundTaskType)
        {
            var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            if (backgroundAccessStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity ||
                backgroundAccessStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity)
            {
                var appTrigger = new ApplicationTrigger();
                string taskEntryPoint = backgroundTaskType.ToString();
                var backgroundTaskBuilder = new BackgroundTaskBuilder
                {
                    Name = backgroundTaskType.Name,
                    TaskEntryPoint = taskEntryPoint
                };

                backgroundTaskBuilder.SetTrigger(appTrigger);

                var task = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(i => i.Name.Equals(backgroundTaskType.Name));
                task?.Unregister(true);
                backgroundTaskBuilder.Register();

                ValueSet message = new ValueSet { { "Command", "Init" } };

                var result = await appTrigger.RequestAsync(message);

                if (result == ApplicationTriggerResult.Allowed)
                {
                    Debug.WriteLine(string.Format("{0} called!", backgroundTaskType.Name));
                }
            }
        }
Example #14
0
        private void Accept_Click(object sender, RoutedEventArgs e)
        {
            ValueSet result = new ValueSet();
            result["Status"] = "Success";
			result["ProductName"] = productName;
            operation.ReportCompleted(result);
        }
Example #15
0
        private void Decline_Click(object sender, RoutedEventArgs e)
        {
            ValueSet result = new ValueSet();
            result["Status"] = "Cancelled";
			result["ProductName"] = productName;
			operation.ReportCompleted(result);
        }
Example #16
0
        /// <summary>
        /// Hệ thống gọi đến hàm này khi association backgroundtask được bật
        /// </summary>
        /// <param name="taskInstance"> hệ thống tự tạo và truyền vào đây</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //System.Diagnostics.Debug.WriteLine("background run");
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(BackgroundTaskCanceled);
            taskInstance.Task.Completed += new BackgroundTaskCompletedEventHandler(BackgroundTaskCompleted);
            _backgroundstarted.Set();//
            _deferral = taskInstance.GetDeferral();

            //Playlist = new BackgroundPlaylist();
            _smtc = initSMTC();


            this._foregroundState = this.initForegroundState();

            BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayer_CurrentStateChanged;
            //Playlist = await BackgroundPlaylist.LoadBackgroundPlaylist("playlist.xml");
            Playlist = new BackgroundPlaylist();
            Playlist.ListPathsource = await BackgroundPlaylist.LoadCurrentPlaylist(Constant.CurrentPlaylist);
            
            if (_foregroundState != eForegroundState.Suspended)
            {
                ValueSet message = new ValueSet();
                message.Add(Constant.BackgroundTaskStarted, "");
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }  
            Playlist.TrackChanged += Playlist_TrackChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            BackgroundMediaPlayer.Current.MediaEnded +=Current_MediaEnded;
            ApplicationSettingHelper.SaveSettingsValue(Constant.BackgroundTaskState, Constant.BackgroundTaskRunning);
            isbackgroundtaskrunning = true;
            _loopState = eLoopState.None;
        }
Example #17
0
		private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
		{
			var lDeferral = args.GetDeferral();
			try
			{
				var message = args.Request.Message;
				if(message.ContainsKey("MessageType") && message.ContainsKey("Message"))
				{
					var type = message["MessageType"] as String;
					var mes = message["Message"] as String;
					if(type != null && mes != null)
					{
						using(var lh = new LoggingHelper())
						{
							var result = lh.LogEntry(type, mes);
							var vs = new ValueSet();
							vs["result"] = result;
							await args.Request.SendResponseAsync(vs);
						}
					}
				}
			}
			catch { }
			lDeferral.Complete();	
		}
Example #18
0
        private async void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var msgDef = args.GetDeferral();
            var msg = args.Request.Message;
            var returnData = new ValueSet();

            var command = msg["Command"] as string;

            switch (command) {
                case "UI":
                    returnData.Add("sketch-test", "X.Extension.ThirdParty.Backgrounds.UI.Test");
                    returnData.Add("sketch-home", "X.Extension.ThirdParty.Backgrounds.UI.Home");
                    break;
                case "RandomBackground":
                    Random rnd = new Random();
                    returnData.Add("filename", $"bkg0{rnd.Next(1, 5)}.jpg");
                    break;
                case "Spritesheet":
                    returnData.Add("spritesheet-img", "bkg-spritesheet.jpg");
                    returnData.Add("spritesheet-xml", "bkg-spritesheet.xml");
                    break;
            }
            
            await args.Request.SendResponseAsync(returnData);
            msgDef.Complete();
        }
        private async void OnPlayClick(object sender, RoutedEventArgs e)
        {
            String url = txtURL.Text;
            String tag = "ra000001";
            Uri hsl = await GetHitChannelHSL(url, tag);
            if (hsl != null)
            {
                // check is phone
                bool isHardwareButtonsAPIPresent =
        Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");

                if (isHardwareButtonsAPIPresent)
                {
                    //Windows.Phone.UI.Input.HardwareButtons.CameraPressed +=
                    //    HardwareButtons_CameraPressed;
                    ValueSet msg = new ValueSet();
                    msg.Add("Play", hsl.OriginalString);
                    BackgroundMediaPlayer.SendMessageToBackground(msg);
                }

                AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(hsl);
                if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
                {
                    _source = result.MediaSource;
                    _source.DownloadRequested += _source_DownloadRequested;
                    _source.DownloadCompleted += _source_DownloadCompleted;
                    _source.DownloadFailed += _source_DownloadFailed;
                    _source.DownloadBitrateChanged += _source_DownloadBitrateChanged;
                    _source.PlaybackBitrateChanged += _source_PlaybackBitrateChanged;

                    mediaPlayer.SetMediaStreamSource(result.MediaSource);
                }
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            InitializeAndSetMediaTransportControl();

            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
            taskInstance.Task.Completed += Taskcompleted;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ConstantValues.AppState);

            if (value == null)
                _foregroundAppState = ForegroundAppStatus.Unknown;
            else
                _foregroundAppState = (ForegroundAppStatus)Enum.Parse(typeof(ForegroundAppStatus), value.ToString());

            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

            UpdateQueue();

            _queue.TrackChanged += playList_TrackChanged;

            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

            if (_foregroundAppState != ForegroundAppStatus.Suspended)
            {
                ValueSet message = new ValueSet { { ConstantValues.BackgroundTaskStarted, "" } };
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }

            _backgroundTaskStarted.Set();
            _backgroundtaskrunning = true;
            
            ApplicationSettingsHelper.SaveSettingsValue(ConstantValues.BackgroundTaskState, ConstantValues.BackgroundTaskRunning);
            _deferral = taskInstance.GetDeferral();
        }
        public static async Task<OperationResult> NewIncomingCallAsync(String contactName, String contactNumber)
        {
            if (!ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1))
            {
                return OperationResult.Failed;
            }

            AppServiceHelper appServiceHelper = new AppServiceHelper();

            ValueSet message = new ValueSet();
            message[BackgroundOperation.NewBackgroundRequest] = (int)BackgroundRequest.NewIncomingCall;
            message[NewCallArguments.ContactImage.ToString()] = "";
            message[NewCallArguments.ContactName.ToString()] = contactName;
            message[NewCallArguments.ContactNumber.ToString()] = contactNumber;
            message[NewCallArguments.ServiceName.ToString()] = "My First UWP Voip App";
            
            ValueSet response = await appServiceHelper.SendMessageAsync(message);

            if (response != null)
            {
                return ((OperationResult)(response[BackgroundOperation.Result]));
            }

            return OperationResult.Failed;
        }
        private async Task<string> SendMessageAsync(ValueSet message)
        {
            using (var connection = new AppServiceConnection())
            {
                connection.AppServiceName = BookServiceName;
                connection.PackageFamilyName = BooksPackageName;

                AppServiceConnectionStatus status = await connection.OpenAsync();
                if (status == AppServiceConnectionStatus.Success)
                {
                    AppServiceResponse response = await connection.SendMessageAsync(message);
                    if (response.Status == AppServiceResponseStatus.Success && response.Message.ContainsKey("result"))
                    {
                        string result = response.Message["result"].ToString();
                        return result;
                    }
                    else
                    {
                        await ShowServiceErrorAsync(response.Status);
                    }

                }
                else
                {
                    await ShowConnectionErrorAsync(status);
                }

                return string.Empty;
            }
        }
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var message = args.Request.Message;
            string command = message["Command"] as string;

            switch (command)
            {
                case "Initialize":
                    var messageDeferral = args.GetDeferral();
                    //Set a result to return to the caller
                    var returnMessage = new ValueSet();
                    HttpServer server = new HttpServer(8000, appServiceConnection);
                    IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
                        (workItem) =>
                        {
                            server.StartServer();
                        });
                    returnMessage.Add("Status", "Success");
                    var responseStatus = await args.Request.SendResponseAsync(returnMessage);
                    messageDeferral.Complete();
                    break;
                case "Quit":
                    //Service was asked to quit. Give us service deferral
                    //so platform can terminate the background task
                    serviceDeferral.Complete();
                    break;
            }
        }
 private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
 {
     var deferral = args.GetDeferral();
     var response = new ValueSet();
     bool stop = false;
     try
     {
         var request = args.Request;
         var message = request.Message;
         if (message.ContainsKey(BackgroundOperation.NewBackgroundRequest))
         {
             switch ((BackgroundRequest)message[BackgroundOperation.NewBackgroundRequest])
             {
                 default:
                     stop = true;
                     break;
             }
         }
     }
     finally
     {
        
         if (stop)
         {
             _deferral.Complete();
         }
     }
 }
        public async Task<IEnumerable<Beer>> GetBeersByFilter(string filter)
        {
            AppServiceConnection connection = new AppServiceConnection();
            connection.AppServiceName = "PlainConcepts-appservicesdemo";
            connection.PackageFamilyName = "cff6d46b-5839-4bb7-a1f2-e59246de63b3_cb1hhkscw5m06";
            AppServiceConnectionStatus connectionStatus = await connection.OpenAsync();

            if (connectionStatus == AppServiceConnectionStatus.Success)
            {
                //Send data to the service
                var message = new ValueSet();
                message.Add("Command", "GetBeersByFilter");
                message.Add("Filter", filter);

                //Send message and wait for response   
                AppServiceResponse response = await connection.SendMessageAsync(message);
                if (response.Status == AppServiceResponseStatus.Success)
                {
                    var resultJson = (string)response.Message["Result"];
                    var list = JsonConvert.DeserializeObject<IEnumerable<Beer>>(resultJson);
                    return list;
                }
            }
            else
            {
                //Drive the user to store to install the app that provides the app service 
                new MessageDialog("Service not installed").ShowAsync();
            }

            return null;
        }
Example #26
0
        private async void GetEmployeeById(object sender, RoutedEventArgs e)
        {

            appServiceConnection = new AppServiceConnection
            {
                AppServiceName = "EmployeeLookupService",
                PackageFamilyName = "3598a822-2b34-44cc-9a20-421137c7511f_4frctqp64dy5c"
            };

            var status = await appServiceConnection.OpenAsync();

            switch (status)
            {
                case AppServiceConnectionStatus.AppNotInstalled:
                    await LogError("The EmployeeLookup application is not installed. Please install it and try again.");
                    return;
                case AppServiceConnectionStatus.AppServiceUnavailable:
                    await LogError("The EmployeeLookup application does not have the available feature");
                    return;
                case AppServiceConnectionStatus.AppUnavailable:
                    await LogError("The package for the app service to which a connection was attempted is unavailable.");
                    return;
                case AppServiceConnectionStatus.Unknown:
                    await LogError("Unknown Error.");
                    return;
            }

            var items = this.EmployeeId.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            var message = new ValueSet();

            for (int i = 0; i < items.Length; i++)
            {
                message.Add(i.ToString(), items[i]);
            }

            var response = await appServiceConnection.SendMessageAsync(message);

            switch (response.Status)
            {
                case AppServiceResponseStatus.ResourceLimitsExceeded:
                    await LogError("Insufficient resources. The app service has been shut down.");
                    return;
                case AppServiceResponseStatus.Failure:
                    await LogError("Failed to receive response.");
                    return;
                case AppServiceResponseStatus.Unknown:
                    await LogError("Unknown error.");
                    return;
            }

            foreach (var item in response.Message)
            {
                this.Items.Add(new Employee
                {
                    Id = item.Key,
                    Name = item.Value.ToString()
                });
            }
        }
Example #27
0
		private async void LaunchUriForResult_Click(object sender, RoutedEventArgs e)
		{
			var protocol = "win10demo2://";
			var packageFamilyName = "041cdcf9-8ef3-40e4-85e2-8f3de5e06155_ncrzdc1cmma1g";
			var status = await Launcher.QueryUriSupportAsync(new Uri(protocol), LaunchQuerySupportType.UriForResults, packageFamilyName);
			if (status == LaunchQuerySupportStatus.Available)
			{
				var options = new LauncherOptions
				{
					TargetApplicationPackageFamilyName = packageFamilyName
				};
				var values = new ValueSet();
				values.Add("TwitterId", "danvy");
				var result = await Launcher.LaunchUriForResultsAsync(new Uri(protocol), options, values);
				if ((result.Status == LaunchUriStatus.Success) && (result.Result != null))
				{
					var authorized = result.Result["Authorized"] as string;
					if (authorized == true.ToString())
					{
						var dialog = new MessageDialog("You are authorized :)");
						await dialog.ShowAsync();
					}
				}
			}
		}
        private async Task CheckOut()
        {
            var checkoutAppUri = new Uri("checkoutdemo:");

            // We want a specific app to perform our checkout operation, not just any that implements the protocol we're using for launch
            var options = new LauncherOptions();
            options.TargetApplicationPackageFamilyName = "7d7072f5-7a53-47f6-9932-97647aad9550_z5jhcbv2wstvg";

            var transactionId = Guid.NewGuid().ToString();

            var inputData = new ValueSet();

            // Our collection is too complicated for ValueSet to understand so we serialize it first
            var serializedSelectedItems = JsonConvert.SerializeObject(this.AvailableProducts.Where(p => p.IsSelected).Select(p => new { Description = p.Name, UnitPrice = p.Price, Quantity = 1 }).ToList());

            inputData["Items"] = serializedSelectedItems;
            inputData["Transaction"] = transactionId;

            var response = await Launcher.LaunchUriForResultsAsync(checkoutAppUri, options, inputData);
            if (response.Status == LaunchUriStatus.Success)
            {
                Frame.Navigate(typeof(Receipt), response.Result);
            }
            else
            {
                // TODO: handle failure to launch...
            }
        }
        /// <summary>
        /// Launch the pick'n'crop task
        /// </summary>
        /// <returns>In case of success, a cropped image saved in StorageFile</returns>
        public async Task<StorageFile> LaunchAsync()
        {
            if (CropWidthPixels <= 0 || CropHeightPixels <= 0)
            {
                throw new ArgumentException("Cannot crop an image with zero or null dimension",
                    CropWidthPixels <= 0 ? "CropWidthPixels" : "CropHeightPixels");
            }

            var storageAssembly = typeof(Windows.ApplicationModel.DataTransfer.DataPackage).GetTypeInfo().Assembly;

            var storageManagerType =
                storageAssembly.GetType("Windows.ApplicationModel.DataTransfer.SharedStorageAccessManager");

            var token =
                storageManagerType.GetTypeInfo()
                    .DeclaredMethods.FirstOrDefault(m => m.Name == "AddFile")
                    .Invoke(storageManagerType, new object[] {OutputFile});

            var parameters = new ValueSet
            {
                {"CropWidthPixels", CropWidthPixels},
                {"CropHeightPixels", CropHeightPixels},
                {"EllipticalCrop", EllipticalCrop},
                {"ShowCamera", ShowCamera},
                {"DestinationToken", token}
            };

            var launcherAssembly = typeof(Launcher).GetTypeInfo().Assembly;

            var optionsType = launcherAssembly.GetType("Windows.System.LauncherOptions");

            var options = Activator.CreateInstance(optionsType);

            var targetProperty = options.GetType().GetRuntimeProperty("TargetApplicationPackageFamilyName");

            targetProperty.SetValue(options, "Microsoft.Windows.Photos_8wekyb3d8bbwe");

            var launcherType = launcherAssembly.GetType("Windows.System.Launcher");

            var launchUriResult = launcherAssembly.GetType("Windows.System.LaunchUriResult");

            var asTask = GetAsTask();

            var t = asTask.MakeGenericMethod(launchUriResult);

            var method = launcherType.GetTypeInfo()
                .DeclaredMethods.FirstOrDefault(
                    m => m.Name == "LaunchUriForResultsAsync" && m.GetParameters().Length == 3);

            var mt = method.Invoke(launcherType,
                new[] { new Uri("microsoft.windows.photos.crop:"), options, parameters });

            var task = t.Invoke(launcherType, new [] { mt });

            var result = await (dynamic)task;

            string statusStr = result.Status.ToString();

            return statusStr.Contains("Success") ? OutputFile : null;
        }
Example #30
0
        private async void OnPCAppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            Debug.WriteLine("OnPCAppServiceRequestReceived");
            AppServiceDeferral messageDeferral = args.GetDeferral();

            try
            {
                if (!args.Request.Message.ContainsKey("Action"))
                {
                    throw new Exception("Invalid message received.");
                }

                string action = args.Request.Message["Action"] as string;

                Debug.WriteLine($"Action: {action}");
                if (action == "Hello")
                {
                    ValueSet vs = new ValueSet
                    {
                        { "Hey", "Hey" }
                    };
                    await args.Request.SendResponseAsync(vs);
                }
                else if (action == "WhyImHere")
                {
                    Debug.WriteLine($"Win32 process asked for its purpose, which is {PCExtensionCurrentPurpose}");
                    if (PCExtensionCurrentPurpose == PCExtensionPurpose.Default)
                    {
                        bool shouldItRun = false;
                        if (ApplicationData.Current.LocalSettings.Values.ContainsKey("SendCloudClipboard"))
                        {
                            bool.TryParse(ApplicationData.Current.LocalSettings.Values["SendCloudClipboard"].ToString(), out shouldItRun);
                        }

                        if (SecureKeyStorage.IsAccountIdStored() == false)
                        {
                            shouldItRun = false;
                        }

                        var status = await args.Request.SendResponseAsync(new ValueSet
                        {
                            { "Answer", shouldItRun ? "Alone" : "Die" },
                            { "AccountId", SecureKeyStorage.GetAccountId() }
                        });
                    }
                    else if (PCExtensionCurrentPurpose == PCExtensionPurpose.Genocide)
                    {
                        var status = await args.Request.SendResponseAsync(new ValueSet
                        {
                            { "Answer", "Genocide" },
                        });
                    }
                    else if (PCExtensionCurrentPurpose == PCExtensionPurpose.ForgetEverything)
                    {
                        var status = await args.Request.SendResponseAsync(new ValueSet
                        {
                            { "Answer", "ForgetEverything" },
                        });
                    }

                    PCExtensionCurrentPurpose = PCExtensionPurpose.Default;
                }
                else if (action == "Die")
                {
                    Application.Current.Exit();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception on OnPCAppServiceRequestReceived: {ex.Message}");
            }
            finally
            {
                messageDeferral.Complete();
                pcAppServiceDeferral?.Complete();
                Debug.WriteLine("Request finished.");
            }
        }
Example #31
0
        /// <summary>
        /// The UWP host has sent a request for something. Responses to the UWP app are
        /// sent by the respective case handlers, to the UWP Connection_RequestReceived handler
        /// via the AppServiceConnection.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var deferral = args.GetDeferral();

            ValueSet message    = args.Request.Message;
            ValueSet returnData = new ValueSet();

            // get the verb or "command" for this request
            string verb = message["verb"] as String;

            switch (verb)
            {
            // we received a request to get the Startup program names
            case "getStartupProgramNames":
            {
                try
                {
                    // we switch on the value of the verb in the UWP app that receives this valueSet
                    returnData.Add("verb", "RegistryReadResult");

                    // open HKLM with a 64bit view. If you use Registry32, your view will be virtualized to the current user
                    RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);

                    // Open the key where the Startup programs are listed for read-only access.  Cannot write
                    // to the registry from an unelevated Win32 process.
                    RegistryKey key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);

                    string[] names = key.GetValueNames();

                    // add the names to our response
                    returnData.Add("StartupProgramNames", names);
                }
                catch (Exception ex)
                {
                    returnData.Add("verb", "RegistryReadError");
                    returnData.Add("exceptionMessage", ex.Message.ToString());
                }

                break;
            }

            // we received a request to write the registry
            case "elevatedRegistryWrite":
            {
                // the exitCode is the only response we receive from LaunchElevatedRegistryWrite
                int exitCode = LaunchElevatedRegistryWrite();

                returnData.Add("exitcode", exitCode);
                break;
            }
            }

            try
            {
                // Return the data to the caller.
                await args.Request.SendResponseAsync(returnData);
            }
            catch (Exception e)
            {
                // Your exception handling code here.
            }
            finally
            {
                // Complete the deferral so that the platform knows that we're done responding to the app service call.
                // Note for error handling: this must be called even if SendResponseAsync() throws an exception.
                deferral.Complete();
            }
        }
Example #32
0
        private async Task Launch(LaunchOption option)
        {
            //Check connection to launch agent
            if (AppServiceManager.appServiceConnection == null)
            {
                return;
            }

            List <MinecraftAssembly> missingLibs   = null; //include missing natives
            List <MinecraftAsset>    missingAssets = new List <MinecraftAsset>();

            #region Libraries and natives check
            ValueSet valueSet = new ValueSet();
            valueSet["type"]    = "librariesCheck";
            valueSet["version"] = option.versionId;
            AppServiceResponse response = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

            string responseJson = response.Message["value"].ToString();
            try
            {
                missingLibs = JsonConvert.DeserializeObject <List <MinecraftAssembly> >(responseJson);
            }
            catch (JsonException)
            { }
            #endregion

            #region Assets check
            valueSet            = new ValueSet();
            valueSet["type"]    = "assetsCheck";
            valueSet["version"] = option.versionId;
            response            = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

            object obj = null;
            response.Message.TryGetValue("index_path", out obj);
            // Asset index dose not exist or invalid
            if (obj != null)
            {
                string path = obj.ToString();
                string url  = response.Message["index_url"].ToString();

                try
                {
                    using (HttpClient client = new HttpClient())
                    {
                        string json = await client.GetStringAsync(url);

                        StorageFile file = await CoreManager.WorkDir.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);

                        await FileIO.WriteTextAsync(file, json);
                    }
                }
                catch (Exception e)
                {
                    await _msgDialog.Show(
                        CoreManager.GetStringFromResource("/StartPage/LaunchFailed"),
                        "Cannot fetch asset index \r\n " + e.Message + "\r\n" + e.StackTrace
                        );

                    return;
                }

                //Check again after asset index downloaded
                response = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

                obj = null;
                response.Message.TryGetValue("index_path", out obj);
                if (obj != null)
                {
                    await _msgDialog.Show(
                        CoreManager.GetStringFromResource("/StartPage/LaunchFailed"),
                        "Asset index validation failed");

                    return;
                }
            }

            responseJson = response.Message["missing_assets"].ToString();
            try
            {
                missingAssets = JsonConvert.DeserializeObject <List <MinecraftAsset> >(responseJson);
            }
            catch (JsonException) { }
            #endregion

            //Found missing libs, go to download.
            if ((missingLibs != null && missingLibs.Count > 0) || (missingAssets != null && missingAssets.Count > 0))
            {
                missingLibs.ForEach(lib =>
                {
                    DownloadItem item = new DownloadItem(lib.Name, lib.Path, lib.Url);
                    DownloadManager.DownloadQuene.Add(item);
                });
                missingAssets.ForEach(ass =>
                {
                    DownloadItem item = new DownloadItem(
                        string.Format("{0}: {1}", CoreManager.GetStringFromResource("/Resources/Asset"), ass.Hash),
                        ass.GetPath(),
                        ass.GetDownloadUrl()
                        );
                    DownloadManager.DownloadQuene.Add(item);
                });

                DownloadManager.StartDownload();
                await DownloadDialog.ShowAsync();

                return;
            }

            DebugWriteLine("Serializing launch message to json");

            string messageJson;
            try
            {
                LaunchOptionBase tmp = option as LaunchOptionBase;
                if (string.IsNullOrWhiteSpace(option.javaExt))
                {
                    tmp.javaExt = CoreManager.GlobalJVMPath;
                }
                messageJson = JsonConvert.SerializeObject(tmp);
            }
            catch (JsonSerializationException exp)
            {
                DebugWriteLine("ERROR: " + exp.Message);
                return;
            }

            DebugWriteLine(messageJson);

            //Check if the launch message was successfully generated
            if (!string.IsNullOrWhiteSpace(messageJson))
            {
                valueSet = new ValueSet();
                valueSet.Add("type", "launch");
                valueSet.Add("launch_option", messageJson);
                valueSet.Add("auth_type", CoreManager.AccountTypeTag);
                valueSet.Add("auth_username", CoreManager.Username);
                response = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

                //Display error
                obj = response.Message["result"];
                if (obj is bool && !((bool)obj))
                {
                    await _msgDialog.Show(
                        CoreManager.GetStringFromResource("/StartPage/LaunchFailed"),
                        response.Message["errorMessage"].ToString() + "\r\n" + response.Message["errorStack"]
                        );
                }
            }
        }
Example #33
0
        private async void GenerateRandomNumber_Click(object sender, RoutedEventArgs e)
        {
            //Parse user input
            int  minValueInput = 0;
            bool valueParsed   = int.TryParse(MinValue.Text, out minValueInput);

            if (!valueParsed)
            {
                NotifyUser("The Minimum Value should be a valid integer", NotifyType.ErrorMessage);
                return;
            }

            int maxValueInput = 0;

            valueParsed = int.TryParse(MaxValue.Text, out maxValueInput);
            if (!valueParsed)
            {
                NotifyUser("The Maximum Value should be a valid integer", NotifyType.ErrorMessage);
                return;
            }

            if (maxValueInput <= minValueInput)
            {
                NotifyUser("Maximum Value must be larger than Minimum Value", NotifyType.ErrorMessage);
                return;
            }

            using (var connection = new AppServiceConnection())
            {
                //Set up a new app service connection
                connection.AppServiceName    = "com.microsoft.randomnumbergenerator";
                connection.PackageFamilyName = "Microsoft.SDKSamples.AppServicesProvider.CS_876gvmnfevegr";

                AppServiceConnectionStatus status = await connection.OpenAsync();

                //The new connection opened successfully
                if (status == AppServiceConnectionStatus.Success)
                {
                    NotifyUser("Connection established", NotifyType.StatusMessage);
                }

                //If something went wrong. Lets figure out what it was and show the
                //user a meaningful message and walk away
                switch (status)
                {
                case AppServiceConnectionStatus.AppNotInstalled:
                    NotifyUser("The app AppServicesProvider is not installed. Deploy AppServicesProvider to this device and try again.", NotifyType.ErrorMessage);
                    return;

                case AppServiceConnectionStatus.AppUnavailable:
                    NotifyUser("The app AppServicesProvider is not available. This could be because it is currently being updated or was installed to a removable device that is no longer available.", NotifyType.ErrorMessage);
                    return;

                case AppServiceConnectionStatus.AppServiceUnavailable:
                    NotifyUser(string.Format("The app AppServicesProvider is installed but it does not provide the app service {0}.", connection.AppServiceName), NotifyType.ErrorMessage);
                    return;

                case AppServiceConnectionStatus.Unknown:
                    NotifyUser("An unkown error occurred while we were trying to open an AppServiceConnection.", NotifyType.ErrorMessage);
                    return;
                }

                //Set up the inputs and send a message to the service
                var inputs = new ValueSet();
                inputs.Add("minvalue", minValueInput);
                inputs.Add("maxvalue", maxValueInput);
                AppServiceResponse response = await connection.SendMessageAsync(inputs);

                //If the service responded with success display the result and walk away
                if (response.Status == AppServiceResponseStatus.Success &&
                    response.Message.ContainsKey("result"))
                {
                    var resultText = response.Message["result"].ToString();
                    if (!string.IsNullOrEmpty(resultText))
                    {
                        Result.Text = resultText;
                        NotifyUser("App service responded with a result", NotifyType.StatusMessage);
                    }
                    else
                    {
                        NotifyUser("App service did not respond with a result", NotifyType.ErrorMessage);
                    }

                    return;
                }

                //Something went wrong while sending a message. Let display
                //a meaningful error message
                switch (response.Status)
                {
                case AppServiceResponseStatus.Failure:
                    NotifyUser("The service failed to acknowledge the message we sent it. It may have been terminated or it's RequestReceived handler might not be handling incoming messages correctly.", NotifyType.ErrorMessage);
                    return;

                case AppServiceResponseStatus.ResourceLimitsExceeded:
                    NotifyUser("The service exceeded the resources allocated to it and had to be terminated.", NotifyType.ErrorMessage);
                    return;

                case AppServiceResponseStatus.Unknown:
                    NotifyUser("An unkown error occurred while we were trying to send a message to the service.", NotifyType.ErrorMessage);
                    return;
                }
            }
        }
Example #34
0
        private void StartBtn_Click(object sender, RoutedEventArgs e)
        {
            source             = new CancellationTokenSource();
            token              = source.Token;
            StopBtn.IsEnabled  = true;
            StartBtn.IsEnabled = false;
            Task.Run(async() =>
            {
                Debug.WriteLine("Start Screen Cast");
                while (token.IsCancellationRequested == false)
                {
                    ValueSet valueSet = new ValueSet
                    {
                        { "screen", isCompressData }
                    };

                    if (App.Connection != null)
                    {
                        stopwatch.Start();
                        AppServiceResponse response = await App.Connection.SendMessageAsync(valueSet);
                        var responseTime            = stopwatch.Elapsed.Milliseconds;

                        var screenBytes = response.Message["screen"] as byte[];
                        var width       = (int)response.Message["screenWidth"];
                        var height      = (int)response.Message["screenHeight"];

                        double len = Math.Round((double)screenBytes.Length / 1024, 2);

                        if (swapChain == null)
                        {
                            await InitShapChain(width, height);
                        }

                        stopwatch.Restart();

                        var decompressTime = 0;
                        if (isCompressData == true)
                        {
                            screenBytes    = Decompress(screenBytes);
                            decompressTime = stopwatch.Elapsed.Milliseconds;
                            stopwatch.Restart();
                        }

                        using (CanvasDrawingSession ds = SwapChainPanel.SwapChain.CreateDrawingSession(Colors.Transparent))
                        {
                            using (CanvasBitmap screen = CanvasBitmap.CreateFromBytes(device, screenBytes, width, height, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized))
                            {
                                ds.DrawImage(screen, new Windows.Foundation.Rect(0, 0, 800, 600));
                            }
                        }
                        SwapChainPanel.SwapChain.Present();
                        var drawTime = stopwatch.Elapsed.Milliseconds;
                        stopwatch.Stop();

                        Debug.WriteLine($"Response: {responseTime} ms Draw:{drawTime} ms Decompress: {decompressTime} ms Length: {len} Kb");
                    }
                    await Task.Delay(TimeSpan.FromMilliseconds(25));
                }
                Debug.WriteLine("Stop Screen Cast");
            }, token);
        }
Example #35
0
        public void CouplingGwRiver()
        {
            /// bit 1: Decides whether the timeInterpolator or grid-to-line adaptor comes first
            /// bit 2: when true, using a 16x16 gw grid (instead of 2x2)
            /// bit 3: when true, bi-directinal: adds a link from gwModel to river, with the gw-level

            for (int runNumber = 0; runNumber < 8; runNumber++)
            {
                //if (runNumber != 3)
                //  continue;

                Console.Out.WriteLine("runNumber: " + runNumber);

                // Create trigger inputs
                Input queryDischargeItem = CreateDischargeInput();
                Input queryVolume        = CreateVolumeInput();

                // Create models
                LinkableEngine      riverModel = CreateRiverModel();
                ITimeSpaceComponent gwModel    = CreateGwModel();

                // Add arguments and initialize
                IDictionary <string, IArgument> gwArgs = gwModel.Arguments.Dictionary();
                // Increasing model grid size (otherwise GW model runs full too fast)
                gwArgs.UpdateValue("dx", 400.0);
                gwArgs.UpdateValue("dy", 400.0);
                gwArgs.UpdateValue("x0", 200.0);
                gwArgs.UpdateValue("y0", 200.0);
                int gwGridSize = 2 * 2;
                if ((runNumber & 2) == 2) // set 16 x 16 grid
                {
                    gwArgs.UpdateValue("dx", 50.0);
                    gwArgs.UpdateValue("dy", 50.0);
                    gwArgs.UpdateValue("XCount", 16);
                    gwArgs.UpdateValue("ycount", 16);
                    gwGridSize = 16 * 16;
                }
                gwModel.Initialize();

                IDictionary <string, IArgument> riverArgs = riverModel.Arguments.Dictionary();
                // Increasing model grid size (otherwise GW model runs full too fast)
                riverArgs.UpdateValue("xyscale", 100.0);
                riverModel.Initialize();

                // Connect triggering inputs
                ITimeSpaceOutput flowOnBranch  = UTHelper.FindOutputItem(riverModel, "Branch:2:Flow");
                TimeInterpolator flowOnBranch2 = new TimeInterpolator(flowOnBranch);
                flowOnBranch.AddAdaptedOutput(flowOnBranch2);
                flowOnBranch2.AddConsumer(queryDischargeItem);

                ITimeSpaceOutput storageInGw  = UTHelper.FindOutputItem(gwModel, "Grid.Storage");
                TimeInterpolator storageInGw2 = new TimeInterpolator(storageInGw);
                storageInGw.AddAdaptedOutput(storageInGw2);
                storageInGw2.AddConsumer(queryVolume);

                //========== Couple leakage items ==========
                // put leakage from river into ground water model
                {
                    ITimeSpaceOutput riverLeakageOutput = UTHelper.FindOutputItem(riverModel, "WholeRiver:Leakage");
                    ITimeSpaceInput  gwInflowInput      = UTHelper.FindInputItem(gwModel, "Grid.Inflow");

                    // Two adaptors are added: Time buffer and line-to-grid adaptor
                    // they can be added in any order (though time buffer first will use less memory)
                    if ((runNumber & 1) == 1)
                    {
                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutput);
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput2,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput2.AddAdaptedOutput(riverLeakageOutputGrid);

                        riverLeakageOutputGrid.AddConsumer(gwInflowInput);
                    }
                    else
                    {
                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutputGrid);

                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutputGrid);
                        riverLeakageOutputGrid.AddAdaptedOutput(riverLeakageOutput2);

                        riverLeakageOutput2.AddConsumer(gwInflowInput);
                    }
                }
                //========== Couple ground water level items ==========

                if ((runNumber & 4) == 4)
                {
                    // put ground water level from ground water model into river
                    ITimeSpaceInput  riverGwleveInput = UTHelper.FindInputItem(riverModel, "WholeRiver:GroundWaterLevel");
                    ITimeSpaceOutput gwLevelOutput    = UTHelper.FindOutputItem(gwModel, "Grid.gwLevel");

                    // Two adaptors are added: Time buffer and grid-to-line adaptor
                    // they can be added in any order (though time buffer last will use less memory)
                    if ((runNumber & 1) == 1)
                    {
                        // Time interpolator
                        var gwLevelOutput2 = new TimeExtrapolator(gwLevelOutput);
                        gwLevelOutput.AddAdaptedOutput(gwLevelOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        var gwLevelOutputLine =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper700"), gwLevelOutput2,
                                                           riverGwleveInput.ElementSet());
                        gwLevelOutput2.AddAdaptedOutput(gwLevelOutputLine);

                        gwLevelOutputLine.AddConsumer(riverGwleveInput);
                    }
                    else
                    {
                        // Element mapper from polyline to polygon, weighted sum version
                        var gwLevelOutputLine =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper700"), gwLevelOutput,
                                                           riverGwleveInput.ElementSet());
                        gwLevelOutput.AddAdaptedOutput(gwLevelOutputLine);

                        // Time interpolator
                        var gwLevelOutput2 = new TimeExtrapolator(gwLevelOutputLine);
                        gwLevelOutputLine.AddAdaptedOutput(gwLevelOutput2);

                        gwLevelOutput2.AddConsumer(riverGwleveInput);
                    }
                }

                //========== Run ==========

                // Validate
                riverModel.Validate();
                Assert.IsTrue(riverModel.Status == LinkableComponentStatus.Valid);
                gwModel.Validate();
                Assert.IsTrue(gwModel.Status == LinkableComponentStatus.Valid);

                // Prepare
                riverModel.Prepare();
                Assert.IsTrue(riverModel.Status == LinkableComponentStatus.Updated);
                gwModel.Prepare();
                Assert.IsTrue(gwModel.Status == LinkableComponentStatus.Updated);


                // specify query times
                double triggerTime0 = riverModel.CurrentTime.StampAsModifiedJulianDay;
                double triggerTime1 = triggerTime0 + 1;
                double triggerTime2 = triggerTime0 + 2;
                double triggerTime3 = triggerTime0 + 12.1;
                double triggerTime4 = triggerTime0 + 16.7;

                /// Properties of the river, without gw-level input
                /// Inflow into each node from rainfall runoff is 10 L/s
                /// Inflow to node 1: 10        L/s - leaking  5   L/s on branch 1
                /// Inflow to node 2: 10 +    5 L/s - leaking 15/2 L/s on branch 2
                /// Inflow to node 3: 10 + 15/2 L/s - leaking 35/4 L/s on branch 3
                /// Total leakage 5+15/2+35/4 = (20+30+35)/4 = 85/4 L/s
                ///
                /// Number of seconds in a day: 60*60*24 = 86400

                // check initial values
                Assert.AreEqual(1, ValueSet.GetElementCount(flowOnBranch.Values), "#values for " + flowOnBranch.Id);
                Assert.AreEqual(7.0, (double)flowOnBranch.Values.GetValue(0, 0), "Value[0] as property");

                Assert.AreEqual(gwGridSize, ValueSet.GetElementCount(storageInGw.Values), "#values for " + storageInGw.Id);
                Assert.AreEqual(0, SumTimeStep(storageInGw.Values, 0));

                // get values for specified query times, 1 days
                // Totally leaking: 86400 * 85/4 = 1.836e6
                // For the bi-directional coupling:
                // the entire first day the river uses extrapolated values from the
                // gwModel, which gives a gwLevel of -10, hence same value as for the uni-directional
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime1);
                ITimeSpaceValueSet valuesV = storageInGw2.GetValues(queryDischargeItem);
                ITimeSpaceValueSet valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                Assert.AreEqual(1.836e6, SumTimeStep(valuesV, 0), 1e-4);

                // Print out, to load in a plotting program for verification
                //StringBuilder b = new StringBuilder();
                //foreach (double val in valuesV.GetElementValuesForTime(0))
                //  b.AppendLine(val.ToString(NumberFormatInfo.InvariantInfo));
                //Console.Out.WriteLine(b.ToString());

                // get values for specified query times, 2 days
                // 2 * 86400 * 85/4 = 3.672e6
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime2);
                valuesV = storageInGw2.GetValues(queryDischargeItem);
                valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                if ((runNumber & 4) != 4) // unidirectional
                {
                    Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                    Assert.AreEqual(3.672e6, SumTimeStep(valuesV, 0), 1e-4);
                }
                else if ((runNumber & 2) != 2) // bi-directional 2x2 grid
                {
                    Assert.AreEqual(8.843648, (double)valuesQ.GetValue(0, 0), 1e-4);
                    Assert.AreEqual(3.66390879366e6, SumTimeStep(valuesV, 0), 1e-4);
                }
                else                    // bi-directional 16x16 grid
                {
                    Assert.AreEqual(9.65307, (double)valuesQ.GetValue(0, 0), 1e-4);
                    Assert.AreEqual(3.59397465219e6, SumTimeStep(valuesV, 0), 1e-4);
                }

                // get values for specified query times, 12.1 days
                // 12.1 * 86400 * 85/4 = 2.22156e7
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime3);
                valuesV = storageInGw2.GetValues(queryDischargeItem);
                valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                if ((runNumber & 4) != 4) // unidirectional
                {
                    Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                    Assert.AreEqual(2.22156e7, SumTimeStep(valuesV, 0), 1e-4);
                }
                else if ((runNumber & 2) != 2) // bi-directional 2x2 grid
                {
                    Assert.AreEqual(9.87828, (double)valuesQ.GetValue(0, 0), 1e-4);
                    Assert.AreEqual(2.16704019338e7, SumTimeStep(valuesV, 0), 1e-4);
                }
                else                    // bi-directional 16x16 grid
                {
                    Assert.AreEqual(18.546999, (double)valuesQ.GetValue(0, 0), 1e-4);
                    Assert.AreEqual(1.722400002557e7, SumTimeStep(valuesV, 0), 1e-4);
                }

                // get values for specified query times, 16.7 days
                // 16.7 * 86400 * 85/4 = 3.06612e7
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime4);
                valuesV = storageInGw2.GetValues(queryDischargeItem);
                valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                if ((runNumber & 4) != 4) // unidirectional
                {
                    Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                    Assert.AreEqual(3.06612e7, SumTimeStep(valuesV, 0), 1e-4);
                }
                else if ((runNumber & 2) != 2) // bi-directional 2x2 grid
                {
                    Assert.AreEqual(10.255535, (double)valuesQ.GetValue(0, 0), 1e-4);
                    Assert.AreEqual(2.9595872035072e7, SumTimeStep(valuesV, 0), 1e-4);
                }
                else                    // bi-directional 16x16 grid
                {
                    Assert.AreEqual(20.98699, (double)valuesQ.GetValue(0, 0), 1e-4);
                    Assert.AreEqual(2.12991179998e7, SumTimeStep(valuesV, 0), 1e-4);
                }
            }
        }
Example #36
0
        protected string DetermineValueSetStatus(Model.ImportValueSet importValueSet, ValueSet currentValueSet)
        {
            if (currentValueSet == null)
            {
                return("Add");
            }
            else
            {
                bool valueSetIsChanged =
                    importValueSet.Code != currentValueSet.Code ||
                    importValueSet.Description != currentValueSet.Description ||
                    importValueSet.Name != currentValueSet.Name;

                if (valueSetIsChanged)
                {
                    return("Update");
                }
            }

            return("None");
        }
Example #37
0
        private async Task SendMessage(KeyValuePair <Guid, AppServiceConnection> connection, ValueSet valueSet)
        {
            try
            {
                var result = await connection.Value.SendMessageAsync(valueSet);

                if (result.Status == AppServiceResponseStatus.Success)
                {
                    await Debug("Successfully sent message to " + connection.Key + ". Result = " + result.Message);

                    return;
                }
                if (result.Status == AppServiceResponseStatus.Failure)
                {
                    // When an app with an open connection is terminated and it fails
                    //      to dispose of its connection, the connection object remains
                    //      in Connections.  When someone tries to send to it, it gets
                    //      an AppServiceResponseStatus.Failure response
                    await Info("Error sending to " + connection.Key + ".  Removing it from the list of active connections.");

                    RemoveConnection(connection.Key);
                    return;
                }
                await Error("Error sending to " + connection.Key + " - " + result.Status);
            }
            catch (Exception ex)
            {
                await Error("Error SendMessage to " + connection.Key + " " + ex.ToString());
            }
        }
Example #38
0
 public void SetArgsAndGetResults(string args, ValueSet data, ProtocolForResultsOperation op)
 {
     _op = op;
     SetArgs(args, data);
 }
Example #39
0
        public static void GetReturnData(ValueSet message, ref ValueSet returnData)
        {
            string command = message["Command"] as string;

            switch (command.ToUpper())
            {
            case "ZIGBEESTATUS":
            {
                returnData.Add("Result", IsZigBeeStatus);
            }
            break;

            case "DISCOVER":
            {
                StartDeviceDiscovery();
                returnData.Add("Status", "OK");
            }
            break;

            case "GETDISCOVERRUNNING":
            {
                bool rst = IsRunningDiscoverDevices();
                //loggingServices.Write(Log, rst.ToString(), LogLevel.Debug);
                returnData.Add("Result", rst);
                returnData.Add("Status", "OK");
            }
            break;

            case "GETENDDEVICES":
            {
                string result = "";
                try
                {
                    result = JsonConvert.SerializeObject(GetEndDevices());
                }
                catch (Exception e)
                {
                    loggingServices.Write(Log, e.Message, LogLevel.Error, e);
                }
                returnData.Add("Result", result);
                returnData.Add("Status", "OK");
            }
            break;

            case "SETENDDEVICES":
            {
                List <string> result = null;
                try
                {
                    result = SetEndDevices(JsonConvert.DeserializeObject <List <ValueSet> >(message["Param"].ToString()));
                }
                catch (Exception e)
                {
                    loggingServices.Write(Log, e.Message, LogLevel.Error, e);
                }
                returnData.Add("Result", JsonConvert.SerializeObject(result));
                returnData.Add("Status", "OK");
            }
            break;

            case "ONOFFTOGGLE":
            {
                string result = "OnOffToggle Success";
                string status = "OK";

                Model.ZigBee.ZigBeeEndPoint endPoint = JsonConvert.DeserializeObject <Model.ZigBee.ZigBeeEndPoint>(message["endPoint"].ToString());

                if (endPoint != null)
                {
                    if (!OnOffToggle(endPoint, "OnOffToggle"))
                    {
                        result = "Failed to On/Off Toggle";
                        status = "NG";
                    }
                }
                else
                {
                    result = "EndPoint is Null";
                    status = "NG";
                }
                returnData.Add("Result", result);
                returnData.Add("Status", status);
            }
            break;

            case "PLUGPOWERON":
            {
                string result = "Power On Success";
                string status = "OK";

                Model.ZigBee.ZigBeeEndPoint endPoint = JsonConvert.DeserializeObject <Model.ZigBee.ZigBeeEndPoint>(message["endPoint"].ToString());

                if (endPoint != null)
                {
                    if (!OnOffToggle(endPoint, "PowerOn"))
                    {
                        result = "Failed to Power On";
                        status = "NG";
                    }
                }
                else
                {
                    result = "EndPoint is Null";
                    status = "NG";
                }
                returnData.Add("Result", result);
                returnData.Add("Status", status);
            }
            break;

            case "PLUGPOWEROFF":
            {
                string result = "Power Off Success";
                string status = "OK";
                Model.ZigBee.ZigBeeEndPoint endPoint = JsonConvert.DeserializeObject <Model.ZigBee.ZigBeeEndPoint>(message["endPoint"].ToString());

                if (endPoint != null)
                {
                    if (!OnOffToggle(endPoint, "PowerOff"))
                    {
                        result = "Failed to Power Off";
                        status = "NG";
                    }
                }
                else
                {
                    result = "EndPoint is Null";
                    status = "NG";
                }
                returnData.Add("Result", result);
                returnData.Add("Status", status);
            }
            break;

            case "MANAGEMENTLEAVE":
            {
                string result = "Management Leave Success";
                string status = "OK";
                Model.ZigBee.ZigBeeEndDevice endDevice = JsonConvert.DeserializeObject <Model.ZigBee.ZigBeeEndDevice>(message["endDevice"].ToString());

                if (endDevice != null)
                {
                    if (!ManagementLeave(endDevice))
                    {
                        result = "Failed to Management Leave";
                        status = "NG";
                    }
                }
                else
                {
                    result = "EndDevice is Null";
                    status = "NG";
                }
                returnData.Add("Result", result);
                returnData.Add("Status", status);
            }
            break;

            default:
            {
                returnData.Add("Status", "Fail: unknown command");
                break;
            }
            }
        }
Example #40
0
        private void DecorateAttributeFromConstraint(string aParentContext, DocumentTemplateElementAttribute aAttribute, IConstraint aConstraint, ValueSet aConstraintValueSet)
        {
            // Set the attribute's value if the constraint indicates one
            if (!string.IsNullOrEmpty(aConstraint.Value))
            {
                aAttribute.SingleValue = !string.IsNullOrEmpty(aConstraint.Value) ? aConstraint.Value.Trim() : string.Empty;
            }

            // Set the data-type for the attribute if one is present in the constraint
            if (!string.IsNullOrEmpty(aConstraint.DataType))
            {
                aAttribute.DataType = aConstraint.DataType;
            }

            // Do we have a valueset on this attribute?
            if (aConstraintValueSet != null)
            {
                aAttribute.ValueSet = this.igTypePlugin.ParseIdentifier(this.valueSet.GetIdentifier(this.igTypePlugin));
            }

            if (this.codeSystem != null)
            {
                //TODO: CDA specific logic, need to refactor this out to make more dynamic
                if ((aAttribute.AttributeName == "code" || aAttribute.AttributeName == "value") && (aParentContext.EndsWith(this.prefix + ":code") || aParentContext.EndsWith(this.prefix + ":value")))
                {
                    aAttribute.CodeSystemOid = this.igTypePlugin.ParseIdentifier(this.codeSystem.Oid);
                }
            }
        }
Example #41
0
        /// <summary>
        /// This is the main public interface for constraint parser. Takes the given constraint and builds an AssertionLineBuilder, applying the values, attributes, context, etc as necessary.
        /// </summary>
        /// <returns>
        /// AssertionLineBuilder representing the values from the constraint given to the parser.
        /// </returns>
        public AssertionLineBuilder CreateAssertionLineBuilder()
        {
            if (this.valueSet == null && this.constraint.ValueSetId != null)
            {
                this.valueSet = this.tdb.ValueSets.Single(y => y.Id == constraint.ValueSetId);
            }

            if (this.codeSystem == null && this.constraint.ValueCodeSystemId != null)
            {
                this.codeSystem = this.tdb.CodeSystems.Single(y => y.Id == constraint.ValueCodeSystemId);
            }

            IConstraint currentConstraint  = this.constraint; //set current constraint, setting this as a variable allows us to move the current constraint to the parent when dealing with branches
            var         containedTemplates = currentConstraint.References.Where(y => y.ReferenceType == ConstraintReferenceTypes.Template);

            if (string.IsNullOrEmpty(currentConstraint.Context) && !containedTemplates.Any()) //we can have empty context but a contained template
            {
                return(null);
            }

            DocumentTemplateElement          element   = null;
            DocumentTemplateElementAttribute attribute = null;

            ConstraintToDocumentElementHelper.ParseContextForElementAndAttribute(currentConstraint, out element, out attribute);
            DocumentTemplateElement parentElement =
                ConstraintToDocumentElementHelper.CreateParentElementForAttribute(currentConstraint, attribute);

            string parentContext =
                CreateParentContextForElement(parentElement, element, currentConstraint);

            AssertionLineBuilder asb             = null;
            AssertionLineBuilder branchedRootAsb = null;

            // Determine if we should create the AssertionLineBuilder starting with an attribute or an element.
            if (attribute != null)
            {
                DecorateAttributeFromConstraint(parentContext, attribute, currentConstraint, this.valueSet);
                if (currentConstraint.Parent != null && currentConstraint.IsBranch)
                {
                    branchedRootAsb = CreateBranchedRootAssertionLineBuilderFromConstraint(currentConstraint);
                }
                else
                {
                    asb = CreateAssertionLineBuilderForAttribute(parentElement, attribute, ref parentContext, ref currentConstraint);
                }
            }
            else //this is an element
            {
                // Only add the code system constraints if there is no value conformance or the value conformance matches the element/attribute conformance
                // This is because in the SchematronGenerator class, a duplicate constraint is created when the value conformance is different from
                // the element/attribute conformance, where the duplicate constraint's conformance matches the value conformance.
                if (string.IsNullOrEmpty(currentConstraint.ValueConformance) || ConformanceParser.Parse(currentConstraint.Conformance) == ConformanceParser.Parse(currentConstraint.ValueConformance))
                {
                    ConstraintToDocumentElementHelper.AddCodeSystemToElement(this.tdb, this.igTypePlugin, element, currentConstraint);
                }

                if (currentConstraint.IsBranch)
                {
                    branchedRootAsb = CreateBranchedRootAssertionLineBuilderFromConstraint(currentConstraint);
                    branchedRootAsb.HasParentContext(parentContext);
                }
                else
                {
                    //if we have a context already then we will append it at end so pass in false, else go ahead and generate (pass in true)
                    asb = CreateAssertionLineBuilderForElement(element, this.constraint, ref parentContext, string.IsNullOrEmpty(parentContext));
                }
            }

            if (branchedRootAsb == null) //if this is a branched root then a separate builder was constructed
            {
                ConstraintToDocumentElementHelper.AddConformance(currentConstraint, asb);
                ConstraintToDocumentElementHelper.AddCardinality(currentConstraint, asb);
                // Determine if we have a valueset
                if (this.valueSet != null && currentConstraint.IsValueSetStatic)
                {
                    var requireValueset = true;

                    if (!string.IsNullOrEmpty(currentConstraint.ValueConformance))
                    {
                        if (ConformanceParser.Parse(currentConstraint.Conformance) != ConformanceParser.Parse(currentConstraint.ValueConformance))
                        {
                            requireValueset = false;
                        }
                    }

                    if (requireValueset)
                    {
                        //TODO: Move into CDA specific library
                        //are we bound directly to a code or value element?
                        bool includeNullFlavor = false;
                        if (element != null && attribute == null && (element.ElementName == "value" || element.ElementName == "code"))
                        {
                            includeNullFlavor = true;
                        }

                        string valueSetIdentifier = this.igTypePlugin.ParseIdentifier(this.valueSet.GetIdentifier(this.igTypePlugin));
                        asb.WithinValueSet(valueSetIdentifier, this.valueSetFile, this.vocabularyOutputType, includeNullFlavor);
                    }
                }

                //determine if we have a parent context
                if (!string.IsNullOrEmpty(parentContext))
                {
                    asb.HasParentContext(parentContext);
                    DecorateParentOptionality(asb, currentConstraint);
                }
            }
            else //branched root, use that one instead
            {
                //determine if we have a parent context
                if (!string.IsNullOrEmpty(parentContext))
                {
                    branchedRootAsb.HasParentContext(parentContext);
                    DecorateParentOptionality(branchedRootAsb, currentConstraint);
                }
            }

            return((branchedRootAsb == null) ? asb : branchedRootAsb);
        }
                internal static void Set(Collection collection, string key, string value)
                {
                    if (collection.GetSync(() =>
                    {
                        ValueSet vs = Get(collection, key);
                        if (vs == null)
                        {
                            vs = new ValueSet(collection, key);

                            if ((vs._previous = collection._lastSet) == null)
                            {
                                collection._firstSet = vs;
                            }
                            else
                            {
                                vs._previous._next = vs;
                            }
                            collection._lastSet = vs;
                            vs._firstParameter = vs._lastParameter = new UrlQueryParameter(null, value, vs);
                            if ((vs._lastParameter._previousParameter = collection._lastParameter) == null)
                            {
                                collection._firstParameter = vs._lastParameter;
                            }
                            else
                            {
                                collection._lastParameter._nextParameter = vs._lastParameter;
                            }
                            collection._lastParameter = vs._lastParameter;
                            return(true);
                        }
                        return(vs.GetSync(() =>
                        {
                            UrlQueryParameter qp = vs._firstParameter._nextValue;
                            if (key == vs._key)
                            {
                                if ((vs._firstParameter._value == null) ? value == null : value != null && value == vs._firstParameter._value)
                                {
                                    if (qp == null)
                                    {
                                        return false;
                                    }
                                }
                            }
                            do
                            {
                                if (qp._previousValue != null)
                                {
                                    qp._previousValue._nextValue = null;
                                    qp._previousValue = null;
                                }
                                if (qp._previousParameter == null)
                                {
                                    if ((collection._firstParameter = qp._nextParameter) == null)
                                    {
                                        collection._lastParameter = null;
                                    }
                                    else
                                    {
                                        qp._nextParameter = qp._nextParameter._previousParameter = null;
                                    }
                                }
                                else
                                {
                                    if ((qp._previousParameter._nextParameter = qp._nextParameter) == null)
                                    {
                                        collection._lastParameter = qp._previousParameter;
                                    }
                                    else
                                    {
                                        qp._nextParameter._previousParameter = qp._previousParameter;
                                        qp._nextParameter = null;
                                    }
                                    qp._previousParameter = null;
                                }
                            } while ((qp = qp._nextValue) != null);
                            vs._firstParameter._key = null;
                            vs._firstParameter._value = value;
                            vs._key = key;
                            return true;
                        }));
                    }))
                    {
                        collection.OnChange();
                    }
                }
                internal static bool Remove(ValueSet vs)
                {
                    if (vs == null)
                    {
                        return(false);
                    }
                    Collection changedColl = vs.GetSync(() =>
                    {
                        if (vs._collection == null)
                        {
                            return(null);
                        }

                        return(vs._collection.GetSync((Collection c) =>
                        {
                            for (UrlQueryParameter qp = vs._firstParameter; qp != null; qp = vs._firstParameter)
                            {
                                qp.InvokeSync(() =>
                                {
                                    if (qp._previousValue != null || qp._set == null || !ReferenceEquals(qp._set, vs))
                                    {
                                        throw new InvalidOperationException("Collection was modified");
                                    }
                                    if ((vs._firstParameter = qp._nextValue) != null)
                                    {
                                        qp._nextValue = qp._nextValue._previousValue = null;
                                    }
                                    if (qp._key == null)
                                    {
                                        qp._key = vs._key;
                                    }
                                    qp._set = null;
                                    if (qp._previousParameter == null)
                                    {
                                        if ((c._firstParameter = qp._nextParameter) == null)
                                        {
                                            c._lastParameter = null;
                                        }
                                        else
                                        {
                                            qp._nextParameter = qp._nextParameter._previousParameter = null;
                                        }
                                    }
                                    else
                                    {
                                        if ((qp._previousParameter._nextParameter = qp._nextParameter) == null)
                                        {
                                            c._lastParameter = qp._previousParameter;
                                        }
                                        else
                                        {
                                            qp._nextParameter._previousParameter = qp._previousParameter;
                                            qp._nextParameter = null;
                                        }
                                        qp._previousParameter = null;
                                    }
                                });
                            }
                            if (vs._previous == null)
                            {
                                if ((c._firstSet = vs._next) == null)
                                {
                                    c._lastSet = null;
                                }
                                else
                                {
                                    vs._next = vs._next._previous = null;
                                }
                            }
                            else
                            {
                                if ((vs._previous._next = vs._next) == null)
                                {
                                    c._lastSet = vs._previous;
                                }
                                else
                                {
                                    vs._next._previous = vs._previous;
                                    vs._next = null;
                                }
                                vs._previous = null;
                            }
                            vs._collection = null;
                            return c;
                        }, vs._collection));
                    });

                    if (changedColl == null)
                    {
                        return(false);
                    }
                    changedColl.OnChange();
                    return(true);
                }
 public bool ContainsKey(string key)
 {
     return(GetSync(() => ValueSet.Get(this, key) != null));
 }
 public bool Remove(UrlQueryParameter parameter)
 {
     return(parameter != null && ValueSet.Remove(parameter));
 }
 public void Add(string key, string value)
 {
     ValueSet.Add(this, key, value);
 }
 public void Clear()
 {
     ValueSet.Clear(this);
 }
    public override ValueSetValidationResult Validate(ValueSet valueSet)
    {
        ValueSetValidationResult baseValidate = base.Validate(valueSet);

        valueSet = baseValidate.ValueSet;
        if (baseValidate.Status == ValueSetValidationStatus.Failed)
        {
            return(new ValueSetValidationResult(ValueSetValidationStatus.Failed, valueSet));
        }

        var isFiltered = baseValidate.Status == ValueSetValidationStatus.Filtered;

        var filteredValues = valueSet.Values.ToDictionary(x => x.Key, x => x.Value.ToList());

        //check for published content
        if (valueSet.Category == IndexTypes.Content && PublishedValuesOnly)
        {
            if (!valueSet.Values.TryGetValue(UmbracoExamineFieldNames.PublishedFieldName, out IReadOnlyList <object>?published))
            {
                return(new ValueSetValidationResult(ValueSetValidationStatus.Failed, valueSet));
            }

            if (!published[0].Equals("y"))
            {
                return(new ValueSetValidationResult(ValueSetValidationStatus.Failed, valueSet));
            }

            //deal with variants, if there are unpublished variants than we need to remove them from the value set
            if (valueSet.Values.TryGetValue(UmbracoExamineFieldNames.VariesByCultureFieldName, out IReadOnlyList <object>?variesByCulture) &&
                variesByCulture.Count > 0 && variesByCulture[0].Equals("y"))
            {
                //so this valueset is for a content that varies by culture, now check for non-published cultures and remove those values
                foreach (KeyValuePair <string, IReadOnlyList <object> > publishField in valueSet.Values
                         .Where(x => x.Key.StartsWith($"{UmbracoExamineFieldNames.PublishedFieldName}_")).ToList())
                {
                    if (publishField.Value.Count <= 0 || !publishField.Value[0].Equals("y"))
                    {
                        //this culture is not published, so remove all of these culture values
                        var cultureSuffix = publishField.Key.Substring(publishField.Key.LastIndexOf('_'));
                        foreach (KeyValuePair <string, IReadOnlyList <object> > cultureField in valueSet.Values
                                 .Where(x => x.Key.InvariantEndsWith(cultureSuffix)).ToList())
                        {
                            filteredValues.Remove(cultureField.Key);
                            isFiltered = true;
                        }
                    }
                }
            }
        }

        //must have a 'path'
        if (!valueSet.Values.TryGetValue(PathKey, out IReadOnlyList <object>?pathValues))
        {
            return(new ValueSetValidationResult(ValueSetValidationStatus.Failed, valueSet));
        }

        if (pathValues.Count == 0)
        {
            return(new ValueSetValidationResult(ValueSetValidationStatus.Failed, valueSet));
        }

        if (pathValues[0] == null)
        {
            return(new ValueSetValidationResult(ValueSetValidationStatus.Failed, valueSet));
        }

        if (pathValues[0].ToString().IsNullOrWhiteSpace())
        {
            return(new ValueSetValidationResult(ValueSetValidationStatus.Failed, valueSet));
        }

        var path = pathValues[0].ToString();

        var filteredValueSet = new ValueSet(valueSet.Id, valueSet.Category, valueSet.ItemType, filteredValues.ToDictionary(x => x.Key, x => (IEnumerable <object>)x.Value));

        // We need to validate the path of the content based on ParentId, protected content and recycle bin rules.
        // We cannot return FAILED here because we need the value set to get into the indexer and then deal with it from there
        // because we need to remove anything that doesn't pass by protected content in the cases that umbraco data is moved to an illegal parent.
        if (!ValidatePath(path !, valueSet.Category) ||
            !ValidateRecycleBin(path !, valueSet.Category) ||
            !ValidateProtectedContent(path !, valueSet.Category))
        {
            return(new ValueSetValidationResult(ValueSetValidationStatus.Filtered, filteredValueSet));
        }

        return(new ValueSetValidationResult(
                   isFiltered ? ValueSetValidationStatus.Filtered : ValueSetValidationStatus.Valid, filteredValueSet));
    }
Example #49
0
 public IEnumerable <ConceptMap> GetConceptMapsForSource(ValueSet source)
 {
     return(GetConceptMapsForSource(source.Url));
 }
Example #50
0
        private async Task HandleShellLibraryMessage(Dictionary <string, object> message)
        {
            switch ((string)message["action"])
            {
            case "Enumerate":
                // Read library information and send response to UWP
                var enumerateResponse = await Win32API.StartSTATask(() =>
                {
                    var response = new ValueSet();
                    try
                    {
                        var libraryItems = new List <ShellLibraryItem>();
                        // https://docs.microsoft.com/en-us/windows/win32/search/-search-win7-development-scenarios#library-descriptions
                        var libFiles = Directory.EnumerateFiles(ShellLibraryItem.LibrariesPath, "*" + ShellLibraryItem.EXTENSION);
                        foreach (var libFile in libFiles)
                        {
                            using var shellItem = new ShellLibrary2(Shell32.ShellUtil.GetShellItemForPath(libFile), true);
                            if (shellItem is ShellLibrary2 library)
                            {
                                libraryItems.Add(ShellFolderExtensions.GetShellLibraryItem(library, libFile));
                            }
                        }
                        response.Add("Enumerate", JsonConvert.SerializeObject(libraryItems));
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Warn(e);
                    }
                    return(response);
                });

                await Win32API.SendMessageAsync(connection, enumerateResponse, message.Get("RequestID", (string)null));

                break;

            case "Create":
                // Try create new library with the specified name and send response to UWP
                var createResponse = await Win32API.StartSTATask(() =>
                {
                    var response = new ValueSet();
                    try
                    {
                        using var library = new ShellLibrary2((string)message["library"], Shell32.KNOWNFOLDERID.FOLDERID_Libraries, false);
                        library.Folders.Add(ShellItem.Open(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));     // Add default folder so it's not empty
                        library.Commit();
                        library.Reload();
                        response.Add("Create", JsonConvert.SerializeObject(ShellFolderExtensions.GetShellLibraryItem(library, library.GetDisplayName(ShellItemDisplayString.DesktopAbsoluteParsing))));
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Warn(e);
                    }
                    return(response);
                });

                await Win32API.SendMessageAsync(connection, createResponse, message.Get("RequestID", (string)null));

                break;

            case "Update":
                // Update details of the specified library and send response to UWP
                var updateResponse = await Win32API.StartSTATask(() =>
                {
                    var response = new ValueSet();
                    try
                    {
                        var folders           = message.ContainsKey("folders") ? JsonConvert.DeserializeObject <string[]>((string)message["folders"]) : null;
                        var defaultSaveFolder = message.Get("defaultSaveFolder", (string)null);
                        var isPinned          = message.Get("isPinned", (bool?)null);

                        bool updated      = false;
                        var libPath       = (string)message["library"];
                        using var library = new ShellLibrary2(Shell32.ShellUtil.GetShellItemForPath(libPath), false);
                        if (folders != null)
                        {
                            if (folders.Length > 0)
                            {
                                var foldersToRemove = library.Folders.Where(f => !folders.Any(folderPath => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase)));
                                foreach (var toRemove in foldersToRemove)
                                {
                                    library.Folders.Remove(toRemove);
                                    updated = true;
                                }
                                var foldersToAdd = folders.Distinct(StringComparer.OrdinalIgnoreCase)
                                                   .Where(folderPath => !library.Folders.Any(f => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase)))
                                                   .Select(ShellItem.Open);
                                foreach (var toAdd in foldersToAdd)
                                {
                                    library.Folders.Add(toAdd);
                                    updated = true;
                                }
                                foreach (var toAdd in foldersToAdd)
                                {
                                    toAdd.Dispose();
                                }
                            }
                        }
                        if (defaultSaveFolder != null)
                        {
                            library.DefaultSaveFolder = ShellItem.Open(defaultSaveFolder);
                            updated = true;
                        }
                        if (isPinned != null)
                        {
                            library.PinnedToNavigationPane = isPinned == true;
                            updated = true;
                        }
                        if (updated)
                        {
                            library.Commit();
                            library.Reload();     // Reload folders list
                            response.Add("Update", JsonConvert.SerializeObject(ShellFolderExtensions.GetShellLibraryItem(library, libPath)));
                        }
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Warn(e);
                    }
                    return(response);
                });

                await Win32API.SendMessageAsync(connection, updateResponse, message.Get("RequestID", (string)null));

                break;
            }
        }
Example #51
0
 public DuplicateFieldException(ValueSet values)
 {
     Values = values;
 }
Example #52
0
        private static async Task parseArguments(AppServiceRequestReceivedEventArgs args, AppServiceDeferral messageDeferral, string arguments, ApplicationDataContainer localSettings)
        {
            switch (arguments)
            {
            case "Terminate":
                // Exit fulltrust process (UWP is closed or suspended)
                appServiceExit.Set();
                messageDeferral.Complete();
                break;

            case "RecycleBin":
                var binAction = (string)args.Request.Message["action"];
                await parseRecycleBinAction(args, binAction);

                break;

            case "StartupTasks":
                // Check QuickLook Availability
                QuickLook.CheckQuickLookAvailability(localSettings);
                break;

            case "ToggleQuickLook":
                var path = (string)args.Request.Message["path"];
                QuickLook.ToggleQuickLook(path);
                break;

            case "ShellCommand":
                // Kill the process. This is a BRUTAL WAY to kill a process.
#if DEBUG
                // In debug mode this kills this process too??
#else
                var pid = (int)args.Request.Message["pid"];
                Process.GetProcessById(pid).Kill();
#endif

                Process process = new Process();
                process.StartInfo.UseShellExecute = true;
                process.StartInfo.FileName        = "explorer.exe";
                process.StartInfo.CreateNoWindow  = false;
                process.StartInfo.Arguments       = (string)args.Request.Message["ShellCommand"];
                process.Start();
                break;

            case "LoadMUIVerb":
                var responseSet = new ValueSet();
                responseSet.Add("MUIVerbString", Win32API.ExtractStringFromDLL((string)args.Request.Message["MUIVerbLocation"], (int)args.Request.Message["MUIVerbLine"]));
                await args.Request.SendResponseAsync(responseSet);

                break;

            case "ParseAguments":
                var responseArray  = new ValueSet();
                var resultArgument = Win32API.CommandLineToArgs((string)args.Request.Message["Command"]);
                responseArray.Add("ParsedArguments", JsonConvert.SerializeObject(resultArgument));
                await args.Request.SendResponseAsync(responseArray);

                break;

            case "Bitlocker":
                var bitlockerAction = (string)args.Request.Message["action"];
                if (bitlockerAction == "Unlock")
                {
                    var drive    = (string)args.Request.Message["drive"];
                    var password = (string)args.Request.Message["password"];
                    Win32API.UnlockBitlockerDrive(drive, password);
                    await args.Request.SendResponseAsync(new ValueSet()
                    {
                        { "Bitlocker", "Unlock" }
                    });
                }
                break;

            default:
                if (args.Request.Message.ContainsKey("Application"))
                {
                    var application = (string)args.Request.Message["Application"];
                    HandleApplicationLaunch(application, args);
                }
                else if (args.Request.Message.ContainsKey("ApplicationList"))
                {
                    var applicationList = JsonConvert.DeserializeObject <IEnumerable <string> >((string)args.Request.Message["ApplicationList"]);
                    HandleApplicationsLaunch(applicationList, args);
                }
                break;
            }
        }
Example #53
0
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            // Get a deferral because we use an awaitable API below to respond to the message
            // and we don't want this call to get cancelled while we are waiting.
            var messageDeferral = args.GetDeferral();

            ValueSet message    = args.Request.Message;
            ValueSet returnData = new ValueSet();

            string command = message["q"] as string;

            switch (command)
            {
            case "lyric":
                var title = message["title"] as string;
                message.TryGetValue("artist", out object art);
                var artists = art as string;

                var localLrc = await LyricSearcher.SearchLrcLocalAsync(title, artists);

                if (!localLrc.IsNullorEmpty())
                {
                    returnData.Add("result", localLrc);

                    returnData.Add("status", 1);
                    break;
                }

                var substitutes = await LyricSearcher.GetSongLrcListAsync(title, artists);

                if (!substitutes.IsNullorEmpty())
                {
                    var result = await ApiRequestHelper.HttpGet(substitutes.First().Value);

                    if (!result.IsNullorEmpty())
                    {
                        await LyricSearcher.SaveLrcLocalAsync(title, artists, result);
                    }
                    returnData.Add("result", result);
                }
                else
                {
                    returnData.Add("result", null);
                }
                returnData.Add("status", 1);
                break;

            case "online_music":
                var action = message["action"] as string;
                switch (action)
                {
                case "search":
                    message.TryGetValue("page", out object page);
                    message.TryGetValue("count", out object count);
                    var result = await OnlineMusicSearcher.SearchAsync(message["keyword"] as string, page as int?, count as int?);

                    var resultList = new List <PropertySet>();
                    if (result == null && result.Data != null)
                    {
                        returnData.Add("status", 0);
                        break;
                    }

                    foreach (var item in result.Data.Song.ListItems)
                    {
                        var set = new PropertySet
                        {
                            ["title"]        = item.Title,
                            ["description"]  = item.SingerItems[0]?.Title,
                            ["addtional"]    = item.Album.Title,
                            ["picture_path"] = OnlineMusicSearcher.GeneratePicturePathByID(item.Album.Mid),
                            ["type"]         = "song",
                            ["id"]           = new string[] { item.Mid },
                            ["album_id"]     = item.Album.Mid
                        };
                        resultList.Add(set);
                    }


                    if (!resultList.IsNullorEmpty())
                    {
                        returnData.Add("search_result", JsonConvert.SerializeObject(resultList.ToArray()));
                        returnData.Add("status", 1);
                    }
                    break;

                case "song":
                    var song = await OnlineMusicSearcher.GetSongAsync(message["id"] as string);

                    if (song != null && !song.DataItems.IsNullorEmpty())
                    {
                        DateTime.TryParseExact(song.DataItems[0].Album.Time_Public, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime t);

                        // TODO: property
                        var songRes = new PropertySet
                        {
                            ["title"]       = song.DataItems[0].Title,
                            ["id"]          = song.DataItems[0].Mid,
                            ["album"]       = song.DataItems[0].Album.Name,
                            ["album_id"]    = song.DataItems[0].Album.Mid,
                            ["performers"]  = song.DataItems[0].SingerItems.Select(x => x.Name).ToArray(),
                            ["year"]        = t.Year,
                            ["bit_rate"]    = (uint)message["bit_rate"] * 1000,
                            ["track"]       = song.DataItems[0].Index_Album,
                            ["track_count"] = 0,
                            ["duration"]    = TimeSpan.Zero.ToString()
                        };
                        songRes["album_artists"] = songRes["performers"];
                        var picture = OnlineMusicSearcher.GeneratePicturePathByID(song.DataItems[0].Album.Mid);
                        songRes["picture_path"] = picture;
                        songRes["file_url"]     = await OnlineMusicSearcher.GenerateFileUriByID(message["id"] as string, (uint)message["bit_rate"]);

                        songRes["file_type"] = OnlineMusicSearcher.GenerateFileTypeByID(message["id"] as string, (uint)message["bit_rate"]);
                        returnData.Add("song_result", JsonConvert.SerializeObject(songRes));
                        returnData.Add("status", 1);
                    }

                    break;

                case "album":
                    var album = await OnlineMusicSearcher.GetAlbumAsync(message["id"] as string);

                    if (album != null && album.Data != null)
                    {
                        DateTime.TryParseExact(album.Data.GetAlbumInfo.Fpublic_Time, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime t);
                        var albumRes = new PropertySet
                        {
                            ["name"]         = album.Data.GetAlbumInfo.Falbum_Name,
                            ["desription"]   = album.Data.GetAlbumDesc.Falbum_Desc.Replace("\n", "\r\n\r\n"),
                            ["year"]         = t.Year,
                            ["track_count"]  = album.Data.GetSongInfoItems.Count,
                            ["disc_count"]   = album.Data.GetSongInfoItems.Max(x => x.Index_Cd) + 1,
                            ["picture_path"] = OnlineMusicSearcher.GeneratePicturePathByID(message["id"] as string),
                            ["genres"]       = new string[] { album.Data.Genre }
                        };
                        returnData.Add("album_result", JsonConvert.SerializeObject(albumRes));
                        returnData.Add("songs", JsonConvert.SerializeObject(album.Data.GetSongInfoItems.Select(x =>
                        {
                            var p = new PropertySet()
                            {
                                ["id"]           = x.Mid,
                                ["title"]        = x.Name,
                                ["album"]        = x.Album.Name,
                                ["album_id"]     = x.Album.Mid,
                                ["performers"]   = x.SingerItems.Select(y => y.Name).ToArray(),
                                ["year"]         = t.Year,
                                ["bit_rate"]     = Settings.Current.GetPreferredBitRate() * 1000,
                                ["picture_path"] = OnlineMusicSearcher.GeneratePicturePathByID(x.Album.Mid),
                                ["track"]        = x.Index_Album,
                                ["duration"]     = TimeSpan.Zero.ToString(),
                                ["file_url"]     = AsyncHelper.RunSync(async() => await OnlineMusicSearcher.GenerateFileUriByID(x.Mid, (uint)message["bit_rate"])),
                                ["file_type"]    = OnlineMusicSearcher.GenerateFileTypeByID(x.Mid, (uint)message["bit_rate"])
                            };
                            p["album_artists"] = p["performers"];
                            return(p);
                        })));
                        returnData.Add("album_artists", JsonConvert.SerializeObject(album.Data.SingerInfoItems.Select(x =>
                        {
                            return(new PropertySet()
                            {
                                ["name"] = x.Fsinger_Name,
                                ["id"] = x.Fsinger_Mid,
                            });
                        })));
                        returnData.Add("status", 1);
                    }
                    break;

                case "artist":
                    var artist = await OnlineMusicSearcher.GetArtistAsync(message["id"] as string);

                    break;

                default:
                    break;
                }
                break;

            case "online_meta":
                var meta_action = message["action"] as string;
                switch (meta_action)
                {
                case "album":
                    var meta_album = await LastfmSearcher.GetAlbumInfo(message["album"] as string, message["artist"] as string);

                    if (meta_album != null)
                    {
                        returnData.Add("status", 1);
                        returnData.Add("album_result", JsonConvert.SerializeObject(new PropertySet()
                        {
                            ["name"]    = meta_album.Name,
                            ["artwork"] = meta_album.AltArtwork?.OriginalString,
                            ["desc"]    = meta_album.Description,
                            ["artist"]  = meta_album.Artist,
                            ["year"]    = meta_album.Year
                        }));
                    }
                    break;

                case "artist":
                    var meta_artist = await LastfmSearcher.GetArtistInfo(message["artist"] as string);

                    if (meta_artist != null)
                    {
                        returnData.Add("status", 1);
                        returnData.Add("artist_result", JsonConvert.SerializeObject(new PropertySet()
                        {
                            ["name"]   = meta_artist.Name,
                            ["avatar"] = meta_artist.AvatarUri.OriginalString,
                            ["desc"]   = meta_artist.Description,
                        }));
                    }
                    break;
                }
                break;

            default:
                returnData.Add("status", 0);
                break;
            }


            await args.Request.SendResponseAsync(returnData);

            // Return the data to the caller.
            // Complete the deferral so that the platform knows that we're done responding to the app service call.
            // Note for error handling: this must be called even if SendResponseAsync() throws an exception.
            messageDeferral.Complete();
        }
        public static ApplicationDataCompositeValue ConvertValueSetToApplicationDataCompositeValue(ValueSet valueSet)
        {
            ApplicationDataCompositeValue converted = new ApplicationDataCompositeValue();

            foreach (var value in valueSet)
            {
                converted[value.Key] = value.Value;
            }

            return(converted);
        }
Example #55
0
        private static async Task parseRecycleBinAction(AppServiceRequestReceivedEventArgs args, string action)
        {
            switch (action)
            {
            case "Empty":
                // Shell function to empty recyclebin
                SHEmptyRecycleBin(IntPtr.Zero, null, SHERB.SHERB_NOCONFIRMATION | SHERB.SHERB_NOPROGRESSUI);
                break;

            case "Query":
                var           responseQuery = new ValueSet();
                SHQUERYRBINFO queryBinInfo  = new SHQUERYRBINFO();
                queryBinInfo.cbSize = (uint)Marshal.SizeOf(queryBinInfo);
                var res = SHQueryRecycleBin(null, ref queryBinInfo);
                if (res == Vanara.PInvoke.HRESULT.S_OK)
                {
                    var numItems = queryBinInfo.i64NumItems;
                    var binSize  = queryBinInfo.i64Size;
                    responseQuery.Add("NumItems", numItems);
                    responseQuery.Add("BinSize", binSize);
                    responseQuery.Add("FileOwner", (string)recycler.Properties[Vanara.PInvoke.Ole32.PROPERTYKEY.System.FileOwner]);
                    if (watchers.Any())
                    {
                        var info = new DirectoryInfo(watchers.First().Path);
                        responseQuery.Add("DateAccessed", info.LastAccessTime.ToBinary());
                        responseQuery.Add("DateCreated", info.CreationTime.ToBinary());
                    }
                    await args.Request.SendResponseAsync(responseQuery);
                }
                break;

            case "Enumerate":
                // Enumerate recyclebin contents and send response to UWP
                var responseEnum       = new ValueSet();
                var folderContentsList = new List <ShellFileItem>();
                foreach (var folderItem in recycler)
                {
                    try
                    {
                        string recyclePath = folderItem.FileSystemPath;         // True path on disk
                        string fileName    = Path.GetFileName(folderItem.Name); // Original file name
                        string filePath    = folderItem.Name;                   // Original file path + name
                        bool   isFolder    = folderItem.IsFolder && Path.GetExtension(folderItem.Name) != ".zip";
                        if (folderItem.Properties == null)
                        {
                            folderContentsList.Add(new ShellFileItem(isFolder, recyclePath, fileName, filePath, DateTime.Now, null, 0, null));
                            continue;
                        }
                        folderItem.Properties.TryGetValue <System.Runtime.InteropServices.ComTypes.FILETIME?>(
                            Vanara.PInvoke.Ole32.PROPERTYKEY.System.DateCreated, out var fileTime);
                        var    recycleDate = fileTime?.ToDateTime().ToLocalTime() ?? DateTime.Now;  // This is LocalTime
                        string fileSize    = folderItem.Properties.TryGetValue <ulong?>(
                            Vanara.PInvoke.Ole32.PROPERTYKEY.System.Size, out var fileSizeBytes) ?
                                             folderItem.Properties.GetPropertyString(Vanara.PInvoke.Ole32.PROPERTYKEY.System.Size) : null;
                        folderItem.Properties.TryGetValue <string>(
                            Vanara.PInvoke.Ole32.PROPERTYKEY.System.ItemTypeText, out var fileType);
                        folderContentsList.Add(new ShellFileItem(isFolder, recyclePath, fileName, filePath, recycleDate, fileSize, fileSizeBytes ?? 0, fileType));
                    }
                    catch (FileNotFoundException)
                    {
                        // Happens if files are being deleted
                    }
                    finally
                    {
                        folderItem.Dispose();
                    }
                }
                responseEnum.Add("Enumerate", JsonConvert.SerializeObject(folderContentsList));
                await args.Request.SendResponseAsync(responseEnum);

                break;

            default:
                break;
            }
        }
Example #56
0
        void OnMessageReceivedFromBackground(object sender, ValueSet notification)
        {
            //Debug.WriteLine("MainPage.OnMessageReceivedFromBackground()");

            long?  memoryValue         = null;
            ulong? appMemoryValue      = null;
            ulong? appMemoryLimitValue = null;
            var    updateMemory        = false;
            string failMessage         = null;
            string trackName           = null;
            var    callShutdown        = false;

            foreach (var kv in notification)
            {
                //Debug.WriteLine(" b->f {0}: {1}", kv.Key, kv.Value);

                try
                {
                    if (null == kv.Key)
                    {
                        Debug.WriteLine("*** MainPage.OnMessageReceivedFromBackground() null key");

                        continue; // This does happen.  It shouldn't, but it does.
                    }

                    BackgroundNotificationType type;
                    if (!Enum.TryParse(kv.Key, true, out type))
                    {
                        continue;
                    }

                    switch (type)
                    {
                    case BackgroundNotificationType.Track:
                        trackName = kv.Value as string ?? string.Empty;

                        break;

                    case BackgroundNotificationType.Fail:
                        callShutdown = true;
                        failMessage  = kv.Value as string;

                        Debug.WriteLine("MainPage.OnMessageReceivedFromBackground() fail " + failMessage);

                        break;

                    case BackgroundNotificationType.Memory:
                        memoryValue = kv.Value as long?;
                        if (memoryValue.HasValue)
                        {
                            updateMemory = true;
                        }

                        break;

                    case BackgroundNotificationType.AppMemory:
                        appMemoryValue = kv.Value as ulong?;
                        if (appMemoryValue.HasValue)
                        {
                            updateMemory = true;
                        }

                        break;

                    case BackgroundNotificationType.AppMemoryLimit:
                        appMemoryLimitValue = kv.Value as ulong?;
                        if (appMemoryLimitValue.HasValue)
                        {
                            updateMemory = true;
                        }

                        break;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("MainPage.OnMessageReceivedFromBackground() failed: " + ex.Message);
                }
            }

            if (null != failMessage)
            {
                _trackName = null;
            }

            if (null != trackName)
            {
                _trackName = trackName;
            }

            if (null != failMessage || null != trackName)
            {
                RequestRefresh();
            }

            if (updateMemory)
            {
                var memoryString = string.Format("{0:F2}MiB {1:F2}MiB/{2:F2}MiB",
                                                 memoryValue.BytesToMiB(), appMemoryValue.BytesToMiB(), appMemoryLimitValue.BytesToMiB());

                var awaiter = Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => txtMemory.Text = memoryString);
            }

            if (callShutdown)
            {
                var awaiter2 = Dispatcher.RunAsync(CoreDispatcherPriority.Low, CleanupFailedPlayer);
            }
        }
Example #57
0
        public void CouplingGwRiver2()
        {
            /// runNumber 0: Using MultiInput
            /// runNumber 1: Using MultiInputAdaptor
            /// runNumber 2: Using MultiInputAdaptorFactory

            for (int runNumber = 0; runNumber < 3; runNumber++)
            {
                Console.Out.WriteLine("runNumber: " + runNumber);

                // Create trigger inputs
                Input queryDischargeItem = CreateDischargeInput();
                Input queryVolume        = CreateVolumeInput();

                // Create models
                LinkableEngine      riverModel  = CreateRiverModel();
                LinkableEngine      riverModel2 = CreateRiverModel();
                ITimeSpaceComponent gwModel     = CreateGwModel();

                // Add arguments and initialize
                IDictionary <string, IArgument> gwArgs = gwModel.Arguments.Dictionary();
                // Increasing model grid size (otherwise GW model runs full too fast)
                gwArgs.UpdateValue("dx", 50.0);
                gwArgs.UpdateValue("dy", 50.0);
                gwArgs.UpdateValue("x0", 0.0);
                gwArgs.UpdateValue("y0", 200.0);
                gwArgs.UpdateValue("XCount", 24);
                gwArgs.UpdateValue("ycount", 16);
                if (runNumber == 0)
                {
                    gwArgs.UpdateValue("UseMultiInput", true);
                }
                gwModel.Initialize();
                int gwGridSize = 24 * 16;

                IDictionary <string, IArgument> riverArgs = riverModel.Arguments.Dictionary();
                // Increasing model grid size (otherwise GW model runs full too fast)
                riverArgs.UpdateValue("xyscale", 100.0);
                riverModel.Initialize();

                IDictionary <string, IArgument> river2Args = riverModel2.Arguments.Dictionary();
                // Increasing model grid size (otherwise GW model runs full too fast)
                river2Args.UpdateValue("xyscale", 100.0);
                // Move river2 sligthly away from river1
                river2Args.UpdateValue("xoffset", -220.0);
                river2Args.UpdateValue("yoffset", 180.0);
                riverModel2.Initialize();

                // Connect triggering inputs
                ITimeSpaceOutput flowOnBranch  = UTHelper.FindOutputItem(riverModel, "Branch:2:Flow");
                TimeInterpolator flowOnBranch2 = new TimeInterpolator(flowOnBranch);
                flowOnBranch.AddAdaptedOutput(flowOnBranch2);
                flowOnBranch2.AddConsumer(queryDischargeItem);

                ITimeSpaceOutput storageInGw  = UTHelper.FindOutputItem(gwModel, "Grid.Storage");
                TimeInterpolator storageInGw2 = new TimeInterpolator(storageInGw);
                storageInGw.AddAdaptedOutput(storageInGw2);
                storageInGw2.AddConsumer(queryVolume);

                //========== Couple leakage items ==========
                ITimeSpaceInput gwInflowInput = UTHelper.FindInputItem(gwModel, "Grid.Inflow");


                //========== IBaseMultiInput linking ==========
                if (runNumber == 0)
                {
                    /// Example of adding up two outputs into one input, by the use of
                    /// an IBaseMultiInput implementation

                    Assert.IsTrue(gwInflowInput is IBaseMultiInput);
                    Assert.IsTrue(gwInflowInput is ITimeSpaceMultiInput);

                    // put leakage from river1 into ground water model
                    {
                        ITimeSpaceOutput riverLeakageOutput = UTHelper.FindOutputItem(riverModel, "WholeRiver:Leakage");

                        // Two adaptors are added: Time buffer and line-to-grid adaptor
                        // they can be added in any order (though time buffer first will use less memory)

                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutput);
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput2,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput2.AddAdaptedOutput(riverLeakageOutputGrid);

                        // Note !!!: No special action
                        riverLeakageOutputGrid.AddConsumer(gwInflowInput);
                    }

                    // put leakage from river2 into ground water model
                    {
                        ITimeSpaceOutput riverLeakageOutput = UTHelper.FindOutputItem(riverModel2, "WholeRiver:Leakage");

                        // Two adaptors are added: Time buffer and line-to-grid adaptor
                        // they can be added in any order (though time buffer first will use less memory)

                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutput);
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput2,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput2.AddAdaptedOutput(riverLeakageOutputGrid);

                        // Note !!!: No special action
                        riverLeakageOutputGrid.AddConsumer(gwInflowInput);
                    }
                }

                //========== MultiInputAdaptor linking ==========
                if (runNumber == 1)
                {
                    /// Example of adding up two outputs into one input, by the use of
                    /// a MultiInputAdaptor class

                    // Note !!!: Creating a MultiInputAdaptor
                    MultiInputAdaptor sourceAdder = new MultiInputAdaptor("SomeId")
                    {
                        SpatialDefinition = gwInflowInput.SpatialDefinition
                    };

                    // put leakage from river1 into ground water model
                    // Two adaptors are added: Time buffer and line-to-grid adaptor
                    {
                        ITimeSpaceOutput riverLeakageOutput = UTHelper.FindOutputItem(riverModel, "WholeRiver:Leakage");

                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutput);
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput2,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput2.AddAdaptedOutput(riverLeakageOutputGrid);

                        // Note !!!: Adding to the list of adaptees
                        sourceAdder.Adaptees.Add(riverLeakageOutputGrid);
                        riverLeakageOutputGrid.AddAdaptedOutput(sourceAdder);
                    }

                    // put leakage from river2 into ground water model
                    // Two adaptors are added: Time buffer and line-to-grid adaptor
                    {
                        ITimeSpaceOutput riverLeakageOutput = UTHelper.FindOutputItem(riverModel2, "WholeRiver:Leakage");

                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutput);
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput2,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput2.AddAdaptedOutput(riverLeakageOutputGrid);

                        // Note !!!: Adding to the list of adaptees
                        sourceAdder.Adaptees.Add(riverLeakageOutputGrid);
                        riverLeakageOutputGrid.AddAdaptedOutput(sourceAdder);
                    }

                    // Note !!!: Connect the gwInflowInput and the multiInputAdaptor
                    sourceAdder.AddConsumer(gwInflowInput);
                }

                //========== MultiInputAdaptorFactory linking ==========
                if (runNumber == 2)
                {
                    /// Example of adding up two outputs into one input, by the use of
                    /// an MultiInputAdaptorFactory implementation

                    var factory = new MultiInputAdaptorFactory(gwModel);

                    // put leakage from river1 into ground water model
                    // Two adaptors are added: Time buffer and line-to-grid adaptor
                    {
                        ITimeSpaceOutput riverLeakageOutput = UTHelper.FindOutputItem(riverModel, "WholeRiver:Leakage");

                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutput);
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput2,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput2.AddAdaptedOutput(riverLeakageOutputGrid);

                        // Note !!!: Creating a new AdaptedOutput and adding it
                        IIdentifiable[]    identifiables = factory.GetAvailableAdaptedOutputIds(riverLeakageOutputGrid, gwInflowInput);
                        IBaseAdaptedOutput myOutput      = factory.CreateAdaptedOutput(identifiables[0], riverLeakageOutputGrid, gwInflowInput);

                        myOutput.AddConsumer(gwInflowInput);
                    }

                    // put leakage from river2 into ground water model
                    // Two adaptors are added: Time buffer and line-to-grid adaptor
                    {
                        ITimeSpaceOutput riverLeakageOutput = UTHelper.FindOutputItem(riverModel2, "WholeRiver:Leakage");

                        // Time interpolator
                        TimeInterpolator riverLeakageOutput2 = new TimeInterpolator(riverLeakageOutput);
                        riverLeakageOutput.AddAdaptedOutput(riverLeakageOutput2);

                        // Element mapper from polyline to polygon, weighted sum version
                        ElementMapperAdaptedOutput riverLeakageOutputGrid =
                            new ElementMapperAdaptedOutput(new Identifier("ElementMapper501"), riverLeakageOutput2,
                                                           gwInflowInput.ElementSet());
                        riverLeakageOutput2.AddAdaptedOutput(riverLeakageOutputGrid);

                        // Note !!!: Creating a new AdaptedOutput and adding it
                        IIdentifiable[]    identifiables = factory.GetAvailableAdaptedOutputIds(riverLeakageOutputGrid, gwInflowInput);
                        IBaseAdaptedOutput myOutput      = factory.CreateAdaptedOutput(identifiables[0], riverLeakageOutputGrid, gwInflowInput);

                        myOutput.AddConsumer(gwInflowInput);
                    }
                }


                //========== Run ==========

                // Validate
                riverModel.Validate();
                Assert.IsTrue(riverModel.Status == LinkableComponentStatus.Valid);
                riverModel2.Validate();
                Assert.IsTrue(riverModel2.Status == LinkableComponentStatus.Valid);
                gwModel.Validate();
                Assert.IsTrue(gwModel.Status == LinkableComponentStatus.Valid);

                // Prepare
                riverModel.Prepare();
                Assert.IsTrue(riverModel.Status == LinkableComponentStatus.Updated);
                riverModel2.Prepare();
                Assert.IsTrue(riverModel2.Status == LinkableComponentStatus.Updated);
                gwModel.Prepare();
                Assert.IsTrue(gwModel.Status == LinkableComponentStatus.Updated);


                // specify query times
                double triggerTime0 = riverModel.CurrentTime.StampAsModifiedJulianDay;
                double triggerTime1 = triggerTime0 + 1;
                double triggerTime2 = triggerTime0 + 2;
                double triggerTime3 = triggerTime0 + 12.1;
                double triggerTime4 = triggerTime0 + 16.7;

                /// Properties of the river, without gw-level input
                /// Inflow into each node from rainfall runoff is 10 L/s
                /// Inflow to node 1: 10        L/s - leaking  5   L/s on branch 1
                /// Inflow to node 2: 10 +    5 L/s - leaking 15/2 L/s on branch 2
                /// Inflow to node 3: 10 + 15/2 L/s - leaking 35/4 L/s on branch 3
                /// Total leakage 5+15/2+35/4 = (20+30+35)/4 = 85/4 L/s
                ///
                /// Number of seconds in a day: 60*60*24 = 86400

                // check initial values
                Assert.AreEqual(1, ValueSet.GetElementCount(flowOnBranch.Values), "#values for " + flowOnBranch.Id);
                Assert.AreEqual(7.0, (double)flowOnBranch.Values.GetValue(0, 0), "Value[0] as property");

                Assert.AreEqual(gwGridSize, ValueSet.GetElementCount(storageInGw.Values), "#values for " + storageInGw.Id);
                Assert.AreEqual(0, SumTimeStep(storageInGw.Values, 0));

                // get values for specified query times, 1 days
                // Totally leaking: 86400 * 85/4 = 1.836e6
                // For the bi-directional coupling:
                // the entire first day the river uses extrapolated values from the
                // gwModel, which gives a gwLevel of -10, hence same value as for the uni-directional
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime1);
                ITimeSpaceValueSet valuesV = storageInGw2.GetValues(queryDischargeItem);
                ITimeSpaceValueSet valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                Assert.AreEqual(2 * 1.836e6, SumTimeStep(valuesV, 0), 1e-4);

                // Print out, to load in a plotting program for verification
                StringBuilder b = new StringBuilder();

                IList valV   = valuesV.GetElementValuesForTime(0);
                int   ivalvV = 0;
                for (int i = 0; i < 16; i++)
                {
                    for (int j = 0; j < 24; j++)
                    {
                        b.Append(((double)valV[ivalvV++]).ToString(NumberFormatInfo.InvariantInfo));
                        b.Append(" ");
                    }
                    b.AppendLine();
                }
                //Console.Out.WriteLine(b.ToString());

                // get values for specified query times, 2 days
                // 2 * 86400 * 85/4 = 3.672e6
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime2);
                valuesV = storageInGw2.GetValues(queryDischargeItem);
                valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                Assert.AreEqual(2 * 3.672e6, SumTimeStep(valuesV, 0), 1e-4);

                // get values for specified query times, 12.1 days
                // 12.1 * 86400 * 85/4 = 2.22156e7
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime3);
                valuesV = storageInGw2.GetValues(queryDischargeItem);
                valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                Assert.AreEqual(2 * 2.22156e7, SumTimeStep(valuesV, 0), 1e-4);

                // get values for specified query times, 16.7 days
                // 16.7 * 86400 * 85/4 = 3.06612e7
                queryDischargeItem.TimeSet.SetSingleTimeStamp(triggerTime4);
                valuesV = storageInGw2.GetValues(queryDischargeItem);
                valuesQ = flowOnBranch2.GetValues(queryDischargeItem);
                Assert.AreEqual(35.0 / 4.0, (double)valuesQ.GetValue(0, 0));
                Assert.AreEqual(2 * 3.06612e7, SumTimeStep(valuesV, 0), 1e-4);
            }
        }
Example #58
0
        private void FillValues(TerminologyOperation termOp, string version, string code, string filter, string vsIdentifier, int offsetNo, int countNo)
        {
            this.GetVsProperties(vsIdentifier);

            this.valueSet   = new ValueSet();
            this.codeSystem = new CodeSystem();

            this.valueSet.Id   = this.vsId;
            this.codeSystem.Id = "NZMT";

            this.codeSystem.CaseSensitive = false;
            this.codeSystem.Content       = CodeSystem.CodeSystemContentMode.NotPresent;
            this.codeSystem.Experimental  = false;
            this.codeSystem.Compositional = false;
            this.codeSystem.VersionNeeded = false;

            // Code System properties
            this.codeSystem.Property.Add(new CodeSystem.PropertyComponent {
                Code = "substance", Description = "The Generic Substance (Medicinal Product) & ingredient data relating to this Code.", Type = CodeSystem.PropertyType.Code
            });

            // there is no Value Set that contains the whole of NZMT
            //this.codeSystem.ValueSet = "http://nzmt.org.nz/vs";

            this.valueSet.Url   = this.vsURL;
            this.codeSystem.Url = NzMt.URI;

            this.valueSet.Title   = this.vsTitle;
            this.codeSystem.Title = NzMt.TITLE;

            this.valueSet.Name   = this.valueSet.Id;
            this.codeSystem.Name = this.codeSystem.Id;

            this.valueSet.Description   = new Markdown(this.vsDescription);
            this.codeSystem.Description = new Markdown(NzMt.DESCRIPTION);

            this.valueSet.Version   = NzMt.CURRENT_VERSION;
            this.codeSystem.Version = NzMt.CURRENT_VERSION;

            this.valueSet.Experimental = true;

            this.valueSet.Status   = PublicationStatus.Active;
            this.codeSystem.Status = PublicationStatus.Active;

            this.valueSet.Date   = Hl7.Fhir.Model.Date.Today().Value;
            this.codeSystem.Date = Hl7.Fhir.Model.Date.Today().Value;

            this.valueSet.Publisher   = "Patients First Ltd";
            this.codeSystem.Publisher = "nzulm.org.nz";

            this.valueSet.Copyright   = new Markdown("© 2010+ New Zealand Crown Copyright");
            this.codeSystem.Copyright = new Markdown("© 2010+ New Zealand Crown Copyright");

            ContactPoint cp = new ContactPoint {
                System = ContactPoint.ContactPointSystem.Email, Value = "*****@*****.**"
            };
            ContactDetail cd = new ContactDetail();

            cd.Telecom.Add(cp);
            this.valueSet.Contact.Add(cd);
            this.codeSystem.Contact.Add(cd);

            ValueSet.ConceptSetComponent cs = new ValueSet.ConceptSetComponent();
            ValueSet.ExpansionComponent  es = new ValueSet.ExpansionComponent();

            cs.System  = this.codeSystem.Url;
            cs.Version = this.codeSystem.Version;

            if (!string.IsNullOrEmpty(vsIdentifier))
            {
                cs.Filter.Add(new ValueSet.FilterComponent {
                    Property = "TermType", Op = FilterOperator.Equal, Value = vsIdentifier
                });
            }

            string codeCode       = string.Empty;
            string codeDisplay    = string.Empty;
            string codeDefinition = string.Empty;

            if ((string.IsNullOrEmpty(version) || version == cs.Version) && termOp != TerminologyOperation.define_cs)
            {
                if (termOp != TerminologyOperation.define_vs)
                {
                    List <Coding> codeVals = new List <Coding>();

                    if (termOp == TerminologyOperation.lookup || termOp == TerminologyOperation.validate_code)
                    {
                        codeVals = NzUlmSearch.GetNzmtCombinedByCode(code);
                        if (codeVals.Count > 0 || termOp == TerminologyOperation.validate_code)
                        {
                            // create filter as need to subsequently check that it belongs in the passed Value Set
                            filter = codeVals[0].Display;
                        }
                    }

                    if (termOp == TerminologyOperation.expand || termOp == TerminologyOperation.validate_code)
                    {
                        if (vsId.StartsWith("NZULM-PT-"))
                        {
                            codeVals = NzUlmSearch.GetNZULMPrescribingTerms(filter, vsId.Replace("NZULM-PT-", "").ToLower());
                        }
                        else if (vsId == "NZULM-CTPP")
                        {
                            codeVals = NzUlmSearch.GetContaineredTradeProductPackByTerm(filter);
                        }
                        else if (vsId == "NZULM-MP")
                        {
                            codeVals = NzUlmSearch.GetMedicinalProductByTerm(filter);
                        }
                        else if (vsId == "NZULM-MPP")
                        {
                            codeVals = NzUlmSearch.GetMedicinalProductPackByTerm(filter);
                        }
                        else if (vsId == "NZULM-MPUU")
                        {
                            codeVals = NzUlmSearch.GetMedicinalProductUnitOfUseByTerm(filter);
                        }
                        else if (vsId == "NZULM-TP")
                        {
                            codeVals = NzUlmSearch.GetTradeProductByTerm(filter);
                        }
                        else if (vsId == "NZULM-TPP")
                        {
                            codeVals = NzUlmSearch.GetTradeProductPackByTerm(filter);
                        }
                        else if (vsId == "NZULM-TPUU")
                        {
                            codeVals = NzUlmSearch.GetTradeProductUnitOfUseByTerm(filter);
                        }
                        else
                        {
                            throw new Exception(TerminologyValueSet.UNFOUND_VALUESET);
                        }
                    }

                    // filtering performed at DB Layer, so add all returned concepts
                    foreach (Coding codeVal in codeVals)
                    {
                        ValueSet.DesignationComponent desig = new ValueSet.DesignationComponent {
                            ElementId = "NZULM", Value = codeVal.Version
                        };
                        cs.Concept.Add(new ValueSet.ConceptReferenceComponent {
                            Code = codeVal.Code, Display = codeVal.Display
                        });
                        es.Contains.Add(new ValueSet.ContainsComponent {
                            Code = codeVal.Code, Display = codeVal.Display, System = cs.System
                        });
                        this.codeSystem.Concept.Add(new CodeSystem.ConceptDefinitionComponent {
                            Code = codeVal.Code, Display = codeVal.Display, Definition = codeVal.Version, ElementId = codeVal.ElementId
                        });
                    }

                    if (termOp == TerminologyOperation.expand || termOp == TerminologyOperation.validate_code)
                    {
                        this.valueSet = TerminologyValueSet.AddExpansion(this.valueSet, es, offsetNo, countNo);
                    }
                    else if (termOp == TerminologyOperation.define_vs)
                    {
                        this.valueSet.Compose = new ValueSet.ComposeComponent();
                        this.valueSet.Compose.Include.Add(cs);
                    }
                }
                else
                {
                    this.valueSet.Compose = new ValueSet.ComposeComponent();
                    this.valueSet.Compose.Include.Add(cs);
                }
            }
        }
        public override async Task <object> ExecuteAsync(ValueSet parameters)
        {
            if (_serviceName.IsNullorEmpty())
            {
                throw new InvalidProgramException("Extension is not a service");
            }
            try
            {
                // do app service call
                using (var connection = new AppServiceConnection())
                {
                    // service name was in properties
                    connection.AppServiceName = _serviceName;

                    // package Family Name is in the extension
                    connection.PackageFamilyName = this.AppExtension.Package.Id.FamilyName;

                    // open connection
                    AppServiceConnectionStatus status = await connection.OpenAsync();

                    if (status != AppServiceConnectionStatus.Success)
                    {
                        throw new InvalidOperationException(status.ToString());
                    }
                    else
                    {
                        // send request to service
                        // get response
                        AppServiceResponse response = await connection.SendMessageAsync(parameters);

                        if (response.Status == AppServiceResponseStatus.Success)
                        {
                            ValueSet message = response.Message as ValueSet;
                            if (message.ContainsKey("status") && (int)message["status"] == 1)
                            {
                                if (message.ContainsKey("search_result") && message["search_result"] is string s)
                                {
                                    return(GetGenericMusicItem(s));
                                }
                                if (message.ContainsKey("song_result") && message["song_result"] is string t)
                                {
                                    return(GetOnlineSong(t));
                                }
                                if (message.ContainsKey("album_result") && message["album_result"] is string r)
                                {
                                    return(GetAlbum(r, message["songs"] as string, message["album_artists"] as string));
                                }
                                if (message.ContainsKey("playlists") && message["playlists"] is string p)
                                {
                                    return(GetPlayLists(p));
                                }
                                if (message.ContainsKey("playlist_result") && message["playlist_result"] is string a)
                                {
                                    return(GetAlbum(a, message["songs"] as string, message["album_artists"] as string));
                                }
                            }
                        }
                    }
                }
                return(null);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private void YesButton_OnClick(object sender, RoutedEventArgs e)
        {
            var result = new ValueSet {{"note", ApplicationData.Current.LocalSettings.Values["note"] as string}};
            _args.ProtocolForResultsOperation.ReportCompleted(result);

            Application.Current.Exit();
        }