Ejemplo n.º 1
0
        public SendSms()
        {
            InitializeComponent();

            try
            {
                LOG_PATH = Globals.FileLogPath;
                ERROR_LOG_PATH = Globals.FileLogPath;

                _tokenSource = new CancellationTokenSource();
                _token = _tokenSource.Token;

                _timer = new System.Timers.Timer();
                _timer.Interval = Convert.ToDouble(ConfigurationManager.AppSettings["serviceInterval"]);
                _timer.AutoReset = true;
                _timer.Enabled = true;

                _timer.Elapsed += timer_Elapsed;

                _sda = new SqlDataAccess();
                _sda.openConnection(Globals.ConnectionString);

                _service = MSCRM.GetOrgService(true);

                _serviceProcess = new ServiceProcess(_sda, _service);
            }
            catch (Exception ex)
            {
                FileLogHelper.LogFunction(this.GetType().Name, "SendSms_SendSms_EXCEPTION:" + ex.Message, ERROR_LOG_PATH);
            }
        }
Ejemplo n.º 2
0
		ICollection<IDataModel> PopulateChildrenInternal() {
			lock (sync) {
				cancelSrc = new CancellationTokenSource();
				CancellationToken = cancelSrc.Token;
			}

			ICollection<IDataModel> children;
			try {
				children = new List<IDataModel>(PopulateChildren());
			}
			catch (Exception ex) {
				children = new IDataModel[] {
					new ErrorModel(
						string.Format("Error while loading:{0}{1}{0}{0}",
							Environment.NewLine, ex))
				};
			}
			finally {
				lock (sync) {
					cancelSrc = null;
					CancellationToken = null;
				}
			}

			return children;
		}
Ejemplo n.º 3
0
        public PrimesFromFile(
      string path, 
      Progress<ProgressEventArgs> progressIndicator = null,
      CancellationToken? maybeCancellationToken = null)
        {
            myPrimes = null;
              myProgressIndicator = progressIndicator;
              myMaybeCancellationToken = maybeCancellationToken;

              Utilities.ReadCompressedFile(path, this.InputFromBinaryReader);
        }
Ejemplo n.º 4
0
        protected override void OnStart(string[] args)
        {
            _tokenSource = new CancellationTokenSource();
            _token = _tokenSource.Token;

            foreach (KeyValuePair<string, IWindSerOperations> windSerOperationKeyValue in _innerDictionary)
            {
                Task startedTask = Task.Factory.StartNew(_ =>
                {
                    windSerOperationKeyValue.Value.StartOperation();
                }, _token);
            }
        }
Ejemplo n.º 5
0
 public EdmondsKarpMaximumFlow(Transaction tx, 
     GraphStorage graphStorage, 
     Node sourceNode, 
     Node targetNode,
     Func<Edge, long> capacity,
     CancellationToken? cancelToken = null)
     : base(capacity)
 {
     _sourceNode = sourceNode;
     _targetNode = targetNode;
     _storage = graphStorage;
     _cancelToken = cancelToken;
     _flow = new Dictionary<Tuple<long, long>, long>();
     _tx = tx;
 }
 public OperationCanceledException2(CancellationToken token)
     : base()
 {
     this.token = token;
 }
Ejemplo n.º 7
0
        public static string RenderContent(
            this Uri uri,
            List <QueryParams> queryParamsList = null,
            Func <TemplateMultiDataRequest, IEnumerable <dynamic> > dataProviders = null,
            CancellationToken?token = null,
            string referrer         = null,
            string userAgent        = null
            )
        {
            // todo: needs heavy refactoring and optimizing
            #region retrieve content
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (queryParamsList?.Any() == true)
            {
                //dataModelContainer.Data = dataModelContainer.Data.GetDataModelParameters();
                // uri to use data model
                uri = new Uri(uri.AbsoluteUri
                              .Fill(queryParamsList)
                              , UriKind.Absolute);
            }
            if (!Uri.IsWellFormedUriString(uri.AbsoluteUri, UriKind.Absolute))
            {
                throw new FormatException(
                          $"Invalid uri format : {uri.AbsoluteUri}");
            }

            string content;
            if ((content = uri
                           .GetContentAsync(token,
                                            referrer, userAgent)
                           .GetAwaiter().GetResult()) == null)
            {
                throw new TimeoutException(
                          $"Uri retrieval timed-out for {uri.AbsoluteUri}");
            }

            if (content == null)
            {
                return(null);
            }
            content = content.FillDates();
            #endregion



            #region check for data providers and data tag availability in content

            IEnumerable <dynamic> dataResponse = null;

            QueryParams newQueryParams = new();

            //var nextOpenMarker = queryParamsList?.OpenMarker;
            //var nextCloseMarker = queryParamsList?.CloseMarker;
            //var nextNullValue = queryParamsList?.NullReplacement;

            if (dataProviders != null)
            {
                var dataRequestMatch = Regex.Match(content,
                                                   DataTagContentRegex,
                                                   RegexOptions.Singleline);

                // get data if data request tags available
                if (dataRequestMatch.Success)
                {
                    // no pre-filling data model before calling data providers
                    // (unless pre-fill = true)
                    // as data model is submitted to data providers
                    // to allow data providers implement their own sql injection
                    // protection if needed


                    //TemplateMultiDataRequest req = new TemplateMultiDataRequest();
                    //req.QueryParamsList = queryParamsList;
                    //req.Request = dataRequestMatch.Groups["content"]?.Value;
                    //req.ConnectionString = dataRequestMatch?.GetAttrib("connection-string");
                    //req.ContentType = dataRequestMatch.GetAttrib("content-type");


                    _ = bool.TryParse((dataRequestMatch
                                       .GetAttrib("pre-render") ?? "false"), out bool preRender);

                    dataResponse = dataProviders(new()
                    {
                        QueryParamsList  = queryParamsList,
                        Request          = dataRequestMatch.Groups["content"]?.Value,
                        ConnectionString = dataRequestMatch?
                                           .GetAttrib("connection-string"),
                        ContentType = dataRequestMatch
                                      .GetAttrib("content-type"),
                        CancellationToken = token,
                        PreRender         = preRender
                    });

                    //if (dataResponse !=null)
                    //    newQueryParams.DataModel = dataResponse;
                    if (dataRequestMatch.GetAttrib("open-marker") != null)
                    {
                        newQueryParams.OpenMarker = dataRequestMatch.GetAttrib("open-marker");
                    }
                    if (dataRequestMatch.GetAttrib("close-marker") != null)
                    {
                        newQueryParams.CloseMarker = dataRequestMatch.GetAttrib("close-marker");
                    }
                    if (dataRequestMatch.GetAttrib("null-value") != null)
                    {
                        newQueryParams.NullReplacement = dataRequestMatch.GetAttrib("null-value");
                    }
                }
            }


            #endregion


            #region loop response data while rendering current recursive level content



            // remove the data tag if it was available as it should
            // already be processed by now and not needed anymore
            content = Regex.Replace(content, DataTagContentRegex,
                                    "", RegexOptions.Singleline);


            string renderedContent = "";
            if (dataResponse != null)
            {
                foreach (var item in dataResponse?.EnsureEnumerable())
                {
                    // todo: replace with markers from regex, failover to
                    // subDataModelContainer markers
                    newQueryParams.DataModel = ((object)item)?.EnsureEnumerable();

                    queryParamsList?.Add(newQueryParams);


                    // content is the template with vars that gets filled with different
                    // data model and the fill result gets accumulated in filledContent
                    var filledContent = content.Fill(queryParamsList);

                    // retrieve sub-templates recursively from current recursive level
                    // rendered content
                    foreach (var templateTagMatch in Regex.Matches(
                                 filledContent, TemplateTagRegex).Cast <Match>())
                    {
                        var subUri = templateTagMatch.Groups["content"]?.Value;
                        // todo: replace {uri{./}} placeholder with functioning uri traversal logic
                        if (subUri?.Contains("{uri{./}}") == true ||
                            subUri?.Contains("{uri{.}}") == true
                            )
                        {
                            subUri = subUri
                                     .Replace("{uri{./}}", uri.GetParentUri().AbsoluteUri + "/")
                                     .Replace("{uri{.}}", uri.GetParentUri().AbsoluteUri.RemoveLast(1));
                        }

                        if (!string.IsNullOrWhiteSpace(subUri)
                            ||
                            Uri.IsWellFormedUriString(subUri, UriKind.Absolute)
                            )
                        {
                            var subTemplateContent = new Uri(subUri).RenderContent(
                                queryParamsList,
                                dataProviders,
                                token,
                                // todo: optional grab of referrer from regex sub-template tag
                                referrer,
                                userAgent
                                );
                            // replace sub-template tag with rendered sub-template content
                            filledContent = filledContent.Replace(templateTagMatch.Value, subTemplateContent);
                        }
                        // sub-template tag removal if no valid uri was available
                        else
                        {
                            filledContent = filledContent.Replace(templateTagMatch.Value, "");
                        }
                    }
                    renderedContent += filledContent;
                }
            }
            else
            {
                if (queryParamsList != null)
                {
                    content = content.Fill(queryParamsList);
                }
                foreach (var templateTagMatch in Regex.Matches(
                             content, TemplateTagRegex).Cast <Match>())
                {
                    var subUri = templateTagMatch.Groups["content"]?.Value;
                    // fill placeholder for current uri
                    if (subUri?.Contains("{uri{./}}") == true ||
                        subUri?.Contains("{uri{.}}") == true
                        )
                    {
                        subUri = subUri
                                 .Replace("{uri{./}}", uri.GetParentUri().AbsoluteUri)
                                 .Replace("{uri{.}}", uri.GetParentUri().AbsoluteUri.RemoveLast(1));
                    }

                    if (!string.IsNullOrWhiteSpace(subUri)
                        ||
                        Uri.IsWellFormedUriString(subUri, UriKind.Absolute)
                        )
                    {
                        var subTemplateContent = new Uri(subUri).RenderContent(
                            queryParamsList,
                            dataProviders,
                            token,
                            // todo: optional grab of referrer from regex sub-template tag
                            referrer,
                            userAgent
                            );
                        // replace sub-template tag with rendered sub-template content
                        content = content.Replace(templateTagMatch.Value, subTemplateContent);
                    }
                    // sub-template tag removal if no valid uri was available
                    else
                    {
                        content = content.Replace(templateTagMatch.Value, "");
                    }
                }
                renderedContent = content;
            }
            #endregion


            return(renderedContent);
        }
Ejemplo n.º 8
0
        /// <summary>Return the balances for the account</summary>
        public async Task <Dictionary <string, Balance> > GetBalances(CancellationToken?cancel = null)
        {
            var jtok = await PostData(Method.Account, "returnCompleteBalances", cancel);

            return(ParseJsonReply <Dictionary <string, Balance> >(jtok));
        }
Ejemplo n.º 9
0
        public void Render(ICamera camera, int[] colors, int width, int height, bool parallel = true, CancellationToken?cancellationToken = null)
        {
            var rayFactory = camera.GetRayFactory(width, height);

            if (parallel)
            {
                Parallel.For(0, height, y =>
                {
                    for (var x = 0; x < width; ++x)
                    {
                        if (cancellationToken.HasValue && cancellationToken.Value.IsCancellationRequested)
                        {
                            return;
                        }
                        var index     = y * width + x;
                        var ray       = rayFactory.GetCameraRay(x, y);
                        colors[index] = Trace(ray, 0).ToArgb();
                    }
                });
            }
            else
            {
                for (var x = 0; x < width; ++x)
                {
                    for (var y = 0; y < height; ++y)
                    {
                        if (cancellationToken.HasValue && cancellationToken.Value.IsCancellationRequested)
                        {
                            return;
                        }
                        var index = y * width + x;
                        var ray   = rayFactory.GetCameraRay(x, y);
                        colors[index] = Trace(ray, 0).ToArgb();
                    }
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Returns features within the specified bounding box.
        /// </summary>
        /// <param name="envelope"></param>
        /// <returns></returns>
        public override IEnumerable <Geometry> GetGeometriesInView(BoundingBox envelope, CancellationToken?ct = null)
        {
            // Identifies all the features within the given BoundingBox
            var geoms = new Collection <Geometry>();

            foreach (var feature in _features)
            {
                if (envelope.Intersects(feature.Geometry.EnvelopeInternal))
                {
                    geoms.Add(feature.Geometry);
                }
            }
            return(geoms);
        }
Ejemplo n.º 11
0
        public async Task <List <Trade> > GetTradeHistory(CurrencyPair pair, UnixSec start_time, UnixSec end_time, CancellationToken?cancel = null)
        {
            // https://poloniex.com/public?command=returnTradeHistory&currencyPair=BTC_NXT&start=1410158341&end=1410499372
            var jtok = await GetData(Method.Public, "returnTradeHistory", cancel, new Params
            {
                { "currencyPair", pair.Id },
                { "start", start_time },
                { "end", end_time },
            });

            return(ParseJsonReply <List <Trade> >(jtok));
        }
Ejemplo n.º 12
0
        void GetClassificationSpansCore(List <HexClassificationSpan> result, HexClassificationContext context, CancellationToken?cancellationToken)
        {
            if (context.IsDefault)
            {
                throw new ArgumentException();
            }
            var textSpan = context.LineSpan;
            var list     = new List <HexClassificationSpan>();

            var taggerContext = new HexTaggerContext(context.Line, context.LineSpan);
            var tags          = !(cancellationToken is null) ? hexTagAggregator.GetAllTags(taggerContext, cancellationToken.Value) : hexTagAggregator.GetAllTags(taggerContext);

            foreach (var tagSpan in tags)
            {
                var overlap = textSpan.Overlap(tagSpan.Span);
                if (!(overlap is null))
                {
                    list.Add(new HexClassificationSpan(overlap.Value, tagSpan.Tag.ClassificationType));
                }
            }

            if (list.Count <= 1)
            {
                if (list.Count == 1)
                {
                    result.Add(list[0]);
                }
                return;
            }

            list.Sort(HexClassificationSpanComparer.Instance);

            // Common case
            if (!HasOverlaps(list))
            {
                result.AddRange(Merge(list));
                return;
            }

            int min       = 0;
            int minOffset = textSpan.Start;
            var newList   = new List <HexClassificationSpan>();
            var ctList    = new List <VSTC.IClassificationType>();

            while (min < list.Count)
            {
                while (min < list.Count && minOffset >= list[min].Span.End)
                {
                    min++;
                }
                if (min >= list.Count)
                {
                    break;
                }
                var cspan = list[min];
                minOffset = Math.Max(minOffset, cspan.Span.Start);
                int end = cspan.Span.End;
                ctList.Clear();
                ctList.Add(cspan.ClassificationType);
                for (int i = min + 1; i < list.Count; i++)
                {
                    cspan = list[i];
                    int cspanStart = cspan.Span.Start;
                    if (cspanStart > minOffset)
                    {
                        if (cspanStart < end)
                        {
                            end = cspanStart;
                        }
                        break;
                    }
                    int cspanEnd = cspan.Span.End;
                    if (minOffset >= cspanEnd)
                    {
                        continue;
                    }
                    if (cspanEnd < end)
                    {
                        end = cspanEnd;
                    }
                    if (!ctList.Contains(cspan.ClassificationType))
                    {
                        ctList.Add(cspan.ClassificationType);
                    }
                }
                Debug.Assert(minOffset < end);
                var ct = ctList.Count == 1 ? ctList[0] : classificationTypeRegistryService.CreateTransientClassificationType(ctList);
                newList.Add(new HexClassificationSpan(VST.Span.FromBounds(minOffset, end), ct));
                minOffset = end;
            }

            Debug.Assert(!HasOverlaps(newList));
            result.AddRange(Merge(newList));
            return;
        }
Ejemplo n.º 13
0
		public OperationCanceledException (string message, CancellationToken token)
			: this (message)
		{
			this.token = token;
		}
Ejemplo n.º 14
0
 /// <summary>
 /// Operation: Get User Presence Status List
 /// HTTP Method: GET
 /// Endpoint: /restapi/v1.0/account/{accountId}/presence
 /// Rate Limit Group: Heavy
 /// App Permission: ReadPresence
 /// User Permission: ReadPresenceStatus
 /// </summary>
 public async Task <RingCentral.AccountPresenceInfo> Get(ReadAccountPresenceParameters queryParams = null,
                                                         CancellationToken?cancellationToken       = null)
 {
     return(await rc.Get <RingCentral.AccountPresenceInfo>(this.Path(), queryParams, cancellationToken));
 }
Ejemplo n.º 15
0
        protected override Task <bool> DoIsFileExistsAsync(StorageItem item, CancellationToken?cancellationToken = null)
        {
            var fullPath = Path.Combine(Options.StoragePath, item.FilePath);

            return(Task.FromResult(File.Exists(fullPath)));
        }
Ejemplo n.º 16
0
 private void ForwardAllResultsToCmdlet(Cmdlet cmdlet, CancellationToken?cancellationToken)
 {
     this.AssertNotDisposed();
     ForwardingHelper.ForwardAllResultsToCmdlet(this, cmdlet, cancellationToken);
 }
Ejemplo n.º 17
0
            public static void ForwardAllResultsToCmdlet(ThrottlingJob throttlingJob, Cmdlet cmdlet, CancellationToken?cancellationToken)
            {
                using (var helper = new ForwardingHelper(throttlingJob))
                {
                    try
                    {
                        throttlingJob.ChildJobAdded += helper.ThrottlingJob_ChildJobAdded;

                        try
                        {
                            throttlingJob.StateChanged += helper.ThrottlingJob_StateChanged;

                            IDisposable cancellationTokenRegistration = null;
                            if (cancellationToken.HasValue)
                            {
                                cancellationTokenRegistration = cancellationToken.Value.Register(helper.CancelForwarding);
                            }
                            try
                            {
                                Interlocked.MemoryBarrier();
                                ThreadPool.QueueUserWorkItem(
                                    delegate
                                {
                                    helper.StartMonitoringJob(throttlingJob);
                                    foreach (Job childJob in throttlingJob.GetChildJobsSnapshot())
                                    {
                                        helper.StartMonitoringJob(childJob);
                                    }

                                    helper.CheckIfThrottlingJobIsComplete();
                                });

                                helper.ForwardResults(cmdlet);
                            }
                            finally
                            {
                                if (cancellationTokenRegistration != null)
                                {
                                    cancellationTokenRegistration.Dispose();
                                }
                            }
                        }
                        finally
                        {
                            throttlingJob.StateChanged -= helper.ThrottlingJob_StateChanged;
                        }
                    }
                    finally
                    {
                        throttlingJob.ChildJobAdded -= helper.ThrottlingJob_ChildJobAdded;
                    }
                }
            }
Ejemplo n.º 18
0
 public Task <IRedLock> CreateLockAsync(string resource, TimeSpan expiryTime, TimeSpan waitTime, TimeSpan retryTime, CancellationToken?cancellationToken = null)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 19
0
        public async Task<UploadResponse> UploadAsync(Dictionary<string, object> transferMetadata = null, CancellationToken? cancellationToken = null)
        {
            await PrepareAsync();

            TransferMetadata = transferMetadata ?? new Dictionary<string, object>();
            Progress.TransferMetadata = TransferMetadata;
            CancellationToken = cancellationToken;

            var response = await InternalUploadAsync();

            try
            {
                var stream = await File.OpenReadAsync();
                stream.Dispose();
            }
            catch (Exception)
            {
                // Eat the exception, we tried to clean up.
            }

            return response;
        }
 public OperationCanceledException(CancellationToken token)
     : this()
 {
     this.token = token;
 }
Ejemplo n.º 21
0
 public FileWatch(CancellationToken?shutdown, ChangedHandler on_changed, params string[] files)
     : this(shutdown, on_changed, 0, null, files)
 {
 }
 public OperationCanceledException(string message, CancellationToken token)
     : this(message)
 {
     this.token = token;
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Returns the data associated with all the geometries that are intersected by 'geom'
 /// </summary>
 /// <param name="geom">Geometry to intersect with</param>
 /// <param name="ds">FeatureDataSet to fill data into</param>
 protected override void OnExecuteIntersectionQuery(Geometry geom, IFeatureCollectionSet fcs, CancellationToken?ct = null)
 {
     using (var ogrGeometry = OgrGeometry.CreateFromWkb(GeometryToWKB.Write(geom)))
     {
         _ogrLayer.SetSpatialFilter(ogrGeometry);
         var fds = new FeatureDataSet();
         ExecuteIntersectionQuery(fds);
         foreach (var fd in fds)
         {
             fcs.Add(fd);
         }
     }
 }
 public OperationCanceledException(string message, Exception innerException, CancellationToken token)
     : base(message, innerException)
 {
     this.token = token;
 }
Ejemplo n.º 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="envelope"></param>
        /// <param name="ds"></param>
        public override void ExecuteIntersectionQuery(BoundingBox envelope, IFeatureCollectionSet ds, CancellationToken?ct = null)
        {
            // Identifies all the features within the given BoundingBox
            var dataTable = CreateFeatureDataTable();

            dataTable.BeginLoadData();
            foreach (Feature feature in _features)
            {
                if (envelope.Intersects(feature.Geometry.EnvelopeInternal))
                {
                    CreateNewRow(dataTable, feature);
                }
            }
            dataTable.EndLoadData();

            ds.Add(dataTable);
        }
Ejemplo n.º 26
0
 /// <inheritdoc cref="IRepository{TEntity}"/>
 public async Task InsertAsync(TEntity entity, CancellationToken?cancellationToken = null)
 {
     await Collection.InsertOneAsync(entity, new InsertOneOptions(), cancellationToken ?? CancellationToken.None);
 }
Ejemplo n.º 27
0
        /// <summary></summary>
        public async Task <List <MarketChartData> > GetChartData(CurrencyPair pair, EMarketPeriod period, UnixSec time_beg, UnixSec time_end, CancellationToken?cancel = null)
        {
            try
            {
                var jtok = await GetData(Method.Public, "returnChartData", cancel, new Params
                {
                    { "currencyPair", pair.Id },
                    { "start", time_beg.Value },
                    { "end", time_end.Value },
                    { "period", (int)period },
                });

                var data = ParseJsonReply <List <MarketChartData> >(jtok);

                // Poloniex returns a single invalid candle if there is no data within the range
                return
                    (data.Count == 0 ? new List <MarketChartData>() :
                     data.Count == 1 && data[0].Invalid ? new List <MarketChartData>() :
                     data);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("too much data"))
                {
                    throw new PoloniexException(EErrorCode.TooMuchDataRequested, "Too much chart data was requested");
                }
                throw;
            }
        }
Ejemplo n.º 28
0
 public Task <bool> UpdateAsync <T>(T record, CancellationToken?cancellationToken = null)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 29
0
        /// <summary>Get the trade history</summary>
        public async Task <Dictionary <string, List <TradeCompleted> > > GetTradeHistory(UnixSec?beg = null, UnixSec?end = null, CancellationToken?cancel = null)
        {
            var parms = new Params {
                { "currencyPair", "all" }
            };

            if (beg != null && end != null)
            {
                parms["start"] = beg.Value.Value;
                parms["end"]   = end.Value.Value;
            }

            var jtok = await PostData(Method.Account, "returnTradeHistory", cancel, parms);

            var history = ParseJsonReply <Dictionary <string, List <TradeCompleted> > >(jtok);

            foreach (var his in history)
            {
                foreach (var h in his.Value)
                {
                    h.Pair = CurrencyPair.Parse(his.Key);
                }
            }

            return(history);
        }
        //public event EventHandler<EventArgs<String>> OnServerCommandReceived;

        public WifiServer(CancellationToken?stopToken = null) : base(stopToken)
        {
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Establishes the websocket against the configured URL.
        /// Try to get the QIX global interface when the connection has been established.
        /// </summary>
        /// <returns></returns>
        public async Task <dynamic> OpenAsync(CancellationToken?ctn = null)
        {
            if (socket != null)
            {
                await CloseAsync(ctn);
            }
            LastOpenError = null;
            CancellationToken ct = ctn ?? CancellationToken.None;

            socket = await config.CreateSocketCall(ct).ConfigureAwait(false);

            // Todo add here the global Cancelation Token that is
            // triggered from the CloseAsync
            bool?connected = null;

            void RPCMethodCall(object sender, JsonRpcRequestMessage e)
            {
                logger.Trace($"RPCMethodCall - {e.Method}:{e.Parameters}");
                if (e.Method == "OnAuthenticationInformation" && (bool?)e.Parameters["mustAuthenticate"] == true)
                {
                    connected     = false;
                    LastOpenError = "Connection established but authentication failed";
                }
                if (e.Method == "OnConnected")
                {
                    LastOpenError = "";
                    connected     = true;
                }
                if (!connected.HasValue)
                {
                    string message = "";
                    try
                    {
                        message = (string)e.Parameters["message"];
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                    string severity = "";
                    try
                    {
                        severity = (string)e.Parameters["severity"];
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                    if (!string.IsNullOrEmpty(severity) && severity == "fatal")
                    {
                        try
                        {
                            LastOpenError = e.Method + "\n" + message;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            LastOpenError = "Communication Error";
                        }
                        connected = false;
                    }
                }
            }

            RPCMethodCalled += RPCMethodCall;
            StartReceiveLoop(ct);
            while (connected == null && !ct.IsCancellationRequested)
            {
                Thread.Sleep(10);
            }
            RPCMethodCalled -= RPCMethodCall;

            if (connected == false)
            {
                socket?.CloseAsync(WebSocketCloseStatus.InternalServerError, "", ct);
                throw new Exception("Connection Error");
            }

            // start SendLoop only if connection is opened
            StartSendLoop(ct);
            var global = new GeneratedAPI(new ObjectResult()
            {
                QHandle = -1, QType = "Global"
            }, this);

            GeneratedApiObjects.TryAdd(-1, new WeakReference <GeneratedAPI>(global));
            return(global);
        }
Ejemplo n.º 32
0
 public string NullableCancellationTokenOnly(CancellationToken? token = null)
 {
     ReceivedToken = token;
     return _returnValue;
 }
Ejemplo n.º 33
0
			public RequestState(HttpWebRequest request, CancellationToken? cancellationToken)
			{
				if (request == null) throw new ArgumentNullException("request");

				this.request = request;
				this.cancellationToken = cancellationToken;
			}
Ejemplo n.º 34
0
 public WorkItem(
   TaskCompletionSource<object> taskSource,
   Action action,
   CancellationToken? cancelToken)
 {
     TaskSource = taskSource;
     Action = action;
     CancelToken = cancelToken;
 }
Ejemplo n.º 35
0
        public void Reset()
        {
            _onStarting = null;
            _onCompleted = null;

            _responseStarted = false;
            _keepAlive = false;
            _autoChunk = false;
            _applicationException = null;

            _requestHeaders.Reset();
            ResetResponseHeaders();
            ResetFeatureCollection();

            Scheme = null;
            Method = null;
            RequestUri = null;
            PathBase = null;
            Path = null;
            QueryString = null;
            _httpVersion = HttpVersionType.Unknown;
            RequestHeaders = _requestHeaders;
            RequestBody = null;
            StatusCode = 200;
            ReasonPhrase = null;
            ResponseHeaders = _responseHeaders;
            ResponseBody = null;
            DuplexStream = null;

            var httpConnectionFeature = this as IHttpConnectionFeature;
            httpConnectionFeature.RemoteIpAddress = _remoteEndPoint?.Address;
            httpConnectionFeature.RemotePort = _remoteEndPoint?.Port ?? 0;

            httpConnectionFeature.LocalIpAddress = _localEndPoint?.Address;
            httpConnectionFeature.LocalPort = _localEndPoint?.Port ?? 0;

            if (_remoteEndPoint != null && _localEndPoint != null)
            {
                httpConnectionFeature.IsLocal = _remoteEndPoint.Address.Equals(_localEndPoint.Address);
            }
            else
            {
                httpConnectionFeature.IsLocal = false;
            }

            _prepareRequest?.Invoke(this);

            _manuallySetRequestAbortToken = null;
            _abortedCts = null;
        }
Ejemplo n.º 36
0
		void MergeOptions (OptionsList list)
		{
			if (list.Item1 != null) {
				if (options == null)
					options = list.Item1;
				else
					Throw ("WithMergeOptions");
			}

			if (list.Item2 != null) {
				if (mode == null)
					mode = list.Item2;
				else
					Throw ("WithExecutionMode");
			}

			if (list.Item3 != null) {
				if (token == null)
					token = list.Item3;
				else
					Throw ("WithCancellationToken");
			}

			if (list.Item4 != -1) {
				if (degreeOfParallelism == null)
					degreeOfParallelism = list.Item4;
				else
					Throw ("WithDegreeOfParallelism");
			}

			// That one is treated specially
			if (list.Item5 != null) {
				implementerToken = implementerToken.Chain (list.Item5);
			}
		}
 public WifiBaseClass(CancellationToken?stopToken = null)
 {
     _cts = CancellationTokenSource.CreateLinkedTokenSource(stopToken ?? CancellationToken.None);
 }
Ejemplo n.º 38
0
 public async Task <bool> SendPost(string url, TimeSpan?timeout = null, CancellationToken?ct = null)
 {
     return(await Send(true, url, timeout ?? Timeout30, ct ?? _cancellationTokenSource.Token));
 }
Ejemplo n.º 39
0
 public string CancellationTokenOnly(CancellationToken token)
 {
     ReceivedToken = token;
     return _returnValue;
 }
Ejemplo n.º 40
0
        protected static async Task <ProcessExecutionResult> RunAsyncInternal(
            Process process,
            ILog log,
            ILog stdout,
            ILog stderr,
            Action <int, int> kill,
            Func <ILog, int, IList <int> > getChildProcessIds,
            TimeSpan?timeout = null,
            Dictionary <string, string>?environmentVariables = null,
            CancellationToken?cancellationToken = null,
            bool?diagnostics = null)
        {
            var stdoutCompletion = new TaskCompletionSource <bool>();
            var stderrCompletion = new TaskCompletionSource <bool>();
            var result           = new ProcessExecutionResult();

            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.RedirectStandardOutput = true;
            // Make cute emojiis show up as cute emojiis in the output instead of ugly text symbols!
            process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            process.StartInfo.StandardErrorEncoding  = Encoding.UTF8;
            process.StartInfo.UseShellExecute        = false;

            if (environmentVariables != null)
            {
                foreach (var kvp in environmentVariables)
                {
                    if (kvp.Value == null)
                    {
                        process.StartInfo.EnvironmentVariables.Remove(kvp.Key);
                    }
                    else
                    {
                        process.StartInfo.EnvironmentVariables[kvp.Key] = kvp.Value;
                    }
                }
            }

            process.OutputDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    lock (stdout)
                    {
                        stdout.WriteLine(e.Data);
                        stdout.Flush();
                    }
                }
                else
                {
                    stdoutCompletion.TrySetResult(true);
                }
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    lock (stderr)
                    {
                        stderr.WriteLine(e.Data);
                        stderr.Flush();
                    }
                }
                else
                {
                    stderrCompletion.TrySetResult(true);
                }
            };

            var sb = new StringBuilder();

            if (process.StartInfo.EnvironmentVariables != null)
            {
                var currentEnvironment = Environment.GetEnvironmentVariables().Cast <DictionaryEntry>().ToDictionary(v => v.Key.ToString(), v => v.Value?.ToString(), StringComparer.Ordinal);
                var processEnvironment = process.StartInfo.EnvironmentVariables.Cast <DictionaryEntry>().ToDictionary(v => v.Key.ToString(), v => v.Value?.ToString(), StringComparer.Ordinal);
                var allKeys            = currentEnvironment.Keys.Union(processEnvironment.Keys).Distinct();
                foreach (var key in allKeys)
                {
                    if (key == null)
                    {
                        continue;
                    }

                    string?a = null, b = null;
                    currentEnvironment?.TryGetValue(key, out a);
                    processEnvironment?.TryGetValue(key, out b);
                    if (a != b)
                    {
                        sb.Append($"{key}={StringUtils.Quote(b)} ");
                    }
                }
            }

            sb.Append($"{StringUtils.Quote(process.StartInfo.FileName)} {process.StartInfo.Arguments}");
            log.WriteLine(sb.ToString());

            process.Start();
            var pid = process.Id;

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            cancellationToken?.Register(() =>
            {
                var hasExited = false;
                try
                {
                    hasExited = process.HasExited;
                }
                catch
                {
                    // Process.HasExited can sometimes throw exceptions, so
                    // just ignore those and to be safe treat it as the
                    // process didn't exit (the safe option being to not leave
                    // processes behind).
                }

                if (!hasExited)
                {
                    stderr.WriteLine($"Killing process {pid} as it was cancelled");
                    kill(pid, 9);
                }
            });

            if (timeout.HasValue)
            {
                if (!await WaitForExitAsync(process, timeout.Value))
                {
                    log.WriteLine($"Process {pid} didn't exit within {timeout} and will be killed");

                    await KillTreeAsync(pid, log, kill, getChildProcessIds, diagnostics ?? true);

                    result.TimedOut = true;

                    lock (stderr)
                    {
                        log.WriteLine($"{pid} Execution timed out after {timeout.Value.TotalSeconds} seconds and the process was killed.");
                    }
                }
            }
            else
            {
                await WaitForExitAsync(process);
            }

            if (process.HasExited)
            {
                // make sure redirected output events are finished
                process.WaitForExit();
            }

            Task.WaitAll(new Task[] { stderrCompletion.Task, stdoutCompletion.Task }, TimeSpan.FromSeconds(1));

            try
            {
                result.ExitCode = process.ExitCode;
                log.WriteLine($"Process {Path.GetFileName(process.StartInfo.FileName)} exited with {result.ExitCode}");
            }
            catch (Exception e)
            {
                result.ExitCode = 12345678;
                log.WriteLine($"Failed to get ExitCode: {e}");
            }

            return(result);
        }
Ejemplo n.º 41
0
 public SendResponse Send(IFluentEmail email, CancellationToken?token = null)
 {
     return(SendAsync(email, token).GetAwaiter().GetResult());
 }
Ejemplo n.º 42
0
        public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null)
        {
            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("from", $"{email.Data.FromAddress.Name} <{email.Data.FromAddress.EmailAddress}>"));
            email.Data.ToAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("to", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.CcAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("cc", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.BccAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("bcc", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.ReplyToAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("h:Reply-To", $"{x.Name} <{x.EmailAddress}>"));
            });
            parameters.Add(new KeyValuePair <string, string>("subject", email.Data.Subject));

            parameters.Add(new KeyValuePair <string, string>(email.Data.IsHtml ? "html" : "text", email.Data.Body));

            if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody))
            {
                parameters.Add(new KeyValuePair <string, string>("text", email.Data.PlaintextAlternativeBody));
            }

            email.Data.Tags.ForEach(x =>
            {
                parameters.Add(new KeyValuePair <string, string>("o:tag", x));
            });

            foreach (var emailHeader in email.Data.Headers)
            {
                var key = emailHeader.Key;
                if (!key.StartsWith("h:"))
                {
                    key = "h:" + emailHeader.Key;
                }

                parameters.Add(new KeyValuePair <string, string>(key, emailHeader.Value));
            }

            var files = new List <HttpFile>();

            email.Data.Attachments.ForEach(x =>
            {
                string param;

                if (x.IsInline)
                {
                    param = "inline";
                }
                else
                {
                    param = "attachment";
                }

                files.Add(new HttpFile()
                {
                    ParameterName = param,
                    Data          = x.Data,
                    Filename      = x.Filename,
                    ContentType   = x.ContentType
                });
            });

            var response = await _httpClient.PostMultipart <MailgunResponse>("messages", parameters, files).ConfigureAwait(false);

            var result = new SendResponse {
                MessageId = response.Data?.Id
            };

            if (!response.Success)
            {
                result.ErrorMessages.AddRange(response.Errors.Select(x => x.ErrorMessage));
                return(result);
            }

            return(result);
        }
Ejemplo n.º 43
0
		public OperationCanceledException (CancellationToken token)
			: this ()
		{
			this.token = token;
		}
Ejemplo n.º 44
0
 public OperationCanceledException2(CancellationToken token)
     : base()
 {
     this.token = token;
 }
Ejemplo n.º 45
0
		public OperationCanceledException (string message, Exception innerException, CancellationToken token)
			: base (message, innerException)
		{
			this.token = token;
		}
Ejemplo n.º 46
0
        /// <summary>
        /// Returns the data associated with all the geometries that are intersected by 'geom'
        /// </summary>
        /// <param name="bbox">Geometry to intersect with</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public override void ExecuteIntersectionQuery(BoundingBox bbox, IFeatureCollectionSet fcs, CancellationToken?ct = null)
        {
            _ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            var fds = new FeatureDataSet();

            ExecuteIntersectionQuery(fds);
            foreach (var fd in fds)
            {
                fcs.Add(fd);
            }
        }