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 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 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 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 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 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 ExecuteFileInScope(self, filename, moduleEO): try: f = StreamReader(filename) runtime.DynamicObjectHelpers.SetMember(moduleEO, "__file__", Path.GetFullPath(filename)) ASTs = parser.ParseFile(f) self.dbgASTs = ASTs scope = etgen.AnalysisScope( None, #parent filename, self, Exprs.Expression.Parameter(Sympl, "symplRuntime"), Exprs.Expression.Parameter(ExpandoObject, "fileModule")) self.dbgascope = scope body = [] self.dbgbody = body for e in ASTs: body.append(etgen.AnalyzeExpr(e, scope)) ## Use ftype with void return so that lambda ignores body result. ftype = Exprs.Expression.GetActionType( System.Array[System.Type]([Sympl, ExpandoObject])) ## Due to .NET 4.0 co/contra-variance, IPy's binding isn't picking ## the overload with just IEnumerable<Expr>, so pick it explicitly. body = Exprs.Expression.Block.Overloads[IEnumerable[ Exprs.Expression]](body) modulefun = Exprs.Expression.Lambda(ftype, body, scope.RuntimeExpr, scope.ModuleExpr) dbgmodfun = modulefun modulefun.Compile()(self, moduleEO) finally: f.Close()
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 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 alternateLoadMasterPluginIndex(): import System, System.Windows.Forms from System.IO import Path, File, StreamReader from System import Environment p = [] r = StreamReader(file) while 1: t = r.ReadLine() if t == None: break p.append(t) r.Close()
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 create_user_control(filename): userControl = None try: s = None if filename: s = StreamReader(filename) userControl = XamlReader.Load(s.BaseStream) except Exception as e: CommonUtil.sprint("Failed to Create UserControl: {}".format(e)) finally: if s: s.Close() s.Dispose() return userControl
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 __init__(self, filePath, uidoc): self.filePath = filePath self.uidoc = uidoc try: self.filereader = StreamReader( filePath ) self.uidoc.Application.Application.OpenSharedParameterFile() except: Alert( 'Check Your Shared Parameters File Path', title="Error", header="Invalid Shared Parameters File", exit=True ) self.temp = os.environ['USERPROFILE'] + "\\AppData\\Local\\temp.txt"
def _request_ironython(self, *args, **kwargs): method, url = args headers = kwargs.get("headers") params = kwargs.get("params") json_data = kwargs.get("json_data") byte_data = kwargs.get("byte_data") urlencode = kwargs.get("urlencode") filepath = kwargs.get("filepath") try: # prepare params if params: url = self._add_url_params(url, params) web_request = WebRequest.Create(url) web_request.Method = method.upper() web_request.Timeout = self.timeout # prepare headers if headers: for key, value in headers.items(): if key == "Content-Type": web_request.ContentType = value elif key == "Content-Length": web_request.ContentLength = value else: web_request.Headers.Add(key, value) byte_arrays = [] if json_data: byte_arrays.append( UTF8.GetBytes(json.dumps(json_data, ensure_ascii=False))) if filepath: byte_arrays.append(File.ReadAllBytes(filepath)) if byte_data: pass # TODO - Add byte input for System.Net if urlencode: byte_arrays.append(UTF8.GetBytes(self._url_encode(urlencode))) for byte_array in byte_arrays: web_request.ContentLength = byte_array.Length with web_request.GetRequestStream() as req_stream: req_stream.Write(byte_array, 0, byte_array.Length) try: with web_request.GetResponse() as response: success = response.StatusDescription in SUCCESS_CODES with response.GetResponseStream() as response_stream: with StreamReader(response_stream) as stream_reader: data = json.loads(stream_reader.ReadToEnd()) except SystemError: return None, None finally: web_request.Abort() except Exception as e: raise e return data, success
def __load_testdata(file): """ Reads the testdata out of a file. Testdata consists of exactly three strings on each line, each one enclosed in quotation marks (" or '). The first is the filename to be parsed, the second is the series name that should be parsed out of it, and the third is the issue number string that should be parsed out of it. Blank lines and lines that begin with # are ignored. """ retval = [] if File.Exists(file): with StreamReader(file, Encoding.UTF8, False) as sr: line = sr.ReadLine() while line is not None: line = line.strip() if len(line) > 0 and not line.startswith("#"): if line.startswith('"'): data = re.findall(r'"(.*?)"', line) else: data = re.findall(r"'(.*?)'", line) if len(data) == 3: data.append("") if len(data) != 4: raise Exception("badly formatted test data"); retval.append( data ) line = sr.ReadLine() return retval
def _check_magic_file(path_s): ''' ComicVine implementation of the identically named method in the db.py ''' series_ref = None file_s = None try: # 1. get the directory to search for a cvinfo file in, or None dir_s = path_s if path_s and Directory.Exists(path_s) else \ Path.GetDirectoryName(path_s) if path_s else None dir_s = dir_s if dir_s and Directory.Exists(dir_s) else None if dir_s: # 2. search in that directory for a properly named cvinfo file # note that Windows filenames are not case sensitive. for f in [dir_s + "\\" + x for x in ["cvinfo.txt", "cvinfo"]]: if File.Exists(f): file_s = f # 3. if we found a file, read it's contents in, and parse the # comicvine series id out of it, if possible. if file_s: with StreamReader(file_s, Encoding.UTF8, False) as sr: line = sr.ReadToEnd() line = line.strip() if line else line series_ref = __url_to_seriesref(line) except: log.debug_exc("bad cvinfo file: " + sstr(file_s)) if file_s and not series_ref: log.debug("ignoring bad cvinfo file: ", sstr(file_s)) return series_ref # may be None!
def deserialize(self, source, prefixes=None, strict=False, as_attribute=None, as_list=None, as_attribute_of_element=None): if isinstance(source, basestring): try: if os.path.exists(source): xtr = XmlTextReader(StreamReader(source)) except ValueError: xtr = XmlTextReader(StringReader(source)) else: xtr = XmlTextReader(StringReader(source)) elif hasattr(source, 'read'): xtr = XmlTextReader(StringReader(source.read())) settings = XmlReaderSettings() settings.ProhibitDtd = True reader = XmlReader.Create(xtr, settings) document = Document() document.as_attribute = as_attribute or {} document.as_list = as_list or {} document.as_attribute_of_element = as_attribute_of_element or {} self._deserialize(reader, document) xtr.Close() reader.Close() return document
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]
class SharedParametersFileClass(): def __init__(self, filePath, uidoc): self.filePath = filePath self.uidoc = uidoc try: self.filereader = StreamReader( filePath ) self.uidoc.Application.Application.OpenSharedParameterFile() except: Alert( 'Check Your Shared Parameters File Path', title="Error", header="Invalid Shared Parameters File", exit=True ) self.temp = os.environ['USERPROFILE'] + "\\AppData\\Local\\temp.txt" def __enter__(self): self.file = StreamWriter( self.temp ) while self.filereader.Peek() > -1: line = self.filereader.ReadLine() if line.startswith(('*', '#', 'META')): self.file.WriteLine( line ) self.file.Close() self.uidoc.Application.Application.SharedParametersFilename = self.temp self.fileDefinition = self.uidoc.Application.Application.OpenSharedParameterFile() self.groupDefinition = self.fileDefinition.Groups.Create('temp_group') return self def __exit__(self, type, value, traceback): Delete( self.temp ) self.uidoc.Application.Application.SharedParametersFilename = self.filePath def copyExternalDefinition(self, guid, definition): xDefOptions = ExternalDefinitionCreationOptions(definition.Name, definition.ParameterType) xDefOptions.Description = '' xDefOptions.GUID = guid return self.groupDefinition.Definitions.Create( xDefOptions )
def load_profiles_from_file(file_path): """ Loads profiles from a file. file_path->The absolute path the xml file Returns a dict of the profiles """ profiles = {} lastused = "" if File.Exists(file_path): try: with StreamReader(file_path) as xmlfile: xmldoc = XmlDocument() xmldoc.Load(xmlfile) if xmldoc.DocumentElement.Name == "Profiles": nodes = xmldoc.SelectNodes("Profiles/Profile") #Individual exported profiles are saved with the document element as Profile elif xmldoc.DocumentElement.Name == "Profile": nodes = xmldoc.SelectNodes("Profile") #Changed from 1.7 to 2.0 to use Profiles/Profile instead of Settings/Setting elif xmldoc.DocumentElement.Name == "Settings": nodes = xmldoc.SelectNodes("Settings/Setting") elif xmldoc.DocumentElement.Name == "Setting": nodes = xmldoc.SelectNodes("Setting") #No valid root elements else: MessageBox.Show(file_path + " is not a valid Library Organizer profile file.", "Not a valid profile file", MessageBoxButtons.OK, MessageBoxIcon.Error) return profiles, lastused if nodes.Count > 0: for node in nodes: profile = Profile() profile.Name = node.Attributes["Name"].Value result = profile.load_from_xml(node) #Error loading the profile if result == False: MessageBox.Show("An error occured loading the profile " + profile.Name + ". That profile has been skipped.") else: profiles[profile.Name] = profile #Load the last used profile rootnode = xmldoc.DocumentElement if rootnode.HasAttribute("LastUsed"): lastused = rootnode.Attributes["LastUsed"].Value.split(",") except Exception, ex: MessageBox.Show("Something seems to have gone wrong loading the xml file.\n\nThe error was:\n" + str(ex), "Error loading file", MessageBoxButtons.OK, MessageBoxIcon.Error)
def __init__(self, model): """ Display the GUI using data in the model class """ self.model = model stream = StreamReader( os.path.join(os.path.dirname(__file__), GUI_XAML_FILE)) self.window = XamlReader.Load(stream.BaseStream) self.window.Title = self.model.title self.lblPrompt = LogicalTreeHelper.FindLogicalNode( self.window, "lblPrompt") self.lblPrompt.Content = self.model.prompt self.choicesGrid = LogicalTreeHelper.FindLogicalNode( self.window, "choicesGrid") self.choicesChk = System.Array.CreateInstance( CheckBox, len(self.model.choiceList)) self.choicesLabels = System.Array.CreateInstance( Label, len(self.model.choiceList)) for ii, choiceName in enumerate(self.model.choiceList): self.choicesGrid.RowDefinitions.Add(RowDefinition()) self.choicesLabels[ii] = Label() self.choicesLabels[ii].Content = choiceName self.choicesLabels[ii].SetValue(Grid.RowProperty, ii) self.choicesLabels[ii].SetValue(Grid.ColumnProperty, 0) if self.model.alignChoices.lower() == 'left': self.choicesLabels[ ii].HorizontalAlignment = HorizontalAlignment.Left else: self.choicesLabels[ ii].HorizontalAlignment = HorizontalAlignment.Right self.choicesGrid.Children.Add(self.choicesLabels[ii]) self.choicesChk[ii] = CheckBox() self.choicesChk[ii].Margin = Thickness(7.0, 7.0, 2.0, 2.0) self.choicesChk[ii].SetValue(Grid.RowProperty, ii) self.choicesChk[ii].SetValue(Grid.ColumnProperty, 1) self.choicesChk[ii].HorizontalAlignment = HorizontalAlignment.Left self.choicesGrid.Children.Add(self.choicesChk[ii]) self.btCancel = LogicalTreeHelper.FindLogicalNode( self.window, "btCancel") self.btCancel.Click += self.cancel_clicked self.btOK = LogicalTreeHelper.FindLogicalNode(self.window, "btOK") self.btOK.Click += self.ok_clicked self.window.Show() self.window.Closed += lambda s, e: self.window.Dispatcher.InvokeShutdown( ) System.Windows.Threading.Dispatcher.Run()
def apiRequest(relativeUrl): url = baseUrl + relativeUrl print 'calling url ' + url request = HttpWebRequest.Create(url) request.Method = 'GET' request.Accept = 'application/json' request.Headers.Add('Authorization', 'Bearer ' + accessToken) response = request.GetResponse() data = json.loads(StreamReader(response.GetResponseStream()).ReadToEnd()) return data
def __init__(self): try: stream = StreamReader(xaml_path) self.window = XamlReader.Load(stream.BaseStream) self.initialise_icon() self.initialise_elements() self.initialise_visibility() Application().Run(self.window) except Exception as ex: print(ex)
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 FetchURIWithParameters(uri, parameters=None): request = WebRequest.Create(uri) if parameters is not None: request.ContentType = "application/x-www-form-urlencoded" request.Method = "POST" bytes = Encoding.ASCII.GetBytes(parameters) request.ContentLength = bytes.Length reqStream = request.GetRequestStream() reqStream.Write(bytes, 0, bytes.Length) reqStream.Close() response = request.GetResponse() result = StreamReader(response.GetResponseStream()).ReadToEnd() return result
def load_regex_from_file(regex_file): """Loads the regex from the specified xml file""" file = StreamReader(regex_file) xml = XmlDocument() xml.Load(file) file.Close() nodes = xml.SelectNodes("WebComicHelper/ImageRegex") images = [] for node in nodes: images.append(ImageRegex(node.InnerText)) nodes = xml.SelectNodes("WebComicHelper/LinkRegex") links = [] for node in nodes: links.append(LinkRegex(node.InnerText)) nodes = xml.SelectNodes("WebComicHelper/Site") sites = [] for node in nodes: sites.append( SiteRegex( node.SelectSingleNode("ImageRegex").InnerText, node.SelectSingleNode("LinkRegex").InnerText, node.SelectSingleNode("Domain").InnerText)) return images, links, sites