def get_idf(self, args, request, uiApplication): ''' deserializes a ModelSnapshot from the POST and then uses the DPV idf writer to export the ModelSnapshot as an IDF file. ''' clr.AddReference('DpvApplication') clr.AddReference('DesignPerformanceViewer') from DesignPerformanceViewer.Model import ModelSnapshotImporter from DesignPerformanceViewer.EnergyPlusCalculation import IdfWriter from System.IO import StreamReader from System.IO import MemoryStream from System.Text import Encoding if request.HttpMethod == 'POST': body = request.InputStream encoding = request.ContentEncoding reader = StreamReader(body, encoding) snapshot_xml = reader.ReadToEnd() snapshot = ModelSnapshotImporter().Import(snapshot_xml) elif request.HttpMethod == 'GET': snapshot = self.take_snapshot(uiApplication) else: return (404, 'text/plain', 'invalid HTTP method: ' + request.HttpMethod) ms = MemoryStream() writer = IdfWriter(ms, Encoding.UTF8) writer.Write(snapshot) ms.Position = 0 idf = StreamReader(ms, Encoding.UTF8).ReadToEnd() print 'idf=', idf return (200, 'text/plain', idf)
def prettify_string(rough_string): """Return an XML string with added whitespace for legibility, using .NET infrastructure. Parameters ---------- rough_string : str XML string """ mStream = MemoryStream() writer = XmlTextWriter(mStream, Encoding.UTF8) document = XmlDocument() document.LoadXml(rough_string) writer.Formatting = Formatting.Indented writer.WriteStartDocument() document.WriteContentTo(writer) writer.Flush() mStream.Flush() mStream.Position = 0 sReader = StreamReader(mStream) formattedXml = sReader.ReadToEnd() return formattedXml
def getWeather(self, sender, event): zipcode = self.textbox1.Text country = self.combobox1.Text appid = "get your own appid" uri = "http://api.openweathermap.org/data/2.5/weather?zip=" + zipcode + "," + country + "&APPID=" + appid request = HttpWebRequest.Create(uri) response = request.GetResponse() # the variable response now holds a JSON string. # in order to parse the JSON string, response has to first be converted into a "stream" using StreamReader() # so it can then be deserialized using the JavaScriptSerializer() and converted into a dictionary. stream_reader = StreamReader(response.GetResponseStream()) json_object = stream_reader.ReadToEnd() my_data = JavaScriptSerializer().DeserializeObject(json_object) # get the data from the dictionary and display it # this api returns temperature as KELVIN so it needs to be converted to FAHRENHEIT city = str(my_data['name']) temp_kelvin = float(my_data['main']['temp']) temp_fahrenheit = float((temp_kelvin - 273.15) * 1.8 + 32) self.textbox2.Text = "The temperature in " + city + " is " + str( temp_fahrenheit) + " F" pass
def post(self, url, payload='', json=None): r = WebRequest.Create(url) r.Method = "POST" #r.Accept = "application/json" if self.proxy_aware: r.Proxy = WebRequest.GetSystemWebProxy() r.Proxy.Credentials = CredentialCache.DefaultCredentials if json: r.ContentType = "application/json" if type(json) == dict: payload = JavaScriptSerializer().Serialize(json) elif hasattr(json, '__serialize__'): payload = JavaScriptSerializer().Serialize( json.__serialize__()) else: raise NotSerializable("{} object is not serializable".format( type(json))) if len(payload): data = Encoding.ASCII.GetBytes(payload) r.ContentLength = data.Length requestStream = r.GetRequestStream() requestStream.Write(data, 0, data.Length) requestStream.Close() response = r.GetResponse() responseStream = StreamReader(response.GetResponseStream()) return Response(responseStream.ReadToEnd())
def get_html_string(url): ''' This method takes a url (string) of a webpage, and connects to the URL, then downloads, htmldecodes, and returns the contents of that page as an html string. This method will throw an WebException or IOException if anything goes wrong, including if the response code is not valid (i.e. 200). ''' try: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 request = WebRequest.Create(url) request.UserAgent = "[ComicVineScraper, version " + \ Resources.SCRIPT_VERSION + "]" response = request.GetResponse() # if the response code is not "OK", throw a web exception immediately. # this stops red-herring errors later on as we try to parse bad results. # usually this only happens if the CV server is temporarily down. if response.StatusCode != HttpStatusCode.OK: raise WebException("server response code " + sstr(int(response.StatusCode)) + " (" + sstr(response.StatusCode) + ")") responseStream = response.GetResponseStream() reader = StreamReader(responseStream, Encoding.UTF8) page = reader.ReadToEnd() with StringWriter() as writer: HttpUtility.HtmlDecode(page, writer) page = writer.ToString() return page finally: if 'reader' in vars(): reader.Close() if 'responseStream' in vars(): responseStream.Close() if 'response' in vars(): response.Close()
def onUpdate(): shortenedUri = None if NetworkInterface.GetIsNetworkAvailable(): try: request = WebRequest.Create(Uri(String.Concat("http://nazr.in/api/shorten.json?url=", urlEncode(uri.ToString())))) response = None stream = None streamReader = None try: response = request.GetResponse() stream = response.GetResponseStream() streamReader = StreamReader(stream) jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd()) if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("url"): shortenedUri = Uri(jsonDictionary["url"]) finally: if streamReader is not None: streamReader.Close() if stream is not None: stream.Close() if response is not None: response.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def serialize(self, document, indent=False, encoding=bridge.ENCODING, prefixes=None, omit_declaration=False): doc = XmlDocument() doc.LoadXml(self.__start_document(document)) if document.xml_text: doc.DocumentElement.AppendChild( doc.CreateTextNode(document.xml_text)) self.__serialize_element(doc, doc.DocumentElement, document) settings = XmlWriterSettings() settings.Indent = indent settings.Encoding = Encoding.GetEncoding(encoding) settings.OmitXmlDeclaration = omit_declaration ms = MemoryStream() xw = XmlWriter.Create(ms, settings) doc.Save(xw) sr = StreamReader(ms) ms.Seek(0, SeekOrigin.Begin) content = sr.ReadToEnd() ms.Close() return content
def request_get(uri): webRequest = HttpWebRequest.Create(uri) webRequest.Method = 'GET' webRequest.ContentType = 'application/json' webRequest.ContentLength = 0 response = webRequest.GetResponse() streamReader = StreamReader(response.GetResponseStream()) jsonData = json.loads(streamReader.ReadToEnd()) response.Close() return jsonData
def LoadFile(filename): store = IsolatedStorageFile.GetUserStoreForApplication() isolatedStream = IsolatedStorageFileStream(filename, FileMode.Open, store) reader = StreamReader(isolatedStream) data = reader.ReadToEnd() reader.Close() isolatedStream.Close() return data
def getNumberOfSpeakers(): vm = ViewModel(Application.Current.MainWindow.DataContext.Speakers.Length) stream = Application.Current.GetType().Assembly.GetManifestResourceStream( "IronPython.UI.Scripts.ResultWindow.xaml") reader = StreamReader(stream) window = XamlReader.Parse(reader.ReadToEnd()) reader.Close() stream.Close() window.DataContext = vm window.FindName("CloseButton").Click += lambda s, e: window.Close() window.Show()
def get(self, url): r = WebRequest.Create(url) r.Method = "GET" if self.proxy_aware: r.Proxy = WebRequest.GetSystemWebProxy() r.Proxy.Credentials = CredentialCache.DefaultCredentials #r.ContentType = "application/json" #r.Accept = "application/json" response = r.GetResponse() responseStream = StreamReader(response.GetResponseStream()) return Response(responseStream.ReadToEnd())
def rsnrequest(): request = WebRequest.Create(file_link) request.Method = "GET" request.UserAgent = "Anything" # Token scenario for closed repositories #token = '' #request.Headers["OAUTH-TOKEN"] = token rsp = request.GetResponse() stream_reader = StreamReader(rsp.GetResponseStream()) jsonData = stream_reader.ReadToEnd() stream_reader.Close() json = JavaScriptSerializer().DeserializeObject(jsonData) return json
def uploadOneFile(dataTable): outputFile = StreamWriter(outputFilePath, "a") fileName = dataTable.Name outputFile.Write("<p>" + str(datetime.datetime.now()) + " - " + fileName + " - start <br/>\n") webRequest = HttpWebRequest.Create(rcqBackendURI + fileName) response = webRequest.GetResponse() streamReader = StreamReader(response.GetResponseStream()) jsonData = streamReader.ReadToEnd() ps.CurrentProgress.CheckCancel() outputFile.Write( str(datetime.datetime.now()) + " - " + fileName + " " + str(jsonData) + "<br/>\n") outputFile.Write( str(datetime.datetime.now()) + " - " + fileName + " - SDBF file re-generated <br/>\n") dataTable.Refresh() ps.CurrentProgress.CheckCancel() outputFile.Write( str(datetime.datetime.now()) + " - " + fileName + " - Analysis Refreshed <br/>\n") try: (found, item) = lm.TryGetItem(folder + fileName, LibraryItemType.SbdfDataFile, LibraryItemRetrievalOption.IncludeProperties) if found: table.ExportDataToLibrary(item, fileName) outputFile.Write( str(datetime.datetime.now()) + " - " + fileName + " - exported (ow) <br/>\n") else: (found2, item2) = lm.TryGetItem( folder, LibraryItemType.Folder, LibraryItemRetrievalOption.IncludeProperties) if found2: table.ExportDataToLibrary(item2, fileName) outputFile.Write( str(datetime.datetime.now()) + " - " + fileName + " - exported (1st) <br/>\n") except Exception as e: outputFile.Write( str(datetime.datetime.now()) + " - " + "Exception Occured:" + str(e) + " <br/>\n") outputFile.Write("</p>\n") outputFile.Close()
def read_wiki(column_size=50): # Create a CLR web request object http = HttpWebRequest.Create(url) http.Timeout = 5000 http.UserAgent = "Red Gate SQL Data Generator" # Read the response with a CLR StreamReader response = http.GetResponse() responseStream = StreamReader(response.GetResponseStream()) html = responseStream.ReadToEnd() # Yield all lines that start with a *, # truncated to the column width for line in html.splitlines(): if line.startswith("*"): yield line[:column_size]
def onSave(): try: fs = None sr = None sw = None try: fs = FileStream(__file__, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) encoding = UTF8Encoding(False) sr = StreamReader(fs, encoding, True) lines = Regex.Replace( Regex.Replace( sr.ReadToEnd(), "username\\s*=\\s*\"\"", String.Format("username = \"{0}\"", username), RegexOptions.CultureInvariant), "password\\s*=\\s*\"\"", String.Format("password = \"{0}\"", password), RegexOptions.CultureInvariant) fs.SetLength(0) sw = StreamWriter(fs, encoding) sw.Write(lines) finally: if sw is not None: sw.Close() if sr is not None: sr.Close() if fs is not None: fs.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def upload_one_file(data_table): file_name = data_table.Name lm = Application.GetService(LibraryManager) ps.CurrentProgress.ExecuteSubtask(file_name + " - start") web_request = HttpWebRequest.Create(rcqBackendURI + file_name) response = web_request.GetResponse() stream_reader = StreamReader(response.GetResponseStream()) json_data = stream_reader.ReadToEnd() ps.CurrentProgress.CheckCancel() ps.CurrentProgress.ExecuteSubtask(file_name + ": " + str(json_data)) ps.CurrentProgress.ExecuteSubtask(file_name + " - SDBF file re-generated") data_table.Refresh() ps.CurrentProgress.CheckCancel() ps.CurrentProgress.ExecuteSubtask(file_name + " - Analysis DataTable Refreshed") try: (found, item) = lm.TryGetItem(folder + file_name, LibraryItemType.SbdfDataFile, LibraryItemRetrievalOption.IncludeProperties) if found: data_table.ExportDataToLibrary(item, file_name) ps.CurrentProgress.ExecuteSubtask(file_name + " - exported (ow)") else: (found2, item2) = lm.TryGetItem( folder, LibraryItemType.Folder, LibraryItemRetrievalOption.IncludeProperties) if found2: data_table.ExportDataToLibrary(item2, file_name) ps.CurrentProgress.ExecuteSubtask(file_name + " - exported (1st)") except Exception as e: ps.CurrentProgress.ExecuteSubtask("Exception occurred on " + file_name + " - " + str(e))
def get_html_string(url): ''' This method takes a url (string) of a webpage, and connects to the URL, then downloads, htmldecodes, and returns the contents of that page as an html string. This method will throw an WebException or IOException if anything goes wrong, including if the response code is not valid (i.e. 200). ''' try: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 request = WebRequest.Create(url) # latest version of comicvine api insists on a user agent (see bug #484). # previously, it didn't like my non-standard user agent, I think (see bug #471). # now, I have a standard user agent, which comicvine api seems to like. request.UserAgent = "ComicVineScraper/" + \ Resources.SCRIPT_VERSION + " (https://github.com/cbanack/comic-vine-scraper/)" response = request.GetResponse() # if the response code is not "OK", throw a web exception immediately. # this stops red-herring errors later on as we try to parse bad results. # usually this only happens if the CV server is temporarily down. if response.StatusCode != HttpStatusCode.OK: raise WebException("server response code " + sstr(int(response.StatusCode))+" ("+sstr(response.StatusCode)+")" ) responseStream = response.GetResponseStream() reader = StreamReader(responseStream, Encoding.UTF8) page = reader.ReadToEnd() with StringWriter() as writer: HttpUtility.HtmlDecode(page, writer) page = writer.ToString() return page finally: if 'reader' in vars(): reader.Close() if 'responseStream' in vars(): responseStream.Close() if 'response' in vars(): response.Close()
def onUpdate(): temp = 0 windSpeed = 0 windDeg = 0 weatherIdList = List[Double]() weatherPathHashSet = HashSet[String]() weatherStreamList = List[MemoryStream]() weatherConditionList = List[String]() if NetworkInterface.GetIsNetworkAvailable(): try: request = WebRequest.Create(Uri(String.Concat("http://api.openweathermap.org/data/2.5/find?q=", urlEncode(location), "&units=metric&cnt=1"))) response = None stream = None streamReader = None try: nowDateTime = DateTime.Now response = request.GetResponse() stream = response.GetResponseStream() streamReader = StreamReader(stream) jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd()) if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("list") and jsonDictionary["list"] is not None and clr.GetClrType(Array).IsInstanceOfType(jsonDictionary["list"]): for obj in jsonDictionary["list"]: if obj is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj): if obj.ContainsKey("main") and obj["main"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["main"]) and obj["main"].ContainsKey("temp"): temp = obj["main"]["temp"] if obj.ContainsKey("wind") and obj["wind"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["wind"]): if obj["wind"].ContainsKey("speed"): windSpeed = obj["wind"]["speed"] if obj["wind"].ContainsKey("deg"): windDeg = obj["wind"]["deg"] if obj.ContainsKey("weather") and obj["weather"] is not None and clr.GetClrType(Array).IsInstanceOfType(obj["weather"]): for o in obj["weather"]: if o is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(o) and o.ContainsKey("id") and o["id"] is not None: weatherIdList.Add(o["id"]) for id in weatherIdList: digit = Convert.ToInt32(id / 100) path = None s = None if digit == 2: path = "Assets\\Cloud-Lightning.png" weatherConditionList.Add("Thunderstorm") elif digit == 3: path = "Assets\\Cloud-Drizzle.png" weatherConditionList.Add("Drizzle") elif digit == 5: d = Convert.ToInt32(id / 10) if d == 0: if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18: path = "Assets\\Cloud-Rain-Sun.png" else: path = "Assets\\Cloud-Rain-Moon.png" else: path = "Assets\\Cloud-Rain.png" weatherConditionList.Add("Rain") elif digit == 6: path = "Assets\\Cloud-Snow.png" weatherConditionList.Add("Snow") elif digit == 7: path = "Assets\\Cloud-Fog.png" if Convert.ToInt32(id) == 701: weatherConditionList.Add("Mist") elif Convert.ToInt32(id) == 711: weatherConditionList.Add("Smoke") elif Convert.ToInt32(id) == 721: weatherConditionList.Add("Haze") elif Convert.ToInt32(id) == 731: weatherConditionList.Add("Dust") elif Convert.ToInt32(id) == 741: weatherConditionList.Add("Fog") elif digit == 8: if Convert.ToInt32(id) == 800: if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18: path = "Assets\\Sun.png" weatherConditionList.Add("Sunny") else: path = "Assets\\Moon.png" weatherConditionList.Add("Clear") elif Convert.ToInt32(id) >= 801 and Convert.ToInt32(id) <= 803: if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18: path = "Assets\\Cloud-Sun.png" else: path = "Assets\\Cloud-Moon.png" weatherConditionList.Add("Cloudy") elif Convert.ToInt32(id) == 804: path = "Assets\\Cloud.png" weatherConditionList.Add("Overcast") else: if Convert.ToInt32(id) == 900: path = "Assets\\Tornado.png" weatherConditionList.Add("Tornado") elif Convert.ToInt32(id) == 905: path = "Assets\\Wind.png" weatherConditionList.Add("Windy") elif Convert.ToInt32(id) == 906: path = "Assets\\Cloud-Hail.png" weatherConditionList.Add("Hail") if path is not None and weatherPathHashSet.Contains(path) == False: fs = None try: fs = FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read) ms = MemoryStream() buffer = Array.CreateInstance(Byte, fs.Length) bytesRead = fs.Read(buffer, 0, buffer.Length) while bytesRead > 0: ms.Write(buffer, 0, bytesRead) bytesRead = fs.Read(buffer, 0, buffer.Length) ms.Seek(0, SeekOrigin.Begin) weatherStreamList.Add(ms) finally: if fs is not None: fs.Close() weatherPathHashSet.Add(path) finally: if streamReader is not None: streamReader.Close() if stream is not None: stream.Close() if response is not None: response.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def onDispatch(task): global httpListener if task.Exception is None: httpListener.GetContextAsync().ContinueWith[List[Entry]]( Func[Task[HttpListenerContext], List[Entry]](onDispatch), TaskContinuationOptions.LongRunning).ContinueWith( Action[Task[List[Entry]]](onCompleted), context) try: if task.Result.Request.HttpMethod.Equals( WebRequestMethods.Http.Post ) and task.Result.Request.Url.AbsolutePath.Equals( "/alert"): if task.Result.Request.ContentType.Equals( "application/json"): stream = None streamReader = None try: stream = task.Result.Request.InputStream streamReader = StreamReader(stream) jsonArray = JsonDecoder.decode( streamReader.ReadToEnd()) if jsonArray is not None and clr.GetClrType( Array).IsInstanceOfType(jsonArray): entryList = List[Entry]() for obj in jsonArray: if clr.GetClrType(Dictionary[ String, Object]).IsInstanceOfType(obj): entry = Entry() if obj.ContainsKey( "resource" ) and clr.GetClrType( String).IsInstanceOfType( obj["resource"]): entry.Resource = Uri( obj["resource"]) if obj.ContainsKey( "title" ) and clr.GetClrType( String).IsInstanceOfType( obj["title"]): entry.Title = obj["title"] if obj.ContainsKey( "description" ) and clr.GetClrType( String).IsInstanceOfType( obj["description"]): entry.Description = obj[ "description"] if obj.ContainsKey( "author" ) and clr.GetClrType( String).IsInstanceOfType( obj["author"]): entry.Author = obj["author"] if obj.ContainsKey( "created" ) and clr.GetClrType( String).IsInstanceOfType( obj["created"]): entry.Created = DateTime.Parse( obj["created"]) if obj.ContainsKey( "modified" ) and clr.GetClrType( String).IsInstanceOfType( obj["modified"]): entry.Modified = DateTime.Parse( obj["modified"]) if obj.ContainsKey( "image" ) and clr.GetClrType( String).IsInstanceOfType( obj["image"]): entry.Image = Uri(obj["image"]) if obj.ContainsKey( "tags") and clr.GetClrType( Array ).IsInstanceOfType( obj["tags"]): for o in obj["tags"]: if clr.GetClrType( String ).IsInstanceOfType(o): entry.Tags.Add(o) entryList.Add(entry) else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.BadRequest) return None return entryList else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.BadRequest) finally: if streamReader is not None: streamReader.Close() if stream is not None: stream.Close() else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.UnsupportedMediaType) else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.Forbidden) except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace) finally:
def get_body(r): body = r.InputStream encoding = r.ContentEncoding reader = StreamReader(body, encoding) s = reader.ReadToEnd() return s
except (ArgumentNullException, System.Security.SecurityException), ex: self._exception = ex return False try: responsestream = request.GetResponse() except (System.Security.SecurityException, WebException), ex: self._exception = ex return False try: streamreader = StreamReader(responsestream.GetResponseStream()) self._source = streamreader.ReadToEnd() except (ArgumentException, ProtocolViolationException), ex: self._exception = ex success = False finally: responsestream.Close() streamreader.Close() return success
print("Parsed file with {} warnings.".format(errorHandler.warnings)) errorHandler = ErrorHandler() tree.Validate(errorHandler) if (errorHandler.warnings == 0): print("Validated parsed data with no warnings.") else: print("Validated parsed data with {} warnings.".format( errorHandler.warnings)) input("Press enter to serialise data.") tree.elements.Insert(0, comment) ms = MemoryStream() stream = StreamWriter(ms, UTF8Encoding(True)) parser.Serialise(tree, stream) ms.Position = 0 sr = StreamReader(ms) myStr = sr.ReadToEnd() print(myStr) # output to the file #f = codecs.open("testFileNew.a2l", 'w+', 'utf-8') #f.write(myStr) #f.close() input("Press enter to close...") else: print("Parsing failed!")