Beispiel #1
0
        public void Get(int page, int ammount, string token)
        {
            var client = new RestClient(Core.siteMap.messageDir[SiteMap.MessageMethod.get]);

            var request = new RestRequest
            {
                RequestFormat = DataFormat.Json,
                Method        = Method.GET
            };

            request.AddParameter("email", User_from);
            request.AddParameter("page", page);
            request.AddParameter("ammount", ammount);
            request.AddParameter("body", token);

            client.ExecuteAsync(request, response =>
            {
                GetEventsArgs args = new GetEventsArgs();
                args.ResponseCode  = response.StatusCode;

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    JObject o    = JObject.Parse(response.Content);
                    args.Message = (string)o["message"];

                    Dictionary <int, string> users = new Dictionary <int, string>();
                    users.Add((int)o["body"]["userFrom"]["id"], (string)o["body"]["userFrom"]["email"]);
                    users.Add((int)o["body"]["userTo"]["id"], (string)o["body"]["userTo"]["email"]);

                    JArray tm = (o["body"].SelectToken("messages") as JArray);
                    List <Message> mesList = new List <Message>();

                    foreach (JObject tmpMes in tm)
                    {
                        mesList.Add(JsonToMessage(tmpMes, users));
                    }

                    args.Messages = mesList;
                }
                else
                {
                    StandardEventArgs standArgs = StandardEventArgsDeserialiser(response);
                    args.Body     = standArgs.Body;
                    args.Message  = standArgs.Message;
                    args.Messages = null;
                }

                OnMessageGet(args);
            });
        }
Beispiel #2
0
        public IHttpActionResult GetEvents([FromBody] GetEventsArgs args)
        {
            string filter = "";

            if (args.EndTime != null)
            {
                filter += "EndTime = $args[2];";
            }

            if (args.EventID != null)
            {
                filter += "ID = @($args[4]);";
            }

            if (args.ProviderName != null)
            {
                filter += "ProviderName = @($args[5]);";
            }

            if (args.Level != null)
            {
                filter += "Level = @($args[6]);";
            }

            string script =
                // workaround a bug documented here: https://connect.microsoft.com/PowerShell/feedback/details/716533/get-winevent-does-not-return-the-content-of-the-event-message-in-v3-ctp2
                "[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]\"en-US\";" +
                "$lastId = $args[3]; $array = @(); $max = $args[1];" +
                "while ($array.count -lt $args[1]) {" +
                "$c = 0; foreach ($e in (Get-WinEvent -ea SilentlyContinue -MaxEvents $max -FilterHashtable @{LogName = $args[0];" + filter + "}))" +
                "{$c++; if ($lastId -eq $null -or $e.RecordId -lt $lastId) {$array += $e; $lastId = $e.RecordId; if ($array.count -eq $args[1]) {break} } }" +
                "if ($c -lt $max) {break} else {$max *= 2}}; $array";

            return(Json(InvokePowerShell(script, PSSelect(
                                             "Id".Alias("EventId"), "Level", "RecordId", "ProviderName", "ProviderId",
                                             "TimeCreated".Expression("$_.TimeCreated.ToUniversalTime().Ticks").TransformTruncUtcTicks(),
                                             "Message".Expression("if ($_.Message.Length -gt 100) { $_.Message.Substring(0,100) + '...'} else {$_.Message}")),
                                         args.LogName,
                                         args.Count,
                                         args.EndTime == null ? null : (DateTime?)args.EndTime.Value.ToLocalTime().AddSeconds(1),
                                         args.ToRecordId,
                                         args.EventID,
                                         args.ProviderName,
                                         args.Level)));
        }
        public void Get(string email, string token)
        {
            var client = new RestClient(Core.siteMap.userDir[SiteMap.UserMethod.get]);

            var request = new RestRequest();

            request.RequestFormat = DataFormat.Json;
            request.Method        = Method.GET;
            request.AddParameter("body", token);
            if (email.Length > 0)
            {
                request.AddParameter("email", email);
            }

            client.ExecuteAsync(request, response =>
            {
                GetEventsArgs args = new GetEventsArgs();
                args.ResponseCode  = response.StatusCode;

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    JObject o    = JObject.Parse(response.Content);
                    args.Message = (string)o["message"];

                    JArray tempUsers = (o.SelectToken("body") as JArray);
                    args.Users       = new List <User>();

                    foreach (JObject tempUser in tempUsers)
                    {
                        //.WriteLine(JsonConvert.SerializeObject(tempUser, Formatting.Indented));
                        args.Users.Add(JsonToUser(tempUser));
                    }
                }
                else
                {
                    StandardEventArgs standArgs = StandardEventArgsDeserialiser(response);
                    args.Body    = standArgs.Body;
                    args.Message = standArgs.Message;
                    args.Users   = null;
                }

                OnGetResult(args);
            });
        }
Beispiel #4
0
 protected virtual void OnMessageGet(GetEventsArgs e)
 {
     MessageGet?.Invoke(this, e);
 }
Beispiel #5
0
        /// <summary>
        ///
        /// This method make it possible to get the events happened as per
        /// specified criteria.
        ///
        /// </summary>
        /// <param name='getEventsArgs'>
        /// (See model for parameter info)
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <GetEventsOKResponse> > GetEventsWithHttpMessagesAsync(GetEventsArgs getEventsArgs = default(GetEventsArgs), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(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("getEventsArgs", getEventsArgs);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetEvents", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.BaseUri.AbsoluteUri;
            var _url     = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "GetEvents").ToString();
            // Create HTTP transport objects
            HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new 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 (getEventsArgs != null)
            {
                _requestContent      = SafeJsonConvert.SerializeObject(getEventsArgs, this.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (this.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.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));
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                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 <GetEventsOKResponse>();

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

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <GetEventsOKResponse>(_responseContent, this.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);
        }
Beispiel #6
0
 /// <summary>
 ///
 /// This method make it possible to get the events happened as per
 /// specified criteria.
 ///
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='getEventsArgs'>
 /// (See model for parameter info)
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <GetEventsOKResponse> GetEventsAsync(this ISupportService operations, GetEventsArgs getEventsArgs = default(GetEventsArgs), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetEventsWithHttpMessagesAsync(getEventsArgs, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Beispiel #7
0
 /// <summary>
 ///
 /// This method make it possible to get the events happened as per
 /// specified criteria.
 ///
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='getEventsArgs'>
 /// (See model for parameter info)
 /// </param>
 public static GetEventsOKResponse GetEvents(this ISupportService operations, GetEventsArgs getEventsArgs = default(GetEventsArgs))
 {
     return(Task.Factory.StartNew(s => ((ISupportService)s).GetEventsAsync(getEventsArgs), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
 protected virtual void OnGetResult(GetEventsArgs e)
 {
     GetResult?.Invoke(this, e);
 }