// GET: Players public ActionResult GetChallengerPlayers() { long playerCount = 0; string apiKey = DataController.GameData.apiKey; foreach (string region in DataController.GameData.gameRegions) { string json = new WebClient().DownloadString("https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/challenger?type=RANKED_SOLO_5x5&api_key=" + apiKey); string JsonString = json.ToString(); JavaScriptSerializer serializer = new JavaScriptSerializer(); RootObject c = serializer.Deserialize <RootObject>(JsonString); foreach (Entry e in c.entries) { LoLPlayer p = new LoLPlayer { //playerOrTeamId = e.playerOrTeamId, //playerOrTeamName = e.playerOrTeamName, rank = "Challenger", region = region }; db.Players.Add(p); db.SaveChanges(); playerCount++; } } ViewBag.Count = playerCount; return(View()); }
// GET: Item public ActionResult AddItems() { int itemCount = 0; for (int z = 1001; z <= 4000; z++) { try { var json = new WebClient().DownloadString("https://global.api.pvp.net/api/lol/static-data/NA/v1.2/item/" + z.ToString() + "?api_key=RGAPI-bdeef08a-76db-47d5-b0e0-33fd0d9f34ff"); string JsonString = json.ToString(); JavaScriptSerializer serializer = new JavaScriptSerializer(); Item t = serializer.Deserialize <Item>(JsonString); db.Items.Add(t); db.SaveChanges(); itemCount++; } catch { } Thread.Sleep(1200); } ViewBag.AddCount = itemCount; return(View()); }
public string obtenerTipoCambio(string sMonedaBase, string sMonedaObjetivo) { string url = "https://free.currconv.com/api/v7/convert?q=" + sMonedaBase + "_" + sMonedaObjetivo + "&compact=ultra&apiKey=e9c22965a0221aae8dfe"; var json = new WebClient().DownloadString(url); string sJSon = json.ToString(); int pFrom = sJSon.IndexOf(":") + ":".Length; int pTo = sJSon.LastIndexOf("}"); String result = sJSon.Substring(pFrom, pTo - pFrom).Trim(); /* * string fecha = DateTime.Now.ToString("yyy/MM/dd"); * try * { * OdbcCommand sql = new OdbcCommand("INSERT INTO tbl_tipocambio VALUES ('" + sMonedaBase + "' ,'" + sMonedaObjetivo + "' , " + result + " , '" + + fecha + "')", conn.conexion("ERP")); + sql.ExecuteNonQuery(); + sql.Connection.Close(); + } + catch (Exception ex) + { + MessageBox.Show("No se pudo Obtener el Tipo de Cambio. \n\n Error: " + ex + "", "TIPO DE CAMBIO", MessageBoxButtons.OK, MessageBoxIcon.Error); + } */ return(result); }
private void prepareModelCollection() { var jsonString = new WebClient().DownloadString(url); stringSample = jsonString.ToString(); Models = JsonConvert.DeserializeObject <NewsModel>(jsonString); }
public IEnumerable <KeyValuePair <string, string> > MapIds(string dbNameFrom, string dbNameTo, string[] proteinIds, out string requestInfo) { var path = "uploadlists"; WebClient webClient = new WebClient(); webClient.BaseAddress = ServerBaseAddress; webClient.Headers.Add("Content-Type", "application/json"); webClient.QueryString.Add("from", dbNameFrom); webClient.QueryString.Add("to", dbNameTo); webClient.QueryString.Add("format", "tab"); webClient.QueryString.Add("query", string.Join("\t", proteinIds)); var mappingResult = webClient.DownloadString(new Uri(ServerBaseAddress + "/" + path)); //JArray mappedIdsJson = null; KeyValuePair <string, string>[] mappedIds = null; if (!string.IsNullOrEmpty(mappingResult)) { mappedIds = mappingResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .Skip(1) .Select(MapIds) //.Select(kv => JObject.FromObject(kv)) .ToArray(); //mappedIdsJson = JArray.FromObject(mappedIds); } requestInfo = webClient.ToString(); return(mappedIds); }
// GET: Champion public ActionResult AddChampions() { int champCount = 0; for (int z = 0; z < 300; z++) { try { var json = new WebClient().DownloadString("https://global.api.pvp.net/api/lol/static-data/NA/v1.2/champion/" + z + "?api_key=RGAPI-bdeef08a-76db-47d5-b0e0-33fd0d9f34ff"); string JsonString = json.ToString(); JavaScriptSerializer serializer = new JavaScriptSerializer(); Champion c = serializer.Deserialize <Champion>(JsonString); db.Champions.Add(c); db.SaveChanges(); champCount++; } catch { } Thread.Sleep(1200); } ViewBag.AddCount = champCount; return(View()); }
private void RestApi() { var json = new WebClient().DownloadString("http://localhost/users2"); string strJson = json.ToString(); JObject arrJson = JObject.Parse(strJson); JArray arrJsons = JArray.Parse(arrJson["data"].ToString()); DataTable dt = JsonConvert.DeserializeObject <DataTable>(arrJson["data"].ToString()); }
private void btnget_Click(object sender, EventArgs e) { lblsts.Text = "Getting ..."; lblsts.ForeColor = Color.White; if (txtfileid.Text == "") { lblsts.Text = "Enter File ID."; lblsts.ForeColor = Color.Red; MessageBox.Show("Enter File ID.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } else { if (txtfilename.Text == "") { lblsts.Text = "Enter File name + Format."; lblsts.ForeColor = Color.Red; MessageBox.Show("Enter File name + Format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } else { try { WebClient webClient = new WebClient(); string r = new WebClient().DownloadString("https://corona-api.000webhostapp.com/mega/m.php?id=" + txtfileid.Text); if (r.Contains("error")) { lblsts.Text = "Check file id."; lblsts.ForeColor = Color.Red; MessageBox.Show("Check file id.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (r.Contains("userstorage.mega.co.nz")) { lblsts.Text = "Done."; lblsts.ForeColor = Color.Lime; txtlink.Text = r.ToString() + "/" + txtfilename.Text; btncopy.Visible = true; } else { lblsts.Text = "Check file id or Try again."; lblsts.ForeColor = Color.Red; MessageBox.Show("Check file id or Try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception error) { MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); lblsts.Text = "..."; lblsts.ForeColor = Color.White; } } } }
public string GetLocation() { var locationResponse = new WebClient().DownloadString("https://freegeoip.net/xml/"); var responseXml = XDocument.Parse(locationResponse.ToString()) .Element("Response"); string city = responseXml.Element("City").Value.ToString(); return(city); }
// Use this for initialization public static bool ConnectionChecking() { try{ //var client = new WebClient(); using(var stream = new WebClient().OpenRead("http://www.google.com")) { Debug.Log(stream.ToString()); return true; } }catch { return false; } }
//TODO Find another way to get the IP other than web string pulling private static void SetPublicIP() { Form1.LogBox.AppendText("Getting External IP" + Environment.NewLine); try { string ExtIp = new WebClient().DownloadString("http://icanhazip.com"); PublicIP = ExtIp.ToString(); } catch (Exception exception) { SomethingNewRecources.GlobalLogbox("There was an error with getting the public IP the error was : " + exception); } }
public MainForm() { if (pingURL("http://yesit.com.au") == true) { string json = new WebClient().DownloadString("http://yesit.com.au/bvsc.php"); if (json.ToString() != "1") { DialogResult result = MessageBox.Show("You are no longer authorized to run this diag.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); if (result == DialogResult.OK) { Environment.Exit(0); } } } InitializeComponent(); }
private void button_read_api_Click(object sender, EventArgs e) { try { string url = $"http://apis.data.go.kr/1721301/KpostDepositProductView/depositGoods"; string myKey = "OdXDUPZk1H5uGX4y0vqwIi2zUsKo6rJTaf7n87m0lLKmr2fr1D1156FYBO1thOiWeZ5sL3u078PqfRmambn9rQ==";//"OdXDUPZk1H5uGX4y0vqwIi2zUsKo6rJTaf7n87m0lLKmr2fr1D1156FYBO1thOiWeZ5sL3u078PqfRmambn9rQ%3D%3D"; /*string myKey2 = "OdXDUPZk1H5uGX4y0vqwIi2zUsKo6rJTaf7n87m0lLKmr2fr1D1156FYBO1thOiWeZ5sL3u078PqfRmambn9rQ%3D%3D";*/ //?ServiceKey=서비스키(URL Encode)&numOfRows=3&pageNo=1 url += "?serviceKey=" + myKey; url += "&GOOD_KOR_NM=Smart"; Console.WriteLine(url); XElement api = XElement.Load(url); List <Post> posts = new List <Post>(); Console.WriteLine(posts); using (WebClient wc = new WebClient()) { var json = new WebClient().DownloadString(url); Console.WriteLine(json.ToString()); } foreach (var item in api.Descendants("item")) { string item_1 = item.Element("GOOD_CLSF").Value; string item_2 = item.Element("GOOD_KOR_NM").Value; string item_3 = item.Element("MAN1_ACC1_ITMS_YN").Value; string item_4 = item.Element("CARD_ISUE_PSBL_YN").Value; string item_5 = item.Element("INTR_PAY_PSBL_YN").Value; string item_6 = item.Element("INTR_PAY_KIND").Value; string item_7 = item.Element("ENTR_CUST_DVSN").Value; string item_8 = item.Element("GOOD_TAXT_DVSN").Value; string item_9 = item.Element("REGISTER_MIN").Value; string item_10 = item.Element("REGISTER_MAX").Value; string item_11 = item.Element("resultCode").Value; string item_12 = item.Element("resultMsg").Value; posts.Add(new Post(item_1, item_2, item_3, item_4, item_5, item_6, item_7, item_8, item_9, item_10, item_11, item_12)); } dataGridView2.DataSource = posts; } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } }
public string jsson() { string sUrlRequest = "http://52.225.225.180:8080/WS_Bodega/webresources/paquete.stock"; var resj = ""; var json = new WebClient().DownloadString(sUrlRequest); JavaScriptSerializer ser = new JavaScriptSerializer(); resj = ser.Serialize(json); resultadoC.Text = json.ToString(); // resultadoC.Text = resj.ToString(); return(resj); }
public ActionResult ItemsInit() { var json = new WebClient().DownloadString("https://global.api.pvp.net/api/lol/static-data/NA/v1.2/item?api_key=RGAPI-bdeef08a-76db-47d5-b0e0-33fd0d9f34ff"); string JsonString = json.ToString(); JavaScriptSerializer serializer = new JavaScriptSerializer(); Item t = serializer.Deserialize <Item>(JsonString); dynamic data = JObject.Parse(json); dynamic data2 = JsonConvert.DeserializeObject(json); return(View()); }
protected void Page_Load(object sender, EventArgs e) { String url = "http://www.omdbapi.com/?s=batman"; string json = new WebClient().DownloadString(url); Debug.WriteLine("JASOOOON: \n" + json.ToString()); XmlDocument doc = JsonConvert.DeserializeXmlNode(json, "root"); Debug.WriteLine("\nXMLLLLLLLL: \n" + doc.InnerXml.ToString()); IMDb imdb = new IMDb("tt0361862", true); Debug.WriteLine("TITLE: " + imdb.Poster.ToString()); string id = imdb.Id.ToString(); string url2 = "http://lab.abhinayrathore.com/imdb/imdbWebService.php?m=" + id + "&o=xml"; }
protected void dC_Click(object sender, EventArgs e) { var id = codig.Text; string sUrlRequest = "http://52.225.225.180:8080/WS_Bodega/webresources/paquete.stock"; var resj = ""; var json = new WebClient().DownloadString(sUrlRequest); JavaScriptSerializer ser = new JavaScriptSerializer(); // dynamic d = ser.Deserialize<dynamic>(json); // string ident = d["productId"]; //JObject jObject = JObject.Parse(json); //Token idss = jObject["productID"].First["id"]; restC.Text = json.ToString(); // Console.WriteLine(memberName); }
/// <summary> /// Get best available address /// </summary> private string GetBestAddress(string city, string street) { // generate address variations string[] addresArray = new[] { city + "," + street, city }; // search best available address foreach (var address in addresArray) { // get result from google maps api string url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + ConfigurationManager.AppSettings["GOOGLEMAPS_API_KEY"]; object getResult = new WebClient().DownloadString(url); JObject parseObj = JObject.Parse(getResult.ToString()); // if address exists, return it if (parseObj.GetValue("status").ToString() != "ZERO_RESULTS") { return(address); } } return(null); }
private void Submit_Click(object sender, RoutedEventArgs e) { NameValueCollection UserInfo = new NameValueCollection(); UserInfo.Add("UserMail", UserMail.Text); UserInfo.Add("UserPassword", UserPassword.Password); byte[] InsertUser = client.UploadValues("http://127.0.0.1/pro/LoginUser.php", "POST", UserInfo); client.Headers.Add("Content-Type", "binary/octet-stream"); switch (client.ToString()) { case "Account non register": { MessageBox.Show("Account non register!!"); break; } case "Wrong Password": { MessageBox.Show("Wrong Password!!!"); break; } case "Login succsefully": { MessageBox.Show("Login succsefully!!!"); break; } default: { MessageBox.Show("bad comunication!!"); break; } } }
static void Main(string[] args) { // Create Reference to Azure Storage Account String strorageconn = System.Configuration.ConfigurationSettings.AppSettings.Get("StorageConnectionString"); CloudStorageAccount storageacc = CloudStorageAccount.Parse(strorageconn); //Create Reference to Azure Blob CloudBlobClient blobClient = storageacc.CreateCloudBlobClient(); //The next 2 lines create if not exists a container named "democontainer" CloudBlobContainer container = blobClient.GetContainerReference("democontainer"); container.CreateIfNotExists(); //The next lines extract metadata from the file and upload it with the name DemoBlob on the container "democontainer" CloudBlockBlob blockBlob = container.GetBlockBlobReference("DemoUpload"); using (var filestream = System.IO.File.OpenRead(@"/Users/DemoUser/Desktop/sample_srt.srt")) { //Extracts the 4th line of the SRT file and extracts the date and time string datetime = System.IO.File.ReadLines("/Users/DemoUser/Desktop/sample_srt.srt").Skip(3).Take(1).First(); string[] datetimewords = datetime.Split(' '); string[] timewords = datetimewords[1].Split(','); //Changes the date from numeric form to readable form (2019-02-28 to February 28, 2019) string[] wordmonth = datetimewords[0].Split('-'); string month = wordmonth[1]; int monthnum = int.Parse(month); System.Globalization.DateTimeFormatInfo mfi = new System.Globalization.DateTimeFormatInfo(); string monthname = mfi.GetMonthName(monthnum).ToString(); string datewords = monthname + " " + wordmonth[2] + ", " + wordmonth[0]; //Extracts the 5th line of the SRT file string latlong = System.IO.File.ReadLines("/Users/DemoUser/Desktop/sample_srt.srt").Skip(4).Take(1).First(); //Extracts the latitude and longitude from the 5th line string[] latlongspec = latlong.Split(']'); string[] lat = latlongspec[7].Split(' '); string[] log = latlongspec[8].Split(' '); //Sets up coordinate string string coord = "(" + lat[2] + "," + log[2] + ")"; string coordnopar = lat[2] + "," + log[2]; //Creates a link that uses Azure Maps API to get cross street information from the given coordinates string crossurl = "https://atlas.microsoft.com/search/address/reverse/crossStreet/json?subscription-key=<ADD-AZURE-MAPS-CONNECTION-STRING-HERE>&api-version=1.0&query=" + coordnopar; //Reads the JSON file from the link and converts to it to string var jsoncross = new WebClient().DownloadString(crossurl); string jsoncrossstr = jsoncross.ToString(); //Extracts text from the JSON file string[] crosss = jsoncross.Split('"'); string crossstreet = ""; //If cross street data was found, it extracts it. If not, the variable is assigned "N/A" if (jsoncrossstr.Contains("streetName")) { string[] streetnamesplit = jsoncrossstr.Split(new string[] { "streetName" }, StringSplitOptions.None); string[] streetnamesplit2 = streetnamesplit[1].Split('"'); crossstreet = streetnamesplit2[2]; } else { crossstreet = "N/A"; } //Metadata being added to the uploaded blobs blockBlob.Metadata.Add("Date", datetimewords[0]); blockBlob.Metadata.Add("Time", timewords[0]); blockBlob.Metadata.Add("Coordinates", coord); blockBlob.Metadata.Add("CrossStreet", crossstreet); blockBlob.Metadata.Add("FullDate", datewords); //Blob uploaded to Blob Storage blockBlob.UploadFromStream(filestream); } }
static void Main(string[] args) { var usuario = ""; var contrasena = ""; Console.WriteLine(" __ "); Console.WriteLine(" .' '."); Console.WriteLine(" _.- / | l "); Console.WriteLine(" , _.- | / 0 `-. "); Console.WriteLine(" |l .-' ---- -.__.'=====================- "); Console.WriteLine(" l '-'` .___.--._)=========================| "); Console.WriteLine(" l .' | | "); Console.WriteLine(" | /,_.-' | - ASIGNADOR - | "); Console.WriteLine(" _ / _.'( | - DE - | "); Console.WriteLine(" / ,-' l l | - TAREAS - | "); Console.WriteLine(" l l `-' | | "); Console.WriteLine(" `-' '--------------------------' "); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Bienvenido Usuario, introdusca sus datos:"); Console.WriteLine("Nombre de Usuario o Correo:"); usuario = Console.ReadLine(); Console.WriteLine("Contraseña:"); contrasena = Console.ReadLine(); string url = "http://200.105.154.18:5000/Login/" + usuario + "/" + contrasena; var json = new WebClient().DownloadString(url); //dynamic m = JsonConvert.DeserializeObject(json); ///.DeserializeObject<IList<Usuario>>(json); var jo = Newtonsoft.Json.Linq.JObject.Parse(json); var msgWel = jo["texto"]; var llave = jo["llave"]; //Console.WriteLine(m); Console.WriteLine(msgWel); Boolean sw = true; int opc = 0; do { Console.WriteLine("****************MENU**************"); Console.WriteLine("* Que deseas hacer? *"); Console.WriteLine("* 1. Buscar tarea *"); Console.WriteLine("* 2. Ver listado de tareas *"); Console.WriteLine("* 3. Realizar tarea Asignada *"); Console.WriteLine("* 0. Salir... *"); Console.WriteLine("**********************************"); opc = int.Parse(Console.ReadLine()); switch (opc) { case 1: Console.WriteLine("Ingrese la tarea a buscar: "); String a = Console.ReadLine(); url = "http://200.105.154.18:5000/Tarea/" + a + "/" + llave.ToString(); var json2 = new WebClient().DownloadString(url); Console.WriteLine(json2.ToString()); var tarea1 = new Tarea(); Console.ReadKey(); break; case 2: url = "http://200.105.154.18:5000/Tarea/" + llave.ToString(); json = new WebClient().DownloadString(url); JArray jsonArray = JArray.Parse(json); var tarea = new Tarea(); foreach (var i in jsonArray) { tarea = i.ToObject <Tarea>(); Console.WriteLine("ROg" + tarea.Nombre); } break; case 3: /*Console.WriteLine("Ingrese la tarea a buscar: "); * /String b = Console.ReadLine(); * /url = "http://200.105.154.18:5000/Tarea/" + b + "/" + llave.ToString(); * /var json3 = new WebClient().DownloadString(url); * Console.WriteLine(json3.ToString()); * var lista = new List<JObject>(5); * * Console.ReadKey(); * break;*/ default: Console.WriteLine("Adios "); sw = false; break; } } while (sw); }
//<---------------------------------Get IP-----------------------------> public static string GetIPAdress() { string jsoon = new WebClient().DownloadString("http://icanhazip.com"); return(jsoon.ToString()); }
protected void btnAddGame_Click(object sender, EventArgs e) { bool baudio = false; bool bJson = false; bool bIDgame = false; bool bplayerID = false; int playerID = 203422649; string strJson = ""; bool gameIDTrue = false; bool playerIdTrue = false; test.InnerText = ""; if (GameIDInput.Value != "") { try { string gameID = GameIDInput.Value; gameIDTrue = true; var json = new WebClient().DownloadString("https://api.opendota.com/api/matches/" + gameID); playerID = 0; int tempintAccount; if (Int32.TryParse(UserAccountInput.Value, out tempintAccount)) { ; } playerID = tempintAccount; strJson = json.ToString(); var JsoncClass = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(json); GameEvents gi = new GameEvents(); string temp = JsoncClass.match_id; gi.md.match_id = double.Parse(temp); gi.md.barracks_status_dire = JsoncClass.barracks_status_dire; gi.md.barracks_status_radiant = JsoncClass.barracks_status_radiant; gi.md.dire_score = JsoncClass.dire_score; gi.md.duration = JsoncClass.duration; gi.md.radiant_score = JsoncClass.radiant_score; gi.md.radiant_win = JsoncClass.radiant_win; gi.md.start_time = JsoncClass.start_time; gi.md.radiant_score = JsoncClass.radiant_score; JArray jObj = JArray.Parse(JsoncClass.objectives.ToString()) as JArray; dynamic oj = jObj; foreach (var o in oj) { GameEvents.objectives oTemp = new GameEvents.objectives(); oTemp.time = o.time; oTemp.who = o.type; oTemp.type = o.key; gi.o.Add(oTemp); } JArray jPlayer = JArray.Parse(JsoncClass.players.ToString()) as JArray; dynamic joP = jPlayer; foreach (var p in joP) { GameEvents.Player oPTemp = new GameEvents.Player(); if (p.account_id == playerID) { playerIdTrue = true; oPTemp.account_id = p.account_id; oPTemp.deaths = p.deaths; oPTemp.denies = p.denies; oPTemp.gold = p.gold; oPTemp.gold_per_min = p.gold_per_min; oPTemp.hero_damage = p.hero_damage; oPTemp.hero_id = p.hero_id; oPTemp.kda = p.kda; oPTemp.kills = p.kills; oPTemp.kills_per_min = p.kills_per_min; oPTemp.last_hits = p.last_hits; oPTemp.total_gold = p.total_gold; oPTemp.total_xp = p.total_xp; oPTemp.lane_efficiency = p.lane_efficiency; oPTemp.radiant_win = p.radiant_win; oPTemp.isRadiant = p.isRadiant; oPTemp.personaname = p.personaname; // per minute data JArray goldTime = JArray.Parse(p.gold_t.ToString()) as JArray; JArray lhTime = JArray.Parse(p.lh_t.ToString()) as JArray; JArray denieTime = JArray.Parse(p.dn_t.ToString()) as JArray; //storing data oPTemp.gold_t = goldTime.Select(jv => (int)jv).ToArray(); oPTemp.lh_t = lhTime.Select(jv => (int)jv).ToArray(); oPTemp.dn_t = denieTime.Select(jv => (int)jv).ToArray(); gi.p = oPTemp; } } // write Json string gameIDWrite = GameIDInput.Value; string JsonPath = HttpContext.Current.Server.MapPath("/JsonData"); File.WriteAllText(JsonPath + '\\' + gameIDWrite + ".json", strJson); bJson = true; // trimming that sweet audio // if the game data is real then we can prep the audio if (gameIDTrue && playerIdTrue) { if (uploadAudioFile.HasFile) { string[] token = uploadAudioFile.FileName.Split('.'); string Extension = token[token.Length - 1]; if (Extension == "mp3") { baudio = true; //getting mp3 to match game time int durationGame = gi.md.duration; uploadAudioFile.SaveAs(Server.MapPath("~") + "audioFiles/FullFile/" + gameID + ".mp3"); var inputStream = new FileStream(Server.MapPath("~") + "audioFiles/FullFile/" + gameID + ".mp3", FileMode.Open, FileAccess.Read, FileShare.None); Mp3FileReader read = new Mp3FileReader(inputStream); WaveFileWriter.CreateWaveFile(Server.MapPath("~") + "audioFiles/FullFile/" + gameID + ".wav", read); //convert mp3 to wave WaveFileReader wv = new WaveFileReader(Server.MapPath("~") + "audioFiles/FullFile/" + gameID + ".wav"); TimeSpan lenghtAudio = wv.TotalTime; int audiolength = (int)Math.Round(lenghtAudio.TotalSeconds); // cut begniing if (audiolength > durationGame) { int CutStart = audiolength - durationGame; TimeSpan tCutStart = TimeSpan.FromSeconds(audiolength - durationGame); TimeSpan tCutEnd = TimeSpan.FromSeconds(0); TrimWavFile(Server.MapPath("~") + "audioFiles/FullFile/" + gameID + ".wav", Server.MapPath("~") + "audioFiles/FullFile/TR" + gameID + ".wav", tCutStart, tCutEnd); } //saving trunced audio int counter = 0; WaveFileReader wvTr = new WaveFileReader(Server.MapPath("~") + "audioFiles/FullFile/TR" + gameID + ".wav"); TimeSpan lenghtAudioTr = wvTr.TotalTime; TimeSpan CutBeginXlip; TimeSpan CutEndClip; foreach (GameEvents.objectives objMusic in gi.o) { if (objMusic.time > 5) { CutBeginXlip = TimeSpan.FromSeconds((double)objMusic.time - 5); CutEndClip = lenghtAudioTr - (CutBeginXlip + TimeSpan.FromSeconds(5)); //if (counter == gi.o.Count) //{ // CutBeginXlip = CutBeginXlip - TimeSpan.FromSeconds(5); // CutEndClip = CutEndClip - TimeSpan.FromSeconds(5); //} //save batch mp3 subfiles TrimWavFile(Server.MapPath("~") + "audioFiles/FullFile/TR" + gameID + ".wav", Server.MapPath("~") + "audioFiles/Clips/" + gameID + "-" + counter + ".wav", CutBeginXlip, CutEndClip); counter++; } } //--- Linking emotion to audioFile for agent metadata using IBM whatson read all music files FileInfo[] filesinfo = new DirectoryInfo(Server.MapPath("~") + "audioFiles/Clips/").GetFiles().Where(f => (f.FullName.EndsWith(".wav")) && (f.FullName.Contains(gameID))).ToArray(); // Create emotion for each Emotion[] eMotionsDetected = new Emotion[filesinfo.Length]; int countEmotionIndex = 0; foreach (FileInfo f in filesinfo) { //Set DataFrom IBM -- stoped working? why eMotionsDetected[countEmotionIndex] = new Emotion(); //save data eMotionsDetected[countEmotionIndex].Mp3ParentName = f.Name; eMotionsDetected[countEmotionIndex].emotionDetected = "EDetctedPlace"; eMotionsDetected[countEmotionIndex].intensity = -99; //eMotionsDetected[countEmotionIndex].delta = -99; eMotionsDetected[countEmotionIndex].ArrayWords = null; countEmotionIndex++; } string[] EmotionLine = new string[eMotionsDetected.Length]; int countEmotionWrite = 0; foreach (Emotion wrtieEmotionFile in eMotionsDetected) { string AllwordSaid = ""; if (eMotionsDetected[countEmotionWrite].ArrayWords != null) { foreach (string word in eMotionsDetected[countEmotionWrite].ArrayWords) { AllwordSaid += word + "*"; } } EmotionLine[countEmotionWrite] = eMotionsDetected[countEmotionWrite].Mp3ParentName + ";" + eMotionsDetected[countEmotionWrite].emotionDetected + ";" + eMotionsDetected[countEmotionWrite].intensity + ";" + AllwordSaid + ";"; countEmotionWrite++; } test.InnerHtml += "<font color=\"green\"> Data Recorded successfully"; lblRedirect.InnerHtml = "<a href =\"GameAnalysis.aspx\">See Results<a>"; //File.WriteAllLines(Server.MapPath("~") + "ProcessedGames/" + gameID + ".emote", EmotionLine); ReflexAgent reflex = new ReflexAgent(gameID, gi, Server.MapPath("~") + "ProcessedGames/" + gameID + ".emote", Server.MapPath("~") + "ProcessedGames/"); } else { test.InnerHtml += "No WMA audio file"; } } } } catch (WebException ex) { if (gameIDTrue == false) { test.InnerHtml += "ERROR. invalid game ID"; } else { if (playerIdTrue == false) { test.InnerHtml += "ERROR. invalid player ID"; } } } } test.InnerHtml += "</font>"; }
//----------------------- //Тестовый комментарий 1 //----------------------- public MainPage() { InitializeComponent(); //client.DownloadFile("test.com", "test_file"); label1.Text = client.ToString(); }