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 onUpdate(): if NetworkInterface.GetIsNetworkAvailable(): try: response = None stream = None try: response = request.GetResponse() stream = response.GetResponseStream() doc = XmlDocument() doc.Load(stream) for itemXmlNode in doc.GetElementsByTagName("item"): entry = Entry() epicenter = None maxLevel = None for xmlNode in itemXmlNode.ChildNodes: if xmlNode.Name.Equals("link"): entry.Resource = Uri(xmlNode.InnerText) elif xmlNode.Name.Equals("description"): entry.Description = xmlNode.InnerText elif xmlNode.Name.Equals("tenkiJP:earthquake"): for attribute in xmlNode.Attributes: if attribute.Name.Equals("epicenter"): epicenter = attribute.Value elif attribute.Name.Equals("max_level"): maxLevel = attribute.Value elif attribute.Name.Equals( "outbreak_datetime"): entry.Created = entry.Modified = DateTime.Parse( attribute.Value) if epicenter is not None: if String.IsNullOrEmpty(maxLevel): maxLevel = "N/A" if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): entry.Title = String.Format( "震度{0} - {1}", maxLevel, epicenter) else: entry.Title = String.Format( "Intensity {0} - {1}", maxLevel, epicenter) entryList.Add(entry) finally: 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 runProc(self): Trace.WriteLine("Start Watching") self.running = True while self.interval > 0 and len(self.targets) > 0: for target in self.targets: try: self.fetch(target) except: Trace.WriteLine(sys.exc_info().ToString()) Thread.Sleep(self.interval * 1000) self.running = False Trace.WriteLine("Stop Watching")
def onUpdate(): if NetworkInterface.GetIsNetworkAvailable(): try: response = None stream = None try: response = request.GetResponse() stream = response.GetResponseStream() doc = XmlDocument() doc.Load(stream) for entryXmlNode in doc.GetElementsByTagName("entry"): entry = Entry() for xmlNode in entryXmlNode.ChildNodes: if xmlNode.Name.Equals("title"): entry.Title = xmlNode.InnerText elif xmlNode.Name.Equals("issued"): entry.Created = DateTime.Parse( xmlNode.InnerText) elif xmlNode.Name.Equals("modified"): entry.Modified = DateTime.Parse( xmlNode.InnerText) elif xmlNode.Name.Equals("link"): for attribute in xmlNode.Attributes: if attribute.Name.Equals("href"): entry.Resource = Uri(attribute.Value) elif xmlNode.Name.Equals("author"): for childXmlNode in xmlNode.ChildNodes: if childXmlNode.Name.Equals("name"): entry.Author = childXmlNode.InnerText entry.Image = Uri( "http://www.google.co.jp/options/icons/gmail.gif") entryList.Add(entry) finally: 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 runProc(self): self.running = True while 1: Thread.Sleep(60 * 60 * 1000) try: self.notify() except: Trace.WriteLine(sys.exc_info().ToString()) self.running = False
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 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:
try: httpListener = HttpListener() httpListener.Prefixes.Add( String.Format( "http://localhost:{0}/", UInt32.Parse("B0B", NumberStyles.HexNumber).ToString( CultureInfo.InvariantCulture))) # localhost:2827 httpListener.Start() httpListener.GetContextAsync().ContinueWith[List[Entry]]( Func[Task[HttpListenerContext], List[Entry]](onDispatch), TaskContinuationOptions.LongRunning).ContinueWith( Action[Task[List[Entry]]](onCompleted), context) except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace) def onExit(sender, args): global sessionEnding, httpListener if not sessionEnding and httpListener is not None: httpListener.Close() def onSessionEnding(sender, args): global sessionEnding, httpListener if httpListener is not None: httpListener.Close()