Esempio n. 1
0
        public static DataSearchResult SearchData(DataSet ds, string queryString, int page, int pageSize,
                                                  string sort            = null, bool excludeBigProperties = true, bool withHighlighting = false,
                                                  bool exactNumOfResults = false)
        {
            Devmasters.DT.StopWatchEx sw = new Devmasters.DT.StopWatchEx();

            sw.Start();
            var query = Lib.Searching.Tools.FixInvalidQuery(queryString, queryShorcuts, queryOperators);

            var res = _searchData(ds, query, page, pageSize, sort, excludeBigProperties, withHighlighting, exactNumOfResults);

            sw.Stop();
            if (!res.IsValid)
            {
                throw DataSetException.GetExc(
                          ds.DatasetId,
                          ApiResponseStatus.InvalidSearchQuery.error.number,
                          ApiResponseStatus.InvalidSearchQuery.error.description,
                          queryString
                          );
            }

            if (res.Total > 0)
            {
                var expConverter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();

                return(new DataSearchResult()
                {
                    ElapsedTime = sw.Elapsed,
                    Q = queryString,
                    IsValid = true,
                    Total = res.Total,
                    Result = res.Hits
                             .Select(m => Newtonsoft.Json.JsonConvert.SerializeObject(m.Source))
                             .Select(s => (dynamic)Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(s, expConverter)),

                    Page = page,
                    PageSize = pageSize,
                    DataSet = ds,
                    ElasticResultsRaw = res,
                });
            }
            else
            {
                return new DataSearchResult()
                       {
                           ElapsedTime       = sw.Elapsed,
                           Q                 = queryString,
                           IsValid           = true,
                           Total             = 0,
                           Result            = new dynamic[] { },
                           Page              = page,
                           PageSize          = pageSize,
                           DataSet           = ds,
                           ElasticResultsRaw = res,
                       }
            };
        }
Esempio n. 2
0
        public async void getMsg(object sender, EventArgs e)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                selFri.friend = ConvoList.SelectedItem.ToString();
            }));
            if (selFri.friend != " ")
            {
                Console.WriteLine(selFri.friend);
                Conversation c    = new Conversation(theUser, selFri.friend.ToString());
                string       json = JsonConvert.SerializeObject(c);
                var          data = new StringContent(json, Encoding.UTF8, "application/json");
                var          msg  = await client.PostAsync(url + "allMessages", data);

                string msgBody = msg.Content.ReadAsStringAsync().Result;
                Console.WriteLine(msgBody);
                var     expConverter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
                dynamic obj          = JsonConvert.DeserializeObject <ExpandoObject>(msgBody, expConverter);
                var     msgJson      = JsonConvert.SerializeObject(obj.messages);
                var     msgList      = JsonConvert.DeserializeObject <List <Messages> >(msgJson);

                Dispatcher.Invoke(new Action(() =>
                {
                    foreach (Messages m in msgList)
                    {
                        if (((m.recUsername == theUser && m.senUsername == selFri.friend) ||
                             (m.recUsername == selFri.friend && m.senUsername == theUser)) &&
                            m.dateEntered > Convert.ToDateTime(msg1Date.Content.ToString()) &&
                            m._id != msg1ID.Text.ToString()
                            )
                        {
                            string decrypted = Decrypt(Convert.FromBase64String(m.message), crypt.Key, crypt.IV);
                            user3Lbl.Content = user2Lbl.Content;
                            msg3Lbl.Content  = msg2Lbl.Content;
                            user2Lbl.Content = user1Lbl.Content;
                            msg2Lbl.Content  = msg1Lbl.Content;
                            user1Lbl.Content = m.senUsername;
                            msg1Lbl.Content  = decrypted;
                            msg1ID.Text      = m._id;
                            msg1Date.Content = m.dateEntered;
                        }
                    }
                }));
            }
            else
            {
                Dispatcher.Invoke(new Action(() => { msg1Lbl.Content = "Select A Conversation"; }));
            }
        }
Esempio n. 3
0
        public async Task <SendMessageTemplate[]> ListTemplatesAsync()
        {
            var client            = new global::SendGrid.SendGridClient(apiKey);
            var responseTemplates = await client.RequestAsync(global::SendGrid.SendGridClient.Method.GET, urlPath : $"/templates");

            var templateInfo = await responseTemplates.Body.ReadAsStringAsync();

            var     converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
            dynamic obj       = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(templateInfo, converter);

            return(((List <object>)obj.templates).Select((dynamic tmp) => new SendMessageTemplate()
            {
                externalTemplateId = tmp.id,
                name = tmp.name,
            }).ToArray());
        }
Esempio n. 4
0
        private async void ProcessStory(string storyId)
        {
            try
            {
                var queryOptions = new FeedOptions {
                    MaxItemCount = -1
                };
                IQueryable <Article> articleExistQuery = documentDBProvider.Client.CreateDocumentQuery <Article>(
                    UriFactory.CreateDocumentCollectionUri("articles", "article"), queryOptions)
                                                         .Where(f => f.Id == storyId);

                var list = articleExistQuery.ToList();

                if (!list.Any())
                {
                    using (var client = new HttpClient())
                    {
                        string url = $"https://hacker-news.firebaseio.com/v0/item/{storyId}.json";
                        HttpResponseMessage response = await client.GetAsync(url);

                        // response.EnsureSuccessStatusCode();
                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            string responseBody = await response.Content.ReadAsStringAsync();

                            var     converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
                            dynamic story     = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(responseBody, converter);

                            // dynamic story = Newtonsoft.Json.JsonConvert.DeserializeObject(responseBody);// (dynamic)Newtonsoft.Json.Linq.JObject.Parse(responseBody);
                            if (!string.IsNullOrEmpty(story.url.ToString()))
                            {
                                InsertStory(story);
                            }
                        }
                        else
                        {
                            string responseBody = await response.Content.ReadAsStringAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 5
0
        public async Task <ExpandoObject> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            string apiKey = "p7ZjMYscB8dYETiVX3Om4e4VfmiQptWe";
            //string apiSecret = "MsqkNKKqhV0yFaKm";

            HttpClient          client   = new HttpClient();
            dynamic             obj      = new ExpandoObject();
            HttpResponseMessage response = client.GetAsync("https://api.nytimes.com/svc/books/v3/lists/current/" + input.QueryStringParameters["list"] + ".json?api-key=" + apiKey).Result;

            response.EnsureSuccessStatusCode();
            string result = response.Content.ReadAsStringAsync().Result;

            var expConverter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();

            obj = JsonConvert.DeserializeObject <ExpandoObject>(result, expConverter);

            return(obj);
        }
Esempio n. 6
0
        public async Task <List <dynamic> > FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            HttpClient client = new HttpClient();
            dynamic    obj    = new ExpandoObject();
            //top cryptos api endpoint
            HttpResponseMessage response = client.GetAsync("https://api.coincap.io/v2/assets").Result;

            response.EnsureSuccessStatusCode();
            string result = response.Content.ReadAsStringAsync().Result;


            var expConverter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();

            obj = JsonConvert.DeserializeObject <ExpandoObject>(result, expConverter);


            Table coins = Table.LoadTable(cli, tableName);


            var json = JsonConvert.SerializeObject(obj.data);


            List <Coin> lCoins = JsonConvert.DeserializeObject <List <Coin> >(json);


            PutItemOperationConfig config = new PutItemOperationConfig();

            foreach (Coin c in lCoins)
            {
                Console.WriteLine(c.id);
                Document res =
                    await coins.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(c)), config);
            }


            return(obj.data);
        }
Esempio n. 7
0
        private static string tableName = "FinalAssignment";                       //Name of the table in DynamoDB
        public async Task <List <dynamic> > FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            //Create an http client and expandoobject
            HttpClient client = new HttpClient();
            dynamic    obj    = new ExpandoObject();

            //Get the quotes from the api and put them into a result string
            HttpResponseMessage response = client.GetAsync("https://quote-garden.herokuapp.com/api/v3/quotes").Result;

            response.EnsureSuccessStatusCode();
            string result = response.Content.ReadAsStringAsync().Result;

            //Convert the result string to an ExpanoObject
            var converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();

            obj = JsonConvert.DeserializeObject <ExpandoObject>(result, converter);

            //Load the quotes tables
            Table quotes = Table.LoadTable(dbClient, tableName);

            //Get the data from the quotes object (we don't want the status codes or anything else, just the data).
            var json = JsonConvert.SerializeObject(obj.data);

            //Create a list of all of the data that's in the json object
            List <Quote> quoteList = JsonConvert.DeserializeObject <List <Quote> >(json);

            PutItemOperationConfig config = new PutItemOperationConfig();

            //Put the data into the table
            foreach (Quote q in quoteList)
            {
                Document res = await quotes.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(q)), config);
            }

            return(obj.data);
        }
Esempio n. 8
0
        public async Task <TResult> SendEmailMessageAsync <TResult>(
            string templateName,
            string toAddress, string toName,
            string fromAddress, string fromName,
            string subject,
            IDictionary <string, string> substitutionsSingle,
            IDictionary <string, IDictionary <string, string>[]> substitutionsMultiple,
            Func <string, TResult> onSuccess,
            Func <TResult> onServiceUnavailable,
            Func <string, TResult> onFailure)
        {
            var message = new SendGridMessage();

            message.From    = new EmailAddress(fromAddress, fromName);
            message.Subject = subject;
            message.SetClickTracking(false, true);
            //message.TemplateId = templateName;

            var emailMute      = false;
            var toAddressEmail = EastFive.Web.Configuration.Settings.GetString(AppSettings.MuteEmailToAddress,
                                                                               (emailMuteString) =>
            {
                if (emailMuteString.IsNullOrWhiteSpace())
                {
                    return(new EmailAddress(toAddress, toName));
                }
                emailMute = true;
                return(new EmailAddress(emailMuteString, $"MUTED[{toAddress}:{toName}]"));
            },
                                                                               (why) => new EmailAddress(toAddress, toName));

            message.AddTo(toAddressEmail);
            // message.SetClickTracking(false, false);

            var bccAddressesAdded = Web.Configuration.Settings.GetString(AppSettings.BccAllAddresses,
                                                                         copyEmail =>
            {
                var bccAddresses = (copyEmail.IsNullOrWhiteSpace() ? "" : copyEmail)
                                   .Split(',')
                                   .Where(s => !String.IsNullOrWhiteSpace(s))
                                   .Select((bccAddress) => new EmailAddress(bccAddress))
                                   .ToList();
                if (bccAddresses.Any())
                {
                    message.AddBccs(bccAddresses);
                }
                return(true);
            },
                                                                         (why) => false);


            var subsitutionsSingleDictionary = substitutionsSingle
                                               .Select(kvp => new KeyValuePair <string, string>($"--{kvp.Key}--", kvp.Value))
                                               .ToDictionary();

            message.AddSubstitutions(subsitutionsSingleDictionary);
            var client = new global::SendGrid.SendGridClient(apiKey);

            var responseTemplates = await client.RequestAsync(global::SendGrid.SendGridClient.Method.GET, urlPath : $"/templates/{templateName}");

            if (responseTemplates.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return(onFailure($"The specified template [{templateName}] does not exist."));
            }
            var templateInfo = await responseTemplates.Body.ReadAsStringAsync();

            if (!responseTemplates.StatusCode.IsSuccess())
            {
                return(onFailure($"Failed to aquire template:{templateInfo}"));
            }

            var     converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
            dynamic obj       = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(templateInfo, converter);
            string  html      = obj.versions[0].html_content;
            var     htmlDoc   = new HtmlAgilityPack.HtmlDocument();

            htmlDoc.LoadHtml(html);
            if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
            {
                return(onFailure($"Template has parse errors:{htmlDoc.ParseErrors.Select(pe => pe.Reason).Join(";")}"));
            }

            var substitutionsMultipleExpanded = substitutionsMultiple
                                                .NullToEmpty()
                                                .SelectMany(
                (substitutionMultiple) =>
            {
                var matchingNodes = htmlDoc.DocumentNode.SelectNodes($"//*[@data-repeat='--{substitutionMultiple.Key}--']");
                if (!matchingNodes.NullToEmpty().Any())
                {
                    return new HtmlAgilityPack.HtmlNode[] { }
                }
                ;

                var substituations = matchingNodes
                                     .Select(
                    matchingNode =>
                {
                    var parentNode = substitutionMultiple.Value
                                     .Where(
                        subValues =>
                    {
                        if (!matchingNode.Attributes.Contains("data-repeat-selector-key"))
                        {
                            return(true);
                        }
                        if (!matchingNode.Attributes.Contains("data-repeat-selector-value"))
                        {
                            return(true);
                        }
                        var key = matchingNode.Attributes["data-repeat-selector-key"].Value;
                        if (!subValues.ContainsKey(key))
                        {
                            return(false);
                        }
                        var value = matchingNode.Attributes["data-repeat-selector-value"].Value;
                        return(subValues[key] == value);
                    })
                                     .Aggregate(matchingNode.ParentNode,
                                                (parentNodeAggr, subValues) =>
                    {
                        var newChildHtml = subValues
                                           .Aggregate(
                            matchingNode.OuterHtml,
                            (subTextAggr, sub) =>
                        {
                            subTextAggr = subTextAggr.Replace($"--{sub.Key}--", sub.Value);
                            return(subTextAggr);
                        });

                        var childNode = HtmlAgilityPack.HtmlNode.CreateNode(newChildHtml);
                        parentNodeAggr.AppendChild(childNode);
                        return(parentNodeAggr);
                    });

                    parentNode.RemoveChild(matchingNode);
                    //return new KeyValuePair<string, string>(matchingNode.OuterHtml, subText);
                    return(matchingNode);
                })
                                     .ToArray();
                return(substituations);
            })
                                                .ToArray();

            // message.AddSubstitutions(substitutionsMultipleExpanded);
            //message.HtmlContent = htmlDoc.DocumentNode.OuterHtml;
            message.PlainTextContent = htmlDoc.DocumentNode.InnerText;

            message.HtmlContent = subsitutionsSingleDictionary.Aggregate(
                htmlDoc.DocumentNode.OuterHtml,
                (outerHtml, substitutionSingle) =>
            {
                return(outerHtml.Replace($"--{substitutionSingle.Key}--", substitutionSingle.Value));
            });

            // Send the email, which returns an awaitable task.
            try
            {
                var response = await client.SendEmailAsync(message);

                var body = await response.Body.ReadAsStringAsync();

                if (!response.StatusCode.IsSuccess())
                {
                    return(onFailure(body));
                }

                var messageIdHeaders = response.Headers
                                       .Where(header => header.Key == "X-Message-Id");
                if (!messageIdHeaders.Any())
                {
                    return(onSuccess(body));
                }

                var messageIds = messageIdHeaders.First().Value;
                if (!messageIds.Any())
                {
                    return(onSuccess(body));
                }

                var messageId = messageIds.First();
                return(onSuccess(messageId));
            }
            catch (Exception ex)
            {
                //var details = new StringBuilder();

                //details.Append("ResponseStatusCode: " + ex.ResponseStatusCode + ".   ");
                //for (int i = 0; i < ex.Errors.Count(); i++)
                //{
                //    details.Append(" -- Error #" + i.ToString() + " : " + ex.Errors[i]);
                //}

                return(onFailure(ex.ToString()));
            }
        }
        public static DataTable GetEntry(string apiKey, string projectId, string jeguid)
        {
            var client = new RestClient(GlasshouseShared.Utils.urlApi);

            var request = new RestRequest(string.Format("projects/{0}/new_journal/entries/{1}", projectId, jeguid), Method.GET);

            //request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
            //request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

            // easily add HTTP Headers
            request.AddHeader("access-token", apiKey);

            //request.RequestFormat = DataFormat.Json;

            // execute the request
            IRestResponse response = client.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(null);
            }
            var content = response.Content; // raw content as string

            var journal = JsonConvert.DeserializeObject <dynamic>(content);

            // not done below this line !!!
            var     converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
            dynamic message   = JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(content, converter);

            dynamic new_journal = journal["new_journal"];

            dynamic entries = new_journal["entries"];


            DataTable table = new DataTable();

            foreach (dynamic entry in entries)
            {
                foreach (dynamic prop in entry)
                {
                    JObject jObject = prop.First as JObject;

                    string name = "";

                    if (jObject == null)
                    {
                        name = prop.Name;
                    }
                    else
                    {
                        name = jObject.Property("human_name").Value.ToString();
                    }

                    if (table.Columns.Contains(name) == false)
                    {
                        table.Columns.Add(name, typeof(string));
                    }
                }

                string[] split = new string[table.Columns.Count];
                for (int j = 0; j < split.Length; j++)
                {
                    split[j] = string.Empty;
                }

                foreach (dynamic prop in entry)
                {
                    JObject jObject = prop.First as JObject;

                    string name  = "";
                    string value = "";

                    if (jObject == null)
                    {
                        name = prop.Name;

                        if (prop.Value == null)
                        {
                            value = string.Empty;
                        }
                        else
                        {
                            value = prop.Value.ToString();
                        }
                    }
                    else
                    {
                        name = jObject.Property("human_name").Value.ToString();

                        if (jObject.Property("value").Value == null)
                        {
                            value = string.Empty;
                        }
                        else
                        {
                            value = jObject.Property("value").Value.ToString();
                        }
                    }

                    split[table.Columns.IndexOf(name)] = value;
                }

                table.Rows.Add(split);
            }

            return(table);
        }