private void ResetIp() { try { textBoxIP.Text = ""; var req = (HttpWebRequest)WebRequest.Create("http://canyouseeme.org"); var resp = (HttpWebResponse)req.GetResponse(); string x = new StreamReader(resp.GetResponseStream()).ReadToEnd(); // input type="hidden" name="IP" value="41.28.175.2"/> string[] sepd = x.Split(new char[] { '<' }); foreach (string s in sepd) if (s.Contains("input type=\"hidden\" name=\"IP\"")) { string[] spdbyspace = s.Split(new char[] { ' ' }); foreach (string sen in spdbyspace) if (sen.Contains("value")) { string[] spd_by_qoute = sen.Split(new char[] { '"' }); this.CurrentExIp = spd_by_qoute[1]; textBoxIP.Text = this.CurrentExIp; this.ExIpDetetected = true; return; } } } catch (Exception z) { textBoxIP.Text = "No internet"; } }
static public Queue <string> ReadFiles(string path) { Queue <string> data = new Queue <string> { }; try { string[] filesPaths = Directory.GetFiles(@path.ToString(), "*.", SearchOption.TopDirectoryOnly); foreach (string filePath in filesPaths) { try { string file = new System.IO.StreamReader(filePath).ReadToEnd(); string[] docs = file.Split(new string[] { "<DOC>" }, StringSplitOptions.None); foreach (string doc in docs) { if (doc.Length > 0) { data.Enqueue(doc.Split(new string[] { "</DOC>" }, StringSplitOptions.None)[0]); } } } catch (Exception e) { throw e; } } } catch (Exception e) { throw e; } return(data); }
static void Main(string[] args) { var text = new StreamReader("text.txt").ReadToEnd().ToLower(); // string regex = @"\b\w+\b"; // MatchCollectionollection words = Regex.Matches(text, regex); var words = text.Split(new char[] { '.', '!', '?', ';', ' ', ':', ',', '-' }, StringSplitOptions.RemoveEmptyEntries); var dictionary = new Dictionary<string, int>(); foreach (var item in words) { if (dictionary.ContainsKey(item)) { dictionary[item]++; } else { dictionary.Add(item, 1); } } foreach (var item in dictionary.OrderBy(x => x.Value)) { Console.WriteLine("{0} -> {1}", item.Key, item.Value); } Console.ReadKey(true); }
public ActionResult Create(InstallModel m) { if (m.InstallType == "SCHEMA" || ModelState.IsValid) { // Read embedded create script Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream("Piranha.Data.Scripts.Create.sql") ; String sql = new StreamReader(str).ReadToEnd() ; str.Close() ; // Read embedded data script str = Assembly.GetExecutingAssembly().GetManifestResourceStream("Piranha.Data.Scripts.Data.sql") ; String data = new StreamReader(str).ReadToEnd() ; str.Close() ; // Split statements and execute string[] stmts = sql.Split(new char[] { ';' }) ; using (IDbTransaction tx = Database.OpenTransaction()) { // Create database from script foreach (string stmt in stmts) { if (!String.IsNullOrEmpty(stmt.Trim())) SysUser.Execute(stmt, tx) ; } tx.Commit() ; } if (m.InstallType.ToUpper() == "FULL") { // Split statements and execute stmts = data.Split(new char[] { ';' }) ; using (IDbTransaction tx = Database.OpenTransaction()) { // Create user SysUser usr = new SysUser() { Login = m.UserLogin, Email = m.UserEmail, GroupId = new Guid("7c536b66-d292-4369-8f37-948b32229b83"), CreatedBy = new Guid("ca19d4e7-92f0-42f6-926a-68413bbdafbc"), UpdatedBy = new Guid("ca19d4e7-92f0-42f6-926a-68413bbdafbc"), Created = DateTime.Now, Updated = DateTime.Now } ; usr.Save(tx) ; // Create user password SysUserPassword pwd = new SysUserPassword() { Id = usr.Id, Password = m.Password, IsNew = false } ; pwd.Save(tx) ; // Create default data foreach (string stmt in stmts) { if (!String.IsNullOrEmpty(stmt.Trim())) SysUser.Execute(stmt, tx) ; } tx.Commit() ; } } return RedirectToAction("index", "account") ; } return Index() ; }
public static struct014a[] m00022e(string p0, string p1, string p2) { FtpWebResponse response = m000230(p0, p1, p2, "LIST").GetResponse() as FtpWebResponse; string str = new StreamReader(response.GetResponseStream(), Encoding.ASCII).ReadToEnd(); response.Close(); List<struct014a> list = new List<struct014a>(); string[] strArray = str.Split(new char[] { '\n' }); enum01fa enumfa = m000231(strArray); foreach (string str2 in strArray) { if ((enumfa != enum01fa.f0000c0) && (str2 != "")) { struct014a item = new struct014a(); item.f0000d7 = ".."; switch (enumfa) { case enum01fa.f00002a: item = m000082(str2); break; case enum01fa.f0000bf: item = m000081(str2); break; } if ((item.f0000d7 != ".") && (item.f0000d7 != "..")) { list.Add(item); } } } return list.ToArray(); }
public EvoSQLExpression(string query) { MemoryStream stream = new MemoryStream(); String errorString; StreamWriter writer = new StreamWriter(stream); writer.Write(query); writer.Flush(); Scanner scanner = new Scanner(stream); Parser parser = new Parser(scanner); MemoryStream errorStream = new MemoryStream(); StreamWriter errorWriter = new StreamWriter(errorStream); parser.errors.errorStream = errorWriter; parser.Parse(); errorWriter.Flush(); errorStream.Seek(0, SeekOrigin.Begin); errorString = new StreamReader(errorStream).ReadToEnd(); errorStream.Close(); stream.Close(); if (parser.errors.count > 0) { Errors = errorString.Split('\n'); HadErrors = true; } else { Tree = parser.RootTree; } }
public static Queue<string> ReadFiles(string path) { Queue<string> data = new Queue<string> { }; try { string[] filesPaths = Directory.GetFiles(@path.ToString(), "*.", SearchOption.TopDirectoryOnly); foreach (string filePath in filesPaths) { try { string file = new System.IO.StreamReader(filePath).ReadToEnd(); string[] docs = file.Split(new string[] { "<DOC>" }, StringSplitOptions.None); foreach (string doc in docs) { if (doc.Length > 0) data.Enqueue(doc.Split(new string[] { "</DOC>" }, StringSplitOptions.None)[0]); } } catch (Exception e) { throw e; } } } catch (Exception e) { throw e; } return data; }
public HttpResponseMessage ssoauth() { var ssoToken = string.Empty; var ssoTokenName = string.Empty; using (var requestStream = HttpContext.Current.Request.InputStream) { requestStream.Seek(0, SeekOrigin.Begin); var rawBody = new StreamReader(requestStream).ReadToEnd(); if (!string.IsNullOrEmpty(rawBody)) { var ary=rawBody.Split("=".ToCharArray(),2); if (ary.Length != 2 || !ConfigHelper.IsValidToken(ary[0])) return Request.CreateErrorResponse(HttpStatusCode.Unauthorized,new Exception("testing")); ssoToken = ary[1]; ssoTokenName = ary[0]; } } var result = new GradeBusiness().GetGradeResponse(ssoToken, ssoTokenName); HttpStatusCode code; if (!Enum.TryParse(result.StatusCode, out code)) code = HttpStatusCode.OK; return Request.CreateResponse(code, result, new JsonMediaTypeFormatter()); }
/// <summary> /// Looks up the messaging address for the phone number /// </summary> /// <param name="cc">Country Code</param> /// <param name="num">Phone Number</param> /// <returns>The messaging address to that phone number</returns> public static string GetAddressForNumber(string cc, string num) { byte[] b = System.Text.Encoding.ASCII.GetBytes("cc=" + cc + "&phonenum=" + num); WebRequest r = WebRequest.Create("http://www.freecarrierlookup.com/getcarrier.php"); r.ContentType = "application/x-www-form-urlencoded"; r.ContentLength = b.Length; r.Method = "POST"; Stream requestStream = r.GetRequestStream(); requestStream.Write(b, 0, b.Length); requestStream.Close(); HttpWebResponse response; response = (HttpWebResponse)r.GetResponse(); string responseStr; if (response.StatusCode == HttpStatusCode.OK) { Stream responseStream = response.GetResponseStream(); responseStr = new StreamReader(responseStream).ReadToEnd(); string[] respTok = responseStr.Split(new string[] { "<", ">" }, StringSplitOptions.RemoveEmptyEntries); foreach (string token in respTok) { if (token.Contains("@")) { return token; } } return null; } else { Console.WriteLine("RETRY."); return null; } }
public static Word GetWordById(List<WordSource> wordSourceList, int sourceId, int wordId) { WordSource wordSource = WordSourceHelper.GetWordSourceById(wordSourceList, sourceId); if (wordSource == null) return null; StreamResourceInfo streamResourceInfo = Application.GetResourceStream(wordSource.fileUri); if (streamResourceInfo != null) { Stream stream = streamResourceInfo.Stream; string fileContent = new StreamReader(stream).ReadToEnd(); string[] lines = fileContent.Split('\n'); for (int i = 0; i < lines.Length; i++) { string[] lineParts = lines[i].Trim().Split('\t'); if (int.Parse(lineParts[0]) == wordId) { Word word = ConvertLineToWord(lines[i]); return word; } } } return null; }
public void runServer() { tcpListener.Start(); //Byte[] bytes = new Byte[16]; //Byte[] data = new Byte[16]; while (true) { TcpClient tcpClient = tcpListener.AcceptTcpClient(); NetworkStream stream = tcpClient.GetStream(); string command = new StreamReader(stream).ReadToEnd(); string[] commands = command.Split(seperators); if (commands[0].Contains("GET")) { file = new File(commands[1]); FileStream fs = new FileStream(commands[1], FileMode.Open); int currentPos = 0; while (currentPos < fs.Length) { byte[] bytes = new byte[16]; int data = fs.Read(bytes, currentPos, 16); stream.Write(bytes, 0, 16); currentPos += 16; } } } }
public static void PrepareRhetosDatabase(ISqlExecuter sqlExecuter) { string rhetosDatabaseScriptResourceName = "Rhetos.Deployment.RhetosDatabase." + SqlUtility.DatabaseLanguage + ".sql"; var resourceStream = typeof(DeploymentUtility).Assembly.GetManifestResourceStream(rhetosDatabaseScriptResourceName); if (resourceStream == null) throw new FrameworkException("Cannot find resource '" + rhetosDatabaseScriptResourceName + "'."); var sql = new StreamReader(resourceStream).ReadToEnd(); var sqlScripts = sql.Split(new[] {"\r\nGO\r\n"}, StringSplitOptions.RemoveEmptyEntries).Where(s => !String.IsNullOrWhiteSpace(s)); sqlExecuter.ExecuteSql(sqlScripts); }
public static string[] SaveIniFileContent(IniFile file, IniOptions options) { string iniFileContent; using (var stream = new MemoryStream()) { file.Save(stream); iniFileContent = new StreamReader(stream, options.Encoding).ReadToEnd(); } return iniFileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); }
public void write(string data) { Request.InputStream.Seek(0, SeekOrigin.Begin); string jsonData = new StreamReader(Request.InputStream).ReadToEnd(); String subject = jsonData.Split('<')[0]; int subjectId = Int32.Parse(subject); String xaml = jsonData.Substring(subject.Length); _db.WS_Subjects.Find(subjectId).Xaml_Data = xaml; _db.SaveChanges(); }
public static void Main() { var text = new StreamReader("../../text.txt").ReadToEnd().ToLower(); var splitedWords = text.Split(new char[] { '.', '!', '?', ';', ' ', ':', ',', '-' }, StringSplitOptions.RemoveEmptyEntries); var dictionary = splitedWords.GroupBy(w => w).ToDictionary(w => w.Key, w => w.Count()).OrderBy(w => w.Value); foreach (var pair in dictionary) { Console.WriteLine("Word: {0} -> appearance {1}", pair.Key, pair.Value); } }
// [OperationBehavior( // TransactionAutoComplete = true, // TransactionScopeRequired = true //)] // [TransactionFlow(TransactionFlowOption.Mandatory)] public string GetFileAttributes(string filePath) { FileInfo fi = new System.IO.FileInfo(filePath); int charCount = 0; int linesCount = 0; string FileText = new System.IO.StreamReader(filePath).ReadToEnd().Replace("\r\n", "\r"); charCount = FileText.Length; linesCount = FileText.Split('\r').Length; long total_size_in_bytes = fi.Length; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Total Size: " + total_size_in_bytes + "\n"); stringBuilder.Append("Character Count: " + FileText.Length + "\n"); stringBuilder.Append("Line Count: " + FileText.Split('\r').Length + "\n"); string fileDetails = stringBuilder.ToString(); return(fileDetails); }
internal static string[] fileToDocString(string filePath) { /* XmlDocument file = new XmlDocument(); XmlNodeList docs = file.GetElementsByTagName("DOC"); foreach (XmlNode doc in docs) { RetrievalEngineProject.MainWindow.docCounter++; Doc newDoc = new Doc(elem); } doc.Load(filePath); */ string file = new System.IO.StreamReader(filePath).ReadToEnd(); return file.Split(new string[] { "<DOC>" }, StringSplitOptions.None); }
internal static string[] fileToDocString(string filePath) { /* * XmlDocument file = new XmlDocument(); * XmlNodeList docs = file.GetElementsByTagName("DOC"); * foreach (XmlNode doc in docs) * { * RetrievalEngineProject.MainWindow.docCounter++; * Doc newDoc = new Doc(elem); * } * doc.Load(filePath); */ string file = new System.IO.StreamReader(filePath).ReadToEnd(); return(file.Split(new string[] { "<DOC>" }, StringSplitOptions.None)); }
internal static string IsPortForwarded(string ip , decimal p) { string port = p.ToString(); string url = "http://canyouseeme.org"; var request = (HttpWebRequest)WebRequest.Create(url); string Text = "Fail"; try { var postData = "port=" + port; postData += "&IP=" + ip; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; request.Referer = "http://canyouseeme.org/"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0)"; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); string[] spd = responseString.Split(new string[] { "<p" }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in spd) if (s.Contains("style=\"padding-left:15px\">")) { if (s.Contains("<form")) { string[] xx = s.Split(new string[] { "<form" }, StringSplitOptions.RemoveEmptyEntries); Text = AnalyzPortOpenResult(xx[0]); } else Text = s; break; } } catch (Exception ph) { } return Text; }
private Hashtable GetFormValues(HttpListenerRequest request) { Hashtable formVars = new Hashtable(); //add request data at bottom of page if (request.HasEntityBody) { var s = new StreamReader(request.InputStream).ReadToEnd(); //string s = reader.ReadToEnd(); string[] pairs = s.Split('&'); for (int x = 0; x < pairs.Length; x++) { string[] item = pairs[x].Split('='); formVars.Add(item[0], System.Web.HttpUtility.UrlDecode(item[1])); } } return formVars; }
private List<string> GetAllImageURLListFromWebPage(string webpageURL) { List<string> lstImgURLS = new List<string>(); HttpWebResponse response = (HttpWebResponse)WebRequest.Create(webpageURL).GetResponse(); string respText = new StreamReader(response.GetResponseStream()).ReadToEnd(); foreach (string tag in respText.Split('<')) { if (IsImageTag(tag)) { string srcVal = GetSubstringBetweenTags(tag, "src=\"", "\""); lstImgURLS.Add(IsValidURL(srcVal) ? srcVal : webpageURL + srcVal); } } return lstImgURLS; }
public NameValueCollection ReadPostParams(Stream stream) { string postData = new StreamReader(stream, Encoding.ASCII).ReadToEnd(); Console.WriteLine(postData); NameValueCollection result = new NameValueCollection(); string[] pairs = postData.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (string pair in pairs) { int d = pair.IndexOf('='); if (d == -1) result.Add(string.Empty, pair); else result.Add( HttpUtility.UrlDecode(pair.Substring(0, d), Encoding.ASCII), HttpUtility.UrlDecode(pair.Substring(d + 1, pair.Length - d - 1), Encoding.ASCII)); } return result; }
public OAuthToken GetRequestToken(Uri baseUri, string consumerKey, string consumerSecret) { var uri = new Uri(baseUri, "oauth/request_token"); uri = SignRequest(uri, consumerKey, consumerSecret); var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Http.Get; var response = request.GetResponse(); var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd(); var parts = queryString.Split('&'); var token = parts[1].Substring(parts[1].IndexOf('=') + 1); var secret = parts[0].Substring(parts[0].IndexOf('=') + 1); return new OAuthToken(token, secret); }
public void Run() { ulong sum = 0; FileStream stream = File.OpenRead("names.txt"); String str = new StreamReader(stream).ReadToEnd(); String[] names = str.Split('"'); foreach (var s in names) if (s != "," && s != "") unordered.Add(s); unordered.Sort(); for (ulong i = 0; i < (ulong)unordered.Count; ++i) { string s = unordered[(int)i]; ulong value = 0; foreach (var c in s.ToCharArray()) value += Convert.ToUInt32(c) - 64; sum += (i+1) * value; } Console.WriteLine("The sum is {0}", sum); }
public static List<Word> ReadWordFileToList(Uri fileUri) { List<Word> list = new List<Word>(); StreamResourceInfo streamResourceInfo = Application.GetResourceStream(fileUri); if (streamResourceInfo != null) { Stream stream = streamResourceInfo.Stream; string fileContent = new StreamReader(stream).ReadToEnd(); string[] lines = fileContent.Split('\n'); for (int i = 0; i < lines.Length; i++) { Word word = ConvertLineToWord(lines[i]); if (word != null) list.Add(word); } } return list; }
protected override void ParseData(MemoryStream ms) { Encoding iso = Encoding.GetEncoding("ISO-8859-1"); string combined = new StreamReader(ms, iso).ReadToEnd(); string[] parts = combined.Split('\0'); if (parts.Length != 2) { // Warn about invalid chunk? } if (parts.Length > 0) { Keyword = parts[0]; } if (parts.Length > 1) { Text = parts[1]; } }
public ActionResult DeleteBlobById() { Stream req = Request.InputStream; req.Seek(0, System.IO.SeekOrigin.Begin); string data = new StreamReader(req).ReadToEnd(); StringBuilder sb = new StringBuilder(); BlobFactory blobFactory = ServiceLocator.Current.GetInstance<BlobFactory>(); string[] idList = data.Split(new []{'\n'}, StringSplitOptions.RemoveEmptyEntries); foreach (string uri in idList) { Uri blobUri = new Uri(uri); sb.AppendFormat("Deleting: {0}", uri); DeleteBlob(blobUri, sb, blobFactory); } ContentResult result = new ContentResult(); result.Content = sb.ToString(); return result; }
private void button1_Click(object sender, EventArgs e) { string ip = this.CurrentExIp; string port = numericUpDownPort.Value.ToString(); string url = "http://canyouseeme.org"; var request = (HttpWebRequest)WebRequest.Create(url); var postData = "port="+port; postData += "&IP="+ip; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; request.Referer = "http://canyouseeme.org/"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0)"; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); string [] spd = responseString.Split(new string[]{"<p"},StringSplitOptions.RemoveEmptyEntries); foreach (string s in spd) if (s.Contains("style=\"padding-left:15px\">")) { if(s.Contains("<form")) { string[] xx = s.Split(new string[] { "<form" }, StringSplitOptions.RemoveEmptyEntries); labelPortCheckResult.Text = AnalyzPortOpenResult(xx[0]); } else labelPortCheckResult.Text = s; break; } }
public OAuthToken GetRequestToken() { var uri = new Uri(new Uri(CloudptBaseUri), "oauth/request_token"); if(_callbackUrl != null) _callbackUrl = _oAuthBase.UrlEncode(_callbackUrl); uri = SignRequest(uri, _consumerKey, _consumerSecret, _callbackUrl); var request = (HttpWebRequest) WebRequest.Create(uri); request.Method = WebRequestMethods.Http.Get; var response = request.GetResponse(); var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd(); var parts = queryString.Split('&'); var token = parts[1].Substring(parts[1].IndexOf('=') + 1); var secret = parts[0].Substring(parts[0].IndexOf('=') + 1); return new OAuthToken(token, secret); }
/// <summary> /// 机票具体信息查询接口 /// </summary> public AiFeiTicketInfo TicketInfo(string num) { try { string url = aifeServerUrl + ticketInfoUrl + _account + num; //string url = "http://localhost:4896/web/af.html"; WebRequest request = WebRequest.Create(url); request.Timeout = 5000; WebResponse response = request.GetResponse(); string responseText = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd(); string[] ticketOptions = responseText.Split('^'); if (ticketOptions.Length == 22) { AiFeiTicketInfo afte = new AiFeiTicketInfo(); afte.fromCityCode = ticketOptions[0]; long id = 0; afte.fromCityName = ReadXmlHelper.GetFromCityNameByCode(ticketOptions[0].ToString(), out id); afte.toCityCode = ticketOptions[1]; afte.toCityName = ReadXmlHelper.GetToCityNameByCode(ticketOptions[1].ToString(), out id); afte.fromAirportCode = ticketOptions[2]; afte.fromAirportName = ReadXmlHelper.GetAirPortNameByCode(ticketOptions[2]); afte.toAirportCode = ticketOptions[3]; afte.toAirportName = ReadXmlHelper.GetAirPortNameByCode(ticketOptions[3]); afte.airlineName = ticketOptions[4]; if (ticketOptions[5] == "SF") { afte.tripType = "1"; } else if (ticketOptions[5] == "DC") { afte.tripType = "0"; } afte.ft = ticketOptions[6]; afte.cangwei = ticketOptions[7]; afte.untaxprice = ticketOptions[8]; afte.shortstayDate = ticketOptions[9]; afte.longstayDate = ticketOptions[10]; afte.childPrice = ticketOptions[11]; afte.fromsaleDate = ticketOptions[12]; afte.tosaleDate = ticketOptions[13]; afte.fromtripDate = ticketOptions[14]; afte.totripDate = ticketOptions[15]; afte.returnMoney = ticketOptions[16]; afte.updateProvision = ticketOptions[17]; afte.wuji = ticketOptions[18]; afte.xingli = ticketOptions[19]; afte.limitProvision = ticketOptions[20]; return(afte); } } catch { return(null); } return(null); }
/// <summary> /// Populates the insert combobox /// </summary> private void PopulateInsertComboBox() { try { String locale = Globals.Settings.LocaleVersion.ToString(); Stream stream = ResourceHelper.GetStream(String.Format("SnippetVars.{0}.txt", locale)); String contents = new StreamReader(stream).ReadToEnd(); String[] varLines = contents.Split(new Char[1]{'\n'}, StringSplitOptions.RemoveEmptyEntries); foreach (String line in varLines) { this.insertComboBox.Items.Add(line.Trim()); } this.insertComboBox.SelectedIndex = 0; stream.Close(); stream.Dispose(); } catch (Exception ex) { ErrorManager.ShowError(ex); } }
/* * private void Request() * { * WebRequest request = WebRequest.Create(_httpUrl); * WebResponse response = request.GetResponse(); * string text = new StreamReader(response.GetResponseStream(), Encoding.Default).ReadToEnd(); * } */ /// <summary> /// /// </summary> /// <param name="Account">账号</param> /// <param name="Dpt">出发城市三字码</param> /// <param name="Arr">母的城市三字码</param> /// <param name="ToTime">出发日期</param> /// <param name="ReTime">返回日期</param> /// <param name="Cate">all 全部,DC 单程,SF往返</param> /// <returns></returns> public ArrayList GlobalTicket(string Dpt, string Arr, string ToTime, string ReTime, string Cate) { ///获得三字码 string url = aifeServerUrl + globalTicketUrl + _account + Dpt + "/" + Arr + "/" + ToTime + "/" + ReTime + "/" + Cate; //string url = "http://*****:*****@'); foreach (string ticketText in ticketArray) { string[] ticketOptions = ticketText.Split('^'); if (ticketOptions.Length == 10) { DateTime dt = DateTime.ParseExact(ticketOptions[6], "yyyyMMdd", Thread.CurrentThread.CurrentCulture); if (dt < DateTime.Now) { continue; } bool iscon = false; foreach (AiFeiTicketEntity v in tickets) { if (Convert.ToInt32(v.ticketPrice) == Convert.ToInt32(ticketOptions[8])) { iscon = true; break; } } if (iscon) { continue; } AiFeiTicketEntity afte = new AiFeiTicketEntity(); afte.fromCity = ticketOptions[0]; afte.toCity = ticketOptions[1]; afte.type = ticketOptions[2]; afte.seatShip = ticketOptions[3]; afte.shotstayDate = ticketOptions[4]; afte.longstayDate = ticketOptions[5]; afte.totripDate = ticketOptions[6]; afte.airlineCode = ticketOptions[7]; afte.ticketPrice = ticketOptions[8]; afte.ticketCode = ticketOptions[9]; tickets.Add(afte); } } return(tickets); }
public void Process(ISemanticProcessor proc, IMembrane membrane, Route route) { IPublicRouterService routerService = proc.ServiceManager.Get<IPublicRouterService>(); HttpListenerContext context = route.Context; HttpVerb verb = context.Verb(); UriPath path = context.Path(); string searchRoute = GetSearchRoute(verb, path); RouteInfo routeInfo; // Semantic routes can be either public or authenticated. if (routerService.Routes.TryGetValue(searchRoute, out routeInfo)) { string data = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd(); Type receptorSemanticType = routeInfo.ReceptorSemanticType; SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType); semanticRoute.PostData = data; if (!String.IsNullOrEmpty(data)) { // Is it JSON? if (data[0] == '{') { JsonConvert.PopulateObject(data, semanticRoute); } else { // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login" string[] parms = data.Split('&'); foreach (string parm in parms) { string[] keyVal = parm.Split('='); PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // TODO: Convert to property type. // TODO: value needs to be re-encoded to handle special characters. pi.SetValue(semanticRoute, keyVal[1]); } } } } else if (verb.Value == "GET") { // Parse parameters NameValueCollection nvc = context.Request.QueryString; foreach(string key in nvc.AllKeys) { PropertyInfo pi = receptorSemanticType.GetProperty(key, BindingFlags.Public | BindingFlags.Instance); if (pi != null) { // TODO: Convert to property type. // TODO: value needs to be re-encoded to handle special characters. pi.SetValue(semanticRoute, nvc[key]); } } } // Must be done AFTER populating the object -- sometimes the json converter nulls the base class! semanticRoute.Context = context; proc.ProcessInstance<WebServerMembrane>(semanticRoute, true); // TODO: Why execute on this thread? } else if (verb.Value == "GET") { // Only issue the UnhandledContext if this is not an authenticated route. if (!proc.ServiceManager.Get<IAuthenticatingRouterService>().IsAuthenticatedRoute(searchRoute)) { // Put the context on the bus for some service to pick up. // All unhandled context are assumed to be public routes. proc.ProcessInstance<WebServerMembrane, UnhandledContext>(c => c.Context = context); } } else { proc.ProcessInstance<WebServerMembrane, ExceptionResponse>(e => { e.Context = context; e.Exception = new Exception("Route " + searchRoute + " not defined."); }); } }
private void download(string url) { try { m_uri = new Uri(url); m_html = ""; m_outstr = ""; m_title = ""; m_good = true; if (url.EndsWith(".rar") || url.EndsWith(".dat") || url.EndsWith(".msi")) { m_good = false; return; } HttpWebRequest rqst = (HttpWebRequest)WebRequest.Create(m_uri); rqst.Timeout = 30000; //rqst.AllowAutoRedirect = true; //rqst.MaximumAutomaticRedirections = 3; //rqst.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)"; //rqst.KeepAlive = true; //rqst.Method = "GET"; //rqst.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; //rqst.Headers.Add("Accept-Language: en-us,en;q=0.5"); //rqst.Headers.Add("Accept-Encoding: gzip,deflate"); //rqst.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); //rqst.Referer = m_uri.Host; lock (DownloadHelper.webcookies) { if (DownloadHelper.webcookies.ContainsKey(m_uri.Host)) rqst.CookieContainer = DownloadHelper.webcookies[m_uri.Host]; else { CookieContainer cc = new CookieContainer(); DownloadHelper.webcookies[m_uri.Host] = cc; rqst.CookieContainer = cc; } } HttpWebResponse rsps = (HttpWebResponse)rqst.GetResponse(); Stream sm = rsps.GetResponseStream(); if (!rsps.ContentType.ToLower().StartsWith("text/") || rsps.ContentLength > 1 << 22) { rsps.Close(); m_good = false; return; } Encoding cding = System.Text.Encoding.Default; string contenttype = rsps.ContentType.ToLower(); int ix = contenttype.IndexOf("charset="); if (ix != -1) { try { cding = System.Text.Encoding.GetEncoding(rsps.ContentType.Substring(ix + "charset".Length + 1)); } catch { cding = Encoding.Default; } //m_html = HttpUtility.HtmlDecode(new StreamReader(sm, cding).ReadToEnd()); m_html = new StreamReader(sm, cding).ReadToEnd(); } else { //m_html = HttpUtility.HtmlDecode(new StreamReader(sm, cding).ReadToEnd()); m_html = new StreamReader(sm, cding).ReadToEnd(); Regex regex = new Regex("charset=(?<cding>[^=]+)?\"", RegexOptions.IgnoreCase); string strcding = regex.Match(m_html).Groups["cding"].Value; try { cding = Encoding.GetEncoding(strcding); } catch { cding = Encoding.Default; } byte[] bytes = Encoding.Default.GetBytes(m_html.ToCharArray()); m_html = cding.GetString(bytes); if (m_html.Split('?').Length > 100) { m_html = Encoding.Default.GetString(bytes); } } m_pagesize = m_html.Length; m_uri = rsps.ResponseUri; rsps.Close(); } catch (Exception ex) { } }
public ActionResult ExecuteUpdate() { if (Application.Current.UserProvider.IsAuthenticated && User.HasAccess("ADMIN")) { // Execute all incremental updates in a transaction. using (IDbTransaction tx = Database.OpenTransaction()) { for (int n = Data.Database.InstalledVersion + 1; n <= Data.Database.CurrentVersion; n++) { // Read embedded create script Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream(Database.ScriptRoot + ".Updates." + n.ToString() + ".sql") ; String sql = new StreamReader(str).ReadToEnd() ; str.Close() ; // Split statements and execute string[] stmts = sql.Split(new char[] { ';' }) ; foreach (string stmt in stmts) { if (!String.IsNullOrEmpty(stmt.Trim())) SysUser.Execute(stmt.Trim(), tx) ; } // Check for update class var utype = Type.GetType("Piranha.Data.Updates.Update" + n.ToString()) ; if (utype != null) { IUpdate update = (IUpdate)Activator.CreateInstance(utype) ; update.Execute(tx) ; } } // Now lets update the database version. SysUser.Execute("UPDATE sysparam SET sysparam_value = @0 WHERE sysparam_name = 'SITE_VERSION'", tx, Data.Database.CurrentVersion) ; SysParam.InvalidateParam("SITE_VERSION") ; tx.Commit() ; } return RedirectToAction("index", "account") ; } else return RedirectToAction("update") ; }