public async Task<CacheResponse> RequestAsync(CacheRequest request)
 {
     try
     {
         if (request.CanonicalUri == manifestUri)
         {
             var response = await DownloadManifestAsync(request.CanonicalUri, cts.Token);
             cts.Token.ThrowIfCancellationRequested();
             return new CacheResponse(response.Stream.Length, "text/xml", response.Headers, response.Stream, response.HttpStatusCode, response.HttpStatusCode.ToString(), DateTime.UtcNow);
         }
         else
         {
             var response = await DownloadChunkAsync(request.CanonicalUri, cts.Token);
             cts.Token.ThrowIfCancellationRequested();
             return new CacheResponse(response.Stream.Length, response.ContentType, response.Headers, response.Stream, response.HttpStatusCode, response.HttpStatusCode.ToString(), DateTime.UtcNow);
         }
     }
     catch (WebRequestorFailure ex)
     {
         return new CacheResponse(0, null, ex.Headers, null, ex.HttpStatusCode, ex.HttpStatusCode.ToString(), DateTime.UtcNow);
     }
     catch
     {
         return new CacheResponse(0, null, null, null, HttpStatusCode.BadRequest, "BadRequest", DateTime.UtcNow);
     }
 }
        public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
        {
            var asyncResult = new CacheAsyncResult() { AsyncState = state, AsyncWaitHandle = new AutoResetEvent(false) };

#if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7
            TaskEx.Run(async () =>
#else
            Task.Run(async () =>
#endif
            {
                asyncResult.Response = await downloaderPlugin.RequestAsync(request);
                asyncResult.IsCompleted = true;

                //callback
                if (callback != null)
                {
                    callback(asyncResult);
                }

                //signal the blocked SSME downloader thread waiting in EndRetrieve
                if (asyncResult.AsyncWaitHandle != null)
                {
                    (asyncResult.AsyncWaitHandle as AutoResetEvent).Set();
                }
            });

            return asyncResult;
        }
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     if (!request.CanonicalUri.ToString().Contains("FragmentInfo") && !request.CanonicalUri.ToString().Contains("Manifest"))
     {
         if (response.StatusCode != HttpStatusCode.OK)
         {
             MessageBox.Show("aaa");
         }
         using (CryptoStream stream = new CryptoStream(response.Response, this._decryptionInfo.Decryptor, CryptoStreamMode.Read))
         {
             MemoryStream stream2 = new MemoryStream();
             long num = 0L;
             int count = 0x1000;
             byte[] buffer = new byte[count];
             while (stream.CanRead)
             {
                 int num2 = stream.Read(buffer, 0, count);
                 num += num2;
                 if (num2 == 0)
                 {
                     break;
                 }
                 stream2.Write(buffer, 0, num2);
             }
             stream2.Position = 0L;
             //response.Response = stream2;
             response = new CacheResponse(stream2);
         }
     }
     return null;
 }
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     if (!request.CanonicalUri.ToString().Contains("FragmentInfo") && !request.CanonicalUri.ToString().Contains("Manifest"))
     {
         try
         {
             using (CryptoStream stream = new CryptoStream(response.Response, this._decryptionInfo.Decryptor, CryptoStreamMode.Read))
             {
                 MemoryStream stream2 = new MemoryStream();
                 int count = 0x1000;
                 byte[] buffer = new byte[count];
                 while (stream.CanRead)
                 {
                     int num = stream.Read(buffer, 0, count);
                     if (num == 0)
                     {
                         break;
                     }
                     stream2.Write(buffer, 0, num);
                 }
                 stream2.Position = 0L;
                 response.Response = stream2;
             }
         }
         catch
         {
             response.Response = null;
         }
     }
     return null;
 }
 public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
 {
     if (!request.CanonicalUri.AbsoluteUri.Contains("FragmentInfo") && !request.CanonicalUri.AbsoluteUri.Contains("Manifest"))
     {
         return null;
     }
     CacheResponse response = null;
     CacheAsyncResult result = new CacheAsyncResult {
         strUrl = request.CanonicalUri.ToString()
     };
     result.Complete(response, true);
     return result;
 }
 public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
 {
     if (this.IsStopped)
     {
         CacheAsyncResult result = new CacheAsyncResult();
         result.Complete(new CacheResponse(0L, null, null, null, HttpStatusCode.NotFound, "Not Found", DateTime.Now, false), true);
         return result;
     }
     if (!request.CanonicalUri.AbsoluteUri.Contains("FragmentInfo") && !request.CanonicalUri.AbsoluteUri.Contains("Manifest"))
     {
         return null;
     }
     CacheResponse response = null;
     CacheAsyncResult result2 = new CacheAsyncResult {
         strUrl = request.CanonicalUri.ToString()
     };
     result2.Complete(response, true);
     return result2;
 }
        public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
        {
            var asyncResult = new CacheAsyncResult() { AsyncState = state, AsyncWaitHandle = new AutoResetEvent(false) };

            Task.Run(async () =>
            {
                asyncResult.Response = await GetCacheResponseAsync(request.CanonicalUri);
                asyncResult.IsCompleted = true;

                //callback
                if (callback != null)
                {
                    callback(asyncResult);
                }

                //signal the blocked SSME downloader thread waiting in EndRetrieve
                if (asyncResult.AsyncWaitHandle != null)
                {
                    (asyncResult.AsyncWaitHandle as AutoResetEvent).Set();
                }
            });

            return asyncResult;
        }
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     return(null);
 }
Beispiel #9
0
        public void DoWork()
        {
            long timeToGetUncached = 0;
            long timeToGetCached   = 0;

            // Create a System.Diagnostics.Stopwatch.
            var stopWatchTimer = new Stopwatch();


            // TEST 1: Get the target element without caching, and retrieve
            //  current properties.

            stopWatchTimer.Start();
            AutomationElement targetNoCache = null;

            try
            {
                targetNoCache = AutomationElement.FromPoint(_targetPoint);
            }
            catch (ElementNotAvailableException)
            {
                OutputLine("Could not retrieve element.");
                return;
            }

            // Get current properties.
            _currentPropCount = 0;
            GetCurrentProperties(targetNoCache, 0);
            stopWatchTimer.Stop();
            timeToGetUncached = stopWatchTimer.Elapsed.Ticks;


            // TEST 2: Get the target element with caching, and retrieve
            //   cached properties.

            // Create CacheRequest.
            var fetchRequest = new CacheRequest();

            // Add properties to fetch.
            fetchRequest.Add(AutomationElement.NameProperty);
            fetchRequest.Add(AutomationElement.AutomationIdProperty);
            fetchRequest.Add(AutomationElement.ControlTypeProperty);
            fetchRequest.Add(AutomationElement.FrameworkIdProperty);
            fetchRequest.Add(AutomationElement.IsContentElementProperty);

            // Set options.
            fetchRequest.AutomationElementMode = _mode;
            fetchRequest.TreeScope             = _treeScope;
            fetchRequest.TreeFilter            = Automation.RawViewCondition;

            // Activate the CacheRequest and fetch the target.
            AutomationElement targetCached = null;

            using (fetchRequest.Activate())
            {
                stopWatchTimer.Reset();
                stopWatchTimer.Start();
                try
                {
                    targetCached = AutomationElement.FromPoint(_targetPoint);
                }
                catch (InvalidOperationException)
                {
                    OutputLine("InvalidOperationException. Could not retrieve element.");
                    return;
                }
                catch (ElementNotAvailableException)
                {
                    OutputLine("ElementNotAvailableException. Could not retrieve element.");
                    return;
                }
            } // CacheRequest is now inactive.

            // Get cached properties.
            GetCachedProperties(targetCached, true);
            stopWatchTimer.Stop();
            timeToGetCached = stopWatchTimer.Elapsed.Ticks;

            // TEST 3: Get updated cache.

            stopWatchTimer.Reset();
            stopWatchTimer.Start();
            var cacheUpdated = false;

            if (_mode == AutomationElementMode.Full)
            {
                var updatedTargetCached = targetCached.GetUpdatedCache(fetchRequest);
                GetCachedProperties(updatedTargetCached, false);
                // Fetches were counted again, so divide count by 2.
                _cachedPropCount /= 2;
                cacheUpdated      = true;
                stopWatchTimer.Stop();
            }
            var updateTicks = stopWatchTimer.Elapsed.Ticks;

            // END OF TESTS.

            // Display results

            var nameProperty = targetNoCache.Current.Name;
            var framework    = targetNoCache.Current.FrameworkId;

            OutputLine("Name: " + nameProperty);
            OutputLine("Framework: " + framework);
            OutputLine(_elementCount + " cached element(s).");

            OutputLine(timeToGetUncached.ToString("N0") + " Ticks to retrieve element(s) and get "
                       + _currentPropCount + " current properties.");
            OutputLine(timeToGetCached.ToString("N0") + " Ticks to retrieve element(s) and get "
                       + _cachedPropCount + " cached properties.");

            // Show ratio between current and cached performance.
            var ratio = timeToGetUncached / (float)timeToGetCached;

            if (ratio > 2)
            {
                OutputLine("Current:Cached = " + ratio.ToString("N0") + ":1");
            }
            else
            {
                // Print with decimal.
                OutputLine("Current:Cached = " + ratio.ToString("N1") + ":1");
            }
            if (cacheUpdated)
            {
                OutputLine(updateTicks.ToString("N0") + " Ticks to update cache and get properties.");
            }
            else
            {
                OutputLine("Cannot update cache in None mode.");
            }
            OutputLine("");
        }
Beispiel #10
0
 public void Init()
 {
     instance = new CacheRequest();
 }
		/// <summary>
		/// Determines if the item should be processed.
		/// </summary>
		/// <param name="item">The <see cref="CacheItem"/> to check.</param>
		/// <returns>true if the item should be processed; otherwise false.</returns>
		private bool OnCanContinueProcessing(CacheRequest item)
		{
			CanContinueProcessingEventArgs arg = new CanContinueProcessingEventArgs(item);
			context.Send(checkProcessingCallback, arg);
			return arg.ContinueProcessing;
		}
		/// <summary>
		/// Pushes the given item to the worker queue.
		/// </summary>
		/// <param name="item">The item to add to the worker queue.</param>
		private void RunWorker(CacheRequest item)
		{
			RunWorker(item, 0);
		}
        /// <summary>
        /// Pushes the given item to the worker queue.
        /// </summary>
        /// <param name="item">The cache item.</param>
        private void RunWorker(CacheRequest item)
        {
            // Get the current synchronization context
            if (context == null)
                context = SynchronizationContext.Current;

            // Already being processed?
            if (processing.ContainsKey (item.Guid))
                return;
            else
                processing.Add (item.Guid, false);

            // Add the item to the queue for processing
            bw.RunWorkerAsync (item);
        }
 /// <summary>
 /// Determines if the item should be processed.
 /// </summary>
 /// <param name="item">The <see cref="CacheRequest"/> to check.</param>
 /// <returns>true if the item should be processed; otherwise false.</returns>
 private bool OnCanContinueProcessing(CacheRequest item)
 {
     CanContinueProcessingEventArgs arg = new CanContinueProcessingEventArgs(item);
     context.Send(checkProcessingCallback, arg);
     return arg.ContinueProcessing;
 }
Beispiel #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CanContinueProcessingEventArgs"/> class.
 /// </summary>
 /// <param name="request">The cache request.</param>
 public CanContinueProcessingEventArgs(CacheRequest request)
 {
     Request            = request;
     ContinueProcessing = true;
 }
 public async Task <CacheResponse> RequestAsync(CacheRequest request)
 {
     return(await downloaderPluginBase.RequestAsync(request));
 }
        private async Task OnUriAsync(Uri uri)
        {
            if (_accepting)
            {
                return;
            }
            _accepting = true;
            var task = Task.Run(async() =>
            {
                await Task.Delay(2000);
                _accepting = false;
            });
            //todo _webSocket.PopularNotifyPage("Meditech");

            var args     = HttpUtility.ParseQueryString(uri.Query);
            var username = args["username"];
            var password = args["password"];
            var domain   = args["domain"];

            if (IsMeditechRunning())
            {
                CloseMeditech();
                return;
            }
            _logger.Debug(this, $"Opening with username: {username}, password (len): {password.Length}, domain: {domain}");

            try
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    OpenMeditech(true);
                });
                await Task.Delay(400);

                var w = FindWindow(null, "Enter Network Password");
                var i = 0;
                while (w == IntPtr.Zero && i < 1000)
                {
                    await Task.Delay(300);

                    w = FindWindow(null, "Enter Network Password");
                    i++;
                }
                if (w == IntPtr.Zero)
                {
                    _logger.Debug(this, "Meditech window not found");
                    CloseMeditech();
                    return;
                }
                var window = AutomationElement.FromHandle(w);
                //MessageBox.Show(window.Current.Name);
                CacheRequest cacheRequest = new CacheRequest();
                cacheRequest.Add(AutomationElement.NameProperty);
                cacheRequest.Add(AutomationElement.HasKeyboardFocusProperty);
                cacheRequest.TreeScope = TreeScope.Element | TreeScope.Children;


                var list = window.GetUpdatedCache(cacheRequest);

                var usernameBox = list.FindFirst(TreeScope.Children, new AndCondition(
                                                     new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                                                     new PropertyCondition(AutomationElement.IsPasswordProperty, false)));

                _logger.Debug(this, "Setting username box focus");
                object valuePattern = null;

                if (!usernameBox.TryGetCurrentPattern(
                        ValuePattern.Pattern, out valuePattern))
                {
                    _logger.Debug(this, "No ValuePattern for username box");
                }
                else
                {
                    if (((ValuePattern)valuePattern).Current.IsReadOnly)
                    {
                        throw new InvalidOperationException(
                                  "The control is read-only.");
                    }
                    else
                    {
                        _logger.Debug(this, "Typing username");
                        ((ValuePattern)valuePattern).SetValue(username);
                    }
                }


                var passwordBox = list.FindFirst(TreeScope.Children, new AndCondition(
                                                     new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                                                     new PropertyCondition(AutomationElement.IsPasswordProperty, true)));

                _logger.Debug(this, "Setting password box focus");
                valuePattern = null;

                if (!passwordBox.TryGetCurrentPattern(
                        ValuePattern.Pattern, out valuePattern))
                {
                    _logger.Debug(this, "No ValuePattern for password box");
                }
                else
                {
                    if (((ValuePattern)valuePattern).Current.IsReadOnly)
                    {
                        throw new InvalidOperationException(
                                  "The control is read-only.");
                    }
                    else
                    {
                        _logger.Debug(this, "Typing password");
                        ((ValuePattern)valuePattern).SetValue(password);
                    }
                }
                var domainBox = list.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ComboBox));

                var    max   = 0.0;
                string value = null;
                var    items = GetComboboxItems(domainBox);

                foreach (var option in items)
                {
                    var current = domain.LongestCommonSubsequence(option).Item2;
                    if (current > max)
                    {
                        max   = current;
                        value = option;
                    }
                }
                _logger.Debug(this, "Setting domain " + value);
                if (value != null)
                {
                    SelectComboboxItem(domainBox, value);
                }

                if (args["AutoLogin"] != null && args["autoLogin"].ToLower() == "true")
                {
                    var okButton = list.FindFirst(TreeScope.Children, new AndCondition(
                                                      new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button),
                                                      new PropertyCondition(AutomationElement.NameProperty, "OK")));
                    await Task.Delay(360);

                    var invokePattern = okButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
                    _logger.Debug(this, "Pressing OK");
                    invokePattern.Invoke();
                }
            }
            catch (Exception ex)
            {
                _logger.Error(this, ex.Message);
            }
        }
Beispiel #18
0
            public static ScreenElement fromAutomationElement(AutomationElement element, CacheRequest cacheRequest = null)
            {
                if (element == null)
                {
                    return(null);
                }

                try
                {
                    bool cacheRequestMine = cacheRequest == null;
                    if (cacheRequestMine)
                    {
                        cacheRequest = new CacheRequest();
                        cacheRequest.Add(AutomationElement.ClassNameProperty);
                        cacheRequest.Add(AutomationElement.ControlTypeProperty);
                        cacheRequest.Add(AutomationElement.AutomationIdProperty);
                        cacheRequest.Add(AutomationElement.IsControlElementProperty);
                        cacheRequest.Add(AutomationElement.BoundingRectangleProperty);
                        cacheRequest.AutomationElementMode = AutomationElementMode.Full;
                        cacheRequest.TreeFilter            = Automation.RawViewCondition;
                        cacheRequest.Push();
                        element = element.GetUpdatedCache(cacheRequest);
                    }

                    var           p = element.Cached;
                    var           b = p.BoundingRectangle;
                    ScreenElement parent;
                    try
                    {
                        parent = ScreenElement.fromAutomationElement(TreeWalker.RawViewWalker.GetParent(element, cacheRequest), cacheRequest);
                    }
                    catch (Exception)
                    {
                        parent = null;
                    }
                    var r = new ScreenElement()
                    {
                        classname = p.ClassName,
                        type      = p.ControlType.ProgrammaticName,
                        id        = p.AutomationId,
                        isControl = p.IsControlElement,
                        x         = b.X,
                        y         = b.Y,
                        width     = b.Width,
                        height    = b.Height,
                        // parent = parent,
                    };
                    if (cacheRequestMine)
                    {
                        cacheRequest.Pop();
                    }
                    return(r);
                }
                catch (Exception)
                {
                    return(null);
                }
            }
Beispiel #19
0
        public void SetSelection(string option)
        {
            if (comboBoxElement == null)
            {
                GetComboBox();
            }


            if ((comboBoxElement != null) &&
                (comboBoxElement.Current.IsEnabled))
            {
                AutomationElement sel = null;

                ExpandCollapsePattern expandPattern
                    = (ExpandCollapsePattern)comboBoxElement
                      .GetCurrentPattern(
                          ExpandCollapsePattern.Pattern);

                expandPattern.Expand();

                CacheRequest cacheRequest = new CacheRequest();
                cacheRequest.Add(AutomationElement.NameProperty);
                cacheRequest.TreeScope = TreeScope.Element
                                         | TreeScope.Children;

                AutomationElement comboboxItems
                    = comboBoxElement.GetUpdatedCache(
                          cacheRequest);

                foreach (AutomationElement item
                         in comboboxItems.CachedChildren)
                {
                    if (item.Current.Name == "")
                    {
                        CacheRequest cacheRequest2 = new CacheRequest();
                        cacheRequest2.Add(AutomationElement.NameProperty);
                        cacheRequest2.TreeScope = TreeScope.Element
                                                  | TreeScope.Children;

                        AutomationElement comboboxItems2
                            = item.GetUpdatedCache(cacheRequest);

                        foreach (AutomationElement item2
                                 in comboboxItems2.CachedChildren)
                        {
                            if (item2.Current.Name == option)
                            {
                                sel = item2;
                            }
                        }
                    }
                }

                if (sel != null)
                {
                    SelectionItemPattern select =
                        (SelectionItemPattern)sel.GetCurrentPattern(
                            SelectionItemPattern.Pattern);

                    select.Select();
                }
                expandPattern.Collapse();
            }
        }
Beispiel #20
0
        private List <DetailGroupViewModel> LoadDetails()
        {
            var detailGroups = new List <DetailGroupViewModel>();
            var cacheRequest = new CacheRequest();

            cacheRequest.TreeScope = TreeScope.Element;
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.AutomationId);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.Name);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.ClassName);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.ControlType);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.LocalizedControlType);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.FrameworkId);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.ProcessId);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.IsEnabled);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.IsOffscreen);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.BoundingRectangle);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.HelpText);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.IsPassword);
            cacheRequest.Add(AutomationElement.Automation.PropertyLibrary.Element.NativeWindowHandle);
            using (cacheRequest.Activate())
            {
                var elementCached = AutomationElement.FindFirst(TreeScope.Element, new TrueCondition());
                // Element identification
                var identification = new List <IDetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("AutomationId", elementCached.Properties.AutomationId),
                    DetailViewModel.FromAutomationProperty("Name", elementCached.Properties.Name),
                    DetailViewModel.FromAutomationProperty("ClassName", elementCached.Properties.ClassName),
                    DetailViewModel.FromAutomationProperty("ControlType", elementCached.Properties.ControlType),
                    DetailViewModel.FromAutomationProperty("LocalizedControlType", elementCached.Properties.LocalizedControlType),
                    new DetailViewModel("FrameworkType", elementCached.FrameworkType.ToString()),
                    DetailViewModel.FromAutomationProperty("FrameworkId", elementCached.Properties.FrameworkId),
                    DetailViewModel.FromAutomationProperty("ProcessId", elementCached.Properties.ProcessId),
                };
                detailGroups.Add(new DetailGroupViewModel("Identification", identification));

                // Element details
                var details = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("IsEnabled", elementCached.Properties.IsEnabled),
                    DetailViewModel.FromAutomationProperty("IsOffscreen", elementCached.Properties.IsOffscreen),
                    DetailViewModel.FromAutomationProperty("BoundingRectangle", elementCached.Properties.BoundingRectangle),
                    DetailViewModel.FromAutomationProperty("HelpText", elementCached.Properties.HelpText),
                    DetailViewModel.FromAutomationProperty("IsPassword", elementCached.Properties.IsPassword)
                };
                // Special handling for NativeWindowHandle
                var nativeWindowHandle       = elementCached.Properties.NativeWindowHandle.ValueOrDefault;
                var nativeWindowHandleString = "Not Supported";
                if (nativeWindowHandle != default(IntPtr))
                {
                    nativeWindowHandleString = String.Format("{0} ({0:X8})", nativeWindowHandle.ToInt32());
                }
                details.Add(new DetailViewModel("NativeWindowHandle", nativeWindowHandleString));
                detailGroups.Add(new DetailGroupViewModel("Details", details));
            }

            // Pattern details
            var allSupportedPatterns = AutomationElement.BasicAutomationElement.GetSupportedPatterns();
            var allPatterns          = AutomationElement.Automation.PatternLibrary.AllForCurrentFramework;
            var patterns             = new List <DetailViewModel>();

            foreach (var pattern in allPatterns)
            {
                var hasPattern = allSupportedPatterns.Contains(pattern);
                patterns.Add(new DetailViewModel(pattern.Name + "Pattern", hasPattern ? "Yes" : "No")
                {
                    Important = hasPattern
                });
            }
            detailGroups.Add(new DetailGroupViewModel("Pattern Support", patterns));

            // GridItemPattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.GridItemPattern))
            {
                var pattern        = AutomationElement.Patterns.GridItem.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("Column", pattern.Column),
                    DetailViewModel.FromAutomationProperty("ColumnSpan", pattern.ColumnSpan),
                    DetailViewModel.FromAutomationProperty("Row", pattern.Row),
                    DetailViewModel.FromAutomationProperty("RowSpan", pattern.RowSpan),
                    DetailViewModel.FromAutomationProperty("ContainingGrid", pattern.ContainingGrid)
                };
                detailGroups.Add(new DetailGroupViewModel("GridItem Pattern", patternDetails));
            }
            // GridPattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.GridPattern))
            {
                var pattern        = AutomationElement.Patterns.Grid.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("ColumnCount", pattern.ColumnCount),
                    DetailViewModel.FromAutomationProperty("RowCount", pattern.RowCount)
                };
                detailGroups.Add(new DetailGroupViewModel("Grid Pattern", patternDetails));
            }
            // LegacyIAccessiblePattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.LegacyIAccessiblePattern))
            {
                var pattern        = AutomationElement.Patterns.LegacyIAccessible.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("Name", pattern.Name),
                    new DetailViewModel("State", AccessibilityTextResolver.GetStateText(pattern.State.ValueOrDefault)),
                    new DetailViewModel("Role", AccessibilityTextResolver.GetRoleText(pattern.Role.ValueOrDefault)),
                    DetailViewModel.FromAutomationProperty("Value", pattern.Value),
                    DetailViewModel.FromAutomationProperty("ChildId", pattern.ChildId),
                    DetailViewModel.FromAutomationProperty("DefaultAction", pattern.DefaultAction),
                    DetailViewModel.FromAutomationProperty("Description", pattern.Description),
                    DetailViewModel.FromAutomationProperty("Help", pattern.Help),
                    DetailViewModel.FromAutomationProperty("KeyboardShortcut", pattern.KeyboardShortcut),
                    DetailViewModel.FromAutomationProperty("Selection", pattern.Selection)
                };
                detailGroups.Add(new DetailGroupViewModel("LegacyIAccessible Pattern", patternDetails));
            }
            // RangeValuePattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.RangeValuePattern))
            {
                var pattern        = AutomationElement.Patterns.RangeValue.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("IsReadOnly", pattern.IsReadOnly),
                    DetailViewModel.FromAutomationProperty("SmallChange", pattern.SmallChange),
                    DetailViewModel.FromAutomationProperty("LargeChange", pattern.LargeChange),
                    DetailViewModel.FromAutomationProperty("Minimum", pattern.Minimum),
                    DetailViewModel.FromAutomationProperty("Maximum", pattern.Maximum),
                    DetailViewModel.FromAutomationProperty("Value", pattern.Value)
                };
                detailGroups.Add(new DetailGroupViewModel("RangeValue Pattern", patternDetails));
            }
            // ScrollPattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.ScrollPattern))
            {
                var pattern        = AutomationElement.Patterns.Scroll.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("HorizontalScrollPercent", pattern.HorizontalScrollPercent),
                    DetailViewModel.FromAutomationProperty("HorizontalViewSize", pattern.HorizontalViewSize),
                    DetailViewModel.FromAutomationProperty("HorizontallyScrollable", pattern.HorizontallyScrollable),
                    DetailViewModel.FromAutomationProperty("VerticalScrollPercent", pattern.VerticalScrollPercent),
                    DetailViewModel.FromAutomationProperty("VerticalViewSize", pattern.VerticalViewSize),
                    DetailViewModel.FromAutomationProperty("VerticallyScrollable", pattern.VerticallyScrollable)
                };
                detailGroups.Add(new DetailGroupViewModel("Scroll Pattern", patternDetails));
            }
            // SelectionItemPattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.SelectionItemPattern))
            {
                var pattern        = AutomationElement.Patterns.SelectionItem.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("IsSelected", pattern.IsSelected),
                    DetailViewModel.FromAutomationProperty("SelectionContainer", pattern.SelectionContainer)
                };
                detailGroups.Add(new DetailGroupViewModel("SelectionItem Pattern", patternDetails));
            }
            // SelectionPattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.SelectionPattern))
            {
                var pattern        = AutomationElement.Patterns.Selection.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("Selection", pattern.Selection),
                    DetailViewModel.FromAutomationProperty("CanSelectMultiple", pattern.CanSelectMultiple),
                    DetailViewModel.FromAutomationProperty("IsSelectionRequired", pattern.IsSelectionRequired)
                };
                detailGroups.Add(new DetailGroupViewModel("Selection Pattern", patternDetails));
            }
            // TableItemPattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.TableItemPattern))
            {
                var pattern        = AutomationElement.Patterns.TableItem.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("ColumnHeaderItems", pattern.ColumnHeaderItems),
                    DetailViewModel.FromAutomationProperty("RowHeaderItems", pattern.RowHeaderItems)
                };
                detailGroups.Add(new DetailGroupViewModel("TableItem Pattern", patternDetails));
            }
            // TablePattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.TablePattern))
            {
                var pattern        = AutomationElement.Patterns.Table.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("ColumnHeaderItems", pattern.ColumnHeaders),
                    DetailViewModel.FromAutomationProperty("RowHeaderItems", pattern.RowHeaders),
                    DetailViewModel.FromAutomationProperty("RowOrColumnMajor", pattern.RowOrColumnMajor)
                };
                detailGroups.Add(new DetailGroupViewModel("Table Pattern", patternDetails));
            }
            // TogglePattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.TogglePattern))
            {
                var pattern        = AutomationElement.Patterns.Toggle.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("ToggleState", pattern.ToggleState)
                };
                detailGroups.Add(new DetailGroupViewModel("Toggle Pattern", patternDetails));
            }
            // ValuePattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.ValuePattern))
            {
                var pattern        = AutomationElement.Patterns.Value.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("IsReadOnly", pattern.IsReadOnly),
                    DetailViewModel.FromAutomationProperty("Value", pattern.Value)
                };
                detailGroups.Add(new DetailGroupViewModel("Value Pattern", patternDetails));
            }
            // WindowPattern
            if (allSupportedPatterns.Contains(AutomationElement.Automation.PatternLibrary.WindowPattern))
            {
                var pattern        = AutomationElement.Patterns.Window.Pattern;
                var patternDetails = new List <DetailViewModel>
                {
                    DetailViewModel.FromAutomationProperty("IsModal", pattern.IsModal),
                    DetailViewModel.FromAutomationProperty("IsTopmost", pattern.IsTopmost),
                    DetailViewModel.FromAutomationProperty("CanMinimize", pattern.CanMinimize),
                    DetailViewModel.FromAutomationProperty("CanMaximize", pattern.CanMaximize),
                    DetailViewModel.FromAutomationProperty("WindowVisualState", pattern.WindowVisualState),
                    DetailViewModel.FromAutomationProperty("WindowInteractionState", pattern.WindowInteractionState)
                };
                detailGroups.Add(new DetailGroupViewModel("Window Pattern", patternDetails));
            }

            return(detailGroups);
        }
Beispiel #21
0
        private void buttonInstall_Click(object sender, System.EventArgs e)
        {
            // EXAMPLE CODE SECTION

            process = Process.Start(srcPath);
            AutomationElement aeDeskTop = AutomationElement.RootElement;

            Thread.Sleep(500);
            //AutomationElement aeForm = null;
            int times = 0;

            process.WaitForInputIdle();
            while (process.MainWindowHandle == null || process.MainWindowHandle == IntPtr.Zero)
            {
                Thread.Sleep(1000);
                if (times > 5 && process.Handle != IntPtr.Zero)
                {
                    break;
                }
                times++;
            }
            if (process.MainWindowHandle == IntPtr.Zero)
            {
                EnumWindows(callBackEnumWindows, 0);
            }
            else
            {
                elementList.Add(AutomationElement.FromHandle(process.MainWindowHandle));
            }

            Condition condition1 = new PropertyCondition(AutomationElement.IsControlElementProperty, true);
            Condition condition2 = new PropertyCondition(AutomationElement.IsEnabledProperty, true);
            Condition condition  = new PropertyCondition(AutomationElement.ProcessIdProperty, process.Id);
            //AutomationElement aeForm = AutomationElement.FromHandle(process.MainWindowHandle);
            CacheRequest fetchRequest = new CacheRequest();

            fetchRequest.Add(AutomationElement.NameProperty);
            fetchRequest.Add(AutomationElement.AutomationIdProperty);
            fetchRequest.Add(AutomationElement.ControlTypeProperty);
            fetchRequest.Add(AutomationElement.BoundingRectangleProperty);

            using (fetchRequest.Activate())
            {
                foreach (AutomationElement aeForm in elementList)
                {
                    AutomationElementCollection tElemList = aeForm.FindAll(TreeScope.Subtree, new AndCondition(condition, condition1, condition2));
                    //elements = aeForm.FindAll(TreeScope.Subtree, new AndCondition(condition1, condition2, condition));
                    ///elements.CopyTo(temp, temp.Count);
                    for (int i = 0; i < tElemList.Count; i++)
                    {
                        childElemList.Add(tElemList[i]);
                    }
                }
                //WalkEnabledElements(aeDeskTop);
            }
            //fetchRequest.Add(AutomationElement.IsContentElementProperty);
            //foreach (AutomationElement element in elementList)
            //{
            //    WalkEnabledElements(element);
            //}

            //elements = aeDeskTop.FindAll(TreeScope.Subtree, new AndCondition(condition1, condition2, condition));

            AddText("Adding mouse hook.");
            mouseHook.InstallHook(this.Handle);

            AddText("Adding keyboard hook.");
            keyboardHook.InstallHook(this.Handle);

            AddText("Adding cbt hook");
            cbtHook.InstallHook(this.Handle);

            buttonInstall.Enabled   = false;
            buttonUninstall.Enabled = true;
        }
        public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
        {
            state = false;
            var ar = new CacheAsyncResult();

            //Manipulate the URI
            String tempUri = request.CanonicalUri.ToString();

            if (!_keyUrls.ContainsKey(tempUri))
            {
                //state = true;
                ar.strUrl = tempUri;
                ar.Complete(response, true);
                return ar;
            }

            ar.Complete(null, true);
            return ar;
        }
Beispiel #23
0
 public void AddRequest(string key, CacheRequest request)
 {
     object[] objArray1 = new object[] { key, request };
     base.method_8("AddRequest", objArray1);
 }
Beispiel #24
0
 public static void ExecuteWithUpdatedCache(this AutomationElement ae, CacheRequest cr, Action <AutomationElement> action)
 {
     using (cr.Activate())
         action(ae.GetUpdatedCache(cr));
 }
Beispiel #25
0
 public static void AddRequest(Asset asset, CacheRequest request)
 {
     object[] objArray1 = new object[] { asset, request };
     MonoClass.smethod_18(TritonHs.MainAssemblyPath, "", "AssetCache", "AddRequest", objArray1);
 }
 public void ResponseData(CacheRequest pDownloaderRequest, CacheResponse pDownloaderResponse)
 {
     // do nothing
 }
 public async Task<CacheResponse> RequestAsync(CacheRequest request)
 {
     return await downloaderPluginBase.RequestAsync(request);
 }
 public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state);
Beispiel #29
0
 public static void AddRequest(Asset asset, CacheRequest request)
 {
     s_cacheTable[asset.GetFamily()].AddRequest(asset.GetName(), request);
 }
			/// <summary>
			/// Initializes a new instance of the <see cref="CanContinueProcessingEventArgs"/> class.
			/// </summary>
			/// <param name="request">The cache request.</param>
			public CanContinueProcessingEventArgs(CacheRequest request)
			{
				Request = request;
				ContinueProcessing = true;
			}
Beispiel #31
0
 public void AddRequest(string key, CacheRequest request)
 {
     this.m_assetRequestMap.Add(key, request);
 }
		/// <summary>
		/// Pushes the given item to the worker queue. Items with high priority are renderer 
		/// or gallery items, ie. large images in gallery and pane views and images requested 
		/// by custom renderers. Items with 0 priority are regular thumbnails.
		/// </summary>
		/// <param name="item">The item to add to the worker queue.</param>
		/// <param name="priority">Priority of the item in the queue.</param>
		private void RunWorker(CacheRequest item, int priority)
		{
			// Get the current synchronization context
			if (context == null)
				context = SynchronizationContext.Current;

			// Already being processed?
			if (item.RequestType == RequestType.Thumbnail)
			{
				if (processing.ContainsKey(item.Guid))
					return;
				else
					processing.Add(item.Guid, false);
			}
			else if (item.RequestType == RequestType.Renderer)
			{
				if (processingRendererItem == item.Guid)
					return;
				else
				{
					bw.CancelAsync(priority);
					processingRendererItem = item.Guid;
				}
			}
			else if (item.RequestType == RequestType.Gallery)
			{
				if (processingGalleryItem == item.Guid)
					return;
				else
				{
					bw.CancelAsync(priority);
					processingGalleryItem = item.Guid;
				}
			}

			// Raise the ThumbnailCaching event
			if (mImageListView != null)
				mImageListView.OnThumbnailCachingInternal(item.Guid, item.Size);

			// Add the item to the queue for processing
			bw.RunWorkerAsync(item, priority, item.RequestType != RequestType.Thumbnail);
		}
Beispiel #33
0
 public void Init()
 {
     instance = new CacheRequest();
 }
        public static AutomationElementCollection FindElementByControlType(this AutomationElement ae, string controlType)
        {
            Condition         c           = null;
            AutomationElement elementList = null;

            if (ae == null || String.IsNullOrEmpty(controlType))
            {
                throw new InvalidOperationException("invalid operation");
            }
            // Set up the CacheRequest.
            CacheRequest cacheRequest = new CacheRequest();

            cacheRequest.Add(AutomationElement.ControlTypeProperty);
            cacheRequest.TreeScope = TreeScope.Element | TreeScope.Children;

            using (cacheRequest.Activate())
            {
                switch (controlType)
                {
                case "List":
                    // Set a property condition that will be used to find the control.
                    c = new PropertyCondition(
                        AutomationElement.ControlTypeProperty, ControlType.List);
                    elementList = ae.FindFirst(TreeScope.Descendants, c);
                    break;

                case "Tree":
                    // Set a property condition that will be used to find the control.
                    c = new PropertyCondition(
                        AutomationElement.ControlTypeProperty, ControlType.Tree);
                    elementList = ae.FindFirst(TreeScope.Descendants, c);
                    break;

                case "Grid":
                    // Set a property condition that will be used to find the control.
                    c = new PropertyCondition(
                        AutomationElement.ControlTypeProperty, ControlType.DataGrid);
                    elementList = ae.FindFirst(TreeScope.Descendants, c);
                    break;

                case "Tab":
                    // Set a property condition that will be used to find the control.
                    c = new PropertyCondition(
                        AutomationElement.ControlTypeProperty, ControlType.Tab);
                    elementList = ae.FindFirst(TreeScope.Descendants, c);
                    break;

                case "Combo":
                    // Set a property condition that will be used to find the control.
                    c = new PropertyCondition(
                        AutomationElement.ControlTypeProperty, ControlType.ComboBox);
                    elementList = ae.FindFirst(TreeScope.Descendants, c);
                    break;

                default:
                    break;
                }

                // Find the element.
                return(elementList.CachedChildren);
            }
        }
Beispiel #35
0
 /// <summary>
 /// Pushes the given item to the worker queue.
 /// </summary>
 /// <param name="item">The item to add to the worker queue.</param>
 private void RunWorker(CacheRequest item)
 {
     RunWorker(item, 0);
 }
Beispiel #36
0
        public void PostCacheRequest(CacheRequest cacheRequest)
        {
            Task.Run(async() =>
            {
                try
                {
                    var cacheResult = await ProcessCacheRequest(cacheRequest);
                    _buildManager.PostCacheResult(cacheRequest, cacheResult);
                }
                catch (Exception e)
                {
                    _buildManager.PostCacheResult(cacheRequest, CacheResult.IndicateException(e));
                }
            }, _cancellationToken);

            async Task <CacheResult> ProcessCacheRequest(CacheRequest request)
            {
                // Prevent needless evaluation if design time builds detected.
                if (_projectCacheDescriptor.VsWorkaround && DesignTimeBuildsDetected)
                {
                    // The BuildManager should disable the cache when it finds its servicing design time builds.
                    return(CacheResult.IndicateNonCacheHit(CacheResultType.CacheMiss));
                }

                EvaluateProjectIfNecessary(request);

                // Detect design time builds.
                if (_projectCacheDescriptor.VsWorkaround)
                {
                    var isDesignTimeBuild = IsDesignTimeBuild(request.Configuration.Project);

                    var previousValue = Interlocked.CompareExchange(
                        ref DesignTimeBuildsDetected,
                        new NullableBool(isDesignTimeBuild),
                        null);

                    ErrorUtilities.VerifyThrowInternalError(
                        previousValue is null || previousValue == false || isDesignTimeBuild,
                        "Either all builds in a build session or design time builds, or none");

                    // No point progressing with expensive plugin initialization or cache query if design time build detected.
                    if (DesignTimeBuildsDetected)
                    {
                        // The BuildManager should disable the cache when it finds its servicing design time builds.
                        return(CacheResult.IndicateNonCacheHit(CacheResultType.CacheMiss));
                    }
                }

                // TODO: remove after we change VS to set the cache descriptor via build parameters.
                // VS workaround needs to wait until the first project is evaluated to extract enough information to initialize the plugin.
                // No cache request can progress until late initialization is complete.
                if (_projectCacheDescriptor.VsWorkaround)
                {
                    if (Interlocked.CompareExchange(
                            ref LateInitializationForVSWorkaroundCompleted,
                            new TaskCompletionSource <bool>(),
                            null) is null)
                    {
                        await LateInitializePluginForVsWorkaround(request);

                        LateInitializationForVSWorkaroundCompleted.SetResult(true);
                    }
                    else
                    {
                        // Can't be null. If the thread got here it means another thread initialized the completion source.
                        await LateInitializationForVSWorkaroundCompleted !.Task;
                    }
                }

                ErrorUtilities.VerifyThrowInternalError(
                    LateInitializationForVSWorkaroundCompleted is null ||
                    _projectCacheDescriptor.VsWorkaround && LateInitializationForVSWorkaroundCompleted.Task.IsCompleted,
                    "Completion source should be null when this is not the VS workaround");

                return(await GetCacheResultAsync(
                           new BuildRequestData(
                               request.Configuration.Project,
                               request.Submission.BuildRequestData.TargetNames.ToArray())));
            }
 public void ResponseData(CacheRequest pDownloaderRequest, CacheResponse pDownloaderResponse)
 {
     // do nothing
 }
 public IAsyncResult BeginPersist(CacheRequest request, CacheResponse response, AsyncCallback callback, object state)
 {
     return null;
 }
Beispiel #39
0
        /// <summary>
        /// add item to a cloud cache add item to a cloud cache
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="appId">Id of CloudApp</param>
        /// <param name="cacheName">Name of cache</param>
        /// <param name="dataKey">key under which data should be store in cache</param>
        /// <param name="body">cache data and master key included got from this object</param>
        /// <returns>Task of string</returns>
        public async System.Threading.Tasks.Task<string> SetAsync (string appId, string cacheName, string dataKey, CacheRequest body)
        {
             ApiResponse<string> localVarResponse = await SetAsyncWithHttpInfo(appId, cacheName, dataKey, body);
             return localVarResponse.Data;

        }
Beispiel #40
0
        /// <summary>
        /// Handles the RunWorkerCompleted event of the queued background worker.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Manina.Windows.Forms.QueuedWorkerCompletedEventArgs"/>
        /// instance containing the event data.</param>
        void bw_RunWorkerCompleted(object sender, QueuedWorkerCompletedEventArgs e)
        {
            CacheRequest request = e.UserState as CacheRequest;
            CacheItem    result  = e.Result as CacheItem;

            // We are done processing
            if (request.RequestType == RequestType.Renderer)
            {
                processingRendererItem = Guid.Empty;
            }
            else if (request.RequestType == RequestType.Gallery)
            {
                processingGalleryItem = Guid.Empty;
            }
            else
            {
                processing.Remove(request.Guid);
            }

            // Do not process the result if the cache operation
            // was cancelled.
            if (e.Cancelled)
            {
                return;
            }

            // Dispose old item and add to cache
            if (request.RequestType == RequestType.Renderer)
            {
                if (rendererItem != null)
                {
                    rendererItem.Dispose();
                }

                rendererItem = result;
            }
            else if (request.RequestType == RequestType.Gallery)
            {
                if (galleryItem != null)
                {
                    galleryItem.Dispose();
                }

                galleryItem = result;
            }
            else if (result != null)
            {
                CacheItem existing = null;
                if (thumbCache.TryGetValue(result.Guid, out existing))
                {
                    existing.Dispose();
                    thumbCache.Remove(result.Guid);
                }
                thumbCache.Add(result.Guid, result);

                if (result.Image != null)
                {
                    // Did the thumbnail size change while we were
                    // creating the thumbnail?
                    if (result.Size != mImageListView.ThumbnailSize)
                    {
                        result.State = CacheState.Unknown;
                    }

                    // Purge invisible items if we exceeded the cache limit
                    MemoryUsed += GetImageMemorySize(result.Image);
                    if (IsCacheLimitExceeded())
                    {
                        PurgeInvisible(true);
                    }
                }
            }

            //Refresh the control
            if (mImageListView != null)
            {
                if (request.RequestType != RequestType.Thumbnail || mImageListView.IsItemVisible(request.Guid))
                {
                    mImageListView.Refresh(false, true);
                }
            }

            // Raise the ThumbnailCached event
            if (mImageListView != null)
            {
                mImageListView.OnThumbnailCachedInternal(result.Guid, result.Image, result.Size, request.RequestType == RequestType.Thumbnail);
            }

            // Raise the CacheError event
            if (e.Error != null && mImageListView != null)
            {
                mImageListView.OnCacheErrorInternal(result.Guid, e.Error, CacheThread.Thumbnail);
            }
        }
        public async Task <IActionResult> Post([FromBody] CacheRequest cacheRequest)
        {
            bool ret = await _cacheService.SetCacheValueAsync(cacheRequest);

            return(ret ? (IActionResult)Ok(ret) : BadRequest(ret));
        }
Beispiel #42
0
 /// <summary>
 /// add item to a cloud cache add item to a cloud cache
 /// </summary>
 /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="appId">Id of CloudApp</param> 
 /// <param name="cacheName">Name of cache</param> 
 /// <param name="dataKey">key under which data should be store in cache</param> 
 /// <param name="body">cache data and master key included got from this object</param> 
 /// <returns>string</returns>
 public string Set (string appId, string cacheName, string dataKey, CacheRequest body)
 {
      ApiResponse<string> localVarResponse = SetWithHttpInfo(appId, cacheName, dataKey, body);
      return localVarResponse.Data;
 }
 public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
 {
     if (this.IsStopped)
     {
         CacheAsyncResult result = new CacheAsyncResult();
         result.Complete(new CacheResponse(0L, null, null, null, HttpStatusCode.NotFound, "Not Found", DateTime.Now, false), true);
         return result;
     }
     if (!request.CanonicalUri.ToString().Contains("FragmentInfo") && !request.CanonicalUri.ToString().Contains("Manifest"))
     {
         return null;
     }
     CacheAsyncResult ar = new CacheAsyncResult {
         strUrl = request.CanonicalUri.ToString()
     };
     HttpWebRequest webRequest = WebRequestCreator.BrowserHttp.Create(request.CanonicalUri) as HttpWebRequest;
     webRequest.BeginGetResponse(delegate (IAsyncResult result) {
         try
         {
             HttpWebResponse response = webRequest.EndGetResponse(result) as HttpWebResponse;
             if (response.StatusCode != HttpStatusCode.OK)
             {
                 ar.Complete(null, true);
             }
             else
             {
                 using (CryptoStream stream = new CryptoStream(response.GetResponseStream(), this._decryptionInfo.Decryptor, CryptoStreamMode.Read))
                 {
                     MemoryStream stream2 = new MemoryStream();
                     long contentLength = 0L;
                     int count = 0x1000;
                     byte[] buffer = new byte[count];
                     while (stream.CanRead)
                     {
                         int num2 = stream.Read(buffer, 0, count);
                         contentLength += num2;
                         if (num2 == 0)
                         {
                             break;
                         }
                         stream2.Write(buffer, 0, num2);
                     }
                     stream2.Position = 0L;
                     if (request.CanonicalUri.ToString().Contains("Manifest"))
                     {
                         StreamReader reader = new StreamReader(stream2);
                         string s = reader.ReadToEnd().Replace("{start time})", "{start time})?" + this._decryptionInfo.SessionID).Replace("300000000", "550000000");
                         stream2 = new MemoryStream(Encoding.Unicode.GetBytes(s)) {
                             Position = 0L
                         };
                     }
                     CacheResponse response2 = new CacheResponse(contentLength, response.ContentType, null, stream2, response.StatusCode, response.StatusDescription, DateTime.Now, true);
                     stream2.Position = 0L;
                     ar.Complete(response2, true);
                 }
             }
         }
         catch (Exception)
         {
             ar.Complete(null, true);
         }
     }, null);
     return ar;
 }
Beispiel #44
0
        /// <summary>
        /// add item to a cloud cache add item to a cloud cache
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="appId">Id of CloudApp</param>
        /// <param name="cacheName">Name of cache</param>
        /// <param name="dataKey">key under which data should be store in cache</param>
        /// <param name="body">cache data and master key included got from this object</param>
        /// <returns>Task of ApiResponse (string)</returns>
        public async System.Threading.Tasks.Task<ApiResponse<string>> SetAsyncWithHttpInfo (string appId, string cacheName, string dataKey, CacheRequest body)
        {
            // verify the required parameter 'appId' is set
            if (appId == null) throw new ApiException(400, "Missing required parameter 'appId' when calling Set");
            // verify the required parameter 'cacheName' is set
            if (cacheName == null) throw new ApiException(400, "Missing required parameter 'cacheName' when calling Set");
            // verify the required parameter 'dataKey' is set
            if (dataKey == null) throw new ApiException(400, "Missing required parameter 'dataKey' when calling Set");
            // verify the required parameter 'body' is set
            if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling Set");
            
    
            var localVarPath = "cache/{app_id}/{cache_name}/{data_key}";
    
            var localVarPathParams = new Dictionary<String, String>();
            var localVarQueryParams = new Dictionary<String, String>();
            var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
            var localVarFormParams = new Dictionary<String, String>();
            var localVarFileParams = new Dictionary<String, FileParameter>();
            Object localVarPostBody = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json", "text/plain;charset=utf-8"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
            if (localVarHttpHeaderAccept != null)
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (appId != null) localVarPathParams.Add("app_id", Configuration.ApiClient.ParameterToString(appId)); // path parameter
            if (cacheName != null) localVarPathParams.Add("cache_name", Configuration.ApiClient.ParameterToString(cacheName)); // path parameter
            if (dataKey != null) localVarPathParams.Add("data_key", Configuration.ApiClient.ParameterToString(dataKey)); // path parameter
            
            
            
            
            if (body.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
            }
            else
            {
                localVarPostBody = body; // byte array
            }

            

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, 
                Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, 
                localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int) localVarResponse.StatusCode;
 
            if (localVarStatusCode >= 400)
                throw new ApiException (localVarStatusCode, "Error calling Set: " + localVarResponse.Content, localVarResponse.Content);
            else if (localVarStatusCode == 0)
                throw new ApiException (localVarStatusCode, "Error calling Set: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);

            return new ApiResponse<string>(localVarStatusCode,
                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string)));
            
        }
        public IAsyncResult BeginRetrieve(CacheRequest request, AsyncCallback callback, object state)
        {
            CacheResponse response = null;
            var ar = new CacheAsyncResult {strUrl = request.CanonicalUri.ToString()};
            // ar.strUrl = "http://mediadl.microsoft.com/mediadl/iisnet/smoothmedia/Experience/BigBuckBunny_720p.ism/Manifest";

            ar.Complete(response, true);
            return ar;
        }