void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { RootObject root = new RootObject(); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)); DataContractJsonSerializer ser = new DataContractJsonSerializer(root.GetType()); ms.Position = 0; root = ser.ReadObject(ms) as RootObject; ms.Close(); #region Saving to storage if (settings.Contains("root")) { settings.Remove("root"); settings.Add("root", root); settings.Save(); Global.Root = root; } else { settings.Add("root", root); settings.Save(); Global.Root = root; } #endregion #region Toastprompt Grid grid = this.LayoutRoot.Children[1] as Grid; ToastPrompt tp = new ToastPrompt(); tp.Title = "Synch success"; tp.Message = "Downloaded " + root.words.Count + " words" ; tp.VerticalAlignment = System.Windows.VerticalAlignment.Center; tp.FontFamily = new FontFamily("Verdana"); tp.FontSize = 22; tp.MillisecondsUntilHidden = 3000; tp.Show(); #endregion }
private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename) { if (updateLevel == PackageVersionClass.Release) { obj = obj.Where(i => !i.prerelease).ToArray(); } else if (updateLevel == PackageVersionClass.Beta) { obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase)).ToArray(); } else if (updateLevel == PackageVersionClass.Dev) { obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) || i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); } var availableUpdate = obj .Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)) .Where(i => i != null) .OrderByDescending(i => Version.Parse(i.AvailableVersion)) .FirstOrDefault(); return availableUpdate ?? new CheckForUpdateResult { IsUpdateAvailable = false }; }
void Req_Completed(List<seanslar.RootObject> data) { SalonBilgisi = data[0]; if (SalonBilgisi.movies != null) { foreach (var movieitem in SalonBilgisi.movies) { movieitem.allseances = new List<string>(); foreach (var item in movieitem.seances) { foreach (var seanceInfo in item) { movieitem.allseances.Add(seanceInfo); } } } } if (getCompleted != null) { getCompleted(this); } }
private void button1_Click(object sender, EventArgs e) { // Create an instance of the open file dialog box. OpenFileDialog openFileDialog1 = new OpenFileDialog(); // Set filter options and filter index. openFileDialog1.Filter = "Text Files (.txt)|*.txt|JSON Files (.json)|*.json"; openFileDialog1.FilterIndex = 2; int size = -1; DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog. if (result == DialogResult.OK) // Test result. { string file = openFileDialog1.FileName; try { string text = File.ReadAllText(file); size = text.Length; HangoutsJSON hg = new HangoutsJSON(); hg.json = text; currentRootObject = hg.parse(); conversationPicker.Items.AddRange(currentRootObject.conversation_state.ToArray()); conversationPicker.SelectedIndex = 0; } catch (IOException) { } } }
public static void Run() { int offset = 0; int limit = 100; RestClient client = new RestClient("https://api.clover.com/v3/merchants/R0YXW6ESBYFNJ/"); RootObject rootObject = new RootObject(); StagedItemBLL _stagedITemCRUD = new StagedItemBLL(); do { // Get all items in the "Package Beer" category - currently 1,156 var endpointParams = "categories/7C7C30CG8QXM8/items?offset=" + offset + "&limit=" + limit; var request = new RestRequest(endpointParams, Method.GET) { RequestFormat = DataFormat.Json }; request.AddHeader("Authorization", "Bearer af214874-074a-4ea7-965b-cb085ffe9394"); var response = client.Execute(request); rootObject = JsonConvert.DeserializeObject<RootObject>(response.Content); var stagedItems = rootObject.elements.Select(x => new StagedItemDTO() { Name = x.Name, UPC = x.Code, StockCount = x.StockCount, ItemPrice = x.Price }).ToList(); _stagedITemCRUD.ProcessStagedItems(stagedItems); offset += limit; } while (rootObject.elements.Count != 0); }
private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename) { if (updateLevel == PackageVersionClass.Release) { // Technically all we need to do is check that it's not pre-release // But let's addititional checks for -beta and -dev to handle builds that might be temporarily tagged incorrectly. obj = obj.Where(i => !i.prerelease && !i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) && !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); } else if (updateLevel == PackageVersionClass.Beta) { obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase)).ToArray(); } else if (updateLevel == PackageVersionClass.Dev) { obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) || i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); } var availableUpdate = obj .Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)) .Where(i => i != null) .OrderByDescending(i => Version.Parse(i.AvailableVersion)) .FirstOrDefault(); return availableUpdate ?? new CheckForUpdateResult { IsUpdateAvailable = false }; }
public void XkcdMe(Message message, IMessageClient client, string number) { IRestClient jsonClient = GetJsonServiceClient("http://xkcd.com"); var result = new RootObject(); string jsonResponse; try { jsonResponse = (string.IsNullOrEmpty(number) || number == "xkcd me") ? jsonClient.Get<string>("/info.0.json") : jsonClient.Get<string>(string.Format("/{0}/info.0.json", number)); } catch (Exception) { jsonResponse = jsonClient.Get<string>("/1/info.0.json"); } result.Value = JsonObject.Parse(jsonResponse); string imgUrl = result.Value.Child("img").Replace("\\", ""); string altText = result.Value.Child("alt"); //Reply with two messages back to back client.ReplyTo(message, imgUrl); client.ReplyTo(message, altText); }
public IEnumerable<Footballer> GetAll(out List<Event> events) { var proxy = client.Proxy; client.UseDefaultCredentials = true; client.Proxy.Credentials = CredentialCache.DefaultCredentials; ServicePointManager.DefaultConnectionLimit = 300; // I need to Deserialise the JSON API object into RootObject, then I need to pick // out the Footballers and return them, also I can return the Events list Stream stream = client.OpenRead("https://fantasy.premierleague.com/drf/bootstrap-static"); using (StreamReader reader = new StreamReader(stream)) { root = (RootObject)JsonConvert.DeserializeObject(reader.ReadLine(), typeof(RootObject)); foreach (var s in root.elements) { footballers.Add(s); } events = root.events; return footballers; } }
public void InitializeInfo() { var dataPath = "~/Content/courses-data.json"; dataPath = HttpContext.Current.Server.MapPath(dataPath); var json = File.ReadAllText(dataPath); rootObj = JsonConvert.DeserializeObject<RootObject>(json); }
private RefreshInfo(RootObject obj) { this.token_type = obj.token_type; this.expires_in = obj.expires_in; this.scopes = obj.scope.Split(' '); this.access_token = obj.access_token; this.refresh_token = obj.refresh_token; }
void Req_Completed(Film.RootObject deserialized) { Data = deserialized; if (getCompleted != null) { getCompleted(Data); } }
private Pod GetPodOfPodNumber(PodEnum number, RootObject rootObject) { foreach (var pod in rootObject.GetComponentsInChildren<Pod>()) { if (pod.PodNumber == number) { return pod; } } return null; }
void client_DownloadLanguageStringCompleted(object sender, DownloadStringCompletedEventArgs e) { var jsonText= e.Result.ToString(); SupportedLanguages = JsonConvert.DeserializeObject<RootObject>(jsonText); foreach (var item in SupportedLanguages.languages) { cboFrom.Items.Add(item.language); cboTo.Items.Add(item.language); } cboFrom.Title = "language"; }
public static ShardInfo get_shard(RootObject root, string str) { if (root == null || root.shardInfo == null) return null; foreach (ShardInfo info in root.shardInfo) if (info.platforms != null && info.platforms.Contains(str)) return info; return null; }
public GoogleDriveRefreshInfo(RootObject data) { if (_Instance == null) _Instance = new GoogleDriveRefreshInfo(); _Instance._AccessToken = data.access_token; _Instance._ExpiresIn = data.expires_in; _Instance._TokenType = data.token_type; _Instance._RefreshToken = data.refresh_token; GoogleDrive.Utilities.WriteDriveSettings(); }
public MainWindow(string openFile, RootObject safeData, string password) { InitializeComponent(); Height = SystemParameters.PrimaryScreenHeight * 0.75; Width = SystemParameters.PrimaryScreenWidth * 0.75; _openFile = openFile; SafeData = safeData; _password = password; Title += $" - {openFile}"; Setup(); }
public RetCode ServerLogin(string trigram, string password) { RootObject rootObject = new RootObject { person = new Person { trigram = trigram, password = password } }; rootObject.person = new Person { trigram = trigram, password = password }; if (CreateObject(rootObject, rRestClient, "login", out rRestResponse) == RetCode.successful) { User = JsonConvert.DeserializeObject<Person>(rRestResponse.Content); return RetCode.successful; } else { //Callbacker.callback(eAction.RestError, rRestResponse.StatusCode, rRestResponse.ErrorMessage, rRestResponse.Content); return RetCode.unsuccessful; } }
public static void LoadConfigFromFile(string configFilePath) { if (File.Exists(m_configFilePath)) { string configuration = File.ReadAllText(m_configFilePath); m_instance = JsonConvert.DeserializeObject<RootObject>(configuration); }; m_instance.JSONCardsFilePath = Environment.ExpandEnvironmentVariables(m_instance.JSONCardsFilePath); m_instance.JSONCardsByClasses = Environment.ExpandEnvironmentVariables(m_instance.JSONCardsByClasses); m_instance.AppLogConfigFilePath = Environment.ExpandEnvironmentVariables(m_instance.AppLogConfigFilePath); m_instance.AppLogFilePath = Environment.ExpandEnvironmentVariables(m_instance.AppLogFilePath); m_instance.GameLogFilePath = Environment.ExpandEnvironmentVariables(m_instance.GameLogFilePath); m_instance.TempFolder = Environment.ExpandEnvironmentVariables(m_instance.TempFolder); m_instance.OCR.TesseractDataPath = Environment.ExpandEnvironmentVariables(m_instance.OCR.TesseractDataPath); }
public JsonMtGOX() { high = new High(); low = new Low(); avg = new Avg(); vwap = new Vwap(); vol = new Vol(); lastlocal = new LastLocal(); lastorig = new LastOrig(); lastall = new LastAll(); last = new Last(); buy = new Buy(); sell = new Sell(); rootobject = new RootObject(); returnObject = new Return(); }
private bool MatchesUpdateLevel(RootObject i, PackageVersionClass updateLevel) { if (updateLevel == PackageVersionClass.Beta) { return !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase); } if (updateLevel == PackageVersionClass.Dev) { return !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) || i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase); } // Technically all we need to do is check that it's not pre-release // But let's addititional checks for -beta and -dev to handle builds that might be temporarily tagged incorrectly. return !i.prerelease && !i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) && !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase); }
private void insert_data(RootObject account) { // setup sql server connection to insert new data using (SqlConnection conn = new SqlConnection(@"Persist Security Info=False;Integrated Security=true;Initial Catalog=Altitude_Production;server=(local)")) { SqlCommand addAccount = new SqlCommand(@"INSERT INTO account (Account_Name, Account_Global_Unique_Identifier, Account_Token, Create_Date, Locked) VALUES (@account_name, @guid, @token, @created, @locked)", conn); addAccount.Parameters.AddWithValue("@account_name", account.Account.First_Name); addAccount.Parameters.AddWithValue("@guid", account.Account.GUID); addAccount.Parameters.AddWithValue("@token", account.Account.Token); addAccount.Parameters.AddWithValue("@created", account.Account.Date_Created); addAccount.Parameters.AddWithValue("@locked", account.Account.Locked); addAccount.Connection.Open(); addAccount.ExecuteNonQuery(); addAccount.Connection.Close(); } }
public RetCode CreateObject(RootObject rootObject, IRestClient rClient, string requestResource, out IRestResponse rResponse) { RestRequest rRequest = new RestRequest(); rRequest.DateFormat = "yyyy-MM-ddTHH:mm:ss.sss"; rRequest.Resource = requestResource; rRequest.Method = Method.POST; rRequest.RequestFormat = DataFormat.Json; if (requestResource != "login") Authorize(rootObject); rRequest.AddBody(rootObject); rResponse = rClient.Execute(rRequest); if (rResponse.StatusCode == System.Net.HttpStatusCode.OK) { if (requestResource != "login") Callbacker.callback(eAction.Message, "Creation Successful."); return RetCode.successful; } else { Callbacker.callback(eAction.RestError, rResponse.StatusCode, rResponse.ErrorMessage, rResponse.Content); return RetCode.unsuccessful; } }
private CheckForUpdateResult CheckForUpdateResult(RootObject obj, Version minVersion, string assetFilename, string packageName, string targetFilename) { Version version; if (!Version.TryParse(obj.tag_name, out version)) { return null; } if (version < minVersion) { return null; } var asset = (obj.assets ?? new List<Asset>()).FirstOrDefault(i => IsAsset(i, assetFilename)); if (asset == null) { return null; } return new CheckForUpdateResult { AvailableVersion = version.ToString(), IsUpdateAvailable = version > minVersion, Package = new PackageVersionInfo { classification = obj.prerelease ? (obj.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase) ? PackageVersionClass.Dev : PackageVersionClass.Beta) : PackageVersionClass.Release, name = packageName, sourceUrl = asset.browser_download_url, targetFilename = targetFilename, versionStr = version.ToString(), requiredVersionStr = "1.0.0", description = obj.body, infoUrl = obj.html_url } }; }
protected void Button3_Click(object sender, EventArgs e) { string name = TextBox4.Text; string area = TextBox5.Text; //string URL = "https://maps.googleapis.com/maps/api/place/textsearch/json"; string URL = "http://localhost:1709/Service1.svc/locate"; //string keyAPI = "AIzaSyCMcvEBMsrgKM3xGA1saqaQfXxGLcnlwsU"; string parameters = "?name=" + name + "&area=" + area; string query = name + " " + area; string myResult = ""; RootObject Jsonstuff = new RootObject(); HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(parameters).Result; if (response.IsSuccessStatusCode) { myResult = response.Content.ReadAsStringAsync().Result; Jsonstuff = JsonConvert.DeserializeObject<RootObject>(response.Content.ReadAsStringAsync().Result); if (Jsonstuff.storeLocateResult.results.Count != 0) { TextBox3.Text = "Your search of: \"" + query + "\" returned these stores\n"; foreach (var result in Jsonstuff.storeLocateResult.results) { TextBox3.Text += result.name + "\n"; } } TextBox4.Text = ""; TextBox5.Text = ""; } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
private void insert_data(RootObject individual) { // setup sql server connection to insert new data using (SqlConnection conn = new SqlConnection(@"Persist Security Info=False;Integrated Security=true;Initial Catalog=Altitude_Production;server=(local)")) { SqlCommand addIndividual = new SqlCommand(@"INSERT INTO Individual (First, Last, Individual_Global_Unique_Identifier, Personal_Email, Create_Date, Company, Address_City, Employee_Office, Employee_Department) VALUES (@first_name, @last_name, @guid, @email, @created, @company, @city, @dept, @office)", conn); addIndividual.Parameters.AddWithValue("@first_name", individual.Individual.First_Name); addIndividual.Parameters.AddWithValue("@guid", individual.Individual.GUID); addIndividual.Parameters.AddWithValue("@email", individual.Individual.Email); addIndividual.Parameters.AddWithValue("@created", individual.Individual.Date_Created); addIndividual.Parameters.AddWithValue("@last_name", individual.Individual.Last_Name); addIndividual.Parameters.AddWithValue("@company", individual.Individual.Company); addIndividual.Parameters.AddWithValue("@city", individual.Individual.City); addIndividual.Parameters.AddWithValue("@dept", individual.Individual.Emp_Dept); addIndividual.Parameters.AddWithValue("@office", individual.Individual.Emp_Office); addIndividual.Connection.Open(); addIndividual.ExecuteNonQuery(); addIndividual.Connection.Close(); } }
/// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { SearchAndUpdateCommand = new RelayCommand(SearchAndUpdateMethod); if (IsInDesignMode) { WeatherList = new ObservableCollection<DayElem>(); WeatherList.Add(new DayElem { temp = new Temp { day = 20, max = 25, min = 10 }, Date = DateTime.Now, weather = new System.Collections.Generic.List<Weather> { new Weather { icon = "01d", description = "light snow" } } }); WeatherList.Add(new DayElem { temp = new Temp { day = 22, max = 27, min = 12 }, Date = DateTime.Now.AddDays(1), weather = new System.Collections.Generic.List<Weather> { new Weather { icon = "02d", description = "light snow" } } }); WeatherList.Add(new DayElem { temp = new Temp { day = 18, max = 28, min = 13 }, Date = DateTime.Now.AddDays(2), weather = new System.Collections.Generic.List<Weather> { new Weather { icon = "03d", description = "light snow" } } }); WeatherList.Add(new DayElem { temp = new Temp { day = 24, max = 29, min = 14 }, Date = DateTime.Now.AddDays(3), weather = new System.Collections.Generic.List<Weather> { new Weather { icon = "04d", description = "light snow" } } }); WeatherList.Add(new DayElem { temp = new Temp { day = 25, max = 30, min = 15 }, Date = DateTime.Now.AddDays(4), weather = new System.Collections.Generic.List<Weather> { new Weather { icon = "10d", description = "light snow" } } }); WeatherList.Add(new DayElem { temp = new Temp { day = 25, max = 31, min = 16 }, Date = DateTime.Now.AddDays(4), weather = new System.Collections.Generic.List<Weather> { new Weather { icon = "13d", description = "light snow" } } }); SelectedDay = WeatherList[0]; Root = new RootObject(); Root.city = new City(); Root.city.name = "Tokyo"; Root.city.country = "JP"; } else { UpdateWeather("Tokyo"); } }
public static void Load() { Logger.InfoFormat("Loading settings from {0}",ConfigurationFileName); try { var applicationDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) ?? ""; var configFile = Path.Combine(applicationDirectory, ConfigurationFileName); if (File.Exists(configFile)) { Settings = JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(configFile)); } else { Logger.Fatal("Could not load application settings."); throw new FileNotFoundException(string.Format("File {0} was not found", configFile)); } } catch (Exception ex) { Logger.Error(ex); } }
public void Dispose() { this.sequence = null; this.rootObject = null; }
/// <summary> /// ReadHandWrittenText - Takes in the uploaded image and, if able, sends it to the API to be converted. /// </summary> /// <param name="formFile">form from the front end</param> /// <returns></returns> public async Task ReadHandwrittenText(IFormFile formFile) { try { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add( "Ocp-Apim-Subscription-Key", Configuration["CognitiveServices:subscriptionKey"]); string uri = $"{Configuration["CognitiveServices:uriBase"]}?mode=Handwritten"; HttpResponseMessage response; string operationLocation; GetImageAsByteArray(formFile); using (ByteArrayContent content = new ByteArrayContent(Ncvm.ByteData)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(uri, content); } if (response.IsSuccessStatusCode) { operationLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault(); } else { string errorString = await response.Content.ReadAsStringAsync(); TempData["Error"] = "Improper image format."; return; } string contentString; int i = 0; do { System.Threading.Thread.Sleep(1000); response = await client.GetAsync(operationLocation); contentString = await response.Content.ReadAsStringAsync(); ++i; }while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1); if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1) { TempData["Error"] = "Request timed-out. Try again later."; return; } ResponseContent = JToken.Parse(contentString).ToString(); RootObject ImageText = JsonParse(contentString); List <Line> Lines = FilteredJson(ImageText); Ncvm.Text = TextString(Lines); ImageDisplayExtensions.DisplayImage(Ncvm.ByteData); } catch (Exception) { TempData["Error"] = "Hmm.. Something went wrong."; } }
public async Task GetAllAllergies() { string json = await jsonResult("http://ec2-54-83-191-130.compute-1.amazonaws.com:8080/Sanjeevani/rest/SV/GetAllergy/" + factor.Passcode); this.rootObject = JsonConvert.DeserializeObject <RootObject>(json); }
public async Task <bool> FetchEpisodeData <T>(MetadataResult <T> itemResult, int episodeNumber, int seasonNumber, string episodeImdbId, string seriesImdbId, string language, string country, CancellationToken cancellationToken) where T : BaseItem { if (string.IsNullOrWhiteSpace(seriesImdbId)) { throw new ArgumentNullException(nameof(seriesImdbId)); } var item = itemResult.Item; var seasonResult = await GetSeasonRootObject(seriesImdbId, seasonNumber, cancellationToken).ConfigureAwait(false); if (seasonResult?.Episodes == null) { return(false); } RootObject result = null; if (!string.IsNullOrWhiteSpace(episodeImdbId)) { foreach (var episode in seasonResult.Episodes) { if (string.Equals(episodeImdbId, episode.imdbID, StringComparison.OrdinalIgnoreCase)) { result = episode; break; } } } // finally, search by numbers if (result == null) { foreach (var episode in seasonResult.Episodes) { if (episode.Episode == episodeNumber) { result = episode; break; } } } if (result == null) { return(false); } // Only take the name and rating if the user's language is set to English, since Omdb has no localization if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport) { item.Name = result.Title; if (string.Equals(country, "us", StringComparison.OrdinalIgnoreCase)) { item.OfficialRating = result.Rated; } } if (!string.IsNullOrEmpty(result.Year) && result.Year.Length >= 4 && int.TryParse(result.Year.AsSpan().Slice(0, 4), NumberStyles.Number, _usCulture, out var year) && year >= 0) { item.ProductionYear = year; } var tomatoScore = result.GetRottenTomatoScore(); if (tomatoScore.HasValue) { item.CriticRating = tomatoScore; } if (!string.IsNullOrEmpty(result.imdbVotes) && int.TryParse(result.imdbVotes, NumberStyles.Number, _usCulture, out var voteCount) && voteCount >= 0) { // item.VoteCount = voteCount; } if (!string.IsNullOrEmpty(result.imdbRating) && float.TryParse(result.imdbRating, NumberStyles.Any, _usCulture, out var imdbRating) && imdbRating >= 0) { item.CommunityRating = imdbRating; } if (!string.IsNullOrEmpty(result.Website)) { item.HomePageUrl = result.Website; } if (!string.IsNullOrWhiteSpace(result.imdbID)) { item.SetProviderId(MetadataProvider.Imdb, result.imdbID); } ParseAdditionalMetadata(itemResult, result); return(true); }
private async Task TalkRecieveAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var activity = await result as Activity; RootObject dataGrammarObj = await LanguageCheckingHelper.CheckGrammarAsync(activity.Text); if (dataGrammarObj.matches.Any()) // has any grammar error { // get words error List <ShowGrammarViewModel> lstError = new List <ShowGrammarViewModel>(); lstError.AddRange(dataGrammarObj.matches.Select(t => new ShowGrammarViewModel { ErrorMessage = t.message, ErrorRule = t.rule.description, Category = t.shortMessage })); // Create the activity and attach a set of Hero cards. var listOfAttachments = new List <Attachment>(); foreach (var itemError in lstError) { List <CardImage> cardImages = new List <CardImage>(); int asomewareWidth = 300; if (itemError.ErrorMessage.Length > 50) { asomewareWidth += 200; } cardImages.Add(new CardImage(url: "data:image/png;base64," + Convert.ToBase64String(ImageHelper.ConvertTextToImage(itemError.ErrorRule, "Bookman Old Style", 12, Color.AliceBlue, asomewareWidth, 100)))); HeroCard plCard = new HeroCard() { Title = itemError.ErrorMessage, Subtitle = itemError.Category, Images = cardImages }; listOfAttachments.Add(plCard.ToAttachment()); } var message = context.MakeMessage(); message.Attachments = listOfAttachments; await context.PostAsync(message); } else { var userName = String.Empty; context.UserData.TryGetValue <string>("Name", out userName); var englishStep = 0; context.UserData.TryGetValue <int>("step", out englishStep); if (englishStep < 3) { englishStep++; context.UserData.SetValue <int>("step", englishStep); await context.PostAsync($" {userName}, " + (englishStep == 1 ? HiBotOptions.LearnEnglishTopics.What_about_you : HiBotOptions.LearnEnglishTopics.Can_you_talk_about_your_job)); } else { englishStep++; context.UserData.SetValue <int>("step", englishStep); await context.PostAsync($"Great, {userName}!, What's else?"); } } context.Wait(TalkRecieveAsync); }
private void ParseAdditionalMetadata <T>(MetadataResult <T> itemResult, RootObject result) where T : BaseItem { T item = itemResult.Item; var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport; // Grab series genres because imdb data is better than tvdb. Leave movies alone // But only do it if english is the preferred language because this data will not be localized if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre)) { item.Genres.Clear(); foreach (var genre in result.Genre .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(i => i.Trim()) .Where(i => !string.IsNullOrWhiteSpace(i))) { item.AddGenre(genre); } } if (isConfiguredForEnglish) { // Omdb is currently english only, so for other languages skip this and let secondary providers fill it in item.Overview = result.Plot; } //if (!string.IsNullOrWhiteSpace(result.Director)) //{ // var person = new PersonInfo // { // Name = result.Director.Trim(), // Type = PersonType.Director // }; // itemResult.AddPerson(person); //} //if (!string.IsNullOrWhiteSpace(result.Writer)) //{ // var person = new PersonInfo // { // Name = result.Director.Trim(), // Type = PersonType.Writer // }; // itemResult.AddPerson(person); //} //if (!string.IsNullOrWhiteSpace(result.Actors)) //{ // var actorList = result.Actors.Split(','); // foreach (var actor in actorList) // { // if (!string.IsNullOrWhiteSpace(actor)) // { // var person = new PersonInfo // { // Name = actor.Trim(), // Type = PersonType.Actor // }; // itemResult.AddPerson(person); // } // } //} }
public static RootObject GetMetadata(this string readerOutput) { RootObject metadata = JsonConvert.DeserializeObject <RootObject>(readerOutput); return(metadata); }
private void ProcessMainInfo(Series series, RootObject seriesInfo) { series.Name = seriesInfo.name; series.SetProviderId(MetadataProviders.Tmdb, seriesInfo.id.ToString(_usCulture)); series.VoteCount = seriesInfo.vote_count; string voteAvg = seriesInfo.vote_average.ToString(CultureInfo.InvariantCulture); float rating; if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out rating)) { series.CommunityRating = rating; } series.Overview = seriesInfo.overview; if (seriesInfo.networks != null) { series.Studios = seriesInfo.networks.Select(i => i.name).ToList(); } if (seriesInfo.genres != null) { series.Genres = seriesInfo.genres.Select(i => i.name).ToList(); } series.HomePageUrl = seriesInfo.homepage; series.RunTimeTicks = seriesInfo.episode_run_time.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault(); if (string.Equals(seriesInfo.status, "Ended", StringComparison.OrdinalIgnoreCase)) { series.Status = SeriesStatus.Ended; series.EndDate = seriesInfo.last_air_date; } else { series.Status = SeriesStatus.Continuing; } series.PremiereDate = seriesInfo.first_air_date; var ids = seriesInfo.external_ids; if (ids != null) { if (!string.IsNullOrWhiteSpace(ids.imdb_id)) { series.SetProviderId(MetadataProviders.Imdb, ids.imdb_id); } if (ids.tvrage_id > 0) { series.SetProviderId(MetadataProviders.TvRage, ids.tvrage_id.ToString(_usCulture)); } if (ids.tvdb_id > 0) { series.SetProviderId(MetadataProviders.Tvdb, ids.tvdb_id.ToString(_usCulture)); } } }
public IHttpActionResult GetProduct(string name) { //string allText = System.IO.File.ReadAllText(@"D:\Java\CatStore\CatStore\App_Data\data.json"); //var serializer = new JavaScriptSerializer(); //dynamic result = serializer.Deserialize<dynamic>(allText); string requestUrl = "http://cat-store-api.frostdigital.se/api"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl); //Response coming HttpWebResponse responce = (HttpWebResponse)request.GetResponse(); // var resstream = responce.GetResponseStream(); Stream responseStream = responce.GetResponseStream(); StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8); var js = new JsonSerializer(); var objText = responseReader.ReadToEnd(); RootObject result = JsonConvert.DeserializeObject <RootObject>(objText); //js.Deserialize<RootObject>(objText); Product[] products = new Product[] { new Product { Code = 1, Name = result.products[0].Name, Description = result.products[0].Description, ImgURL = result.products[0].ImgURL, Price = 500, IsAvaiable = true, Stock = result.products[0].Stock }, new Product { Code = 2, Name = result.products[1].Name, Description = result.products[1].Description, ImgURL = result.products[1].ImgURL, Price = 4000, IsAvaiable = true, Stock = result.products[1].Stock }, new Product { Code = 3, Name = result.products[2].Name, Description = result.products[2].Description, ImgURL = result.products[2].ImgURL, Price = 1500, IsAvaiable = true, Stock = result.products[2].Stock }, new Product { Code = 4, Name = result.products[3].Name, Description = result.products[3].Description, ImgURL = result.products[3].ImgURL, Price = 1000, IsAvaiable = true, Stock = result.products[3].Stock } }; var product = from c in products where products.Any(i => c.Name.Contains(name.Trim())) select c; if (product == null) { return(NotFound()); } return(Ok(product)); }
async System.Threading.Tasks.Task updateFriendsInfo() { try { var fb = new Facebook.FacebookClient(session.AccessToken); string query = "select uid, first_name, last_name from user where uid in (select uid2 from friend where uid1 = me()) and is_app_user"; var result = await fb.GetTaskAsync("fql", new { q = query }); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result.ToString())); RootObject obj = new RootObject(); DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); obj = ser.ReadObject(ms) as RootObject; List<string> ids = new List<string>(); List<string> last_names = new List<string>(); List<string> first_names = new List<string>(); foreach (User u in obj.data) { ids.Add(u.uid); last_names.Add(u.last_name); first_names.Add(u.first_name); //System.Diagnostics.Debug.WriteLine("UID: " + u.uid + u.first_name + u.last_name); } ADFacebookWP8Impl.friendsInfo(ids.ToArray(), last_names.ToArray(), first_names.ToArray()); //System.Diagnostics.Debug.WriteLine("Result: " + result); } catch (Exception) { System.Diagnostics.Debug.WriteLine("updateFriendsInfo failed "); } }
private void ProcessMainInfo(Series series, RootObject seriesInfo, string preferredCountryCode) { series.Name = seriesInfo.name; series.SetProviderId(MetadataProviders.Tmdb, seriesInfo.id.ToString(_usCulture)); //series.VoteCount = seriesInfo.vote_count; string voteAvg = seriesInfo.vote_average.ToString(CultureInfo.InvariantCulture); float rating; if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out rating)) { series.CommunityRating = rating; } series.Overview = seriesInfo.overview; if (seriesInfo.networks != null) { series.Studios = seriesInfo.networks.Select(i => i.name).ToArray(seriesInfo.networks.Count); } if (seriesInfo.genres != null) { series.Genres = seriesInfo.genres.Select(i => i.name).ToList(); } series.HomePageUrl = seriesInfo.homepage; series.RunTimeTicks = seriesInfo.episode_run_time.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault(); if (string.Equals(seriesInfo.status, "Ended", StringComparison.OrdinalIgnoreCase)) { series.Status = SeriesStatus.Ended; series.EndDate = seriesInfo.last_air_date; } else { series.Status = SeriesStatus.Continuing; } series.PremiereDate = seriesInfo.first_air_date; var ids = seriesInfo.external_ids; if (ids != null) { if (!string.IsNullOrWhiteSpace(ids.imdb_id)) { series.SetProviderId(MetadataProviders.Imdb, ids.imdb_id); } if (ids.tvrage_id > 0) { series.SetProviderId(MetadataProviders.TvRage, ids.tvrage_id.ToString(_usCulture)); } if (ids.tvdb_id > 0) { series.SetProviderId(MetadataProviders.Tvdb, ids.tvdb_id.ToString(_usCulture)); } } var contentRatings = (seriesInfo.content_ratings ?? new ContentRatings()).results ?? new List <ContentRating>(); var ourRelease = contentRatings.FirstOrDefault(c => string.Equals(c.iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase)); var usRelease = contentRatings.FirstOrDefault(c => string.Equals(c.iso_3166_1, "US", StringComparison.OrdinalIgnoreCase)); var minimumRelease = contentRatings.FirstOrDefault(); if (ourRelease != null) { series.OfficialRating = ourRelease.rating; } else if (usRelease != null) { series.OfficialRating = usRelease.rating; } else if (minimumRelease != null) { series.OfficialRating = minimumRelease.rating; } if (seriesInfo.videos != null && seriesInfo.videos.results != null) { foreach (var video in seriesInfo.videos.results) { if (video.type.Equals("trailer", System.StringComparison.OrdinalIgnoreCase) || video.type.Equals("clip", System.StringComparison.OrdinalIgnoreCase)) { if (video.site.Equals("youtube", System.StringComparison.OrdinalIgnoreCase)) { var videoUrl = string.Format("http://www.youtube.com/watch?v={0}", video.key); series.AddTrailerUrl(videoUrl); } } } } }
public async Task <IActionResult> Index() { using (HttpClientHandler httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }; var credential = new NetworkCredential("cdrapi", "cdrapi123"); httpClientHandler.Credentials = credential; httpClientHandler.PreAuthenticate = true; using (HttpClient client = manager.Client(httpClientHandler)) { //HttpResponseMessage response = await client.GetAsync("todos/1"); HttpResponseMessage response = await client.GetAsync("cdrapi?format=json"); RootObject list = new RootObject(); List <CDR> ResultList = new List <CDR>(); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); //list = JsonConvert.DeserializeObject<ObjTest>(result); list = JsonConvert.DeserializeObject <RootObject>(result); foreach (var item in list.cdr_root) { if (!string.IsNullOrEmpty(item.recordfiles)) { item.recordfiles = $"{client.BaseAddress}recapi?filename={item.recordfiles}"; } if (item.main_cdr != null) { item.main_cdr.recordfiles = string.IsNullOrEmpty(item.main_cdr.recordfiles) ? string.Empty : $"{client.BaseAddress}recapi?filename={item.main_cdr.recordfiles}"; } if (item.sub_cdr_1 != null) { item.sub_cdr_1.recordfiles = string.IsNullOrEmpty(item.sub_cdr_1.recordfiles) ? string.Empty : $"{client.BaseAddress}recapi?filename={item.sub_cdr_1.recordfiles}"; } if (item.sub_cdr_2 != null) { item.sub_cdr_2.recordfiles = string.IsNullOrEmpty(item.sub_cdr_2.recordfiles) ? string.Empty : $"{client.BaseAddress}recapi?filename={item.sub_cdr_2.recordfiles}"; } if (item.sub_cdr_3 != null) { item.sub_cdr_3.recordfiles = string.IsNullOrEmpty(item.sub_cdr_3.recordfiles) ? string.Empty : $"{client.BaseAddress}recapi?filename={item.sub_cdr_3.recordfiles}"; } if (item.sub_cdr_4 != null) { item.sub_cdr_4.recordfiles = string.IsNullOrEmpty(item.sub_cdr_4.recordfiles) ? string.Empty : $"{client.BaseAddress}recapi?filename={item.sub_cdr_4.recordfiles}"; } ResultList.Add(item); } } return(View(ResultList)); } } }
public IAdapterPresentation BeginAuthentication(System.Security.Claims.Claim identityClaim, System.Net.HttpListenerRequest request, IAuthenticationContext context) { string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config"; System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value; string authToken = cfg.AppSettings.Settings["apiKey"].Value; string upn = identityClaim.Value; string baseUrl = oktaTenant + "/api/v1/"; //string tenantName = "marcjordan"; //string baseUrl = "https://" + tenantName + ".oktapreview.com/api/v1/"; //string authToken = "SSWS 009RUU8EeUvD-EpOEH1qHL0OZwmCTJK71kzFjsQufr"; string pinSuccess = "no"; string verifyResult = "false"; string pollingEndpoint = ""; bool isPermanentFailure = false; string message = string.Empty; HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + upn); upnRequest.Headers.Add("Authorization", authToken); upnRequest.Method = "GET"; upnRequest.ContentType = "application/json"; var upnResponse = (HttpWebResponse)upnRequest.GetResponse(); var idReader = new StreamReader(upnResponse.GetResponseStream()); var id = idReader.ReadToEnd(); RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id); string userID = userProfile.id.ToString(); HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors"); factorRequest.Headers.Add("Authorization", authToken); factorRequest.Method = "GET"; factorRequest.ContentType = "application/json"; factorRequest.Accept = "application/json"; var factorResponse = (HttpWebResponse)factorRequest.GetResponse(); var factorReader = new StreamReader(factorResponse.GetResponseStream()); var factorList = factorReader.ReadToEnd(); RootObject[] factors = JsonConvert.DeserializeObject <RootObject[]>(factorList); string factorID = ""; foreach (RootObject factor in factors) { if (factor.provider == "OKTA" && factor.factorType == "push") { string pushfactorID = factor.id; HttpWebRequest pushRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + pushfactorID + "/verify"); pushRequest.Headers.Add("Authorization", authToken); pushRequest.Method = "POST"; pushRequest.ContentType = "application/json"; pushRequest.Accept = "application/json"; pushRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"; var pushResponse = (HttpWebResponse)pushRequest.GetResponse(); var pushReader = new StreamReader(pushResponse.GetResponseStream()); var pushStatus = pushReader.ReadToEnd(); RootObject pushResult = JsonConvert.DeserializeObject <RootObject>(pushStatus); pollingEndpoint = pushResult._links.poll.href.ToString(); } } return(new AdapterPresentation(message, upn, isPermanentFailure, pollingEndpoint)); }
public ActionResult ViewWeather(RootObject rootObject) { if (!ModelState.IsValid) { return(RedirectToAction("Index", "Home")); } rootObject.Zipcodes = rootObject.Zipcode.Split(','); if (rootObject.Zipcodes.Length > 1) { for (int i = 0; i < rootObject.Zipcodes.Length; i++) { HttpWebRequest apiRequest = WebRequest.Create($"http://api.wunderground.com/api/d9cca49bf824a20b/forecast10day/q/{rootObject.Zipcodes[i]}.json") as HttpWebRequest; string apiResponse = ""; var zip = rootObject.Zipcodes[i]; if (i == 0) { using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); rootObject.Weather1 = JsonConvert.DeserializeObject <Weather1>(apiResponse); rootObject.Weather1.Zipcode = zip; } } if (i == 1) { using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); rootObject.Weather2 = JsonConvert.DeserializeObject <Weather2>(apiResponse); rootObject.Weather2.Zipcode = zip; } } if (i == 2) { using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); rootObject.Weather3 = JsonConvert.DeserializeObject <Weather3>(apiResponse); rootObject.Weather3.Zipcode = zip; } } if (i == 3) { using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); rootObject.Weather4 = JsonConvert.DeserializeObject <Weather4>(apiResponse); rootObject.Weather4.Zipcode = zip; } } if (i == 4) { using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); rootObject.Weather5 = JsonConvert.DeserializeObject <Weather5>(apiResponse); rootObject.Weather5.Zipcode = zip; } } } return(View("ViewWeatherMulti", rootObject)); } else { HttpWebRequest apiRequest = WebRequest.Create($"http://api.wunderground.com/api/d9cca49bf824a20b/forecast10day/q/{rootObject.Zipcode}.json") as HttpWebRequest; var zip = rootObject.Zipcode; string apiResponse; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); rootObject = JsonConvert.DeserializeObject <RootObject>(apiResponse); rootObject.Zipcode = zip; } return(View(rootObject)); } }
public IEnumerable <Product> GetAllProducts() { //string allText = System.IO.File.ReadAllText(@"D:\Java\CatStore\CatStore\App_Data\data.json"); //var serializer = new JavaScriptSerializer(); //dynamic result = serializer.Deserialize<dynamic>(allText); string requestUrl = "http://cat-store-api.frostdigital.se/api"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl); //Response coming HttpWebResponse responce = (HttpWebResponse)request.GetResponse(); // var resstream = responce.GetResponseStream(); Stream responseStream = responce.GetResponseStream(); StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8); var js = new JsonSerializer(); var objText = responseReader.ReadToEnd(); RootObject result = JsonConvert.DeserializeObject <RootObject>(objText); //js.Deserialize<RootObject>(objText); Product[] products = new Product[] { new Product { Code = 1, Name = result.products[0].Name, Description = result.products[0].Description, ImgURL = result.products[0].ImgURL, Price = 500, IsAvaiable = true, Stock = result.products[0].Stock }, new Product { Code = 2, Name = result.products[1].Name, Description = result.products[1].Description, ImgURL = result.products[1].ImgURL, Price = 4000, IsAvaiable = true, Stock = result.products[1].Stock }, new Product { Code = 3, Name = result.products[2].Name, Description = result.products[2].Description, ImgURL = result.products[2].ImgURL, Price = 1500, IsAvaiable = true, Stock = result.products[2].Stock }, new Product { Code = 4, Name = result.products[3].Name, Description = result.products[3].Description, ImgURL = result.products[3].ImgURL, Price = 1000, IsAvaiable = true, Stock = result.products[3].Stock } }; return(products); }
private bool ScanMarket(Games game, int startIndex = 0) { try { RootObject ro = null; do { int timeout = (int)TimeSpan.FromMinutes(3).TotalMilliseconds; string target = "http://arkarrsourceservers.ddns.net:27019/steammarketitems?apikey=" + APIkey + "&appid=" + (int)game + "&version=2"; string json = fetcher.Fetch(target, "GET", null, true, "", true, timeout); ro = JsonConvert.DeserializeObject <RootObject>(json); if (ro == null) { Console.WriteLine("Error fetching : " + target + " !"); Console.WriteLine("Trying again."); } }while (ro == null && !stop); if (stop) { return(false); } List <Item> items = ro.items; if (ro.success && stop == false) { List <Item> itemToAdd = new List <Item>(); foreach (Item item in items) { Item i = null; if (game == Games.TF2) { i = steamMarketItemsTF2.FirstOrDefault(x => x.Name == item.Name); } else if (game == Games.CSGO) { i = steamMarketItemsCSGO.FirstOrDefault(x => x.Name == item.Name); } else if (game == Games.Dota2) { i = steamMarketItemsDOTA2.FirstOrDefault(x => x.Name == item.Name); } if (i != null && i.Value != item.Value) { i.Value = item.Value; i.LastUpdated = item.LastUpdated; } else if (i == null) { itemToAdd.Add(item); } } if (itemToAdd.Count != 0) { if (game == Games.TF2) { steamMarketItemsTF2.AddRange(itemToAdd); } else if (game == Games.CSGO) { steamMarketItemsCSGO.AddRange(itemToAdd); } else if (game == Games.Dota2) { steamMarketItemsDOTA2.AddRange(itemToAdd); } itemToAdd.Clear(); } return(true); } else { Console.WriteLine("Error while fetching " + game.ToString() + "'s market : "); Console.WriteLine(ro.message); return(false); } } catch (Exception e) { Console.WriteLine("Error while fetching " + game.ToString() + "'s market : "); Console.WriteLine(e.Message); return(false); } }
public override string ToString() { return($"Csv Meta Model \n FileName: {FileName} \n {RootObject.ToString()}"); }
public static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log) { System.Text.StringBuilder ErrorRecords = new System.Text.StringBuilder(); System.Text.StringBuilder AcceptedRecords = new System.Text.StringBuilder(); RootObject rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject <RootObject>(eventGridEvent.Data.ToString()); if (rootObject.url.Contains("/LandBlob/")) { string blobName = rootObject.url.Substring(rootObject.url.IndexOf("/claimshark/")).Replace("/claimshark/", ""); string PayerID = blobName.Split("/")[0]; if (!CheckFileExists(PayerID, System.IO.Path.GetFileName(blobName))) { CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("StorageConnection")); CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("claimshark"); CloudBlob cloudBlockBlob = container.GetBlobReference(blobName); string text; List <FileError> fileErrors = new List <FileError>(); using (var stream = new System.IO.MemoryStream()) { cloudBlockBlob.DownloadToStreamAsync(stream).Wait(); text = System.Text.Encoding.UTF8.GetString(stream.ToArray()); } if (!String.IsNullOrEmpty(text)) { var binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string PayerSchemaFile = Path.Combine(binDirectory, PayerID + ".json"); string PayerSchema; if (System.IO.File.Exists(PayerSchemaFile)) { PayerSchema = File.ReadAllText(PayerSchemaFile); } else { binDirectory = binDirectory.Substring(0, binDirectory.LastIndexOf(@"\")); PayerSchemaFile = Path.Combine(binDirectory, PayerID + ".json"); PayerSchema = File.ReadAllText(PayerSchemaFile); } FileSchema fileSchema = Newtonsoft.Json.JsonConvert.DeserializeObject <FileSchema>(PayerSchema); CreateTable(fileSchema.Fileds); string[] data = text.Split('\n'); int LineNo = 1; foreach (var value in data) { if (value.Trim().Length > 0) { System.Data.DataRow dataRow = dtPayerDataTable.NewRow(); dataRow["IsValid"] = 1; if (fileSchema.FieldSeprator == "FixedLength") { int startPosition = 1; int fieldLength = 0; foreach (var field in fileSchema.Fileds) { fieldLength = Convert.ToInt32(field.Length); if (value.Length >= (startPosition + fieldLength)) { dataRow[field.FieldName] = value.Substring(startPosition - 1, fieldLength); if (field.IsRequired == "Yes") { if (value.Substring(startPosition - 1, fieldLength).Trim().Length <= 0) { fileErrors.Add(new FileError() { FieldName = field.FieldName, StartingPostiton = startPosition.ToString(), FileLinePosition = LineNo.ToString() }); dataRow["IsValid"] = 0; } } } else { if (value.Length > startPosition) { dataRow[field.FieldName] = value.Substring(startPosition - 1); if (field.IsRequired == "Yes") { if (value.Substring(startPosition - 1).Trim().Length <= 0) { fileErrors.Add(new FileError() { FieldName = field.FieldName, StartingPostiton = startPosition.ToString(), FileLinePosition = LineNo.ToString() }); dataRow["IsValid"] = 0; } } break; } } startPosition += fieldLength; } dtPayerDataTable.Rows.Add(dataRow); } } if (fileErrors.Count > 0) { ErrorRecords.Append(value); } else { AcceptedRecords.Append(value); } LineNo += 1; } } LogFileDetails(fileErrors, blobName, PayerID); UploadBlob(fileErrors, ErrorRecords, AcceptedRecords, blobName, PayerID); SendEmail(blobName, PayerID); log.LogInformation(Newtonsoft.Json.JsonConvert.SerializeObject(fileErrors)); } } }
public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { string cashOrgMent = ""; //DbConnect db = new DbConnect(); //DButil dbutil = new DButil(); DButil.HistoryLog("db connect !! "); //HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); HttpResponseMessage response; Activity reply1 = activity.CreateReply(); Activity reply2 = activity.CreateReply(); Activity reply3 = activity.CreateReply(); Activity reply4 = activity.CreateReply(); // Activity 값 유무 확인하는 익명 메소드 Action <Activity> SetActivity = (act) => { if (!(reply1.Attachments.Count != 0 || reply1.Text != "")) { reply1 = act; } else if (!(reply2.Attachments.Count != 0 || reply2.Text != "")) { reply2 = act; } else if (!(reply3.Attachments.Count != 0 || reply3.Text != "")) { reply3 = act; } else if (!(reply4.Attachments.Count != 0 || reply4.Text != "")) { reply4 = act; } else { } }; if (activity.Type == ActivityTypes.ConversationUpdate && activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id)) { startTime = DateTime.Now; //activity.ChannelId = "facebook"; //파라메터 호출 if (LUIS_NM.Count(s => s != null) > 0) { //string[] LUIS_NM = new string[10]; Array.Clear(LUIS_NM, 0, LUIS_NM.Length); } if (LUIS_APP_ID.Count(s => s != null) > 0) { //string[] LUIS_APP_ID = new string[10]; Array.Clear(LUIS_APP_ID, 0, LUIS_APP_ID.Length); } //Array.Clear(LUIS_APP_ID, 0, 10); DButil.HistoryLog("db SelectConfig start !! "); List <ConfList> confList = db.SelectConfig(); DButil.HistoryLog("db SelectConfig end!! "); for (int i = 0; i < confList.Count; i++) { switch (confList[i].cnfType) { case "LUIS_APP_ID": LUIS_APP_ID[LUIS_APP_ID.Count(s => s != null)] = confList[i].cnfValue; LUIS_NM[LUIS_NM.Count(s => s != null)] = confList[i].cnfNm; break; case "LUIS_SUBSCRIPTION": LUIS_SUBSCRIPTION = confList[i].cnfValue; break; case "BOT_ID": BOT_ID = confList[i].cnfValue; break; case "MicrosoftAppId": MicrosoftAppId = confList[i].cnfValue; break; case "MicrosoftAppPassword": MicrosoftAppPassword = confList[i].cnfValue; break; case "LUIS_SCORE_LIMIT": LUIS_SCORE_LIMIT = confList[i].cnfValue; break; case "LUIS_TIME_LIMIT": LUIS_TIME_LIMIT = Convert.ToInt32(confList[i].cnfValue); break; default: //미 정의 레코드 Debug.WriteLine("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue); DButil.HistoryLog("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue); break; } } Debug.WriteLine("* DB conn : " + activity.Type); DButil.HistoryLog("* DB conn : " + activity.Type); //초기 다이얼로그 호출 DButil.HistoryLog("초기 인사말 시작 "); List <DialogList> dlg = db.SelectInitDialog(activity.ChannelId); ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); foreach (DialogList dialogs in dlg) { Activity initReply = activity.CreateReply(); initReply.Recipient = activity.From; initReply.Type = "message"; initReply.Attachments = new List <Attachment>(); //initReply.AttachmentLayout = AttachmentLayoutTypes.Carousel; Attachment tempAttachment; if (dialogs.dlgType.Equals(CARDDLG)) { foreach (CardList tempcard in dialogs.dialogCard) { tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity); initReply.Attachments.Add(tempAttachment); } } else { if (activity.ChannelId.Equals("facebook") && string.IsNullOrEmpty(dialogs.cardTitle) && dialogs.dlgType.Equals(TEXTDLG)) { Activity reply_facebook = activity.CreateReply(); reply_facebook.Recipient = activity.From; reply_facebook.Type = "message"; DButil.HistoryLog("facebook card Text : " + dialogs.cardText); reply_facebook.Text = dialogs.cardText; var reply_ment_facebook = connector.Conversations.SendToConversationAsync(reply_facebook); //SetActivity(reply_facebook); } else { tempAttachment = dbutil.getAttachmentFromDialog(dialogs, activity); initReply.Attachments.Add(tempAttachment); } } DButil.HistoryLog("초기 인사말 종료 "); await connector.Conversations.SendToConversationAsync(initReply); } //현재위치사용승인 테스트 //Activity replyLocation = activity.CreateReply(); //replyLocation.Recipient = activity.From; //replyLocation.Type = "message"; //replyLocation.Attachments = new List<Attachment>(); //replyLocation.AttachmentLayout = AttachmentLayoutTypes.Carousel; //replyLocation.Attachments.Add( // GetHeroCard_facebookMore( // "", "", // "현재 위치 사용 승인", // new CardAction(ActionTypes.ImBack, "현재 위치 사용 승인", value: MessagesController.queryStr)) //); //await connector.Conversations.SendToConversationAsync(replyLocation); DateTime endTime = DateTime.Now; Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds)); Debug.WriteLine("* activity.Type : " + activity.Type); Debug.WriteLine("* activity.Recipient.Id : " + activity.Recipient.Id); Debug.WriteLine("* activity.ServiceUrl : " + activity.ServiceUrl); DButil.HistoryLog("* activity.Type : " + activity.ChannelData); DButil.HistoryLog("* activity.Recipient.Id : " + activity.Recipient.Id); DButil.HistoryLog("* activity.ServiceUrl : " + activity.ServiceUrl); } else if (activity.Type == ActivityTypes.Message) { //activity.ChannelId = "facebook"; ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); try { Debug.WriteLine("* activity.Type == ActivityTypes.Message "); channelID = activity.ChannelId; string orgMent = activity.Text; //현재위치사용승인 if (orgMent.Contains("current location") || orgMent.Equals("현재위치사용승인")) { if (!orgMent.Contains(':')) { //첫번쨰 메세지 출력 x response = Request.CreateResponse(HttpStatusCode.OK); return(response); } else { //위도경도에 따른 값 출력 try { string location = orgMent.Replace("current location:", ""); //테스트용 //string location = "129.0929788:35.2686635"; string[] location_result = location.Split(':'); //regionStr = db.LocationValue(location_result[1], location_result[2]); DButil.HistoryLog("*regionStr : " + location_result[0] + " " + location_result[1]); Debug.WriteLine("*regionStr : " + location_result[0] + " " + location_result[1]); DButil.mapSave(location_result[0], location_result[1]); Activity reply_brach = activity.CreateReply(); reply_brach.Recipient = activity.From; reply_brach.Type = "message"; reply_brach.Attachments = new List <Attachment>(); reply_brach.AttachmentLayout = AttachmentLayoutTypes.Carousel; reply_brach.Attachments.Add( DButil.GetHeroCard_Map( "타이호인스트", "연락처", "주소", new CardImage(url: "https://nanetChatBot.azurewebsites.net/image/map/" + location_result[1] + "," + location_result[0] + ".png"), new CardAction(ActionTypes.OpenUrl, "타이호인스트", value: "http://www.taihoinst.com/"), location_result[1], location_result[0]) ); var reply_brach1 = await connector.Conversations.SendToConversationAsync(reply_brach); response = Request.CreateResponse(HttpStatusCode.OK); return(response); } catch { queryStr = "서울 시승센터"; } } } apiFlag = "COMMON"; //대화 시작 시간 startTime = DateTime.Now; long unixTime = ((DateTimeOffset)startTime).ToUnixTimeSeconds(); DButil.HistoryLog("orgMent : " + orgMent); //금칙어 체크 CardList bannedMsg = db.BannedChk(orgMent); Debug.WriteLine("* bannedMsg : " + bannedMsg.cardText);//해당금칙어에 대한 답변 if (bannedMsg.cardText != null) { Activity reply_ment = activity.CreateReply(); reply_ment.Recipient = activity.From; reply_ment.Type = "message"; reply_ment.Text = bannedMsg.cardText; var reply_ment_info = await connector.Conversations.SendToConversationAsync(reply_ment); response = Request.CreateResponse(HttpStatusCode.OK); return(response); } else { String checkBookIntent = ""; String checkIntent = ""; String bookName = ""; if (activity.Text.Contains("[") && activity.Text.Contains("]")) { int apiIntentS = activity.Text.IndexOf("["); int apiIntentE = activity.Text.IndexOf("]"); bookName = activity.Text.Substring(apiIntentS + 1, (apiIntentE - 1) - apiIntentS); Debug.WriteLine("bookName-------------" + bookName); } queryStr = orgMent; //인텐트 엔티티 검출 //캐시 체크 cashOrgMent = Regex.Replace(orgMent, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline); cacheList = db.CacheChk(cashOrgMent.Replace(" ", "")); // 캐시 체크 (TBL_QUERY_ANALYSIS_RESULT 조회..) Debug.WriteLine("smalltalk 로 intent 찾기"); String apiActiveText = Regex.Replace(activity.Text, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);//공백 및 특수문자 제거 Activity apiMakerReply = activity.CreateReply(); apiMakerReply.Recipient = activity.From; apiMakerReply.Type = "message"; apiMakerReply.Attachments = new List <Attachment>(); string smallTalkConfirm = ""; String sampleData = ""; /************************ * 임시로 책장보는 하드코딩 한다. *************************/ String bookData = "삼국지,조선왕조실록,90년생이온다,여행의이유,호모커넥서스,임나일본부해부"; String[] bookDataArray = bookData.Split(','); for (int i = 0; i < bookDataArray.Length; i++) { if (cashOrgMent.Contains(bookDataArray[i])) { checkBookIntent = "F_도서검색"; searchWord = bookDataArray[i]; } } //이용안내TIP if (apiActiveText.Equals("이용안내TIP")) { checkIntent = "F_이용안내TIP"; } else { if (checkBookIntent.Equals("") || checkBookIntent == null) { //checkIntent = db.getIntentFromSmallTalk(orgMent); String IntentDataFromRelation = db.getIntentDataFromRelation().Substring(1); String[] IntentDataFromRelationArray = IntentDataFromRelation.Split('%'); for (int j = 0; j < IntentDataFromRelationArray.Length; j++) { String[] checkData = IntentDataFromRelationArray[j].Split(':'); String intentString = checkData[0]; String EntityString = checkData[1]; if (EntityString.Contains(",")) { String[] checkEntityArray = EntityString.Split(','); for (int ii = 0; ii < checkEntityArray.Length; ii++) { if (apiActiveText.Contains(checkEntityArray[ii])) { checkIntent = intentString; break; } } } else { if (apiActiveText.Contains(EntityString)) { checkIntent = intentString; break; } } } } else { checkIntent = checkBookIntent; } } if (checkIntent.Equals("") || checkIntent == null) { relationList = null; //INTENT 가 없으니까 SORRY MESSAGE Activity sorryReply = activity.CreateReply(); string queryStr = activity.Text; queryStr = Regex.Replace(queryStr, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline); queryStr = queryStr.Replace(" ", "").ToLower(); sorryReply.Recipient = activity.From; sorryReply.Type = "message"; sorryReply.Attachments = new List <Attachment>(); //sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel; List <TextList> text = new List <TextList>(); List <CardAction> cardButtons = new List <CardAction>(); text = db.SelectSorryDialogText("5"); for (int i = 0; i < text.Count; i++) { UserHeroCard plCard = new UserHeroCard() { Title = text[i].cardTitle, Text = text[i].cardText, //Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); sorryReply.Attachments.Add(plAttachment); } SetActivity(sorryReply); //db.InsertError(activity.Conversation.Id, e.Message); DateTime endTime1 = DateTime.Now; int dbResult1 = db.insertUserQuery(null, "", "", "", "", "E", queryStr); //db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), "", "", "", "","E"); db.insertHistory(null, activity.Conversation.Id, activity.ChannelId, ((endTime1 - MessagesController.startTime).Milliseconds), "", "", "", "", "E", queryStr); } else if (checkIntent.Equals("F_도서검색")) { relationList = null; /************************************************************ * 네이버 API 적용 * ******************************************************/ if (apiActiveText.Contains("도서자료") && !string.IsNullOrEmpty(bookName)) { //bookName = System.Web.HttpUtility.UrlEncode(bookName); int currentPage = 1; if (queryStr.IndexOf("페이지") > 0) { string[] pageResult = queryStr.Split(' '); Debug.WriteLine(pageResult[1]); currentPage = Convert.ToInt32(Regex.Replace(pageResult[1], @"\D", "")); } string url = "https://openapi.naver.com/v1/search/book.json?query=" + System.Web.HttpUtility.UrlEncode(bookName) + "&display=10&start=" + currentPage + "&sort=sim"; //news JSON result //string blogUrl = "https://openapi.naver.com/v1/search/blog.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //search JSON result //string cafeUrl = "https://openapi.naver.com/v1/search/cafearticle.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //cafe JSON result //string url = "https://openapi.naver.com/v1/search/blog.xml?query=" + query; //blog XML result HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Headers.Add("X-Naver-Client-Id", "8V_GHk868_ggD3d1Kr7x"); request.Headers.Add("X-Naver-Client-Secret", "EUIOkjlFKX"); HttpWebResponse httpwebresponse = (HttpWebResponse)request.GetResponse(); string status = httpwebresponse.StatusCode.ToString(); if (status == "OK") { Stream stream = httpwebresponse.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.UTF8); string text = reader.ReadToEnd(); RootObject serarchList = JsonConvert.DeserializeObject <RootObject>(text); apiMakerReply.Attachments = new List <Attachment>(); apiMakerReply.AttachmentLayout = AttachmentLayoutTypes.Carousel; int searchTotal = 0; searchTotal = serarchList.total; Activity apiMakerReply1 = activity.CreateReply(); apiMakerReply1.Recipient = activity.From; apiMakerReply1.Type = "message"; apiMakerReply1.Attachments = new List <Attachment>(); UserHeroCard plCard1 = new UserHeroCard() { Title = "", Text = "도서자료 <strong>" + bookName + "</strong> 검색결과<br>검색건수 : " + searchTotal + "건" + " 현재페이지 : " + currentPage, }; Attachment plattachment1 = plCard1.ToAttachment(); apiMakerReply1.Attachments.Add(plattachment1); SetActivity(apiMakerReply1); for (int i = 0; i < serarchList.display; i++) { string searchTitle = ""; string searchSubTitle = ""; string searchText = ""; string searchImageUrl = ""; string searchAuthor = ""; string searchPublisher = ""; searchTitle = serarchList.items[i].title; searchAuthor = serarchList.items[i].author; searchPublisher = serarchList.items[i].publisher; searchImageUrl = serarchList.items[i].image; searchText = serarchList.items[i].description; searchImageUrl = serarchList.items[i].image; searchSubTitle = "저자 : " + searchAuthor + " | " + "출판사 : " + searchPublisher; List <CardImage> cardImages = new List <CardImage>(); CardImage img = new CardImage(); img.Url = searchImageUrl; cardImages.Add(img); List <CardAction> cardButtons = new List <CardAction>(); CardAction[] plButton = new CardAction[1]; plButton[0] = new CardAction() { Value = Regex.Replace(serarchList.items[i].link, "amp;", ""), Type = "openUrl", Title = "자세히보기" }; cardButtons = new List <CardAction>(plButton); LinkHeroCard card = new LinkHeroCard() { Title = searchTitle, Subtitle = searchSubTitle, Text = searchText, Images = cardImages, Buttons = cardButtons, //Link = Regex.Replace(serarchList.items[i].link, "amp;", "") Link = null }; var attachment = card.ToAttachment(); apiMakerReply.Attachments.Add(attachment); } //apiMakerReply.Attachments.Add(attachment); } SetActivity(apiMakerReply); Activity apiMakerReplyPageing = activity.CreateReply(); apiMakerReplyPageing.Recipient = activity.From; apiMakerReplyPageing.Type = "message"; apiMakerReplyPageing.Attachments = new List <Attachment>(); List <CardAction> cardPagingButtons = new List <CardAction>(); if (currentPage == 1) { int nextMovePage = currentPage + 1; CardAction plButtonPaging_new = new CardAction(); plButtonPaging_new = new CardAction() { Value = "도서자료[" + bookName + "] " + nextMovePage + "페이지로 이동", Type = "imBack", Title = "다음 페이지" }; cardPagingButtons.Add(plButtonPaging_new); } else { int nextMovePage = currentPage + 1; int preMovePage = currentPage - 1; CardAction[] plButtonPaging_new = new CardAction[2]; for (int pageCnt = 0; pageCnt < 2; pageCnt++) { if (pageCnt == 0) { plButtonPaging_new[pageCnt] = new CardAction() { Value = "도서자료[" + bookName + "] " + preMovePage + "페이지로 이동", Type = "imBack", Title = "이전 페이지" }; } else { plButtonPaging_new[pageCnt] = new CardAction() { Value = "도서자료[" + bookName + "] " + nextMovePage + "페이지로 이동", Type = "imBack", Title = "다음 페이지" }; } cardPagingButtons.Add(plButtonPaging_new[pageCnt]); } } //cardPagingButtons = new List<CardAction>(plButtonPaging); //cardPagingButtons.Add(plButtonPaging); UserHeroCard plCardPageing = new UserHeroCard() { Title = null, Text = "다음 페이지로 이동합니다.", Buttons = cardPagingButtons }; Attachment plAttachmentPageing = plCardPageing.ToAttachment(); apiMakerReplyPageing.Attachments.Add(plAttachmentPageing); SetActivity(apiMakerReplyPageing); } else { List <CardAction> cardButtons = new List <CardAction>(); CardAction bookButton1 = new CardAction(); bookButton1 = new CardAction() { Type = "imBack", Value = "전체자료[" + searchWord + "]", Title = "전체자료(30건)" }; cardButtons.Add(bookButton1); CardAction bookButton2 = new CardAction(); bookButton2 = new CardAction() { Type = "imBack", Value = "학위논문[" + searchWord + "]", Title = "학위논문(0건)" }; cardButtons.Add(bookButton2); CardAction bookButton3 = new CardAction(); bookButton3 = new CardAction() { Type = "imBack", Value = "특종기사[" + searchWord + "]", Title = "특종기사(21건)" }; cardButtons.Add(bookButton3); CardAction bookButton4 = new CardAction(); bookButton4 = new CardAction() { Type = "imBack", Value = "도서자료[" + searchWord + "]", Title = "도서자료(7건)" }; cardButtons.Add(bookButton4); CardAction bookButton5 = new CardAction(); bookButton5 = new CardAction() { Type = "imBack", Value = "인터넷자료[" + searchWord + "]", Title = "인터넷자료(2건)" }; cardButtons.Add(bookButton5); UserHeroCard plCard = new UserHeroCard() { Title = "", Text = "아래와 같이 자료에 대해서 알려 드릴 수 있습니다.", Buttons = cardButtons, }; Attachment plAttachment = plCard.ToAttachment(); apiMakerReply.Attachments.Add(plAttachment); SetActivity(apiMakerReply); } } else if (checkIntent.Equals("F_이용안내TIP")) { relationList = null; UserHeroCard plCard = new UserHeroCard() { Title = "NALI 이용안내", Text = "1. 대화예시문<br>저자 검색 :<br>예시)<br> 박경리가 쓴 책을 알려줘<br> 저자 박경리 검색해줘<br>자료명 검색 :<br> 예시)<br> 삼국지 검색해줘<br> 수호지 찾아줘<br><br> 2. 결과내 검색<br> 검색 후 결과내 검색을 클릭 후 검색하시면 됩니다.<br><br> 3. 결과 더 보기<br> 결과 더보기를 클릭하시면 전체 검색결과를 확인 할 수 있습니다.", }; Attachment plAttachment = plCard.ToAttachment(); apiMakerReply.Attachments.Add(plAttachment); SetActivity(apiMakerReply); } else { relationList = db.DefineTypeChkSpare(checkIntent, luisEntities); } DButil.HistoryLog("luisId : " + luisId); DButil.HistoryLog("luisIntent : " + luisIntent); DButil.HistoryLog("luisEntities : " + luisEntities); if (relationList != null) { dlgId = ""; for (int m = 0; m < relationList.Count; m++) { DialogList dlg = db.SelectDialog(relationList[m].dlgId, "MOBILE"); dlgId += Convert.ToString(dlg.dlgId) + ","; Activity commonReply = activity.CreateReply(); Attachment tempAttachment = new Attachment(); DButil.HistoryLog("dlg.dlgType : " + dlg.dlgType); if (dlg.dlgType.Equals(CARDDLG)) { foreach (CardList tempcard in dlg.dialogCard) { tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity); if (tempAttachment != null) { commonReply.Attachments.Add(tempAttachment); } //2018-04-19:KSO:Carousel 만드는부분 추가 if (tempcard.card_order_no > 1) { commonReply.AttachmentLayout = AttachmentLayoutTypes.Carousel; } } } else { //DButil.HistoryLog("* facebook dlg.dlgId : " + dlg.dlgId); DButil.HistoryLog("* activity.ChannelId : " + activity.ChannelId); tempAttachment = dbutil.getAttachmentFromDialog(dlg, activity); commonReply.Attachments.Add(tempAttachment); } if (commonReply.Attachments.Count > 0) { SetActivity(commonReply); replyresult = "H"; } } } //SMALLTALK 확인 else if (!string.IsNullOrEmpty(smallTalkConfirm)) { Debug.WriteLine("smalltalk dialogue-------------"); Random rand = new Random(); //SMALLTALK 구분 string[] smallTalkConfirm_result = smallTalkConfirm.Split('$'); int smallTalkConfirmNum = rand.Next(0, smallTalkConfirm_result.Length); Activity smallTalkReply = activity.CreateReply(); smallTalkReply.Recipient = activity.From; smallTalkReply.Type = "message"; smallTalkReply.Attachments = new List <Attachment>(); HeroCard plCard = new HeroCard() { Title = "", Text = smallTalkConfirm_result[smallTalkConfirmNum] }; Attachment plAttachment = plCard.ToAttachment(); smallTalkReply.Attachments.Add(plAttachment); SetActivity(smallTalkReply); replyresult = "S"; } else { } DateTime endTime = DateTime.Now; int dbResult = db.insertUserQuery(relationList, luisId, luisIntent, luisEntities, luisIntentScore, replyresult, orgMent); db.insertHistory(null, activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), luisIntent, luisEntities, luisIntentScore, dlgId, replyresult, orgMent); replyresult = ""; luisIntent = ""; } } catch (Exception e) { Debug.Print(e.StackTrace); DButil.HistoryLog("ERROR===" + e.Message); Activity sorryReply = activity.CreateReply(); string queryStr = activity.Text; queryStr = Regex.Replace(queryStr, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline); queryStr = queryStr.Replace(" ", "").ToLower(); sorryReply.Recipient = activity.From; sorryReply.Type = "message"; sorryReply.Attachments = new List <Attachment>(); //sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel; List <TextList> text = new List <TextList>(); List <CardAction> cardButtons = new List <CardAction>(); text = db.SelectSorryDialogText("5"); for (int i = 0; i < text.Count; i++) { UserHeroCard plCard = new UserHeroCard() { Title = text[i].cardTitle, Text = text[i].cardText, //Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); sorryReply.Attachments.Add(plAttachment); } SetActivity(sorryReply); //db.InsertError(activity.Conversation.Id, e.Message); DateTime endTime = DateTime.Now; int dbResult = db.insertUserQuery(null, "", "", "", "", "E", queryStr); //db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), "", "", "", "","E"); db.insertHistory(null, activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), "", "", "", "", "E", queryStr); } finally { if (reply1.Attachments.Count != 0 || reply1.Text != "") { await connector.Conversations.SendToConversationAsync(reply1); } if (reply2.Attachments.Count != 0 || reply2.Text != "") { await connector.Conversations.SendToConversationAsync(reply2); } if (reply3.Attachments.Count != 0 || reply3.Text != "") { await connector.Conversations.SendToConversationAsync(reply3); } if (reply4.Attachments.Count != 0 || reply4.Text != "") { await connector.Conversations.SendToConversationAsync(reply4); } } } else { HandleSystemMessage(activity); } response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
private void ParseAdditionalMetadata <T>(MetadataResult <T> itemResult, RootObject result) where T : BaseItem { var item = itemResult.Item; var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport; // Grab series genres because IMDb data is better than TVDB. Leave movies alone // But only do it if English is the preferred language because this data will not be localized if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre)) { item.Genres = Array.Empty <string>(); foreach (var genre in result.Genre .Split(',', StringSplitOptions.RemoveEmptyEntries) .Select(i => i.Trim()) .Where(i => !string.IsNullOrWhiteSpace(i))) { item.AddGenre(genre); } } if (isConfiguredForEnglish) { // Omdb is currently English only, so for other languages skip this and let secondary providers fill it in item.Overview = result.Plot; } if (!Plugin.Instance.Configuration.CastAndCrew) { return; } if (!string.IsNullOrWhiteSpace(result.Director)) { var person = new PersonInfo { Name = result.Director.Trim(), Type = PersonType.Director }; itemResult.AddPerson(person); } if (!string.IsNullOrWhiteSpace(result.Writer)) { var person = new PersonInfo { Name = result.Writer.Trim(), Type = PersonType.Writer }; itemResult.AddPerson(person); } if (!string.IsNullOrWhiteSpace(result.Actors)) { var actorList = result.Actors.Split(','); foreach (var actor in actorList) { if (!string.IsNullOrWhiteSpace(actor)) { var person = new PersonInfo { Name = actor.Trim(), Type = PersonType.Actor }; itemResult.AddPerson(person); } } } }
public async void ClickedNext() { OpentdbParams opentdbParams = new OpentdbParams(); if (SelectedCategoryIndex > 0) { opentdbParams.Category = "&category=" + (SelectedCategoryIndex + 8); } else { opentdbParams.Category = ""; } if (SelectedDifficulty == null || SelectedDifficulty.Equals("All difficulties", StringComparison.Ordinal)) { opentdbParams.Difficulty = ""; } else { opentdbParams.Difficulty = "&difficulty=" + SelectedDifficulty.ToLower(new CultureInfo("en-Us", false)); } if (SelectedAmount == 0) { opentdbParams.Amount = "&amount=3"; } else { opentdbParams.Amount = "&amount=" + selectedAmount; } RootObject rootObject = await ExternalRequest.GetQuizzesFromExternal(opentdbParams).ConfigureAwait(true); if (rootObject == null) { DisplayErrorMessageAsync("Didn't find enough quizzes to match your request!"); return; } Quiz quiz = new Quiz(); quiz.QuizName = SelectedCategoryItem + " Quiz"; quiz.QuizCategory = SelectedCategoryItem; foreach (var opentdbQuestion in rootObject.results) { Question question = new Question(); question.QuestionText = System.Web.HttpUtility.HtmlDecode(opentdbQuestion.question); question.CorrectAnswerNumber = 1; question.AnswersList.Add(new Answer(System.Web.HttpUtility.HtmlDecode(opentdbQuestion.correct_answer), question, 1, 0)); int i = 2; foreach (var answer in opentdbQuestion.incorrect_answers) { question.AnswersList.Add(new Answer(System.Web.HttpUtility.HtmlDecode(answer), question, i++, 0)); } quiz.QuestionList.Add(question); } QuizCompletionParams q = new QuizCompletionParams(); q.Quiz = quiz; q.QuestionToHandle = 1; if (quiz.QuestionList.Count == 0) { DisplayErrorMessageAsync("Didn't find enough quizzes to match your request!"); return; } foreach (var question in quiz.QuestionList) { ScrambleAnswers(question); } NavigationService.Navigate(typeof(TakeQuiz), q); }
/// <summary> /// JsonParse - Takes in the JSON string and deserialises it based on the RootObject. /// </summary> /// <param name="jsonString">the JSON string</param> /// <returns>Deserialized root object</returns> public static RootObject JsonParse(string jsonString) { RootObject ImageText = Newtonsoft.Json.JsonConvert.DeserializeObject <RootObject>(jsonString); return(ImageText); }
public void LoadEvaluationsAdvance( long idCall, EvaluationType type, Int32 idCommunity, long idCommission, dtoEvaluationsFilters filters, int pageIndex, int pageSize, CallForPaperType CpType) { Boolean allowManage = true; View.CurrentFilters = filters; ModuleCallForPaper module = Service.CallForPaperServicePermission(UserContext.CurrentUserID, idCommunity); allowManage = (module.CreateCallForPaper || module.Administration || module.ManageCallForPapers || module.EditCallForPaper); bool IsPresident = ServiceCall.CommissionUserIsPresident(idCommission, UserContext.CurrentUserID); bool IsSecretary = ServiceCall.CommissionUserIsSecretary(idCommission, UserContext.CurrentUserID); allowManage |= IsPresident | IsSecretary; //E controllo sui membri della commissione! View.SetActionUrl((allowManage) ? CallStandardAction.Manage : CallStandardAction.List, RootObject.ViewCalls(idCall, CpType, ((allowManage) ? CallStandardAction.Manage : CallStandardAction.List), idCommunity, View.PreloadView)); if (UserContext.isAnonymous) { View.DisplaySessionTimeout(); } else if (allowManage) { LoadItemsAdv(idCall, type, idCommunity, idCommission, filters, pageIndex, pageSize); } else { View.DisplayNoPermission(idCommunity, View.IdCallModule); } }
static void Main(string[] args) { var client = new RestClient("http://ae.integration.operando.esilab.org:8092/operando/core/ae/personaldata/search"); RootObject myObj = new RootObject(); myObj.requesterId = "1"; myObj.query = "SELECT DISTINCT`operando_personaldatadb`.`occupation`.`DESCRIPTION_0` AS `OCCUPATION`,`operando_personaldatadb`.`salary_class`.`DESCRIPTION_0` AS `SALARY_CLASS`,`operando_personaldatadb`.`genders`.`DESCRIPTION_0` AS `GENDER`,`operando_personaldatadb`.`education`.`DESCRIPTION_0` AS `EDUCATION`,`operando_personaldatadb`.`countries`.`DESCRIPTION_0` AS `COUNTRY`,`operando_personaldatadb`.`race`.`DESCRIPTION_0` AS `RACE`,`operando_personaldatadb`.`generic_personal_data`.`EMAIL_ADDRESS` AS `EMAIL_ADDRESS`,`operando_personaldatadb`.`generic_personal_data`.`CELL_PHONE_NUMBER` AS `CELL_PHONE_NUMBER`,`operando_personaldatadb`.`generic_personal_data`.`SURNAME` AS `SURNAME`,`operando_personaldatadb`.`generic_personal_data`.`NUMBER_OF_CHILDREN` AS `NUMBER_OF_CHILDREN`,`operando_personaldatadb`.`generic_personal_data`.`RESIDENCE_POST_CODE` AS `RESIDENCE_POST_CODE`,`operando_personaldatadb`.`generic_personal_data`.`NAME` AS `NAME`,`operando_personaldatadb`.`generic_personal_data`.`IDENTIFICATION_NUMBER` AS `IDENTIFICATION_NUMBER`,`operando_personaldatadb`.`generic_personal_data`.`DATE_OF_BIRTH` AS `DATE_OF_BIRTH`,`operando_personaldatadb`.`generic_personal_data`.`SSN` AS `SSN`,`operando_personaldatadb`.`marital_status`.`DESCRIPTION_0` AS `MARITAL_STATUS`,`operando_personaldatadb`.`work_class`.`DESCRIPTION_0` AS `WORK_CLASS`FROM ((((((((`operando_personaldatadb`.`occupation` JOIN `operando_personaldatadb`.`salary_class`) JOIN `operando_personaldatadb`.`genders`) JOIN `operando_personaldatadb`.`education`) JOIN `operando_personaldatadb`.`countries`) JOIN `operando_personaldatadb`.`race`) JOIN `operando_personaldatadb`.`generic_personal_data` ON (( (`operando_personaldatadb`.`occupation`.`ID` = `operando_personaldatadb`.`generic_personal_data`.`OCCUPATION_ID`) AND (`operando_personaldatadb`.`salary_class`.`ID` = `operando_personaldatadb`.`generic_personal_data`.`SALARY_CLASS_ID`) AND (`operando_personaldatadb`.`genders`.`ID` = `operando_personaldatadb`.`generic_personal_data`.`GENDER_ID`) AND (`operando_personaldatadb`.`education`.`ID` =`operando_personaldatadb`.`generic_personal_data`.`EDUCATION_ID`) AND (`operando_personaldatadb`.`countries`.`ID` = `operando_personaldatadb`.`generic_personal_data`.`NATIVE_COUNTRY_ID`) AND (`operando_personaldatadb`.`race`.`ID` = `operando_personaldatadb`.`generic_personal_data`.`RACE_ID`)))) JOIN `operando_personaldatadb`.`marital_status` ON ((`operando_personaldatadb`.`marital_status`.`ID` = `operando_personaldatadb`.`generic_personal_data`.`MARITAL_STATUS_ID`)))JOIN `operando_personaldatadb`.`work_class`ON ((`operando_personaldatadb`.`work_class`.`ID` = `operando_personaldatadb`.`generic_personal_data`.`WORK_CLASS_ID`)))"; myObj.queryName = "personalData"; myObj.dataTypeMap = "{\"MARITAL_STATUS\":\"String\",\"NAME\":\"String\",\"SURNAME\":\"String\",\"OCCUPATION\":\"String\",\"NUMBER_OF_CHILDREN\":\"Integer\",\"COUNTRY\":\"String\",\"SALARY_CLASS\":\"String\",\"WORK_CLASS\":\"String\",\"GENDER\":\"String\",\"DATE_OF_BIRTH\":\"String\",\"IDENTIFICATION_NUMBER\":\"String\",\"EDUCATION\":\"String\",\"CELL_PHONE_NUMBER\":\"String\",\"RACE\":\"String\",\"EMAIL_ADDRESS\":\"String\"}"; myObj.attributeTypeMap = "{\"MARITAL_STATUS\":\"INSENSITIVE_ATTRIBUTE\",\"NAME\":\"IDENTIFYING_ATTRIBUTE\",\"SURNAME\":\"IDENTIFYING_ATTRIBUTE\",\"OCCUPATION\":[[\"Tech-suppo\",\"Technical\",\"*\\r\"],[\"Craft-repa\",\"Technical\",\"*\\r\"],[\"Other-serv\",\"Other\",\"*\\r\"],[\"Sales\",\"Nontechnic\",\"*\\r\"],[\"Exec-manag\",\"Nontechnic\",\"*\\r\"],[\"Prof-speci\",\"Technical\",\"*\\r\"],[\"Handlers-c\",\"Nontechnic\",\"*\\r\"],[\"Machine-op\",\"Technical\",\"*\\r\"],[\"Adm-cleric\",\"Other\",\"*\\r\"],[\"Farming-fi\",\"Other\",\"*\\r\"],[\"Transport-\",\"Other\",\"*\\r\"],[\"Priv-house\",\"Other\",\"*\\r\"],[\"Protective\",\"Other\",\"*\\r\"],[\"Armed-Forc\",\"Other\",\"*\\r\"]],\"NUMBER_OF_CHILDREN\":\"INSENSITIVE_ATTRIBUTE\",\"COUNTRY\":[[\"United-States\",\"North America\",\"*\\r\"],[\"Cambodia\",\"Asia\",\"*\\r\"],[\"England\",\"Europa\",\"*\\r\"],[\"Puerto-Rico\",\"North America\",\"*\\r\"],[\"Canada\",\"North America\",\"*\\r\"],[\"Germany\",\"Europe\",\"*\\r\"],[\"Outlying-US(Guam-USVI-etc)\",\"North America\",\"*\\r\"],[\"India\",\"Asia\",\"*\\r\"],[\"Japan\",\"Asia\",\"*\\r\"],[\"Greece\",\"Europe\",\"*\\r\"],[\"South\",\"Africa\",\"*\\r\"],[\"China\",\"Asia\",\"*\\r\"],[\"Cuba\",\"North America\",\"*\\r\"],[\"Iran\",\"Asia\",\"*\\r\"],[\"Honduras\",\"North America\",\"*\\r\"],[\"Philippines\",\"Asia\",\"*\\r\"],[\"Italy\",\"Europe\",\"*\\r\"],[\"Poland\",\"Europe\",\"*\\r\"],[\"Jamaica\",\"North America\",\"*\\r\"],[\"Vietnam\",\"Asia\",\"*\\r\"],[\"Mexico\",\"North America\",\"*\\r\"],[\"Portugal\",\"Europe\",\"*\\r\"],[\"Ireland\",\"Europe\",\"*\\r\"],[\"France\",\"Europe\",\"*\\r\"],[\"Dominican-Republic\",\"North America\",\"*\\r\"],[\"Laos\",\"Asia\",\"*\\r\"],[\"Ecuador\",\"South America\",\"*\\r\"],[\"Taiwan\",\"Asia\",\"*\\r\"],[\"Haiti\",\"North America\",\"*\\r\"],[\"Columbia\",\"South America\",\"*\\r\"],[\"Hungary\",\"Europe\",\"*\\r\"],[\"Guatemala\",\"North America\",\"*\\r\"],[\"Nicaragua\",\"South America\",\"*\\r\"],[\"Scotland\",\"Europe\",\"*\\r\"],[\"Thailand\",\"Asia\",\"*\\r\"],[\"Yugoslavia\",\"Europe\",\"*\\r\"],[\"El-Salvador\",\"North America\",\"*\\r\"],[\"Trinadad&Tobago\",\"South America\",\"*\\r\"],[\"Peru\",\"South America\",\"*\\r\"],[\"Hong\",\"Asia\",\"*\\r\"],[\"Holand-Netherlands\",\"Europe\",\"*\\r\"]],\"SALARY_CLASS\":[[\"<=50K\",\"*\",\"*\"],[\">50K\",\"*\",\"*\"]],\"WORK_CLASS\":[[\"Private\",\"Non-Government\",\"*\\r\"],[\"Self-emp-not-inc\",\"Non-Government\",\"*\\r\"],[\"Self-emp-inc\",\"Non-Government\",\"*\\r\"],[\"Federal-gov\",\"Government\",\"*\\r\"],[\"Local-gov\",\"Government\",\"*\\r\"],[\"State-gov\",\"Government\",\"*\\r\"],[\"Without-pay\",\"Unemployed\",\"*\\r\"],[\"Never-worked\",\"Unemployed\",\"*\\r\"]],\"GENDER\":\"INSENSITIVE_ATTRIBUTE\",\"DATE_OF_BIRTH\":\"IDENTIFYING_ATTRIBUTE\",\"IDENTIFICATION_NUMBER\":\"IDENTIFYING_ATTRIBUTE\",\"EDUCATION\":[[\"Bachelors\",\"Undergraduate\",\"Higher education\"],[\"Some-college\",\"Undergraduate\",\"Higher education\"],[\"11th\",\"High School\",\"Secondary education\"],[\"HS-grad\",\"High School\",\"Secondary education\"],[\"Prof-school\",\"Professional Education\",\"Higher education\"],[\"Assoc-acdm\",\"Professional Education\",\"Higher education\"],[\"Assoc-voc\",\"Professional Education\",\"Higher education\"],[\"9th\",\"High School\",\"Secondary education\"],[\"7th-8th\",\"High School\",\"Secondary education\"],[\"12th\",\"High School\",\"Secondary education\"],[\"Masters\",\"Graduate\",\"Higher education\"],[\"1st-4th\",\"Primary School\",\"Primary education\"],[\"10th\",\"High School\",\"Secondary education\"],[\"Doctorate\",\"Graduate\",\"Higher education\"],[\"5th-6th\",\"Primary School\",\"Primary education\"],[\"Preschool\",\"Primary School\",\"Primary education\"]],\"CELL_PHONE_NUMBER\":\"IDENTIFYING_ATTRIBUTE\",\"RACE\":\"INSENSITIVE_ATTRIBUTE\",\"EMAIL_ADDRESS\":\"IDENTIFYING_ATTRIBUTE\"}"; myObj.kanonymity = 2; string _myObj = JsonConvert.SerializeObject(myObj); var request = new RestRequest("", Method.POST); request.AddParameter("application/json", _myObj, ParameterType.RequestBody); request.AddHeader("cache-control", "no-cache"); request.AddHeader("content-type", "application/json"); request.AddHeader("postman-token", "efc35b48-6699-5666-afd5-aa226487a17a"); // execute the request IRestResponse response = client.Execute(request); var content = response.Content; // raw content as string //object value = JsonConvert.DeserializeObject(content); JToken token = JObject.Parse(content); string code = ""; string type = ""; string message = ""; code = (string)token.SelectToken("code"); type = (string)token.SelectToken("type"); message = (string)token.SelectToken("message"); Debug.Assert(code == "4", "Error code"); Debug.Assert(type == "ok", "Type Error"); String[] messageArray = message.Split(']'); for (int i = 0; i < messageArray.Length; i++) { messageArray[i] = messageArray[i].Replace("[", "").Replace("]", ""); } DataTable mytb = new DataTable("Dati"); String[] colonne = messageArray[0].Split(','); foreach (String item in colonne) { mytb.Columns.Add(item.Replace(" ", "")); } for (int i = 1; i < messageArray.Length; i++) { if (String.IsNullOrEmpty(messageArray[i])) { continue; } DataRow riga = mytb.NewRow(); String[] valori = messageArray[i].Split(','); for (int r = 0; r < colonne.Length; r++) { riga[r] = valori[r]; } mytb.Rows.Add(riga); } }
public void InitView() { Boolean isAnonymousUser = UserContext.isAnonymous; long idCall = View.PreloadIdCall; Int32 idUser = UserContext.CurrentUserID; lm.Comol.Modules.CallForPapers.Domain.CallForPaperType type = ServiceCall.GetCallType(idCall); int idModule = (type == CallForPaperType.CallForBids) ? ServiceCall.ServiceModuleID() : ServiceRequest.ServiceModuleID(); dtoCall call = (type == CallForPaperType.CallForBids) ? ServiceCall.GetDtoCall(idCall) : null; if (call != null) { View.SetContainerName(call.Name, call.EndEvaluationOn); } int idCommunity = GetCurrentCommunity(call); View.IdCall = idCall; View.IdCallModule = idModule; View.IdCallCommunity = idCommunity; View.CallType = type; ModuleCallForPaper module = ServiceCall.CallForPaperServicePermission(idUser, idCommunity); Boolean allowAdmin = ((module.ManageCallForPapers || module.Administration || ((module.CreateCallForPaper || module.EditCallForPaper) && call.Owner.Id == idUser))); View.SetActionUrl((allowAdmin) ? CallStandardAction.Manage : CallStandardAction.List, RootObject.ViewCalls(idCall, type, ((allowAdmin) ? CallStandardAction.Manage : CallStandardAction.List), idCommunity, View.PreloadView)); if (UserContext.isAnonymous) { View.DisplaySessionTimeout(RootObject.EvaluationsSummary(idCall, idCommunity, View.PreloadView, 0, View.PreloadIdSubmitterType, View.PreloadFilterBy, View.PreloadOrderBy, View.PreloadAscending, View.PreloadPageIndex, View.PreloadPageSize, View.GetItemEncoded(View.PreloadSearchForName))); } else if (call == null) { View.DisplayUnknownCall(idCommunity, idModule, idCall); } else if (type == CallForPaperType.RequestForMembership) { View.DisplayEvaluationUnavailable(); } else if (allowAdmin) { // //EvaluationType EvalType = (call.AdvacedEvaluation) ? // ServiceCall.CommissionGetEvalType(idCommission): // call.EvaluationType; //EvaluationType EvalType = call.EvaluationType; //call.EvaluationType; if (call.EvaluationType == EvaluationType.Dss) { View.CallUseFuzzy = Service.CallUseFuzzy(idCall); } View.AllowExportAll = Service.HasEvaluations(idCall); View.DisplayEvaluationInfo(call.EndEvaluationOn); if (!call.AdvacedEvaluation) { View.CurrentEvaluationType = call.EvaluationType; InitializeView(idCall, call.EvaluationType, idCommunity, View.PreloadFilters); View.SetStepSummaryLink(0, 0, false); } } if (call.AdvacedEvaluation) { long idCommission = View.IdCallAdvCommission; long StepId = ServiceCall.StepGetIdFromComm(idCommission); bool ShowGenericLink = ServiceCall.CommissionUserIsPresidentOrSegretaryInMaster(idCommission, UserContext.CurrentUserID); View.SetStepSummaryLink(StepId, idCommission, ShowGenericLink); EvaluationType oldEvtype = EvaluationType.Average; Advanced.dto.dtoCommEvalInfo evinfo = ServiceCall.CommissionEvalTypeGet(idCommission); switch (evinfo.Type) { case Advanced.EvalType.Average: oldEvtype = EvaluationType.Average; break; case Advanced.EvalType.Sum: oldEvtype = EvaluationType.Sum; break; } View.CurrentEvaluationType = (evinfo.Type == Advanced.EvalType.Sum) ? EvaluationType.Sum : EvaluationType.Average; View.minRange = evinfo.minRange; View.LockBool = evinfo.LockBool; bool cancloseAdvance = ServiceCall.CommissionCanClose(idCommission); View.ShowCloseCommission(cancloseAdvance); InitializeViewAvance(idCall, oldEvtype, idCommunity, idCommission, View.PreloadFilters, call.Type); } }
public override void OnCreate() { base.OnCreate(); json = new RootObject(); }
public PhpOutputFile(RootObject root, TemplateMeta meta) : base(root, meta) { }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int oid = !string.IsNullOrEmpty(Request.QueryString["pid"]) ? Convert.ToInt32(Request.QueryString["pid"].ToString()) : 0; //订单表ID string code = !string.IsNullOrEmpty(Request.QueryString["code"]) ? Request.QueryString["code"] : ""; string UserId = ""; string UserKey = ""; string appid = ""; string appms = ""; if (!String.IsNullOrEmpty(code) && oid > 0) { string json = ""; string str = ""; string openid = ""; //System.Threading.Thread.Sleep(new Random().Next(100, 500)); JMP.MDL.jmp_order morder = new JMP.BLL.jmp_order().SelectOrderGoodsName(oid, "jmp_order"); if (JMP.TOOL.CacheHelper.IsCache(morder.o_code) == false) { string ddjj = Get_paystr(morder.o_interface_id.ToString()); UserId = ddjj.ToString().Split(',')[0]; UserKey = ddjj.ToString().Split(',')[1]; appid = ddjj.ToString().Split(',')[2]; appms = ddjj.ToString().Split(',')[3]; string URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appms + "&code=" + code + "&grant_type=authorization_code"; Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Timeout = 3000; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8)) { string jmpay = reader.ReadToEnd(); //解析json对象 JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary <string, object> jsonstr = (Dictionary <string, object>)serializer.DeserializeObject(jmpay); object value = null; jsonstr.TryGetValue("openid", out value); openid = value.ToString(); } string xml = "<?xml version='1.0' encoding='utf-8' ?><ORDER_REQ><BUSI_ID>" + UserId + "</BUSI_ID><OPER_ID>oper01</OPER_ID><DEV_ID>dev01</DEV_ID><AMT>" + morder.o_price + "</AMT><CHANNEL_TYPE>2</CHANNEL_TYPE><TRADE_TYPE>JSAPI</TRADE_TYPE><subAppid>" + appid + "</subAppid><subOpenid>" + openid + "</subOpenid><PAY_SUBJECT>" + morder.o_goodsname + "</PAY_SUBJECT ><CHARGE_CODE>" + morder.o_code + "</CHARGE_CODE><NODIFY_URL>" + ConfigurationManager.AppSettings["pfalpayNotifyUrl"].ToString().Replace("{0}", morder.o_interface_id.ToString()) + "</NODIFY_URL></ORDER_REQ>"; string timestamp = JMP.TOOL.WeekDateTime.GetMilis;//时间戳 string signstr = timestamp + UserKey + xml.Replace(" ", ""); string sign = JMP.TOOL.MD5.md5strGet(signstr, true).ToLower() + ":" + timestamp;; string url = ConfigurationManager.AppSettings["pfalpayPostUrl"].ToString() + "?sign=" + sign + "&_type=json&busiCode=" + UserId; json = JMP.TOOL.postxmlhelper.postxml(url, xml); JMP.TOOL.CacheHelper.CacheObject(morder.o_code, json, 1);//存入缓存 } else { json = JMP.TOOL.CacheHelper.GetCaChe <string>(morder.o_code); } RootObject obj = new RootObject(); obj = JMP.TOOL.JsonHelper.Deserializes <RootObject>(json); if (obj != null && obj.ORDER_RESP.RESULT.CODE == "SUCCESS") { if (string.IsNullOrEmpty(morder.o_showaddress)) { morder.o_showaddress = ConfigurationManager.AppSettings["succeed"].ToString(); } string chengstr = "<script src=\"http://res.wx.qq.com/open/js/jweixin-1.2.0.js\"></script><script type=\"text/javascript\">function onBridgeReady(){WeixinJSBridge.invoke( 'getBrandWCPayRequest', {\"appId\": \"" + obj.ORDER_RESP.appId + "\", \"timeStamp\": \"" + obj.ORDER_RESP.timeStamp + "\", \"nonceStr\": \"" + obj.ORDER_RESP.nonceStr + "\",\"package\":\"" + obj.ORDER_RESP.packageData + "\",\"signType\": \"MD5\",\"paySign\": \"" + obj.ORDER_RESP.sign + "\" },function(res) {if (res.err_msg ==\"get_brand_wcpay_request:ok\") { window.location.href=\"" + morder.o_showaddress + "\" }else{ alert(res.err_msg) } });}if (typeof WeixinJSBridge == \"undefined\"){if (document.addEventListener){document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);}else if (document.attachEvent){document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);} }else{onBridgeReady();}</script> "; Response.Write(chengstr); } else { PayApiDetailErrorLogger.UpstreamPaymentErrorLog("浦发银行公众号支付失败信息:" + json, channelId: oid); str = "{\"Message\":\"支付通道异常\",\"ErrorCode\":104}"; Response.Write(str); } } else { Response.Write("非法访问!"); } } }
public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, System.Net.HttpListenerRequest request, out System.Security.Claims.Claim[] claims) { claims = null; IAdapterPresentation result = null; string userName = proofData.Properties["upn"].ToString(); string pin = proofData.Properties["pin"].ToString(); string pollingEndpoint = proofData.Properties["pollingEndpoint"].ToString(); string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config"; System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value; string authToken = cfg.AppSettings.Settings["apiKey"].Value; string baseUrl = oktaTenant + "/api/v1/"; string pinSuccess = "no"; string verifyResult = "false"; HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userName); upnRequest.Headers.Add("Authorization", authToken); upnRequest.Method = "GET"; upnRequest.ContentType = "application/json"; var upnResponse = (HttpWebResponse)upnRequest.GetResponse(); var idReader = new StreamReader(upnResponse.GetResponseStream()); var id = idReader.ReadToEnd(); RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id); string userID = userProfile.id.ToString(); HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors"); factorRequest.Headers.Add("Authorization", authToken); factorRequest.Method = "GET"; factorRequest.ContentType = "application/json"; factorRequest.Accept = "application/json"; var factorResponse = (HttpWebResponse)factorRequest.GetResponse(); var factorReader = new StreamReader(factorResponse.GetResponseStream()); var factorList = factorReader.ReadToEnd(); RootObject[] factors = JsonConvert.DeserializeObject <RootObject[]>(factorList); string factorID = ""; foreach (RootObject factor in factors) { if (factor.provider == "OKTA" && factor.factorType == "push") { // string pushfactorID = factor.id; // HttpWebRequest pushRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + pushfactorID + "/verify"); // pushRequest.Headers.Add("Authorization", authToken); // pushRequest.Method = "POST"; // pushRequest.ContentType = "application/json"; // pushRequest.Accept = "application/json"; // pushRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"; // var pushResponse = (HttpWebResponse)pushRequest.GetResponse(); // var pushReader = new StreamReader(pushResponse.GetResponseStream()); // var pushStatus = pushReader.ReadToEnd(); // RootObject pushResult = JsonConvert.DeserializeObject<RootObject>(pushStatus); // string pollingEndpoint = pushResult._links.poll.href.ToString(); int attemptPoll = 1; while (verifyResult == "false" && attemptPoll <= 20 && pinSuccess == "no") { HttpWebRequest verifyRequest = (HttpWebRequest)WebRequest.Create(pollingEndpoint); verifyRequest.Headers.Add("Authorization", authToken); verifyRequest.Method = "GET"; verifyRequest.ContentType = "application/json"; verifyRequest.Accept = "application/json"; verifyRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"; var pushAnswer = (HttpWebResponse)verifyRequest.GetResponse(); var pushStatus2 = new StreamReader(pushAnswer.GetResponseStream()); var pushStatus3 = pushStatus2.ReadToEnd(); RootObject pushWait = JsonConvert.DeserializeObject <RootObject>(pushStatus3); if (pushWait.factorResult == "SUCCESS") { verifyResult = "true"; Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } else { attemptPoll++; } } return(result); } if (factor.provider == "OKTA" && factor.factorType == "token:software:totp" && verifyResult == "false" && pin != "") { factorID = factor.id; HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify"); httprequest.Headers.Add("Authorization", authToken); httprequest.Method = "POST"; httprequest.ContentType = "application/json"; otpCode otpCode = new otpCode { passCode = pin }; string otpString = JsonConvert.SerializeObject(otpCode); using (var streamWriter = new StreamWriter(httprequest.GetRequestStream())) { streamWriter.Write(otpString); } try { var httpResponse = (HttpWebResponse)httprequest.GetResponse(); if (httpResponse.StatusCode.ToString() == "OK" && pin != "") { pinSuccess = "yes"; Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } // using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) // { // var factorResult = streamReader.ReadToEnd(); // } } catch (WebException we) { var failResponse = we.Response as HttpWebResponse; if (failResponse == null) { throw; } result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false); } } } //HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify"); //httprequest.Headers.Add("Authorization", authToken); //httprequest.Method = "POST"; //httprequest.ContentType = "application/json"; //otpCode otpCode = new otpCode //{ passCode = pin }; //string otpString = JsonConvert.SerializeObject(otpCode); //using (var streamWriter = new StreamWriter(httprequest.GetRequestStream())) //{ // streamWriter.Write(otpString); //} //try //{ // var httpResponse = (HttpWebResponse)httprequest.GetResponse(); // if (httpResponse.StatusCode.ToString() == "OK") // { // System.Security.Claims.Claim claim = new System.Security.Claims.Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); // claims = new System.Security.Claims.Claim[] { claim }; // } // using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) // { // var factorResult = streamReader.ReadToEnd(); // } //} //catch (WebException we) //{ // var failResponse = we.Response as HttpWebResponse; // if (failResponse == null) // throw; // result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false); //} if (pinSuccess == "yes" || verifyResult == "true") { Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } else { result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false); } return(result); }
private void ParseAdditionalMetadata(BaseItem item, RootObject result) { // Grab series genres because imdb data is better than tvdb. Leave movies alone // But only do it if english is the preferred language because this data will not be localized if (ShouldFetchGenres(item) && !string.IsNullOrWhiteSpace(result.Genre) && !string.Equals(result.Genre, "n/a", StringComparison.OrdinalIgnoreCase)) { item.Genres.Clear(); foreach (var genre in result.Genre .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(i => i.Trim()) .Where(i => !string.IsNullOrWhiteSpace(i))) { item.AddGenre(genre); } } var hasMetascore = item as IHasMetascore; if (hasMetascore != null) { float metascore; if (!string.IsNullOrEmpty(result.Metascore) && float.TryParse(result.Metascore, NumberStyles.Any, _usCulture, out metascore) && metascore >= 0) { hasMetascore.Metascore = metascore; } } var hasAwards = item as IHasAwards; if (hasAwards != null && !string.IsNullOrEmpty(result.Awards) && !string.Equals(result.Awards, "n/a", StringComparison.OrdinalIgnoreCase)) { hasAwards.AwardSummary = WebUtility.HtmlDecode(result.Awards); } var hasShortOverview = item as IHasShortOverview; if (hasShortOverview != null) { // Imdb plots are usually pretty short hasShortOverview.ShortOverview = result.Plot; } }
public TunerResponse(Stream stream, IJsonSerializer json) { _root = json.DeserializeFromStream <RootObject>(stream); }
private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken) { PopulateImages(list, obj.hdtvlogo, ImageType.Logo, 800, 310); PopulateImages(list, obj.hdclearart, ImageType.Art, 1000, 562); PopulateImages(list, obj.clearlogo, ImageType.Logo, 400, 155); PopulateImages(list, obj.clearart, ImageType.Art, 500, 281); PopulateImages(list, obj.showbackground, ImageType.Backdrop, 1920, 1080, true); PopulateImages(list, obj.seasonthumb, ImageType.Thumb, 500, 281); PopulateImages(list, obj.tvthumb, ImageType.Thumb, 500, 281); PopulateImages(list, obj.tvbanner, ImageType.Banner, 1000, 185); PopulateImages(list, obj.tvposter, ImageType.Primary, 1000, 1426); }
public void Complex_JSON_objects_in_string_can_be_handled([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, RootObject test, [Frozen] IAmazonSecretsManager secretsManager, SecretsManagerConfigurationProvider sut, IFixture fixture) { var getSecretValueResponse = fixture.Build <GetSecretValueResponse>() .With(p => p.SecretString, JsonConvert.SerializeObject(test)) .Without(p => p.SecretBinary) .Create(); Mock.Get(secretsManager).Setup(p => p.ListSecretsAsync(It.IsAny <ListSecretsRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(listSecretsResponse); Mock.Get(secretsManager).Setup(p => p.GetSecretValueAsync(It.IsAny <GetSecretValueRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(getSecretValueResponse); sut.Load(); Assert.That(sut.Get(testEntry.Name, nameof(RootObject.Property)), Is.EqualTo(test.Property)); Assert.That(sut.Get(testEntry.Name, nameof(RootObject.Mid), nameof(MidLevel.Property)), Is.EqualTo(test.Mid.Property)); Assert.That(sut.Get(testEntry.Name, nameof(RootObject.Mid), nameof(MidLevel.Leaf), nameof(Leaf.Property)), Is.EqualTo(test.Mid.Leaf.Property)); }