ThrowIfCancellationRequested() public method

public ThrowIfCancellationRequested ( ) : void
return void
Ejemplo n.º 1
0
 public async Task RunAsync(Graph graph, Stream outputStream, RendererLayouts layout, RendererFormats format, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     var fileName = Path.Combine(graphvizBin, GetRendererLayoutExecutable(layout));
     var arguments = GetRendererFormatArgument(format);
     var startInfo = new ProcessStartInfo
     {
         FileName = fileName,
         Arguments = arguments,
         UseShellExecute = false,
         CreateNoWindow = true,
         RedirectStandardInput = true,
         RedirectStandardOutput = true,
         RedirectStandardError = true
     };
     var tcs = new TaskCompletionSource<object>();
     using (var process = Process.Start(startInfo))
     {
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.Register(() =>
         {
             tcs.TrySetCanceled();
             process.CloseMainWindow();
         });
         using (var standardInput = process.StandardInput)
         {
             graph.WriteTo(standardInput);
         }
         using (var standardOutput = process.StandardOutput)
         {
             await Task.WhenAny(tcs.Task, standardOutput.BaseStream.CopyToAsync(outputStream, 4096, cancellationToken));
         }
     }
     cancellationToken.ThrowIfCancellationRequested();
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 模拟登录
        /// </summary>
        /// <param name="passport"></param>
        /// <param name="password"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        public async Task<OAuthAccessToken> LoginAsync(string passport, string password, CancellationToken cancelToken)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            {
                return true;
            };
            var request = WebRequest.Create(Settings.AuthorizeUrl) as HttpWebRequest;

            request.Referer = GetAuthorizeUrl();
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();

            var postBody = GetSimulateLoginPostBody(passport, password);
            var postData = System.Text.Encoding.UTF8.GetBytes(postBody);

            cancelToken.ThrowIfCancellationRequested();
            var result = "";
            using (var requestStream = await request.GetRequestStreamAsync())
            {
                await requestStream.WriteAsync(postData, 0, postData.Length, cancelToken);
            }
            using (var response = await request.GetResponseAsync())
            {
                using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    cancelToken.ThrowIfCancellationRequested();
                    result = await sr.ReadToEndAsync();
                    return ConvertToAccessTokenByRegex(result);
                }
            }
        }
        internal static async Task<IEnumerable<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>> FindNavigableDeclaredSymbolInfos(Project project, string pattern, CancellationToken cancellationToken)
        {
            var patternMatcher = new PatternMatcher(pattern);

            var result = new List<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>();
            foreach (var document in project.Documents)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var declaredSymbolInfos = await document.GetDeclaredSymbolInfosAsync(cancellationToken).ConfigureAwait(false);
                foreach (var declaredSymbolInfo in declaredSymbolInfos)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var patternMatches = patternMatcher.GetMatches(
                        GetSearchName(declaredSymbolInfo),
                        declaredSymbolInfo.FullyQualifiedContainerName,
                        includeMatchSpans: false);

                    if (patternMatches != null)
                    {
                        result.Add(ValueTuple.Create(declaredSymbolInfo, document, patternMatches));
                    }
                }
            }

            return result;
        }
 public void CheckAndReport(string date, CancellationToken cancellationToken)
 {
     var settings = _settingsRepository.Get<ContentsAvailabilitySettings>(SubscriptionsSettingId.ContentsAvailabilityMonitoring);
     _logger.Info("Запущена проверка доступности сервисов контент провайдеров запланированная на {0}", date);
     try
     {
         var badContentsByProvider = GetBadContents(settings, cancellationToken);
         //Если ни одного плохого контента не нашлось - прекращаем выполнение.
         if (!badContentsByProvider.Any())
             return;
         cancellationToken.ThrowIfCancellationRequested();
         //Отправляем письмо со всеми плохими контентами по дефолтным адресам.
         SendToDefaultMails(badContentsByProvider.Select(c => c.Value).ToArray(), settings);
         var providers = GetProviderEmailAddresses();
         //Отправляем каждому провайдеру у которого нашлись плохие контенты свое письмо с его плохими контентами.
         foreach (var providerBadContents in badContentsByProvider)
         {
             cancellationToken.ThrowIfCancellationRequested();
             SendToProvider(providerBadContents.Key, providerBadContents.Value, providers);
         }
     }
     catch (Exception ex)
     {
         _logger.Fatal(ex, ex.Message);
         throw;
     }
     _logger.Info("Проверка доступности сервисов контент провайдеров завершена");
 }
        private static async Task<ImmutableArray<INavigateToSearchResult>> FindNavigableDeclaredSymbolInfosAsync(
            Project project, Document searchDocument, string pattern, CancellationToken cancellationToken)
        {
            var containsDots = pattern.IndexOf('.') >= 0;
            using (var patternMatcher = new PatternMatcher(pattern, allowFuzzyMatching: true))
            {
                var result = ArrayBuilder<INavigateToSearchResult>.GetInstance();
                foreach (var document in project.Documents)
                {
                    if (searchDocument != null && document != searchDocument)
                    {
                        continue;
                    }

                    cancellationToken.ThrowIfCancellationRequested();
                    var declarationInfo = await document.GetSyntaxTreeIndexAsync(cancellationToken).ConfigureAwait(false);

                    foreach (var declaredSymbolInfo in declarationInfo.DeclaredSymbolInfos)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        var patternMatches = patternMatcher.GetMatches(
                            GetSearchName(declaredSymbolInfo),
                            declaredSymbolInfo.FullyQualifiedContainerName,
                            includeMatchSpans: true);

                        if (!patternMatches.IsEmpty)
                        {
                            result.Add(ConvertResult(containsDots, declaredSymbolInfo, document, patternMatches));
                        }
                    }
                }

                return result.ToImmutableAndFree();
            }
        }
        /// <summary>
        /// Gets all project collections.
        /// </summary>
        /// <param name="client">The <see cref="ProjectCollectionHttpClient"/> to use.</param>
        /// <param name="pageSize">Page size to use while retrieving Project Collections.</param>
        /// <param name="userState">The user state object.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public static async Task<IList<TeamProjectCollection>> GetAllProjectCollections(this ProjectCollectionHttpClient client, int pageSize = 10, object userState = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (client == null) throw new ArgumentNullException(nameof(client));
            if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize));
            
            var result = new List<TeamProjectCollection>();

            int currentPage = 0;
            var currentProjectCollectionReferences = (await client.GetProjectCollections(pageSize, currentPage, userState).ConfigureAwait(false)).ToList();
            while (currentProjectCollectionReferences.Count > 0)
            {
                foreach (var projectCollectionReference in currentProjectCollectionReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    result.Add(await client.GetProjectCollection(projectCollectionReference.Id, userState).ConfigureAwait(false));
                }
                
                // check whether the recently returned item(s) were less than the max page size
                if (currentProjectCollectionReferences.Count < pageSize)
                    break; // if so, break the loop as we've read all instances

                // otherwise continue
                cancellationToken.ThrowIfCancellationRequested();
                currentProjectCollectionReferences = (await client.GetProjectCollections(pageSize, currentPage++, userState).ConfigureAwait(false)).ToList();
            }

            cancellationToken.ThrowIfCancellationRequested();
            return result;
        }
Ejemplo n.º 7
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var pokemons = await session.Inventory.GetPokemons();

            foreach (var pokemon in pokemons)
            {
                cancellationToken.ThrowIfCancellationRequested();

                double perfection = Math.Round(PokemonInfo.CalculatePokemonPerfection(pokemon));
                string pokemonName = pokemon.PokemonId.ToString();
                // iv number + templating part + pokemonName <= 12
                int nameLength = 12 - (perfection.ToString(CultureInfo.InvariantCulture).Length + session.LogicSettings.RenameTemplate.Length - 6);
                if (pokemonName.Length > nameLength)
                {
                    pokemonName = pokemonName.Substring(0, nameLength);
                }
                string newNickname = String.Format(session.LogicSettings.RenameTemplate, pokemonName, perfection);
                string oldNickname = (pokemon.Nickname.Length != 0) ? pokemon.Nickname : pokemon.PokemonId.ToString();

                if (perfection >= session.LogicSettings.KeepMinIvPercentage && newNickname != oldNickname &&
                    session.LogicSettings.RenameAboveIv)
                {
                    await session.Client.Inventory.NicknamePokemon(pokemon.Id, newNickname);

                    session.EventDispatcher.Send(new NoticeEvent
                    {
                        Message = session.Translation.GetTranslation(Common.TranslationString.PokemonRename, pokemon.PokemonId, pokemon.Id, oldNickname, newNickname)
                    });
                }
            }
        }
Ejemplo n.º 8
0
            async Task LoadAsync(int carId, String url, string userAgent, CancellationToken cancel)
            {
                var handler = new HttpClientHandler { AllowAutoRedirect = false };
                var http = new HttpClient(handler);
                http.DefaultRequestHeaders.Add("User-Agent", userAgent );



                //Get a correct URL from the given one (e.g. transform codeproject.com to http://codeproject.com)
                var uri = Sanitize(url);

                //Make the request
                var request = await http.GetAsync(uri);
                //var request = await http.GetStringAsync(uri);
                cancel.ThrowIfCancellationRequested();

                //Get the response stream
                var response = await request.Content.ReadAsStringAsync();
                cancel.ThrowIfCancellationRequested();
                var html = new Html
                {
                    CarId = carId,
                    html = response,
                    Processed = false
                };
                var data = new Data();
                data.InsertHtmlData(html);
                cancel.ThrowIfCancellationRequested();

                /* Use the document */
            }
        private static async Task<ImmutableArray<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>> FindNavigableDeclaredSymbolInfos(
            Project project, Document searchDocument, string pattern, CancellationToken cancellationToken)
        {
            using (var patternMatcher = new PatternMatcher(pattern, allowFuzzyMatching: true))
            {
                var result = ArrayBuilder<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>.GetInstance();
                foreach (var document in project.Documents)
                {
                    if (searchDocument != null && document != searchDocument)
                    {
                        continue;
                    }

                    cancellationToken.ThrowIfCancellationRequested();
                    var declarationInfo = await document.GetDeclarationInfoAsync(cancellationToken).ConfigureAwait(false);

                    foreach (var declaredSymbolInfo in declarationInfo.DeclaredSymbolInfos)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        var patternMatches = patternMatcher.GetMatches(
                            GetSearchName(declaredSymbolInfo),
                            declaredSymbolInfo.FullyQualifiedContainerName,
                            includeMatchSpans: false);

                        if (patternMatches != null)
                        {
                            result.Add(ValueTuple.Create(declaredSymbolInfo, document, patternMatches));
                        }
                    }
                }

                return result.ToImmutableAndFree();
            }
        }
		IEnumerable<SharpTreeNode> FindReferences(LoadedAssembly asm, CancellationToken ct)
		{
			string asmName = asm.AssemblyDefinition.Name.Name;
			string name = analyzedMethod.Name;
			string declTypeName = analyzedMethod.DeclaringType.FullName;
			foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.AssemblyDefinition.MainModule.Types, t => t.NestedTypes))
			{
				ct.ThrowIfCancellationRequested();
				SharpTreeNode newNode = null;
				try {
					if (!TypesHierarchyHelpers.IsBaseType(analyzedMethod.DeclaringType, type, resolveTypeArguments: false))
						continue;

					foreach (MethodDefinition method in type.Methods) {
						ct.ThrowIfCancellationRequested();

						if (TypesHierarchyHelpers.IsBaseMethod(analyzedMethod, method)) {
							bool hidesParent = !method.IsVirtual ^ method.IsNewSlot;
							newNode = new AnalyzedMethodTreeNode(method, hidesParent ? "(hides) " : "");
						}
					}
				}
				catch (ReferenceResolvingException) {
					// ignore this type definition. maybe add a notification about such cases.
				}
				if (newNode != null)
					yield return newNode;
			}
		}
        internal static async Task ImplementationAsync(Func<CancellationToken, Task> action, Context context, IEnumerable<ExceptionPredicate> shouldHandlePredicates, ICircuitController breakerController, CancellationToken cancellationToken, bool continueOnCapturedContext)
        {
            cancellationToken.ThrowIfCancellationRequested();

            breakerController.OnActionPreExecute();

            try
            {
                await action(cancellationToken).ConfigureAwait(continueOnCapturedContext);

                breakerController.OnActionSuccess(context);
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    if (ex is OperationCanceledException && ((OperationCanceledException) ex).CancellationToken == cancellationToken)
                    {
                        throw;
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                }

                if (!shouldHandlePredicates.Any(predicate => predicate(ex)))
                {
                    throw;
                }

                breakerController.OnActionFailure(ex, context);

                throw;
            }
        }
        public async Task BeginPublishWorkflowAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IOleCommandTarget oleCommandTarget = ServiceProvider.GlobalProvider.GetService(typeof(SUIHostCommandDispatcher)) as IOleCommandTarget;

            // Execute the add to source control command. In an actual Source Control Provider, query the status before executing the command.
            oleCommandTarget.Exec(GuidList.guidSccProviderCmdSet, CommandId.icmdAddToSourceControl, 0, IntPtr.Zero, IntPtr.Zero);

            cancellationToken.ThrowIfCancellationRequested();

            IVsUIShell uiShell = (IVsUIShell)_sccProvider.GetService(typeof(SVsUIShell));
            if (uiShell != null)
            {
                int result;
                uiShell.ShowMessageBox(dwCompRole: 0,
                                       rclsidComp: Guid.Empty,
                                       pszTitle: Resources.ProviderName,
                                       pszText: Resources.PublishClicked,
                                       pszHelpFile: string.Empty,
                                       dwHelpContextID: 0,
                                       msgbtn: OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                       msgdefbtn: OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                                       msgicon: OLEMSGICON.OLEMSGICON_INFO,
                                       fSysAlert: 0,        // false = application modal; true would make it system modal
                                       pnResult: out result);
            }
        }
Ejemplo n.º 13
0
 internal static HtmlAgilityPack.HtmlDocument TryGrabPageWithCancellation(Uri PageURI, String UserAgent, CancellationToken CancToken)
 {
     if (PageURI == null) { throw new ArgumentNullException("PageURI"); }
     CancToken.ThrowIfCancellationRequested();
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PageURI);
     request.Method = "GET";
     request.UserAgent = UserAgent;
     CancToken.ThrowIfCancellationRequested();
     StringBuilder raw_HTML;
     try
     {
         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
         {
             raw_HTML = response.GetTextContent();
         }
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException
             (String.Format("Произошла ошибка при получении ответа от сервера по URI '{0}'", PageURI), ex);
     }
     HtmlAgilityPack.HtmlDocument HTML_doc = new HtmlDocument();
     CancToken.ThrowIfCancellationRequested();
     try
     {
         HTML_doc.LoadHtml(raw_HTML.ToString());
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException(String.Format(
             "Произошла ошибка при попытке преобразовать полученный от сервера по URI '{0}' HTTP-ответ "+
             "с содержимым длиной {1} символов в HTML документ", PageURI.ToString(), raw_HTML.Length), ex);
     }
     return HTML_doc;
 }
        private async Task<Solution> FixEFModelAsync(Project project, Compilation compilation,
            IEnumerable<IClassAssumption> classAssumptions, IEnumerable<IPropertyAssumption> propertyAssumptions, ObjectTheoremResult objectTheoremResult,
            CancellationToken cancellationToken)
        {
            Trace.WriteLine("FixEFModelAsync");
            try
            {
                var newSolution = project.Solution;

                foreach (var syntaxTree in compilation.SyntaxTrees)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var syntaxRoot = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
                    var semanticModel = compilation.GetSemanticModel(syntaxTree);

                    var rewriter = new AttributeAssumptionsRewriter(semanticModel, classAssumptions, propertyAssumptions, objectTheoremResult, cancellationToken);
                    var newSyntaxRoot = rewriter.Visit(syntaxRoot);

                    cancellationToken.ThrowIfCancellationRequested();

                    var documentId = newSolution.GetDocumentId(syntaxTree);
                    newSolution = newSolution.WithDocumentSyntaxRoot(documentId, newSyntaxRoot);
                }

                return newSolution;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw;
            }
        }
        private async Task<ImmutableArray<INavigateToSearchResult>> SearchAsync(
             Func<INavigateToSearchResultProvider, Task<ImmutableArray<INavigateToSearchResult>>> searchAsync,
             CancellationToken cancellationToken)
        {
            var tasks = new Task<ImmutableArray<INavigateToSearchResult>>[_resultProviders.Length];
            for (int i = 0; i < _resultProviders.Length; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var resultProvider = _resultProviders[i];
                tasks[i] = searchAsync(resultProvider);
            }

            await Task.WhenAll(tasks).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            var results = ArrayBuilder<INavigateToSearchResult>.GetInstance();
            foreach (var task in tasks)
            {
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    results.AddRange(task.Result);
                }
            }

            return results.ToImmutableAndFree();
        }
        /// <summary>
        /// Sets <param name="targetPackageStream"></param> for a given <param name="packageIdentity"></param> 
        /// from the given <param name="sourceRepository"></param>. If successfully set, returns true. Otherwise, false
        /// </summary>
        public static async Task<bool> GetPackageStream(SourceRepository sourceRepository, PackageIdentity packageIdentity, Stream targetPackageStream, CancellationToken token)
        {
            // TODO: Tie up machine cache with CacheClient?!

            try
            {
                token.ThrowIfCancellationRequested();
                // Step-1 : Get the download stream for packageIdentity
                Stream downloadStream = await GetDownloadStream(sourceRepository, packageIdentity, token);

                if(downloadStream == null)
                {
                    return false;
                }

                token.ThrowIfCancellationRequested();
                // Step-2: Copy download stream to targetPackageStream if it is not null
                await downloadStream.CopyToAsync(targetPackageStream);
                return true;
            }
            catch (Exception)
            {
                return false;
            } 
        }
Ejemplo n.º 17
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await session.Inventory.RefreshCachedInventory();

            var pokemons = await session.Inventory.GetPokemons();

            foreach (var pokemon in pokemons)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var perfection = Math.Round(PokemonInfo.CalculatePokemonPerfection(pokemon));

                if (session.LogicSettings.AutoFavoritePokemon && perfection >= session.LogicSettings.FavoriteMinIvPercentage && pokemon.Favorite!=1)
                {
                    await session.Client.Inventory.SetFavoritePokemon(pokemon.Id, true);

                    session.EventDispatcher.Send(new NoticeEvent
                    {
                        Message =
                            session.Translation.GetTranslation(TranslationString.PokemonFavorite, perfection, session.Translation.GetPokemonTranslation(pokemon.PokemonId), pokemon.Cp)
                    });
                }
            }
        }
Ejemplo n.º 18
0
        public void Start(CancellationToken token)
        {
            try
            {
                var code = RewriteAndPreprocess();
                token.ThrowIfCancellationRequested();

                var attributes = _attributeParser.Parse(_component);

                token.ThrowIfCancellationRequested();

                // temporal coupling... comments must be acquired before we walk the parse tree for declarations
                // otherwise none of the annotations get associated to their respective Declaration
                var commentListener = new CommentListener();
                var annotationListener = new AnnotationListener(new VBAParserAnnotationFactory(), _qualifiedName);

                var stopwatch = Stopwatch.StartNew();
                ITokenStream stream;
                var tree = ParseInternal(code, new IParseTreeListener[]{ commentListener, annotationListener }, out stream);
                stopwatch.Stop();
                if (tree != null)
                {
                    Debug.Print("IParseTree for component '{0}' acquired in {1}ms (thread {2})", _component.Name, stopwatch.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId);
                }

                var comments = QualifyAndUnionComments(_qualifiedName, commentListener.Comments, commentListener.RemComments);
                token.ThrowIfCancellationRequested();

                ParseCompleted.Invoke(this, new ParseCompletionArgs
                {
                    ParseTree = tree,
                    Tokens = stream,
                    Attributes = attributes,
                    Comments = comments,
                    Annotations = annotationListener.Annotations
                });
            }
            catch (COMException exception)
            {
                Debug.WriteLine("Exception thrown in thread {0}:\n{1}", Thread.CurrentThread.ManagedThreadId, exception);
                ParseFailure.Invoke(this, new ParseFailureArgs
                {
                    Cause = exception
                });
            }
            catch (SyntaxErrorException exception)
            {
                Debug.WriteLine("Exception thrown in thread {0}:\n{1}", Thread.CurrentThread.ManagedThreadId, exception);
                ParseFailure.Invoke(this, new ParseFailureArgs
                {
                    Cause = exception
                });
            }
            catch (OperationCanceledException cancel)
            {
                Debug.WriteLine("Operation was Cancelled", cancel);
                // no results to be used, so no results "returned"
                //ParseCompleted.Invoke(this, new ParseCompletionArgs());
            }
        }
Ejemplo n.º 19
0
 public static Task CopyAsync(string sourceFileName, string destFileName, CancellationToken token, IProgress<double> progress)
 {
     int pbCancel = 0;
     CopyProgressRoutine copyProgressHandler;
     if (progress != null)
     {
         copyProgressHandler = (total, transferred, streamSize, streamByteTrans, dwStreamNumber, reason, hSourceFile, hDestinationFile, lpData) =>
         {
             progress.Report((double)transferred / total * 100);
             return CopyProgressResult.PROGRESS_CONTINUE;
         };
     }
     else
     {
         copyProgressHandler = EmptyCopyProgressHandler;
     }
     token.ThrowIfCancellationRequested();
     var ctr = token.Register(() => pbCancel = 1);
     var copyTask = Task.Run(() =>
     {
         try
         {
             CopyFileEx(sourceFileName, destFileName, copyProgressHandler, IntPtr.Zero, ref pbCancel, CopyFileFlags.COPY_FILE_RESTARTABLE);
             token.ThrowIfCancellationRequested();
         }
         finally
         {
             ctr.Dispose();
         }
     }, token);
     return copyTask;
 }
Ejemplo n.º 20
0
        private async Task LoadAsync(String url, CancellationToken cancel)
        {
            var handler = new HttpClientHandler {AllowAutoRedirect = false};
            var http = new HttpClient(handler);
            http.DefaultRequestHeaders.Add("User-Agent",
                "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");



            //Get a correct URL from the given one (e.g. transform codeproject.com to http://codeproject.com)
            var uri = Sanitize(url);

            //Make the request
            var request = await http.GetAsync(uri);
            //var request = await http.GetStringAsync(uri);
            cancel.ThrowIfCancellationRequested();

            //Get the response stream
            var response = await request.Content.ReadAsStringAsync();
            cancel.ThrowIfCancellationRequested();
            var html = new Html();
            txtHtml.Text = response;
            html.CarId = Convert.ToInt32(textBox1.Text);
            html.html = response;
            html.Processed = false;
            var data = new Data();
            data.InsertHtmlData(html);
            cancel.ThrowIfCancellationRequested();

            /* Use the document */
        }
        /// <inheritdoc />
        protected override async Task<IPrincipal> AuthenticateAsync(string userName, string password, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested(); 

            // Get the Endpoint of the web service for user credential validation
            string url = WebConfigurationManager.AppSettings[Constants.Authentication.WebServiceKey];

            // Call the web service
            AuthenticateUserRequestData requestData = new AuthenticateUserRequestData();
            requestData.UserName = userName;
            requestData.ApiKey = password;
            requestData.AnetAccountType = 'M';
            ANetApiWebService authWS = new ANetApiWebService();
            authWS.Url = url;
            AuthenticateUserResponseData authenticationResponse = authWS.AuthenticateUser(requestData);

            if (!authenticationResponse.Successful)
            {
                // No user with userName/password exists.
                return null;
            }

            // Create a ClaimsIdentity with all the claims for this user.
            cancellationToken.ThrowIfCancellationRequested(); // Unfortunately, IClaimsIdenityFactory doesn't support CancellationTokens.
            ClaimsIdentity identity = new ClaimsIdentity(Constants.ClaimsIdentity.AuthenticationType, userName, Constants.ClaimsIdentity.RoleType);
            return new ClaimsPrincipal(identity);
        }
Ejemplo n.º 22
0
 private async Task<string> FindLink(CancellationToken ct)
 {
     if (!continued)
     {
         await ClickOnContinue();
         continued = true;
     }
     string fileUrl = Convert.ToString(await requestBrowser.EvaluateJavaScriptRawAsync(
             @"(function() {
                 var elements = document.getElementsByClassName('stream-content');
                 if (elements.length > 0) {
                     return elements[0].getAttribute('data-url');
                 } else {
                     return 'failed';
                 }
             })();"
         ));
     Logger.Log("VivoLoading", "fileUrl: " + fileUrl);
     if (fileUrl != "")
     {
         ct.ThrowIfCancellationRequested();
         return fileUrl;
     }
     else
     {
         ct.ThrowIfCancellationRequested();
         return (await Task.Delay(500).ContinueWith(t => FindLink(ct))).Result;
     }
 }
Ejemplo n.º 23
0
		IEnumerable<SharpTreeNode> FindReferences(LoadedAssembly asm, CancellationToken ct)
		{
			string name = analyzedField.Name;
			string declTypeName = analyzedField.DeclaringType.FullName;
			foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.AssemblyDefinition.MainModule.Types, t => t.NestedTypes)) {
				ct.ThrowIfCancellationRequested();
				foreach (MethodDefinition method in type.Methods) {
					ct.ThrowIfCancellationRequested();
					bool found = false;
					if (!method.HasBody)
						continue;
					foreach (Instruction instr in method.Body.Instructions) {
						if (CanBeReference(instr.OpCode.Code)) {
							FieldReference fr = instr.Operand as FieldReference;
							if (fr != null && fr.Name == name && fr.DeclaringType.FullName == declTypeName && fr.Resolve() == analyzedField) {
								found = true;
								break;
							}
						}
					}
					if (found)
						yield return new AnalyzedMethodTreeNode(method);
				}
			}
		}
Ejemplo n.º 24
0
        protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var previewDialogService = _workspace.Services.GetService<IPreviewDialogService>();
            if (previewDialogService == null)
            {
                return null;
            }

            var changedSolution = previewDialogService.PreviewChanges(
                EditorFeaturesResources.PreviewChanges,
                "vs.codefix.previewchanges",
                _originalCodeAction.Title,
                EditorFeaturesResources.PreviewChangesRootNodeText,
                CodeAnalysis.Glyph.OpenFolder,
                _changeSummary.NewSolution,
                _changeSummary.OldSolution,
                showCheckBoxes: false);

            if (changedSolution == null)
            {
                // User pressed the cancel button.
                return null;
            }

            cancellationToken.ThrowIfCancellationRequested();
            return await _originalCodeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false);
        }
Ejemplo n.º 25
0
        public static Task FixMissingKsSkyBoxShader(string filename, CancellationToken cancellation) {
            return Task.Run(() => {
                var backup = FileUtils.EnsureUnique(filename + @".bak");
                File.Move(filename, backup);
                cancellation.ThrowIfCancellationRequested();

                var kn5 = Kn5.FromFile(backup);
                cancellation.ThrowIfCancellationRequested();

                var changed = false;
                foreach (var material in kn5.Materials.Values) {
                    if (material.ShaderName == @"ksSkyBox") {
                        material.ShaderName = @"ksSky";
                        material.TextureMappings = new Kn5Material.TextureMapping[0];
                        changed = true;
                    }
                }

                if (!changed) {
                    throw new InformativeException("Nothing to fix", "None of materials is using ksSkyBox shader");
                }

                cancellation.ThrowIfCancellationRequested();
                kn5.Save(filename);
            }, cancellation); 
        }
Ejemplo n.º 26
0
        // Fetches all the data for the specified file
        public async static Task<FileItem> fromStorageFile(StorageFile f, CancellationToken ct)
        {
            FileItem item = new FileItem();
            item.Filename = f.DisplayName;
            
            // Block to make sure we only have one request outstanding
            await gettingFileProperties.WaitAsync();

            BasicProperties bp = null;
            try
            {
                bp = await f.GetBasicPropertiesAsync().AsTask(ct);
            }
            catch (Exception) { }
            finally
            {
                gettingFileProperties.Release();
            }

            ct.ThrowIfCancellationRequested();

            item.Size = (int)bp.Size;
            item.Key = f.FolderRelativeId;

            StorageItemThumbnail thumb = await f.GetThumbnailAsync(ThumbnailMode.SingleItem).AsTask(ct);
            ct.ThrowIfCancellationRequested();
            BitmapImage img = new BitmapImage();
            await img.SetSourceAsync(thumb).AsTask(ct);

            item.ImageData = img;
            return item;
        }
Ejemplo n.º 27
0
        private async Task<IEnumerable<string>> GetFileSystemObjectsAsync(string currentDirectory, string[] searchTemplateParts, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var currentPart = searchTemplateParts[0];

            if (searchTemplateParts.Length == 1)
                return await _fileSystem.GetFileSystemEntriesAsync(currentDirectory, currentPart, cancellationToken);

            if (currentPart == "**")
                return await GetFileSystemObjectsFromAllSubDirectoriesAsync(currentDirectory, searchTemplateParts.Skip(1).ToArray(), cancellationToken);

            var directories = await _fileSystem.GetDirectoriesAsync(currentDirectory, currentPart, cancellationToken);

            var results = new List<string>();
            foreach (var directory in directories)
            {
                cancellationToken.ThrowIfCancellationRequested();

                results.AddRange(await GetFileSystemObjectsAsync(
                    directory,
                    searchTemplateParts.Skip(1).ToArray(),
                    cancellationToken));
            }
            return results;
        }
Ejemplo n.º 28
0
		public IEnumerable<object> Run(IApp app, CancellationToken token) {
			if (typeDef == null) {
				yield return new AnalysisError("Failed to resolve '" + type.FullName + "'.");
				yield break;
			}

			var comparer = new SigComparer();
			if (typeDef.IsInterface) {
				foreach (var type in app.Modules.GetModules().SelectMany(module => module.GetTypes())) {
					token.ThrowIfCancellationRequested();

					if (!type.HasInterfaces)
						continue;
					foreach (var iface in type.Interfaces) {
						if (comparer.Equals(iface.Interface, typeDef))
							yield return type;
					}
				}
			}
			else {
				foreach (var type in app.Modules.GetModules().SelectMany(module => module.GetTypes())) {
					token.ThrowIfCancellationRequested();

					if (comparer.Equals(type.BaseType, typeDef))
						yield return type;
				}
			}
		}
        internal static async Task<IEnumerable<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>> FindNavigableDeclaredSymbolInfos(Project project, string pattern, CancellationToken cancellationToken)
        {
            var generatedCodeRecognitionService = project.LanguageServices.WorkspaceServices.GetService<IGeneratedCodeRecognitionService>();
            var patternMatcher = new PatternMatcher(pattern);

            var result = new List<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>();
            foreach (var document in project.Documents.Where(d => !generatedCodeRecognitionService?.IsGeneratedCode(d) ?? true))
            {
                cancellationToken.ThrowIfCancellationRequested();
                var declaredSymbolInfos = await document.GetDeclaredSymbolInfosAsync(cancellationToken).ConfigureAwait(false);
                foreach (var declaredSymbolInfo in declaredSymbolInfos)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var patternMatches = patternMatcher.GetMatches(
                        GetSearchName(declaredSymbolInfo),
                        declaredSymbolInfo.FullyQualifiedContainerName);

                    if (patternMatches != null)
                    {
                        result.Add(ValueTuple.Create(declaredSymbolInfo, document, patternMatches));
                    }
                }
            }

            return result;
        }
Ejemplo n.º 30
0
    private void StartListen()
    {
        // Start the receive task, that will remain running for the whole connection
        System.Threading.CancellationToken ct = stopServerTokenSource.Token;
        var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            ct.ThrowIfCancellationRequested();
            while (true)
            {
                try
                {
                    System.Threading.Tasks.Task <Response> receiveTask = ReceiveMessage();
                    receiveTask.Wait();

                    if (receiveTask.Result.MessageId == Messages.EVENT)
                    {
                        ProcessEvent(receiveTask.Result);
                    }
                    else if (taskCompletion != null)
                    {
                        taskCompletion.SetResult(receiveTask.Result);
                    }
                    else
                    {
                        throw new ErrorException("Received WAMP message that we did not expect.");
                    }

                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }
                }
                catch (System.Exception e)
                {
                    if (e.InnerException.GetType() == typeof(System.Net.WebSockets.WebSocketException))
                    {
                        var exception = e.InnerException as System.Net.WebSockets.WebSocketException;
                        if (exception.WebSocketErrorCode == System.Net.WebSockets.WebSocketError.ConnectionClosedPrematurely)
                        {
                            if (taskCompletion != null)
                            {
                                taskCompletion.SetException(e);
                            }

                            OnDisconnect();

                            return;
                        }
                    }

                    if (ws.State != System.Net.WebSockets.WebSocketState.Open)
                    {
                        OnDisconnect();
                        return;
                    }


                    // Signal the exception to the other thread and continue to listen
                    if (taskCompletion != null)
                    {
                        taskCompletion.SetException(e);
                    }
                }
            }
        }, stopServerTokenSource.Token);
    }
Ejemplo n.º 31
0
        /// <summary>
        /// Returns the entity with the key from ExecutionMedia
        /// </summary>
        /// <remarks>
        /// Required permissions: ExecutionMedia.View.
        /// </remarks>
        /// <param name='id'>
        /// key: Id
        /// </param>
        /// <param name='expand'>
        /// Expands related entities inline.
        /// </param>
        /// <param name='select'>
        /// Selects which properties to include in the response.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <ExecutionMediaDto> > GetByIdWithHttpMessagesAsync(long id, string expand = default(string), string select = default(string), Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("id", id);
                tracingParameters.Add("expand", expand);
                tracingParameters.Add("select", select);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetById", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/ExecutionMedia({Id})").ToString();

            _url = _url.Replace("{Id}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(id, Client.SerializationSettings).Trim('"')));
            List <string> _queryParameters = new List <string>();

            if (expand != null)
            {
                _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
            }
            if (select != null)
            {
                _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <ExecutionMediaDto>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ExecutionMediaDto>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Call operation  DownloadMediaByJobId
        /// </summary>
        /// <remarks>
        /// Required permissions: ExecutionMedia.View.
        /// </remarks>
        /// <param name='jobId'>
        /// parameter: jobId
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <Stream> > DownloadMediaByJobIdWithHttpMessagesAsync(long jobId, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("jobId", jobId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "DownloadMediaByJobId", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/ExecutionMedia/UiPath.Server.Configuration.OData.DownloadMediaByJobId(jobId={jobId})").ToString();

            _url = _url.Replace("{jobId}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(jobId, Client.SerializationSettings).Trim('"')));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 204)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <Stream>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Uploads a new package or a new version of an existing package. The content
        /// of the package is sent as a .nupkg file embedded in the HTTP request.
        /// </summary>
        /// <remarks>
        /// Required permissions: Packages.Create.
        /// </remarks>
        /// <param name='file'>
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> UploadPackageWithHttpMessagesAsync(Stream file, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (file == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "file");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("file", file);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "UploadPackage", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/Processes/UiPath.Server.Configuration.OData.UploadPackage").ToString();
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            MultipartFormDataContent _multiPartContent = new MultipartFormDataContent();

            if (file != null)
            {
                StreamContent _file = new StreamContent(file);
                _file.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data");
                _contentDispositionHeaderValue.Name = "file";
                // get filename from stream if it's a file otherwise, just use  'unknown'
                var _fileStream = file as FileStream;
                var _fileName   = (_fileStream != null ? _fileStream.Name : null) ?? "unknown";
                if (System.Linq.Enumerable.Any(_fileName, c => c > 127))
                {
                    // non ASCII chars detected, need UTF encoding:
                    _contentDispositionHeaderValue.FileNameStar = _fileName;
                }
                else
                {
                    // ASCII only
                    _contentDispositionHeaderValue.FileName = _fileName;
                }
                _file.Headers.ContentDisposition = _contentDispositionHeaderValue;
                _multiPartContent.Add(_file, "file");
            }
            _httpRequest.Content = _multiPartContent;
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Get process parameters
        /// </summary>
        /// <remarks>
        /// Required permissions: Packages.View.
        /// </remarks>
        /// <param name='key'>
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <ArgumentMetadata> > GetArgumentsByKeyWithHttpMessagesAsync(string key, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (key == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "key");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("key", key);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetArgumentsByKey", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/Processes/UiPath.Server.Configuration.OData.GetArguments(key='{key}')").ToString();

            _url = _url.Replace("{key}", System.Uri.EscapeDataString(key));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <ArgumentMetadata>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ArgumentMetadata>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Saves process arguments
        /// </summary>
        /// <remarks>
        /// Required permissions: Packages.Edit.
        /// </remarks>
        /// <param name='setArgumentsParameters'>
        /// SetArguments action parameters
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> SetArgumentsWithHttpMessagesAsync(SetArgumentsParameters setArgumentsParameters = default(SetArgumentsParameters), Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("setArgumentsParameters", setArgumentsParameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "SetArguments", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/Processes/UiPath.Server.Configuration.OData.SetArguments").ToString();
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (setArgumentsParameters != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(setArgumentsParameters, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Deletes a package.
        /// </summary>
        /// <remarks>
        /// Required permissions: Packages.Delete.
        /// </remarks>
        /// <param name='id'>
        /// key: Id
        /// </param>
        /// <param name='ifMatch'>
        /// If-Match header
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse> DeleteByIdWithHttpMessagesAsync(string id, string ifMatch = default(string), Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (id == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "id");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("id", id);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "DeleteById", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/Processes('{Id}')").ToString();

            _url = _url.Replace("{Id}", System.Uri.EscapeDataString(id));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("DELETE");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 204)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Returns the computed processing status for a given queue in the last
        /// specified days.
        /// </summary>
        /// <remarks>
        /// Required permissions: Queues.View and Transactions.View.
        /// </remarks>
        /// <param name='daysNo'>
        /// The number of days to go back from the present moment when calculating the
        /// report. If it is 0 the report will be computed for the last hour.
        /// </param>
        /// <param name='queueDefinitionId'>
        /// The Id of the queue for which the report is computed.
        /// </param>
        /// <param name='xUIPATHOrganizationUnitId'>
        /// Folder/OrganizationUnit Id
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <ODataResponseListQueueProcessingRecordDto> > RetrieveLastDaysProcessingRecordsByDaysnoAndQueuedefinitionidWithHttpMessagesAsync(int daysNo, long queueDefinitionId, long?xUIPATHOrganizationUnitId = default(long?), Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("daysNo", daysNo);
                tracingParameters.Add("queueDefinitionId", queueDefinitionId);
                tracingParameters.Add("xUIPATHOrganizationUnitId", xUIPATHOrganizationUnitId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "RetrieveLastDaysProcessingRecordsByDaysnoAndQueuedefinitionid", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/QueueProcessingRecords/UiPathODataSvc.RetrieveLastDaysProcessingRecords(daysNo={daysNo},queueDefinitionId={queueDefinitionId})").ToString();

            _url = _url.Replace("{daysNo}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(daysNo, Client.SerializationSettings).Trim('"')));
            _url = _url.Replace("{queueDefinitionId}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queueDefinitionId, Client.SerializationSettings).Trim('"')));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (xUIPATHOrganizationUnitId != null)
            {
                if (_httpRequest.Headers.Contains("X-UIPATH-OrganizationUnitId"))
                {
                    _httpRequest.Headers.Remove("X-UIPATH-OrganizationUnitId");
                }
                _httpRequest.Headers.TryAddWithoutValidation("X-UIPATH-OrganizationUnitId", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(xUIPATHOrganizationUnitId, Client.SerializationSettings).Trim('"'));
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <ODataResponseListQueueProcessingRecordDto>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ODataResponseListQueueProcessingRecordDto>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Edits a machine based on its key.
        /// </summary>
        /// <remarks>
        /// Required permissions: Machines.Edit.
        /// </remarks>
        /// <param name='id'>
        /// key: Id
        /// </param>
        /// <param name='machineDto'>
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <MachineDto> > PutByIdWithHttpMessagesAsync(long id, MachineDto machineDto, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (machineDto == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "machineDto");
            }
            if (machineDto != null)
            {
                machineDto.Validate();
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("id", id);
                tracingParameters.Add("machineDto", machineDto);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "PutById", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/Machines({Id})").ToString();

            _url = _url.Replace("{Id}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(id, Client.SerializationSettings).Trim('"')));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (machineDto != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(machineDto, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <MachineDto>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <MachineDto>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
        /// 32-bit signed integer to measure the time interval, while observing a <see
        /// cref="T:System.Threading.CancellationToken"/>.
        /// </summary>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
        /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
        /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
        /// observe.</param>
        /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
        /// false.</returns>
        /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
        /// negative number other than -1, which represents an infinite time-out.</exception>
        /// <exception cref="T:System.InvalidOperationException">
        /// The maximum number of waiters has been exceeded.
        /// </exception>
        /// <exception cref="T:System.Threading.OperationCanceledException"><paramref
        /// name="cancellationToken"/> was canceled.</exception>
        public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
        {
            ThrowIfDisposed();
            cancellationToken.ThrowIfCancellationRequested(); // an early convenience check

            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
            }

            if (!IsSet)
            {
                if (millisecondsTimeout == 0)
                {
                    // For 0-timeouts, we just return immediately.
                    return(false);
                }


                // We spin briefly before falling back to allocating and/or waiting on a true event.
                uint startTime = 0;
                bool bNeedTimeoutAdjustment  = false;
                int  realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.

                if (millisecondsTimeout != Timeout.Infinite)
                {
                    // We will account for time spent spinning, so that we can decrement it from our
                    // timeout.  In most cases the time spent in this section will be negligible.  But
                    // we can't discount the possibility of our thread being switched out for a lengthy
                    // period of time.  The timeout adjustments only take effect when and if we actually
                    // decide to block in the kernel below.

                    startTime = TimeoutHelper.GetTime();
                    bNeedTimeoutAdjustment = true;
                }

                // Spin
                int spinCount = SpinCount;
                var spinner   = new SpinWait();
                while (spinner.Count < spinCount)
                {
                    spinner.SpinOnce(SpinWait.Sleep1ThresholdForLongSpinBeforeWait);

                    if (IsSet)
                    {
                        return(true);
                    }

                    if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                    }
                }

                // Now enter the lock and wait.
                EnsureLockObjectCreated();

                // We must register and unregister the token outside of the lock, to avoid deadlocks.
                using (cancellationToken.UnsafeRegister(s_cancellationTokenCallback, this))
                {
                    lock (m_lock)
                    {
                        // Loop to cope with spurious wakeups from other waits being canceled
                        while (!IsSet)
                        {
                            // If our token was canceled, we must throw and exit.
                            cancellationToken.ThrowIfCancellationRequested();

                            //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
                            if (bNeedTimeoutAdjustment)
                            {
                                realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
                                if (realMillisecondsTimeout <= 0)
                                {
                                    return(false);
                                }
                            }

                            // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock,
                            // so after updating waiters, we must check IsSet again.
                            // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
                            // read from IsSet.  This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
                            // operation which provides a full memory barrier.
                            // If we see IsSet=false, then we are guaranteed that Set() will see that we are
                            // waiting and will pulse the monitor correctly.

                            Waiters = Waiters + 1;

                            if (IsSet)     //This check must occur after updating Waiters.
                            {
                                Waiters--; //revert the increment.
                                return(true);
                            }

                            // Now finally perform the wait.
                            try
                            {
                                // ** the actual wait **
                                if (!Monitor.Wait(m_lock, realMillisecondsTimeout))
                                {
                                    return(false); //return immediately if the timeout has expired.
                                }
                            }
                            finally
                            {
                                // Clean up: we're done waiting.
                                Waiters = Waiters - 1;
                            }
                            // Now just loop back around, and the right thing will happen.  Either:
                            //     1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
                            // or  2. the wait was successful. (the loop will break)
                        }
                    }
                }
            } // automatically disposes (and unregisters) the callback

            return(true); //done. The wait was satisfied.
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Returns a CSV containing the filtered audit.
        /// </summary>
        /// <remarks>
        /// Required permissions: Audit.View.
        /// </remarks>
        /// <param name='expand'>
        /// Expands related entities inline.
        /// </param>
        /// <param name='filter'>
        /// Filters the results, based on a Boolean condition.
        /// </param>
        /// <param name='select'>
        /// Selects which properties to include in the response.
        /// </param>
        /// <param name='orderby'>
        /// Sorts the results.
        /// </param>
        /// <param name='top'>
        /// Returns only the first n results.
        /// </param>
        /// <param name='skip'>
        /// Skips the first n results.
        /// </param>
        /// <param name='count'>
        /// Includes a count of the matching results in the odata-count header.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <Stream> > ReportsWithHttpMessagesAsync(string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), int?top = default(int?), int?skip = default(int?), bool?count = default(bool?), Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("expand", expand);
                tracingParameters.Add("filter", filter);
                tracingParameters.Add("select", select);
                tracingParameters.Add("orderby", orderby);
                tracingParameters.Add("top", top);
                tracingParameters.Add("skip", skip);
                tracingParameters.Add("count", count);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Reports", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/AuditLogs/UiPath.Server.Configuration.OData.Reports()").ToString();
            List <string> _queryParameters = new List <string>();

            if (expand != null)
            {
                _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
            }
            if (filter != null)
            {
                _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
            }
            if (select != null)
            {
                _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
            }
            if (orderby != null)
            {
                _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(orderby)));
            }
            if (top != null)
            {
                _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
            }
            if (skip != null)
            {
                _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
            }
            if (count != null)
            {
                _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <Stream>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Ejemplo n.º 41
-1
		public async Task BeginListeningAsync (CancellationToken token)
		{
			var client = new UdpClient (BroadcastEndpoint);
			client.JoinMulticastGroup (BroadcastEndpoint.Address);
			token.Register (() => client.Close ());

			while (true) {
				token.ThrowIfCancellationRequested ();
				try {
					var result = await client.ReceiveAsync ();
					var data = Encoding.UTF8.GetString (result.Buffer);
					if (data.StartsWith (Header, StringComparison.Ordinal)) {
						if (ServerFound != null) {
							var details = new ServerDetails {
								Hostname = result.RemoteEndPoint.Address.ToString (),
								Port = int.Parse (data.Substring (Header.Length))
							};
							LoggingService.LogInfo ("Found TunezServer at {0}", details.FullAddress);
							ServerFound (this, details);
						}
					}
				} catch (ObjectDisposedException) {
					token.ThrowIfCancellationRequested ();
					throw;
				} catch (SocketException) {
					token.ThrowIfCancellationRequested ();
					// Ignore this
				} catch (Exception ex) {
					token.ThrowIfCancellationRequested ();
					LoggingService.LogInfo ("Ignoring bad UDP {0}", ex);
				}
			}
		}