public static string Api(string Temperature,string Humidity)
        {
            string url = (string)Properties.Settings.Default["ApiAddress"];
            string resText = "";
            try {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.Collections.Specialized.NameValueCollection ps =
                    new System.Collections.Specialized.NameValueCollection();

                ps.Add("MachineName", (string)Properties.Settings.Default["MachineName"]);
                ps.Add("Temperature", Temperature);
                ps.Add("Humidity", Humidity);

                byte[] ResData = wc.UploadValues(url, ps);
                wc.Dispose();
                resText = System.Text.Encoding.UTF8.GetString(ResData);
                if (resText != "OK")
                {
                    return "APIエラー";
                }
            }
            catch (Exception ex){
                return ex.ToString();
            }

            return null;
        }
 private static string APIRequest(string request)
 {
     System.Net.WebClient http = new System.Net.WebClient();
     http.Headers.Add("X-Mashape-Key: LigI9kHL7omsh5NN0rCWg0d6PA5jp1TdGUUjsnexk2zQ42JwCA");
     var response = http.DownloadString(request);
     http.Dispose();
     return response;
 }
Exemple #3
0
		public void PopulateScoreAndBody()
		{
			var wb = new System.Net.WebClient();
			var html = wb.DownloadString(URL);

			Body = GetBody(html);
			Score = GetScore(html);

			wb.Dispose();
		}
Exemple #4
0
        /// <summary>
        /// 开始下载更新升级包
        /// </summary>
        public void DownLoad()
        {
            System.Net.WebClient webC = new System.Net.WebClient();//用于读取文件最新版信息的WebClient
            string versionStr = "";

            try
            {
                versionStr = webC.DownloadString(this.VersionFileURI);
            }
            catch { }

            if (versionStr.Trim() == "")//如果没有获得升级文件版本信息
            {
                webC.Dispose();
                this.webFile1.Dispose();
                this.Dispose();
            }
            else
            {
                webC.Dispose();
                if (versionStr.Trim() != System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString())//如果软件版本与现有的客户端不同,则下载最新版本
                    if (MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                        + "已有更新版本,是否下载并安装?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        this.Visible = true;
                        this.Width = 334;
                        this.Height = 154;
                        this.label1.Text = "正在下载更新程序,请稍等...";
                        this.timer1.Enabled = true;//开始执行下载最新版升级程序任务
                    }
                    else
                    {
                        this.webFile1.Dispose();
                        this.Dispose();
                    }
                else
                {
                    this.webFile1.Dispose();
                    this.Dispose();
                }
            }
        }
Exemple #5
0
        static void Main(string[] args)
        {
            DBUtil.Connect();

            Logger.Instance.Debug("aa");

            // YPからチャンネル情報を取得
            List<ChannelDetail> channelDetails = GetChannelDetails();

            // 配信者マスターの更新
            UpdateChannel(channelDetails);

            // スレッド情報の更新
            UpdateBBSThread(channelDetails);

            // レス情報の更新
            UpdateBBSResponse();

            /*
            List<string> imgList = new List<string>();
            // レス一覧の取得
            List<BBSResponse> resList = BBSResponseDao.Select();
            foreach (BBSResponse res in resList)
            {
                Match match = Regex.Match(res.Message, @"ttp://.*\.(jpg|JPG|jpeg|JPEG|bmp|BMP|png|PNG)");

                if (match.Success)
                {
                    string imageUrl = "h" + match.Value;
                    imgList.Add(imageUrl);
                    ImageLinkDao.Insert(res.ThreadUrl, res.ResNo, imageUrl, res.WriteTime);
                }
            }
             */

            List<ImageLink> imageList = ImageLinkDao.Select();

            foreach (ImageLink link in imageList)
            {
                try
                {
                    System.Net.WebClient wc = new System.Net.WebClient();
                    wc.DownloadFile(link.ImageUrl, @"S:\MyDocument_201503\dev\github\PecaTsu_BBS\src_BBS\img\" + (link.WriteTime.Replace("/", "").Replace(":", "")) + ".jpg");
                    wc.Dispose();
                }
                catch (Exception)
                {
                }
            }

            DBUtil.Close();
        }
Exemple #6
0
 public static void downloadFile(string url, string sourcefile, string user, string pwd)
 {
     try
     {
         System.Net.WebClient Client = new System.Net.WebClient();
         Client.Credentials = new System.Net.NetworkCredential(user, pwd);
         Client.DownloadFile(url, sourcefile);
         Client.Dispose();
     }
     catch (Exception e)
     {
         throw (e);
     }
 }
        /// <summary>  
        /// 根据WEBSERVICE地址获取一个 Assembly  
        /// </summary>  
        /// <param name="p_Url">地址</param>  
        /// <param name="p_NameSpace">命名空间</param>  
        /// <returns>返回Assembly</returns>  
        public static Assembly GetWebServiceAssembly(string p_Url, string p_NameSpace)
        {
            try
            {
                System.Net.WebClient _WebClient = new System.Net.WebClient();

                System.IO.Stream _WebStream = _WebClient.OpenRead(p_Url);

                ServiceDescription _ServiceDescription = ServiceDescription.Read(_WebStream);

                _WebStream.Close();
                _WebClient.Dispose();
                ServiceDescriptionImporter _ServiceDescroptImporter = new ServiceDescriptionImporter();
                _ServiceDescroptImporter.AddServiceDescription(_ServiceDescription, "", "");
                System.CodeDom.CodeNamespace _CodeNameSpace = new System.CodeDom.CodeNamespace(p_NameSpace);
                System.CodeDom.CodeCompileUnit _CodeCompileUnit = new System.CodeDom.CodeCompileUnit();
                _CodeCompileUnit.Namespaces.Add(_CodeNameSpace);
                _ServiceDescroptImporter.Import(_CodeNameSpace, _CodeCompileUnit);

                System.CodeDom.Compiler.CodeDomProvider _CodeDom = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters _CodeParameters = new System.CodeDom.Compiler.CompilerParameters();
                _CodeParameters.GenerateExecutable = false;
                _CodeParameters.GenerateInMemory = true;
                _CodeParameters.ReferencedAssemblies.Add("System.dll");
                _CodeParameters.ReferencedAssemblies.Add("System.XML.dll");
                _CodeParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
                _CodeParameters.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults _CompilerResults = _CodeDom.CompileAssemblyFromDom(_CodeParameters, _CodeCompileUnit);

                if (_CompilerResults.Errors.HasErrors)
                {
                    string _ErrorText = "";
                    foreach (CompilerError _Error in _CompilerResults.Errors)
                    {
                        _ErrorText += _Error.ErrorText + "/r/n";
                    }
                    throw new Exception(_ErrorText);
                }

                return _CompilerResults.CompiledAssembly;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage :  ");
                Console.WriteLine("cssd http://example.com/styles.css");
                return;
            }
            // No options. Just URL of the css.
            string cssFile = args[0];

            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                Uri furi = new Uri(cssFile);
                string content = wc.DownloadString(furi);
                Console.WriteLine("File downloaded.. Looking for url() references to download.");
                DirectoryInfo di = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, furi.Segments[furi.Segments.Length - 1]));
                UriBuilder ub = new UriBuilder();
                ub.Host = furi.Host;
                ub.Scheme = furi.Scheme;
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex("url(\\((.*?)\\))");
                MatchCollection matches = rg.Matches(content);
                int i = 0;
                foreach (Match item in matches)
                {
                    string url = item.Groups[2].Value;
                    ub.Path = url;
                    wc.DownloadFile(ub.Uri, System.IO.Path.Combine(di.FullName, ub.Uri.Segments[ub.Uri.Segments.Length - 1]));
                    content = content.Replace(url, ub.Uri.Segments[ub.Uri.Segments.Length - 1]);
                    DrawProgressBar(i, matches.Count, 40, '=');
                    i++;
                }
                wc.Dispose();

                DrawProgressBar(matches.Count, matches.Count, 40, '=');
                Console.WriteLine("");
                Console.WriteLine("Complete!");
                System.Threading.Thread.Sleep(300);
                System.IO.File.WriteAllText(System.IO.Path.Combine(di.FullName, furi.Segments[furi.Segments.Length - 1]), content);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
            }
        }
Exemple #9
0
        /// <summary>
        /// このクラスでの実行すること。
        /// </summary>
        /// <param name="runChildren"></param>
        public override void Run(bool runChildren)
        {
            string apiIds = ApiId;
            if (string.IsNullOrEmpty(ApiId))
            {
                apiIds = Rawler.Tool.GlobalVar.GetVar("YahooApiId");
            }
            if (string.IsNullOrEmpty(apiIds))
            {
                Rawler.Tool.ReportManage.ErrReport(this, "YahooApiIdがありません。SetTmpValで指定してください");
                return;
            }
            string apiId = apiIds.Split(',').OrderBy(n => Guid.NewGuid()).First();
            string baseUrl = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
            var post = "appid=" + apiId + "&sentence=" +Uri.EscapeUriString(GetText());
            string result = string.Empty;
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Headers.Add("Content-Type","application/x-www-form-urlencoded");
                wc.Encoding = Encoding.UTF8;
                result = wc.UploadString(new Uri(baseUrl), "POST", post);
                wc.Dispose();
            }
            catch(Exception e)
            {
                ReportManage.ErrReport(this, e.Message +"\t"+GetText());
            }
            if (result != string.Empty)
            {
                var root = XElement.Parse(result);
                var ns = root.GetDefaultNamespace();
                var list = root.Descendants(ns + "Result").Select(n => new KeyphraseResult() { Keyphrase = n.Element(ns + "Keyphrase").Value, Score = double.Parse(n.Element(ns + "Score").Value) });

                List<string> list2 = new List<string>();
                foreach (var item in list)
                {
                    list2.Add(Codeplex.Data.DynamicJson.Serialize(item));
                }

                base.RunChildrenForArray(runChildren, list2);
            }
        }
Exemple #10
0
        private static void Discover()
        {
            var c = new System.Net.WebClient();
            var p = c.DownloadString("http://localhost:4743/PingTrace/Ping");
            var ts = c.DownloadString("http://localhost:4743/PingTrace/Traces");

            Console.WriteLine("Ping:");
            Console.WriteLine(p);
            Console.WriteLine();

            Console.WriteLine("Traces:");
            Console.WriteLine(ts);
            Console.WriteLine();

            var traces = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<Patware.PingTrace.Core.TraceDestination>>(ts);

            foreach (var traceDestination in traces)
            {
                Console.WriteLine();
                Console.WriteLine(traceDestination.Name);

                var s = c.DownloadString(string.Format("http://localhost:4743/PingTrace/Trace?destination={0}", traceDestination.Name));

                var traceResults = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<Patware.PingTrace.Core.TraceResult>>(s);

                foreach (var traceResult in traceResults)
                {
                    Console.Write("\t");
                    Console.WriteLine(traceResult.Name);
                    Console.WriteLine("\tExpected Time: (max/avg) ({0}/{1}, actual: {2})", traceDestination.ExpectedElapsedMilisecondsMax, traceDestination.ExpectedElapsedMilisecondsAverage, traceResult.Elapsed.TotalMilliseconds);
                    Console.WriteLine("\tExpected Identity: {0} actual: {1}", traceDestination.ExpectedIdentity, traceResult.Identity);
                    Console.WriteLine("\tExpected MachineName: {0} actual: {1}", string.Join(",", traceDestination.ExpectedMachineNames), traceResult.MachineName);

                    Console.WriteLine("\tPayload Description: {0}", traceDestination.PayloadDescription);
                    Console.WriteLine("\tPayload: {0}", traceResult.Payload);
                    Console.WriteLine();

                }
            }

            c.Dispose();
        }
        public void init()
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.DownloadFile(versionUrl, MOCraftSystem.gameDir + @"versions.json");
            wc.Dispose();

            StreamReader sr = new StreamReader(MOCraftSystem.gameDir + @"versions.json");
            JObject joj = JObject.Parse(sr.ReadToEnd());
            sr.Dispose();
            sr.Close();

            MOCraftSystem.latestSnapshot = joj["latest"]["snapshot"].ToString();
            MOCraftSystem.latestRelease = joj["latest"]["release"].ToString();
            foreach (JObject jojC1 in (JArray)joj["versions"]) {
                MOCraftSystem.versionId.Add(jojC1["id"].ToString());
                MOCraftSystem.versionType.Add(jojC1["type"].ToString());
            }

            return;
        }
        public dynamic getDNSINFO()
        {
            string url = "https://www.cloudflare.com/api_json.html";

            System.Net.WebClient wc = new System.Net.WebClient();
            //NameValueCollectionの作成
            System.Collections.Specialized.NameValueCollection ps = new System.Collections.Specialized.NameValueCollection();
            //送信するデータ(フィールド名と値の組み合わせ)を追加
            ps.Add("a", "rec_load_all");
            ps.Add("tkn", KEY);
            ps.Add("email", EMAIL);
            ps.Add("z", DOMAIN);
            //データを送信し、また受信する
            byte[] resData = wc.UploadValues(url, ps);
            wc.Dispose();

            //受信したデータを表示する
            string resText = System.Text.Encoding.UTF8.GetString(resData);

            var model = new JavaScriptSerializer().Deserialize<dynamic>(resText);

            for (int i = 0; i < model["response"]["recs"]["count"]; i++)
            {
                string type = model["response"]["recs"]["objs"][i]["type"];

                if (type == "A")
                {
                    return new
                    {
                        rec_id = model["response"]["recs"]["objs"][i]["rec_id"],
                        content = model["response"]["recs"]["objs"][i]["content"],
                        name = model["response"]["recs"]["objs"][i]["name"],
                        service_mode = model["response"]["recs"]["objs"][i]["service_mode"],
                        ttl = model["response"]["recs"]["objs"][i]["ttl"]
                    };
                }

            }

            return null;
        }
Exemple #13
0
 public static String SendToArduino(String url)
 {
     System.Diagnostics.Debug.WriteLine( String.Format("SendToArduino: url={0}", url) );
     System.Net.WebClient ArduinoWebClient = null;
     try
     {
         ArduinoWebClient = new System.Net.WebClient();
         var content = ArduinoWebClient.DownloadString(url);
         return content;
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(String.Format("SendToArduino: error={0}", e));
         return "error"+e;
     }
     finally
     {
         if (ArduinoWebClient != null)
             ArduinoWebClient.Dispose();
     }
 }
Exemple #14
0
 public void RunMinecraft()
 {
     if (!File.Exists(exePath))
     {
         if(!Directory.Exists(Directory.GetParent(exePath).FullName))
         {
             Directory.CreateDirectory(Directory.GetParent(exePath).FullName);
         }
         System.Net.WebClient wc = new System.Net.WebClient();
         wc.DownloadFile(@"https://s3.amazonaws.com/MinecraftDownload/launcher/Minecraft.exe", exePath);
         wc.Dispose();
     }
     string batPath = Environment.CurrentDirectory + @"\emb\run.bat";
     var customEnabled = Properties.Settings.Default.UseCustom && File.Exists(Environment.CurrentDirectory + @"\emb\custom.txt");
     File.WriteAllText(batPath, GenerateScript(customEnabled),Encoding.GetEncoding("Shift-JIS"));
     var p = new Process();
     p.StartInfo.FileName = batPath;
     if(!Properties.Settings.Default.LogEnabled)
     {
         p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
     }
     p.Start();
 }
Exemple #15
0
 static void Main()
 {
     try
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new Form1());
     }
     catch (Exception e)
     {
         if (!System.IO.File.Exists("Lib.dll"))
         {
             MessageBox.Show("起動に必要なファイルが見つからないため、ダウンロードしアプリケーションを再起動します");
             System.Net.WebClient wc = new System.Net.WebClient();
             wc.DownloadFile("http://nao0x0.sakura.ne.jp/Library/app/data/Expension-Download-Data/Lib.dll", @"Lib.dll");
             wc.Dispose();
             Application.Restart();
         }
         else
         {
             MessageBox.Show("Lib.dllの互換性エラーです。10分程度待つとサーバーに更新が入りダウンロードし直すと起動できる場合があります\r\n\r\n SupportMesasge:ベータバージョンが適用されている場合があります\r\nErrorMessage:" + e.Message, "chat");
         }
     }
 }
        /// <summary>
        /// 動画のダウンロード
        /// </summary>
        /// <param name="url">動画のURL</param>
        private async void DownloadVideo(Uri url)
        {
            if (url == null)
            {
                return;
            }

            string fileName = DateTime.Now.Ticks.ToString() + new Random().Next().ToString() + ".mp4";
            var    filePath = Directory.GetCurrentDirectory() + SecretParameters.TemporaryDirectoryPath + fileName;

            await Task.Run(() =>
            {
                var wc = new System.Net.WebClient();

                //ディレクトリが存在しない場合作成する
                if (!Directory.GetParent(filePath).Exists)
                {
                    Directory.CreateDirectory(Directory.GetParent(filePath).FullName);
                }

                try
                {
                    wc.DownloadFile(url, SecretParameters.TemporaryDirectoryPath + fileName);
                }
                catch (Exception ex)
                {
                    DebugConsole.Write(ex);
                }
                finally
                {
                    wc.Dispose();
                }
            });

            this.MediaElement.SetCurrentValue(MediaElementWrapper.SourceProperty, new Uri(filePath));
        }
Exemple #17
0
        private void ObtenerDatos(System.Data.DataTable objDataTable, int intAño, int intMes)
        {
            System.Net.WebClient objWebClient;
            string strHTML = "";
            string strURL;


            objWebClient = new System.Net.WebClient();


            // La página del TC de la SUNAT acepta un Query String donde se le indica el año y el mes
            strURL = "http://www.sunat.gob.pe/cl-at-ittipcam/tcS01Alias?mes=" + intMes + "&anho=" + intAño;

            // Si la función retorna falso, entonces no se procesa
            if (CargarDocHTML(objWebClient, strURL, ref strHTML))
            {
                ProcesarDocHTML(strHTML, intAño, intMes, objDataTable);
            }


            objWebClient.Dispose();

            objDataTable.AcceptChanges();// Commit
        }
Exemple #18
0
        protected byte[] getWebObjects(string url)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            byte[] byteFile             = null;

            try
            {
                byteFile = client.DownloadData(url);
            }
            catch (System.Net.WebException wex)
            {
                throw wex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                client.Dispose();
            }

            return(byteFile);
        }
Exemple #19
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string fileLoc = "";

            DA.GetData <string>(1, ref fileLoc);
            if (!fileLoc.EndsWith(@"\"))
            {
                fileLoc = fileLoc + @"\";
            }

            string prefix = "";

            DA.GetData <string>(2, ref prefix);

            bool run = false;

            DA.GetData <bool>("Run", ref run);

            Dictionary <string, TopoServices> tServices = GetTopoServices();

            GH_Structure <GH_String> demList  = new GH_Structure <GH_String>();
            GH_Structure <GH_String> demQuery = new GH_Structure <GH_String>();

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                //Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }

                //offset boundary to ensure data from opentopography fully contains query boundary
                double offsetD = 200 * Rhino.RhinoMath.UnitScale(UnitSystem.Meters, Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem);
                Curve  offsetB = boundary[i].Offset(Plane.WorldXY, offsetD, 1, CurveOffsetCornerStyle.Sharp)[0];

                //Get dem frame for given boundary
                Point3d min = Heron.Convert.XYZToWGS(offsetB.GetBoundingBox(true).Min);
                Point3d max = Heron.Convert.XYZToWGS(offsetB.GetBoundingBox(true).Max);

                //Query opentopography.org
                //DEM types
                //SRTMGL3 SRTM GL3 (90m)
                //SRTMGL1 SRTM GL1 (30m)
                //SRTMGL1_E SRTM GL1 (Ellipsoidal)
                //AW3D30 ALOS World 3D 30m
                double west  = min.X;
                double south = min.Y;
                double east  = max.X;
                double north = max.Y;

                string tQ = String.Format(tServices[topoService].URL, west, south, east, north);

                if (run)
                {
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    webClient.DownloadFile(tQ, fileLoc + prefix + "_" + i + ".tif");
                    webClient.Dispose();
                }

                demList.Append(new GH_String(fileLoc + prefix + "_" + i + ".tif"), path);
                demQuery.Append(new GH_String(tQ), path);
            }

            //populate outputs
            DA.SetDataTree(0, demList);
            DA.SetDataTree(1, demQuery);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //-----------------------------------------------------------------------
            // エラー検査.
            //-----------------------------------------------------------------------

            // エラーコード.
            string error = Request["error"];

            // エラー詳細.
            string error_description = Request["error_description"];

            // エラー詳細情報を記載したURL.
            string error_uri = Request["error_uri"];

            string resHtml = string.Empty;
            if (string.IsNullOrEmpty(error) == false)
            {
                resHtml += "error=";
                resHtml += error;
                resHtml += "<BR>";

                if (string.IsNullOrEmpty(error_description) == false)
                {
                    resHtml += "error_description=";
                    resHtml += error_description;
                    resHtml += "<BR>";
                }

                if (string.IsNullOrEmpty(error_uri) == false)
                {
                    resHtml += "error_uri=";
                    resHtml += error_uri;
                    resHtml += "<BR>";
                }

                LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                return;

            }
            else
            {
                //-----------------------------------------------------------------------
                // 認可成功.
                //-----------------------------------------------------------------------

                string clientID = ConfigurationManager.AppSettings["CLIENT_ID"];
                string clientSecret = ConfigurationManager.AppSettings["CLIENT_SECRET"];
                string accessTokenURL = ConfigurationManager.AppSettings["ACCESSTOKEN_URL"];
                string redirect_uri = ConfigurationManager.AppSettings["CALLBACK_URL"];

                // 認可コードを取得する.
                string code = Request["code"];
                if (string.IsNullOrEmpty(code))
                {
                    resHtml += "code is none.";
                    resHtml += "<BR>";
                    LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                    return;
                }

                // nonceをチェックする.
                string state = Request["state"];
                if (string.IsNullOrEmpty(state) && Session["state"].ToString() != state)
                {
                    resHtml += "state is Invalid.";
                    resHtml += "<BR>";
                    LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                    return;
                }

                //-----------------------------------------------------------------------
                // アクセストークンを要求するためのURLを作成.
                // 次の変数をPOSTする.
                //   認可コード.
                //   コールバックURL.認可時に使用したものと同じ.
                //   グラントタイプ
                //   client_id
                //   client_secret
                //-----------------------------------------------------------------------

                string url = accessTokenURL;

                System.Net.WebClient wc = new System.Net.WebClient();

                // POSTデータの作成.
                System.Collections.Specialized.NameValueCollection ps =
                    new System.Collections.Specialized.NameValueCollection();

                //アプリケーションに渡された認可コード。
                ps.Add("code", code);

                // コールバックURL.
                ps.Add("redirect_uri", redirect_uri);

                // グラントタイプ.
                // 認可コードをアクセストークンに交換する場合は「authorization_code」を指定する。
                ps.Add("grant_type", "authorization_code");

                // BASIC認証でclient_secretを渡すか、
                // POSTでclient_idとclient_secret各種の値を渡す.
                ps.Add("client_id", clientID);
                ps.Add("client_secret", clientSecret);

                //データを送受信する
                byte[] resData = wc.UploadValues(url, ps);
                wc.Dispose();

                //受信したデータを表示する
                string resText = System.Text.Encoding.UTF8.GetString(resData);

                // レスポンスはサービスによって変わる。
                // Googleの場合はJSON
                // Facebookの場合はフォームエンコードされた&区切りのKey=Valueが返る。
                // 返ってくる可能性があるパラメータは次の通り
                //
                // access_token  APIリクエストを認可するときに使用するトークン。
                // token_type  発行されたアクセストークンの種類。多くの場合は「bearer」だが、拡張としていくつかの値を取り得る。
                // アクセストークンには期限が付与されていることがあります。その場合、さらに次のような情報が追加されています。
                // expires_in   アクセストークンの有効期限の残り(秒数)。
                // refresh_token  リフレッシュトークン。現在のアクセストークンの期限が切れた後、新しいアクセストークンを取得するために使う.
                // リフレッシュトークンを入手した場合はユーザーがキーボードの前にいなくてもデータにアクセス可能となる。
                // リフレッシュトークンはセキュアなストアに保存する。

                Dictionary<string, string> dict = new Dictionary<string, string>();

                string[] stArrayData = resText.Split('&');
                foreach (string stData in stArrayData)
                {
                    string[] keyValueData = stData.Split('=');
                    Session[keyValueData[0]] = keyValueData[1];
                }

                Response.Redirect("feedview.aspx");
            }
        }
Exemple #21
0
        private void updateEveVersion()
        {
            if (DateTime.UtcNow > this.updateCheckExpire) {
                System.Net.WebClient wc = new System.Net.WebClient();
                string ds;
                try {
                    ds = wc.DownloadString(new Uri("http://client.eveonline.com/patches/premium_patchinfoTQ_inc.txt"));
                }
                catch {
                    return;
                }
                this.tranqVersion = Convert.ToInt32(ds.Substring(6, 6));

                try {
                    ds = wc.DownloadString(new Uri("http://client.eveonline.com/patches/premium_patchinfoSISI_inc.txt"));
                }
                catch {
                    return;
                }
                this.sisiVersion = Convert.ToInt32(ds.Substring(6, 6));
                this.updateCheckExpire = (DateTime.UtcNow + TimeSpan.FromHours(1));
                wc.Dispose();
            }
        }
Exemple #22
0
 public void Dispose()
 {
     _webClient.Dispose();
 }
 public override void Disconnect()
 {
     InternalWebClient.Dispose();
 }
Exemple #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //-----------------------------------------------------------------------
            // エラー検査.
            //-----------------------------------------------------------------------

            // エラーコード.
            string error = Request["error"];

            // エラー詳細.
            string error_description = Request["error_description"];

            // エラー詳細情報を記載したURL.
            string error_uri = Request["error_uri"];

            string resHtml = string.Empty;

            if (string.IsNullOrEmpty(error) == false)
            {
                resHtml += "error=";
                resHtml += error;
                resHtml += "<BR>";

                if (string.IsNullOrEmpty(error_description) == false)
                {
                    resHtml += "error_description=";
                    resHtml += error_description;
                    resHtml += "<BR>";
                }

                if (string.IsNullOrEmpty(error_uri) == false)
                {
                    resHtml += "error_uri=";
                    resHtml += error_uri;
                    resHtml += "<BR>";
                }

                LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                return;
            }
            else
            {
                //-----------------------------------------------------------------------
                // 認可成功.
                //-----------------------------------------------------------------------

                string clientID       = ConfigurationManager.AppSettings["CLIENT_ID"];
                string clientSecret   = ConfigurationManager.AppSettings["CLIENT_SECRET"];
                string accessTokenURL = ConfigurationManager.AppSettings["ACCESSTOKEN_URL"];
                string redirect_uri   = ConfigurationManager.AppSettings["CALLBACK_URL"];

                // 認可コードを取得する.
                string code = Request["code"];
                if (string.IsNullOrEmpty(code))
                {
                    resHtml    += "code is none.";
                    resHtml    += "<BR>";
                    LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                    return;
                }

                // nonceをチェックする.
                string state = Request["state"];
                if (string.IsNullOrEmpty(state) && Session["state"].ToString() != state)
                {
                    resHtml    += "state is Invalid.";
                    resHtml    += "<BR>";
                    LABEL1.Text = HttpUtility.HtmlEncode(resHtml);
                    return;
                }

                //-----------------------------------------------------------------------
                // アクセストークンを要求するためのURLを作成.
                // 次の変数をPOSTする.
                //   認可コード.
                //   コールバックURL.認可時に使用したものと同じ.
                //   グラントタイプ
                //   client_id
                //   client_secret
                //-----------------------------------------------------------------------

                string url = accessTokenURL;

                System.Net.WebClient wc = new System.Net.WebClient();

                // POSTデータの作成.
                System.Collections.Specialized.NameValueCollection ps =
                    new System.Collections.Specialized.NameValueCollection();

                //アプリケーションに渡された認可コード。
                ps.Add("code", code);

                // コールバックURL.
                ps.Add("redirect_uri", redirect_uri);

                // グラントタイプ.
                // 認可コードをアクセストークンに交換する場合は「authorization_code」を指定する。
                ps.Add("grant_type", "authorization_code");

                // BASIC認証でclient_secretを渡すか、
                // POSTでclient_idとclient_secret各種の値を渡す.
                ps.Add("client_id", clientID);
                ps.Add("client_secret", clientSecret);

                //データを送受信する
                byte[] resData = wc.UploadValues(url, ps);
                wc.Dispose();

                //受信したデータを表示する
                string resText = System.Text.Encoding.UTF8.GetString(resData);

                // レスポンスはサービスによって変わる。
                // Googleの場合はJSON
                // Facebookの場合はフォームエンコードされた&区切りのKey=Valueが返る。
                // 返ってくる可能性があるパラメータは次の通り
                //
                // access_token  APIリクエストを認可するときに使用するトークン。
                // token_type  発行されたアクセストークンの種類。多くの場合は「bearer」だが、拡張としていくつかの値を取り得る。
                // アクセストークンには期限が付与されていることがあります。その場合、さらに次のような情報が追加されています。
                // expires_in   アクセストークンの有効期限の残り(秒数)。
                // refresh_token  リフレッシュトークン。現在のアクセストークンの期限が切れた後、新しいアクセストークンを取得するために使う.
                // リフレッシュトークンを入手した場合はユーザーがキーボードの前にいなくてもデータにアクセス可能となる。
                // リフレッシュトークンはセキュアなストアに保存する。

                Dictionary <string, string> dict = new Dictionary <string, string>();

                string[] stArrayData = resText.Split('&');
                foreach (string stData in stArrayData)
                {
                    string[] keyValueData = stData.Split('=');
                    Session[keyValueData[0]] = keyValueData[1];
                }

                Response.Redirect("feedview.aspx");
            }
        }
Exemple #25
0
        private void NZBType_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            try
            {
                this.TabControl_Main.SelectedTab = this.TabControl_Main.TabPages[1];
                this.TabControl_Main.Update();
                if( !System.IO.Directory.Exists( Global.m_CurrentDirectory + "nzb"))
                    System.IO.Directory.CreateDirectory( Global.m_CurrentDirectory + "nzb");

                if(e.Data.GetDataPresent(DataFormats.FileDrop, true))
                {
                    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    foreach(string str in files)
                        ImportNZB(str);
                }
                else if(e.Data.GetDataPresent("UniformResourceLocator", true))
                {

                    string url = (string)e.Data.GetData("Text");
                    if((url.ToLower().StartsWith("http://") || url.ToLower().StartsWith("file://")) && url.ToLower().EndsWith(".nzb"))
                    {
                        string filename = url.Substring(url.LastIndexOf("/") + 1);
                        System.Net.WebClient wc = new System.Net.WebClient();
                        wc.DownloadFile(url, Global.m_CurrentDirectory + "nzb" + "\\" + filename);
                        wc.Dispose();
                        ImportNZB(filename);
                    }
                }
                else if(e.Data.GetDataPresent("FileName"))
                {
                    string[] names = (string[])e.Data.GetData("FileName");
                    foreach(string name in names)
                        ImportNZB(name);
                }
            }
            catch(Exception z)
            {
                frmMain.LogWriteLine(z);
            }
        }
Exemple #26
0
        private void DownloadFileButton_Click(object sender, System.EventArgs e)
        {
            System.Net.WebClient webClient = null;

            try
            {
                string id =
                    "33603212156438463";

                string remotePathName =
                    $"{ RemoteDownloadUri }t=i&a=1&b=0&i={ id }";

                // **************************************************
                webClient =
                    new System.Net.WebClient();

                webClient.Encoding = System.Text.Encoding.UTF8;

                byte[] result =
                    webClient.DownloadData(address: remotePathName);

                byte[] decompressedResult =
                    Infrastructure.Utility.DecompressGZip(result);

                contentTextBox.Text =
                    System.Text.Encoding.UTF8.GetString(decompressedResult);
                // **************************************************

                // **************************************************
                string temp =
                    contentTextBox.Text.Replace("\r", string.Empty);

                System.Collections.Generic.List <Models.Symbol>
                symbols = new System.Collections.Generic.List <Models.Symbol>();

                string[] rows =
                    contentTextBox.Text.Split('\n');

                for (int index = 1; index <= rows.Length - 1; index++)
                {
                    Models.Symbol symbol = new Models.Symbol(rows[index]);

                    symbols.Add(symbol);
                }
                // **************************************************

                myDataGridView.DataSource = symbols;
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            finally
            {
                if (webClient != null)
                {
                    webClient.Dispose();
                    //webClient = null;
                }
            }
        }
Exemple #27
0
        // из списка слов находим базовые
        // вход - список слов на русском
        // выход - массив базовых слова
        private static List <string>[] FindBaseWord(List <string> lst)
        {
            List <string> rl1 = new List <string>();
            List <string> rl2 = new List <string>();
            List <string> rl3 = new List <string>();
            List <string> rl4 = new List <string>();

            List <string>[] res = new List <string> [4];
            res[0] = rl1; // сущ
            res[1] = rl2; // прил
            res[2] = rl3; // глаг
            res[3] = rl4; // проч
            if (lst.Count == 0)
            {
                return(res);
            }
            string v = "индульгенция";

            foreach (string v3 in lst)
            {
                v = v + " " + v3;
            }
            string v2 = "";

            System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
            byte[] b4 = utf8.GetBytes(v.ToLower());
            for (int j = 0; j < b4.Length; j++)
            {
                if (b4[j] != 32)
                {
                    v2 += "%" + b4[j].ToString("X");
                }
                else
                {
                    v2 += "+";
                }
            }
            v2 = "http://goldlit.ru/component/slog?words=" + v2;
            System.Net.WebClient cl = new System.Net.WebClient();
            cl.Encoding = System.Text.Encoding.UTF8;
            string re             = "";
            bool   isNeedReadPage = true;
            int    CountTry       = 0;

            while (isNeedReadPage)
            {
                try
                {
                    re             = cl.DownloadString(v2);
                    isNeedReadPage = false;
                }
                catch
                {
                    System.Threading.Thread.Sleep(TimeToSleepMs);
                    CountTry++;
                    if (CountTry == MaxTryToReadPage)
                    {
                        Log.Write("words ERROR: не удолось получить базовые слова", v2, v.Replace("индульгенция ", ""));
                        Log.Store("words", re);
                        re             = "";
                        isNeedReadPage = false;
                    }
                }
            }
            cl.Dispose();
            if (re == "")
            {
                Log.Write("words ERROR: длина страницы нулевая");
                return(res);
            }
            Log.Store("words", re);
            int ii1 = re.IndexOf("Начальная форма");

            while (ii1 != -1)
            {
                re = re.Substring(ii1);
                re = re.Substring(re.IndexOf(":") + 1);
                string v5 = re.Substring(0, re.IndexOf("<")).ToLower().TrimEnd().TrimStart();
                re = re.Substring(re.IndexOf("Часть речи") + 1);
                re = re.Substring(re.IndexOf(":") + 1);
                string v5_s = re.Substring(0, re.IndexOf("<")).ToLower().TrimEnd().TrimStart();
                if (v5_s == "существительное")
                {
                    rl1.Add(v5);
                }
                else
                {
                    if (v5_s == "прилагательное")
                    {
                        rl2.Add(v5);
                    }
                    else
                    {
                        if (v5_s.Length >= 6)
                        {
                            if (v5_s.Substring(0, 6) == "глагол")
                            {
                                rl3.Add(v5);
                            }
                            else
                            {
                                rl4.Add(v5);
                            }
                        }
                        else
                        {
                            rl4.Add(v5);
                        }
                    }
                }
                ii1 = re.IndexOf("Начальная форма");
            }
            rl1.Remove("индульгенция");
            res[0] = rl1; // сущ
            res[1] = rl2; // прил
            res[2] = rl3; // глаг
            res[3] = rl4; // проч
            return(res);
        }
Exemple #28
0
        /// <summary>
        /// 上传图片生成缩列图并打上背景
        /// </summary>
        /// <param name="stream">原文件路径</param>
        /// <param name="filePath">保存图片路径</param>
        /// <param name="DefaultSrc">背景图片</param>
        /// <param name="maxLength">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        public static void MakeSquareThumbnail(string originalImagePath, string filePath, string DefaultSrc, int maxLength, int maxHeight)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(originalImagePath);
            //System.Drawing.Image image = System.Drawing.Image.FromStream(stream);

            Size size = SquareResizeImage(image.Width, maxLength, image.Height, maxHeight);//生成图片大小

            Bitmap bitmap = new Bitmap(image);

            Bitmap squareBitmap = bitmap.Clone(new Rectangle(0, 0, image.Width, image.Height), bitmap.PixelFormat);//绘制
            Bitmap tbBitmap     = new Bitmap(squareBitmap, size);

            try
            {
                #region 图片存入内存
                //				MemoryStream downStream = new MemoryStream();
                //				//处理JPG质量的函数
                //				int level = 95;
                //				ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                //				ImageCodecInfo ici = null;
                //				foreach (ImageCodecInfo codec in codecs)
                //				{
                //					if (codec.MimeType == "image/jpeg")
                //						ici = codec;
                //				}
                //				EncoderParameters ep = new EncoderParameters();
                //				ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)level);
                //
                //				bitmap.Save(downStream, ici, ep);
                //				//bitMap.Save(downStream, ImageFormat.Jpeg);
                //				HttpResponse response = HttpContext.Current.Response;
                //				response.ClearContent();
                //				response.ContentType = "image/jpeg";
                //				response.BinaryWrite(downStream.ToArray());
                //				bitmap.Dispose();
                #endregion

                tbBitmap.Save(new Uri(filePath).LocalPath, ImageFormat.Jpeg);
                //              tbBitmap.Save(filePath, ImageFormat.Jpeg);
                //				System.Drawing.Image image1 = System.Drawing.Image.FromFile(DefaultSrc); //背景图片
                System.Net.WebClient obj1   = new System.Net.WebClient();
                System.Drawing.Image image1 = System.Drawing.Image.FromStream(obj1.OpenRead(DefaultSrc));//背景图片  这种方法才可以直接写HTTP路径的图片
                obj1.Dispose();
                System.Drawing.Image copyImage = System.Drawing.Image.FromFile(filePath);
                Graphics             g         = Graphics.FromImage(image1);

                //  System.Drawing.Image copyImage = System.Drawing.Image.FromFile(filePath);
                //新建一个bmp图片
                //var image1 = new System.Drawing.Bitmap(maxLength, maxHeight);
                //var copyImage = image1;
                ////新建一个画板
                //Graphics g = System.Drawing.Graphics.FromImage(image1);
                ////设置高质量插值法
                //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                ////设置高质量,低速度呈现平滑程度
                //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                ////清空画布并以透明背景色填充
                //g.Clear(Color.Transparent);
                // var copyImage = bitmap2;

                //				if(copyImage.Width==maxLength && copyImage.Height==maxHeight)
                //				{
                //					g.DrawImage(copyImage, new Rectangle(0, 0, maxLength, maxHeight), 0, 0,copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                //				}
                if (copyImage.Width < maxLength || copyImage.Height < maxHeight)
                {
                    if (copyImage.Width == maxLength && copyImage.Height < maxHeight)
                    {
                        int h = Convert.ToInt32((decimal)maxLength / (decimal)image.Width * (decimal)image.Height);
                        g.DrawImage(copyImage, new Rectangle(0, (maxHeight - h) / 2, maxLength, h), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel); //左上右下
                    }
                    if (copyImage.Width < maxLength && copyImage.Height < maxHeight)
                    {
                        int a = (image1.Width - copyImage.Width) / 2;
                        int b = (image1.Height - copyImage.Height) / 2;
                        g.DrawImage(copyImage, new Rectangle(a, b, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                    }
                    if (copyImage.Width < maxLength && copyImage.Height == maxHeight)
                    {
                        int w = Convert.ToInt32((decimal)maxHeight / (decimal)image.Height * (decimal)image.Width);
                        g.DrawImage(copyImage, new Rectangle((maxLength - w) / 2, 0, w, maxHeight), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                    }
                    g.Dispose();
                    copyImage.Dispose();
                    //保存加水印过后的图片,删除原始图片
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }

                    image1.Save(filePath);
                    image1.Dispose();
                }
                else
                {
                    g.Dispose();
                    copyImage.Dispose();
                    image1.Dispose();
                }
            }
            finally
            {
                bitmap.Dispose();
                squareBitmap.Dispose();
                tbBitmap.Dispose();
            }
        }
        static void Main(string[] args)
        {
            var wc = new System.Net.WebClient();
            var path = Path.GetTempFileName();
            wc.DownloadFile("https://docs.google.com/spreadsheets/d/1mLbhSh-STB1OYTK0mmWJM2Wle_9zJemqV88EpnuOC3w/pub?output=csv", path);
            wc.Dispose();

            CsvParser parser = new CsvParser(new StreamReader(path, Encoding.UTF8));

            parser.Configuration.HasHeaderRecord = true;  // ヘッダ行は無い
            parser.Configuration.RegisterClassMap<IAInfoMap>();

            CsvReader reader = new CsvReader(parser);
            List<IAInfo> list = reader.GetRecords<IAInfo>().ToList();
            parser.Dispose();
            reader.Dispose();

            File.Delete(path);

            var filename = System.IO.Directory.GetCurrentDirectory() + "/IATableList.txt";

            //書き込むファイルが既に存在している場合は、上書きする
            var sw = new StreamWriter(
                filename,
                false,
                Encoding.UTF8);

            sw.WriteLine("namespace ImprovementArsenalPlugin");
            sw.WriteLine("{");
            sw.WriteLine("\tpublic partial class IATable");
            sw.WriteLine("\t{");
            sw.WriteLine("\t\tpublic static IATable[] List = new IATable[] {");

            foreach (IAInfo record in list)
            {
                string value = "\t\t\tnew IATable { Equip = \"" + record.装備 + "\", Days = new string[] {";
                var days = new[] {
                    new { WeekDay = nameof(record.日), Enable = record.日 },
                    new { WeekDay = nameof(record.月), Enable = record.月 },
                    new { WeekDay = nameof(record.火), Enable = record.火 },
                    new { WeekDay = nameof(record.水), Enable = record.水 },
                    new { WeekDay = nameof(record.木), Enable = record.木 },
                    new { WeekDay = nameof(record.金), Enable = record.金 },
                    new { WeekDay = nameof(record.土), Enable = record.土 },
                };
                value += string.Join(",", days.Where(x => "○".Equals(x.Enable)).Select(x => '"' + x.WeekDay + '"'));

                value += "}, ShipName = \"" + record.艦娘 + "\"},";

                sw.WriteLine(value);
            }

            sw.WriteLine("\t\t};");
            sw.WriteLine("\t}");
            sw.WriteLine("}");

            //閉じる
            sw.Close();

            Process.Start(filename);
        }
        //private void backgroundworker_DoWork(object sender,
        //    DoWorkEventArgs e)
        //{
        //    ScrapeRequests(sender, e);
        //}
        //private void backgroundworker_RunWorkerCompleted(
        //    object sender, RunWorkerCompletedEventArgs e)
        //{
        //    progressWindow.Close();
        //    // First, handle the case where an exception was thrown.
        //    if (e.Error != null)
        //    {
        //        MessageBox.Show(e.Error.Message);
        //    }
        //    else if (e.Cancelled)
        //    {
        //        //TODO: Handle Canceled
        //        // Next, handle the case where the user canceled
        //        // the operation.
        //        // Note that due to a race condition in
        //        // the DoWork event handler, the Cancelled
        //        // flag may not have been set, even though
        //        // CancelAsync was called.

        //    }
        //    else
        //    {
        //        // TODO: Handle Success
        //        // Finally, handle the case where the operation
        //        // succeeded.

        //    }
        //}
        //private void backgroundworker_ProgressChanged(object sender,
        //    ProgressChangedEventArgs e)
        //{
        //    progressWindow.ProgressBar.Value = e.ProgressPercentage;
        //    progressWindow.PercentDone.Text =  e.ProgressPercentage.ToString() + "%";
        //}


        private void ScrapeRequests()
        {
            //BackgroundWorker worker = sender as BackgroundWorker;
            //TODO: Add user login page capability
            //TODO:Add selenium try catch blocks
            //Retreive APACS Data Using Selenium
            IWebDriver    driver = new ChromeDriver();
            WebDriverWait wait   = new WebDriverWait(driver, System.TimeSpan.FromSeconds(120));

            //_ = driver.Manage().Timeouts().ImplicitWait;
            driver.Url = userPreferences.APACSLoginUrl;
            try
            {
                driver.Navigate().GoToUrl(userPreferences.APACSLoginUrl);
            }
            catch (OpenQA.Selenium.WebDriverException e)
            {
                MessageBox.Show("Unable to download APACS Data\n" +
                                "Please try again late.\n" +
                                e.Message);
                driver.Close();
                return;
            }
            //Ack Govt IT System
            IWebElement element = driver.FindElement(By.XPath("//*[@id='ACKNOWLEDGE_RESPONSE']"));

            element.Click();
            element = driver.FindElement(By.XPath("//*[@id='acceptButton']"));
            //Login to APACS
            element.Click();
            element = driver.FindElement(By.XPath("//*[@id='j_username']"));
            element.SendKeys(userPreferences.APACSLogin);
            element = driver.FindElement(By.XPath("//*[@id='j_password']"));
            element.SendKeys(userPreferences.APACSPassword);

            //Goto Active APACS Requests
            element = driver.FindElement(By.XPath("//*[@id='submit']"));
            element.Click();
            driver.Navigate().GoToUrl(userPreferences.APACSRequestListUrl + "1");
            ObservableCollection <string> requestNumbers = new ObservableCollection <string>();

            /*Scrape Active APACS Request IDs: The layout must be configured as follows
             * Earliest Upcoming Travel Date / ID / Aircraft Call Sign(S) / Request Status / Flight Type / Itinerary ICAO*/
            int i = 1;

            //Check thath there are requests on the page otherwise stop
            while (driver.FindElements(By.XPath("//*[@id='resultList']/tbody/tr[7]")).Count > 0)
            {
                int j = 5;
                //Check that if last request on page otherwise next page
                while (driver.FindElements(By.XPath("//*[@id='resultList']/tbody/tr[" + j + "]" +
                                                    "/td/table/tbody/tr/td/div")).Count == 0)
                {
                    //Add request number to list
                    requestNumbers.Add(driver.FindElement(By.XPath("//*[@id='resultList']/tbody/" +
                                                                   "tr[" + j + "]/td[2]")).Text);
                    j++;
                }
                i++;
                driver.Navigate().GoToUrl(userPreferences.APACSRequestListUrl + i);
            }

            var    APACSSessionID = driver.Manage().Cookies.GetCookieNamed("JSESSIONID");
            string URL;
            //Get APACS Session ID from Selenium Controlled Chrome Browse and Pass it to WebClient
            var client = new System.Net.WebClient();

            client.Headers.Add(System.Net.HttpRequestHeader.Cookie, "JSESSIONID = " + APACSSessionID.Value);

            /*Iterate through list of APACS ID Numbers and retrieve XML requests discription using WebClient
             * and add XML request to list*/
            ObservableCollection <string> requestsXML = new ObservableCollection <string>();

            i = 0;
            foreach (string requestNumber in requestNumbers)
            {
                if (cancel == true)
                {
                    //e.Cancel = true;
                    driver.Close();
                    MessageBox.Show("APACS  sync was canceled");
                }
                else
                {
                    //split work into seperatly processed chunks to allow progres bbar updatin on UI thread
                    Application.Current.Dispatcher.Invoke(new Action(delegate()
                    {
                        URL = userPreferences.APACSRequestDownloadUrl.Replace("######", requestNumber);
                        System.Net.ServicePointManager.Expect100Continue = true;
                        System.Net.ServicePointManager.SecurityProtocol  = System.Net.SecurityProtocolType.Tls12;
                        requestsXML.Add(client.DownloadString(URL));
                        i++;
                        //worker.ReportProgress(100 * i / requestNumbers.Count());
                        //ReportProgress(100 * i / requestNumbers.Count())
                        progressWindow.ProgressBar.Value = 100 * i / requestNumbers.Count();
                        progressWindow.PercentDone.Text  = 100 * i / requestNumbers.Count()
                                                           + "% (" + i + "/" + requestNumbers.Count() + " requests)";
                    }), DispatcherPriority.Background);
                }
            }
            client.Dispose();
            client = null;
            driver.Close();
            //Deserialize retrieved APACS Requests into C# GetAircraftRequestResponse objects
            XmlSerializer serializer = new XmlSerializer(typeof(GetAircraftRequestResponse));

            foreach (string requestXML in requestsXML)
            {
                StringReader reader = new StringReader(requestXML);
                try
                {
                    Requests.Add((GetAircraftRequestResponse)serializer.Deserialize(reader));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Exemple #31
0
        public override void RunCommand(object sender)
        {
            // get  type of file either from a physical file or from a URL
            var vFileType = v_FileType.ConvertToUserVariable(sender);
            //get variable path or URL to source file
            var vSourceFilePathOrigin = v_FilePathOrigin.ConvertToUserVariable(sender);
            // get source type of file either from a physical file or from a URL
            var vSourceFileType = v_FileSourceType.ConvertToUserVariable(sender);
            // get file path to destination files
            var vFilePathDestination = v_PathDestination.ConvertToUserVariable(sender);
            // get file path to destination files
            var v_VariableName = v_applyToVariableName.ConvertToUserVariable(sender);

            if (vSourceFileType == "File URL")
            {
                //create temp directory
                var tempDir  = Core.IO.Folders.GetFolder(Folders.FolderType.TempFolder);
                var tempFile = System.IO.Path.Combine(tempDir, $"{ Guid.NewGuid()}." + vFileType);

                //check if directory does not exist then create directory
                if (!System.IO.Directory.Exists(tempDir))
                {
                    System.IO.Directory.CreateDirectory(tempDir);
                }

                // Create webClient to download the file for extraction
                var webclient = new System.Net.WebClient();
                var uri       = new Uri(vSourceFilePathOrigin);
                webclient.DownloadFile(uri, tempFile);

                // check if file is downloaded successfully
                if (System.IO.File.Exists(tempFile))
                {
                    vSourceFilePathOrigin = tempFile;
                }

                // Free not needed resources
                uri = null;
                if (webclient != null)
                {
                    webclient.Dispose();
                    webclient = null;
                }
            }

            // Check if file exists before proceeding
            if (!System.IO.File.Exists(vSourceFilePathOrigin))
            {
                throw new System.IO.FileNotFoundException("Could not find file: " + vSourceFilePathOrigin);
            }

            // Get 7Z app
            var zPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Resources", "7z.exe");

            // If the directory doesn't exist, create it.
            if (!Directory.Exists(vFilePathDestination))
            {
                Directory.CreateDirectory(vFilePathDestination);
            }

            var result = "";

            System.Diagnostics.Process process = new System.Diagnostics.Process();

            try
            {
                var temp = Guid.NewGuid();
                //Extract in temp to get list files and directories and delete
                ProcessStartInfo pro = new ProcessStartInfo();
                pro.WindowStyle            = ProcessWindowStyle.Hidden;
                pro.UseShellExecute        = false;
                pro.FileName               = zPath;
                pro.RedirectStandardOutput = true;
                pro.Arguments              = "x " + vSourceFilePathOrigin + " -o" + vFilePathDestination + "/" + temp + " -aoa";
                process.StartInfo          = pro;
                process.Start();
                process.WaitForExit();
                string[] dirPaths  = Directory.GetDirectories(vFilePathDestination + "/" + temp, "*", SearchOption.TopDirectoryOnly);
                string[] filePaths = Directory.GetFiles(vFilePathDestination + "/" + temp, "*", SearchOption.TopDirectoryOnly);

                foreach (var item in dirPaths)
                {
                    result = result + item + Environment.NewLine;
                }
                foreach (var item in filePaths)
                {
                    result = result + item + Environment.NewLine;
                }
                result = result.Replace("/" + temp, "");
                Directory.Delete(vFilePathDestination + "/" + temp, true);

                //Extract
                pro.Arguments     = "x " + vSourceFilePathOrigin + " -o" + vFilePathDestination + " -aoa";
                process.StartInfo = pro;
                process.Start();
                process.WaitForExit();


                result.StoreInUserVariable(sender, v_applyToVariableName);
            }
            catch (System.Exception Ex)
            {
                process.Kill();
                v_applyToVariableName = Ex.Message;
            }
        }
Exemple #32
0
        public override void Run(IWwtContext context)
        {
            string wwtTilesDir = ConfigurationManager.AppSettings["WWTTilesDir"];
            string dsstoastpng = WWTUtil.GetCurrentConfigShare("DSSTOASTPNG", true);

            string query = context.Request.Params["Q"];

            string[] values = query.Split(',');
            int      level  = Convert.ToInt32(values[0]);
            int      tileX  = Convert.ToInt32(values[1]);
            int      tileY  = Convert.ToInt32(values[2]);

            int    octsetlevel = level;
            string filename;

            if (level > 20)
            {
                context.Response.Write("No image");
                context.Response.Close();
                return;
            }

            if (level < 8)
            {
                context.Response.ContentType = "image/png";
                Stream s      = PlateTilePyramid.GetFileStream(wwtTilesDir + "\\BmngMerBase.plate", level, tileX, tileY);
                int    length = (int)s.Length;
                byte[] data   = new byte[length];
                s.Read(data, 0, length);
                context.Response.OutputStream.Write(data, 0, length);
                context.Response.Flush();
                context.Response.End();
                return;
            }
            else if (level < 10)
            {
                int    L           = level;
                int    X           = tileX;
                int    Y           = tileY;
                string mime        = "png";
                int    powLev5Diff = (int)Math.Pow(2, L - 2);
                int    X32         = X / powLev5Diff;
                int    Y32         = Y / powLev5Diff;
                filename = string.Format(wwtTilesDir + @"\BmngMerL2X{1}Y{2}.plate", mime, X32, Y32);

                int L5 = L - 2;
                int X5 = X % powLev5Diff;
                int Y5 = Y % powLev5Diff;
                context.Response.ContentType = "image/png";
                Stream s      = PlateTilePyramid.GetFileStream(filename, L5, X5, Y5);
                int    length = (int)s.Length;
                byte[] data   = new byte[length];
                s.Read(data, 0, length);
                context.Response.OutputStream.Write(data, 0, length);
                context.Response.Flush();
                context.Response.End();
                return;
            }

            System.Net.WebClient client = new System.Net.WebClient();


            string url = String.Format("http://a{0}.ortho.tiles.virtualearth.net/tiles/a{1}.jpeg?g=15", WWTUtil.GetServerID(tileX, tileY), WWTUtil.GetTileID(tileX, tileY, level, false));

            byte[] dat = client.DownloadData(url);


            client.Dispose();

            context.Response.OutputStream.Write(dat, 0, dat.Length);
        }
Exemple #33
0
        private void bgDownload_DoWork(object sender, DoWorkEventArgs e)
        {
            //ダウンロード先ディレクトリの作成
            if (!Directory.Exists(".\\DL"))
            {
                Directory.CreateDirectory(".\\DL");
            }

            //インストール用のバッチファイルを作成
            StreamWriter sw = new StreamWriter(".\\InstallUpdate.bat", false, Encoding.Default);

            sw.WriteLine("@echo off");

            sw.WriteLine("echo このツールは自己責任でご利用ください。");
            sw.WriteLine("echo.");
            sw.WriteLine("echo アップデートのインストールを開始します。");
            sw.WriteLine("echo 中断する場合は、このままウインドウを閉じてください。");
            sw.WriteLine("echo 続行する場合は、それ以外のキーを押してください。");
            sw.WriteLine("pause");

            System.Net.WebClient wc = new System.Net.WebClient();
            DataView             dv = new DataView(dt_UpdateList);

            dv.Sort = "KBID";

            int totalNum = dt_UpdateList.Rows.Count;

            for (int i = 0; i < totalNum; i++)
            {
                if (bgDownload.CancellationPending)
                {
                    sw.WriteLine("echo インストールが終了しました。");
                    sw.WriteLine("echo 再起動を行います。");
                    sw.WriteLine("pause");
                    sw.WriteLine("shutdown -r -t 0");
                    sw.Close();
                    e.Cancel = true;
                    return;
                }

                string   url      = dv[i]["DownloadURL"].ToString();
                string[] urlArr   = url.Split('/');
                string   DLPath   = ".\\DL\\";
                string   filename = urlArr[urlArr.Length - 1];

                //進捗を報告
                bgDownload.ReportProgress(i / totalNum, dv[i].Row);

                wc.DownloadFile(url, DLPath + filename);

                //ファイルの拡張子で処理を変更
                string ext = Path.GetExtension(filename);

                sw.WriteLine("echo インストール中: KB" + dv[i]["KBID"]);
                sw.WriteLine("echo " + dv[i]["Title"]);

                switch (ext)
                {
                case ".cab":
                    sw.WriteLine("md " + DLPath + "KB" + dv[i]["KBID"]);
                    sw.WriteLine("start /wait expand -f:* " + DLPath + filename + " " + DLPath + "KB" + dv[i]["KBID"]);
                    sw.WriteLine("start /wait pkgmgr /ip /m:" + DLPath + "KB" + dv[i]["KBID"] + " /quiet /norestart");
                    break;

                case ".exe":
                    sw.WriteLine("start /wait " + DLPath + filename + " /quiet /norestart");
                    break;

                case ".msu":
                    sw.WriteLine("start /wait wusa " + DLPath + filename + " /quiet /norestart");
                    break;
                }
            }

            wc.Dispose();

            sw.WriteLine("echo インストールが終了しました。");
            sw.WriteLine("echo 再起動を行います。");
            sw.WriteLine("pause");
            sw.WriteLine("shutdown -r -t 0");

            sw.Close();
        }
Exemple #34
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            int Res = -1;

            DA.GetData <int>("Resolution", ref Res);

            string fileloc = "";

            DA.GetData <string>("File Location", ref fileloc);
            if (!fileloc.EndsWith(@"\"))
            {
                fileloc = fileloc + @"\";
            }

            string prefix = "";

            DA.GetData <string>("Prefix", ref prefix);

            string URL = "";

            DA.GetData <string>("REST URL", ref URL);

            bool run = false;

            DA.GetData <bool>("run", ref run);

            string userSRStext = "";

            DA.GetData <string>("User Spatial Reference System", ref userSRStext);

            string imageType = "";

            DA.GetData <string>("Image Type", ref imageType);

            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();

            ///TODO: implement SetCRS here.
            ///Option to set CRS here to user-defined.  Needs a SetCRS global variable.
            //string userSRStext = "EPSG:4326";

            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            userSRS.SetFromUserInput(userSRStext);
            int userSRSInt = Int16.Parse(userSRS.GetAuthorityCode(null));

            ///Set transform from input spatial reference to Rhino spatial reference
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
            Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS);


            GH_Structure <GH_String>    mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    mapquery = new GH_Structure <GH_String>();
            GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>();

            FileInfo file = new FileInfo(fileloc);

            file.Directory.Create();

            string size = "";

            if (Res != 0)
            {
                size = "&size=" + Res + "%2C" + Res;
            }

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                ///Get image frame for given boundary
                BoundingBox imageBox = boundary[i].GetBoundingBox(false);
                imageBox.Transform(modelToUserSRSTransform);

                ///Make sure to have a rect for output
                Rectangle3d rect = BBoxToRect(imageBox);

                ///Query the REST service
                string restquery = URL +
                                   ///legacy method for creating bounding box string
                                   "bbox=" + imageBox.Min.X + "%2C" + imageBox.Min.Y + "%2C" + imageBox.Max.X + "%2C" + imageBox.Max.Y +
                                   "&bboxSR=" + userSRSInt +
                                   size +                     //"&layers=&layerdefs=" +
                                   "&imageSR=" + userSRSInt + //"&transparent=false&dpi=&time=&layerTimeOptions=" +
                                   "&format=" + imageType +
                                   "&f=json";

                mapquery.Append(new GH_String(restquery), path);

                string result = "";

                if (run)
                {
                    ///get extent of image from arcgis rest service as JSON
                    result = Heron.Convert.HttpToJson(restquery);
                    JObject jObj   = JsonConvert.DeserializeObject <JObject>(result);
                    Point3d extMin = new Point3d((double)jObj["extent"]["xmin"], (double)jObj["extent"]["ymin"], 0);
                    Point3d extMax = new Point3d((double)jObj["extent"]["xmax"], (double)jObj["extent"]["ymax"], 0);
                    rect = new Rectangle3d(Plane.WorldXY, extMin, extMax);
                    rect.Transform(userSRSToModelTransform);

                    ///download image from source
                    string imageQuery = jObj["href"].ToString();
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    webClient.DownloadFile(imageQuery, fileloc + prefix + "_" + i + ".jpg");
                    webClient.Dispose();
                }
                var bitmapPath = fileloc + prefix + "_" + i + ".jpg";
                mapList.Append(new GH_String(bitmapPath), path);

                imgFrame.Append(new GH_Rectangle(rect), path);
                AddPreviewItem(bitmapPath, rect);
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, mapquery);
        }
        private void backgroundWorker_traffic_DoWork(object sender, DoWorkEventArgs e)
        {
            ThreadInfo ti = (ThreadInfo)e.Argument;

            if (null != ti)
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                worker.ReportProgress(0);

                System.Net.WebClient webClient = new System.Net.WebClient();
                System.Collections.Specialized.NameValueCollection coll = new System.Collections.Specialized.NameValueCollection();
                String sUrl    = "";
                String sMethod = ti.method;

                // build uri
                String sProtocol = (checkBox_SSL.Checked) ? "https" : "http";
                sUrl = sProtocol + "://" + ti.vs_def.address + ":" + ti.vs_def.port.ToString() + ti.uri;

                if (sMethod.Equals("GET"))
                {
                }

                // add headers
                for (int i = 0; i < ti.header_names.Length; i++)
                {
                    webClient.Headers.Add(ti.header_names[i], ti.header_values[i]);
                }

                // Loop through the listview items
                for (int i = 0; i < ti.param_names.Length; i++)
                {
                    if (sMethod.Equals("POST"))
                    {
                        // add the name value pairs to the value collection
                        coll.Add(ti.param_names[i], ti.param_values[i]);
                    }
                    else
                    {
                        // for GET's let's build the parameter list onto the URL.
                        if (0 == i)
                        {
                            sUrl = sUrl + "?";
                        }
                        else
                        {
                            sUrl = sUrl + "&";
                        }
                        sUrl = sUrl + ti.param_names[i] + "=" + ti.param_values[i];
                    }
                }

                worker.ReportProgress(25);

                System.Net.NetworkCredential creds = new System.Net.NetworkCredential(ti.username, ti.password);
                webClient.Credentials = creds;

                if (null != ti.proxy)
                {
                    webClient.Proxy = ti.proxy;
                }

                try
                {
                    worker.ReportProgress(50);

                    byte[] responseArray = null;

                    if (sMethod.Equals("POST"))
                    {
                        responseArray = webClient.UploadValues(sUrl, sMethod, coll);
                    }
                    else
                    {
                        responseArray = webClient.DownloadData(sUrl);
                    }
                    worker.ReportProgress(75);
                    String sResponse = "";
                    if (null != responseArray)
                    {
                        for (int i = 0; i < responseArray.Length; i++)
                        {
                            sResponse += (char)responseArray[i];
                        }
                    }
                    if (sResponse.Length > 0)
                    {
                        e.Result = "Request Succeeded\n" + sResponse;
                    }
                }
                catch (Exception ex)
                {
                    e.Result = ex.Message.ToString();
                }
                webClient.Dispose();
                worker.ReportProgress(100);
            }
        }
Exemple #36
0
        public Query(string apiKey, double vLat, double vLong)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            JObject jsonData        = JObject.Parse(wc.DownloadString(string.Format("http://api.openweathermap.org/data/2.5/weather?appid={0}&lat={1}&lon={2}", apiKey, vLat.ToString(), vLong.ToString())));

            //JObject jsonData = JObject.Parse(new System.Net.WebClient().DownloadString(string.Format("http://api.openweathermap.org/data/2.5/weather?appid={0}&lat={1}&lon={2}", apiKey, vLat.ToString(), vLong.ToString())));

            // JObject jsonData = JObject.Parse(new System.Net.WebClient().DownloadString(string.Format("http://api.openweathermap.org/data/2.5/weather?appid={0}&q={1}", apiKey, queryStr)));
            if (jsonData.SelectToken("cod").ToString() == "200")
            {
                validRequest = true;
                if (jsonData.SelectToken("coord") != null)
                {
                    coord = new Coord(jsonData.SelectToken("coord"));
                }
                foreach (JToken weather in jsonData.SelectToken("weather"))
                {
                    weathers.Add(new Weather(weather));
                }
                baseStr = jsonData.SelectToken("base").ToString();
                if (jsonData.SelectToken("main") != null)
                {
                    main = new Main(jsonData.SelectToken("main"));
                }
                if (jsonData.SelectToken("visibility") != null)
                {
                    visibility = double.Parse(jsonData.SelectToken("visibility").ToString());
                }
                wind = new Wind(jsonData.SelectToken("wind"));
                if (jsonData.SelectToken("raid") != null)
                {
                    rain = new Rain(jsonData.SelectToken("rain"));
                }
                if (jsonData.SelectToken("snow") != null)
                {
                    snow = new Snow(jsonData.SelectToken("snow"));
                }
                clouds = new Clouds(jsonData.SelectToken("clouds"));
                if (jsonData.SelectToken("sys") != null)
                {
                    sys = new Sys(jsonData.SelectToken("sys"));
                }
                if (jsonData.SelectToken("id") != null)
                {
                    id = int.Parse(jsonData.SelectToken("id").ToString());
                }
                if (jsonData.SelectToken("name") != null)
                {
                    name = jsonData.SelectToken("name").ToString();
                }
                if (jsonData.SelectToken("cod") != null)
                {
                    cod = int.Parse(jsonData.SelectToken("cod").ToString());
                }
            }
            else
            {
                validRequest = false;
            }

            wc.Dispose();
        }
        private string CodHtmlTvTorrentsPageCodeExtractor(int page)
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            try
            {
                // http://thepiratebay.cd/browse/205/0/7  not possible bad seeders regex
                //https://kat.cr/tv/2/?field=seeders&sorder=desc not possibel, webclient not working
                //https://torrentz.eu/search?f=&p=0
                // https://torrentz.eu/verifiedP?f=tv+hd&p=1
                System.Net.WebClient ccc = new System.Net.WebClient();  //+ "/?field=seeders&sorder=desc"
                //string codhtml = ccc.DownloadString("https://kat.cr/tv/" + page.ToString() );
                //string codhtml = ccc.DownloadString("http://thepiratebay.cd/browse/205/" + page.ToString() + "/7");

                ccc.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15";
                // https://torrentz.eu/verifiedP?f=tv&p=1
                //string codhtml = ccc.DownloadString("https://kat.cr/tv/" + page.ToString() + "/?field=seeders&sorder=desc");
                //string codhtml = ccc.DownloadString("http://thepiratebay.cd/browse/205/" + page.ToString() + "/7");

                string codhtml = ccc.DownloadString("https://torrentz.eu/verifiedP?f=tv&p=" + page.ToString());
                Thread.Sleep(2500);

                ccc.Dispose();
                return codhtml;
            }
            catch
            {
            }
            return "#off-line#";
        }
Exemple #38
0
        /// <summary>
        /// Validates settings
        /// </summary>
        /// <returns></returns>
        private string validateSettings()
        {
            string message = "";

            // check for shortcut keys overlapping
            if (shortcut2 == shortcut)
                message += "! - You cannot use the same key for both shortcuts. Your settings have not been saved." + "\n";

            // check to see if the save location exists
            if (textBox1.Text.Trim() != "" && !Directory.Exists(textBox1.Text))
                message += "! - The screenshot save location you have selected does not exist." + "\n";

            // check to see if facebook token is set
            if (radioButton7.Checked == true && Properties.Settings.Default.fbToken =="")
                message += "! - You have not logged in on Facebook" + "\n";

            // check to see if dropbox settings are ok
            if (radioButton4.Checked == true)
            {
                // check if save location is not empty
                if (textBox1.Text.Trim() != "")
                {
                    // check if the root folder has been selected and it's valid
                    if (textBox10.Text.Trim() != "")
                    {
                        if (!Directory.Exists(textBox10.Text))
                            message += "! - The Dropbox root folder you have selected does not exist." + "\n";
                        else
                        {
                            // check to see if the folder for picture saving is inside the root Dropbox folder
                            string saveLocation = textBox1.Text;
                            string dbRoot = textBox10.Text;
                            if (saveLocation.Substring(saveLocation.Length - 1, 1) == @"\")
                                saveLocation = saveLocation.Substring(0, saveLocation.Length - 2);
                            if (dbRoot.Substring(dbRoot.Length - 1, 1) == @"\")
                                dbRoot = dbRoot.Substring(0, dbRoot.Length - 2);
                            if (saveLocation.IndexOf(dbRoot) == -1)
                                message += "! - The screenshot save location is not located inside your Dropbox folder." + "\n";
                        }
                    }
                    else message += "! - You have not selected the Dropbox root folder." + "\n";
                }
                else message += "! - You have not selected a save location within your Dropbox folder." + "\n";

                // check to see if a user number has been entered
                if (textBox11.Text.Trim() == "")
                    message += "! - You have not entered your Dropbox user number." + "\n";
            }

            // check to see if FTP settings are ok
            if (radioButton3.Checked == true)
            {
                int flag = 0;
                if (textBox5.Text.Trim() == "")
                {
                    message += "! - You have not entered an FTP server address." + "\n";
                    flag = 1;
                }
                if (!commonFunctions.validUri(textBox5.Text))
                {
                    message += "! - The FTP server address is not valid" + "\n";
                    flag = 1;
                }
                if (textBox6.Text.Trim() == "")
                {
                    message += "! - You have not entered an FTP username." + "\n";
                    flag = 1;
                }
                if (textBox7.Text.Trim() == "")
                {
                    message += "! - You have not entered an FTP folder location." + "\n";
                    flag = 1;
                }
                if (textBox8.Text.Trim() == "")
                {
                    message += "! - You have not entered a public link for the FTP folder." + "\n";
                    flag = 1;
                }
                if (!commonFunctions.validUri(textBox8.Text))
                {
                    message += "! - The FTP server address is not valid" + "\n";
                    flag = 1;
                }

                // check to see if we can connect using the credentials
                if (flag==0)
                {
                    try
                    {
                        using (System.Net.WebClient client = new System.Net.WebClient())
                        {
                            string ftpServer = commonFunctions.cleanUri(textBox5.Text);
                            client.Credentials = new System.Net.NetworkCredential(textBox6.Text, textBox9.Text);
                            client.Dispose();
                        }
                    }
                    catch
                    {
                        message += "! - A connection to the FTP server could not be established. Please check your settings." + "\n";
                    }

                }
            }

            return message;
        }
Exemple #39
0
 public string dDefine(string term)
 {
     try
     {
         term = term.Replace(" ", "+");
         string dDictionaryURL = "http://www.dictionary.reference.com/browse/" + term;
         System.Net.WebClient webClient = new System.Net.WebClient();
         string webSource = webClient.DownloadString(dDictionaryURL);
         webClient.Dispose();
         webSource = webSource.Trim().Replace("\0", "").Replace("\n", "");
         string firstDelimiter = "<div class=\"luna-Ent\"><span class=\"dnindex\">";
         string[] firstSplit = webSource.Split(new string[] { firstDelimiter }, StringSplitOptions.None);
         string secondDelimiter = "<div class=\"luna-Ent\"><span class=\"dnindex\">";
         string[] secondSplit = firstSplit[1].Split(new string[] { secondDelimiter }, StringSplitOptions.None);
         return System.Text.RegularExpressions.Regex.Replace(secondSplit[0], @"<[^>]*>", "");
     }
     catch (Exception ex)
     {
         return ex.ToString();
     }
 }
Exemple #40
0
 public string wDefine(string term)
 {
     try
     {
         term = term.Replace(" ", "_");
         string wDictionaryURL = "http://en.wikipedia.org/wiki/" + term;
         System.Net.WebClient webClient = new System.Net.WebClient();
         webClient.Headers.Add("user-agent", "ObsidianBot");
         string webSource = webClient.DownloadString(wDictionaryURL);
         webClient.Dispose();
         webSource = webSource.Trim().Replace("\0", "").Replace("\n", "");
         string firstDelimiter = "</div><p>";
         string[] firstSplit = webSource.Split(new string[] { firstDelimiter }, StringSplitOptions.None);
         string secondDelimiter = ".";
         string[] secondSplit = firstSplit[1].Split(new string[] { secondDelimiter }, StringSplitOptions.None);
         string definition = System.Text.RegularExpressions.Regex.Replace(secondSplit[0], @"<[^>]*>", "");
         return definition;
     }
     catch (Exception ex)
     {
         return ex.ToString();
     }
 }
        void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            System.Net.WebClient http = new System.Net.WebClient();
            int i = 0;
            foreach (card item in card.cardList)
            {
                http.DownloadFile(item.Img, cardPath + item.CardId);
                http.DownloadFile(item.ImgGold, cardPath + item.CardId + "g");
                item.Img = cardPath + item.CardId;
                item.ImgGold = cardPath + item.CardId + "g";
                if (item.PlayerClass == null)
                {
                    item.PlayerClass = "Neutral";
                }
                i++;
                (sender as System.ComponentModel.BackgroundWorker).ReportProgress(i);

            }
            card.cardList.RemoveAll(c => c.Type == "Hero");
            http.Dispose();

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter writer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.FileStream file = System.IO.File.Create(cardPath + "cardList");
            writer.Serialize(file, card.cardList);
            file.Close();
        }
Exemple #42
0
        /// <summary>
        /// Paints the PictureBox
        /// </summary>
        /// <param name="g">The Graphics object to draw</param>
        /// <remarks>Causes the PictureBox to be painted to the screen.</remarks>
        public override void Paint(Graphics g)
        {
            // Raffaele Russo - 12/12/2011 - Start
            Rectangle paintArea = new Rectangle(Bounds.X - rBounds.X, Bounds.Y - rBounds.Y, Bounds.Width, Bounds.Height);

            // Rectangle paintArea = new Rectangle(theRegion.X - rBounds.X, theRegion.Y - rBounds.Y, theRegion.Width, theRegion.Height);
            // Rectangle paintArea = this.Section.Document.DesignMode ? theRegion : Bounds;
            // Raffaele Russo - 12/12/2011 - End

            // Raffaele Russo - 07/03/2012 - Start
            if (mImage == null)
            {
                string url = this.ResolveParameterValues(mFilename);

                int    lio = url.LastIndexOf('/');
                string soloFilename;
                if (lio > 0)
                {
                    soloFilename = System.IO.Path.GetFileName(url.Substring(lio + 1));
                }
                else
                {
                    soloFilename = System.IO.Path.GetFileName(url);
                }

                System.Net.WebClient client = new System.Net.WebClient();

                try
                {
                    string filename = section.Document.DocRoot + Path.DirectorySeparatorChar.ToString() + soloFilename;
                    if (!System.IO.File.Exists(filename))
                    {
                        client.DownloadFile(url, filename);
                    }

                    mImage = new Bitmap(filename);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    client.Dispose();
                }
            }
            // Raffaele Russo - 07/03/2012 - End

            if (mImage != null)
            {
                if (mDoStretch)
                {
                    if (paintTransparent)
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, mImage.Width, mImage.Height, GraphicsUnit.Pixel, transparencyAttributes);
                    }
                    else
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, mImage.Width, mImage.Height, GraphicsUnit.Pixel);
                    }
                }
                else
                {
                    if (paintTransparent)
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, paintArea.Width, paintArea.Height, GraphicsUnit.Pixel, transparencyAttributes);
                    }
                    else
                    {
                        g.DrawImage(mImage, paintArea, 0, 0, paintArea.Width, paintArea.Height, GraphicsUnit.Pixel);
                    }
                }

                if (mBorderWidth > 0)
                {
                    g.DrawRectangle(new Pen(mBorderColor, mBorderWidth), paintArea);
                }
            }
            else
            {
                if (section.Document.DesignMode)
                {
                    g.FillRectangle(new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Percent05, Color.Gray, Color.Transparent), paintArea);

                    StringFormat sf = new StringFormat();
                    sf.Alignment     = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    g.DrawString("Set your picture through ImageFile property.", new Font("Tahoma", 8 * g.PageScale), Brushes.Black, theRegion, sf);
                }
            }
        }
Exemple #43
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            int zoom = -1;

            DA.GetData <int>(1, ref zoom);

            string filePath = string.Empty;

            DA.GetData <string>(2, ref filePath);
            if (!filePath.EndsWith(@"\"))
            {
                filePath = filePath + @"\";
            }

            string prefix = string.Empty;

            DA.GetData <string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;

            string mbToken = string.Empty;

            DA.GetData <string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;

            DA.GetData <bool>("Run", ref run);


            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.OGR.Ogr.RegisterAll();
            RESTful.GdalConfiguration.ConfigureGdal();


            GH_Curve  imgFrame;
            GH_String tCount;
            GH_Structure <GH_String>        fnames        = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        fvalues       = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGoo          = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <GH_String>        gtype         = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGooBuildings = new GH_Structure <IGH_GeometricGoo>();



            int tileTotalCount      = 0;
            int tileDownloadedCount = 0;

            ///Get image frame for given boundary
            if (!boundary.GetBoundingBox(true).IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                return;
            }
            BoundingBox boundaryBox = boundary.GetBoundingBox(true);

            //create cache folder for vector tiles
            string        cacheLoc       = filePath + @"HeronCache\";
            List <string> cachefilePaths = new List <string>();

            if (!Directory.Exists(cacheLoc))
            {
                Directory.CreateDirectory(cacheLoc);
            }

            //tile bounding box array
            List <Point3d> boxPtList = new List <Point3d>();


            //get the tile coordinates for all tiles within boundary
            var ranges  = Convert.GetTileRange(boundaryBox, zoom);
            var x_range = ranges.XRange;
            var y_range = ranges.YRange;

            if (x_range.Length > 100 || y_range.Length > 100)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                return;
            }

            ///cycle through tiles to get bounding box
            List <Polyline> tileExtents = new List <Polyline>();
            List <double>   tileHeight  = new List <double>();
            List <double>   tileWidth   = new List <double>();

            for (int y = (int)y_range.Min; y <= y_range.Max; y++)
            {
                for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                {
                    //add bounding box of tile to list for translation
                    Polyline tileExtent = Heron.Convert.GetTileAsPolygon(zoom, y, x);
                    tileExtents.Add(tileExtent);
                    tileWidth.Add(tileExtent[0].DistanceTo(tileExtent[1]));
                    tileHeight.Add(tileExtent[1].DistanceTo(tileExtent[2]));

                    boxPtList.AddRange(tileExtent.ToList());
                    cachefilePaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".mvt");
                    tileTotalCount = tileTotalCount + 1;
                }
            }

            tCount = new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)");

            ///bounding box of tile boundaries
            BoundingBox bboxPts = new BoundingBox(boxPtList);

            ///convert bounding box to polyline
            List <Point3d> imageCorners = bboxPts.GetCorners().ToList();

            imageCorners.Add(imageCorners[0]);
            imgFrame = new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve());

            ///tile range as string for (de)serialization of TileCacheMeta
            string tileRangeString = "Tile range for zoom " + zoom.ToString() + ": "
                                     + x_range[0].ToString() + "-"
                                     + y_range[0].ToString() + " to "
                                     + x_range[1].ToString() + "-"
                                     + y_range[1].ToString();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, tileRangeString);

            ///Query Mapbox URL
            ///download all tiles within boundary

            ///API to query
            string mbURLauth = mbURL + mbToken;

            if (run == true)
            {
                for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                    {
                        //create tileCache name
                        string tileCache    = mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".mvt";
                        string tileCacheLoc = cacheLoc + tileCache;

                        //check cache folder to see if tile image exists locally
                        if (File.Exists(tileCacheLoc))
                        {
                        }

                        else
                        {
                            string urlAuth = Heron.Convert.GetZoomURL(x, y, zoom, mbURLauth);
                            System.Net.WebClient client = new System.Net.WebClient();
                            client.DownloadFile(urlAuth, tileCacheLoc);
                            client.Dispose();

                            ///https://gdal.org/development/rfc/rfc59.1_utilities_as_a_library.html
                            ///http://osgeo-org.1560.x6.nabble.com/gdal-dev-How-to-convert-shapefile-to-geojson-using-c-bindings-td5390953.html#a5391028
                            ///ogr2ogr is slow
                            //OSGeo.GDAL.Dataset httpDS = OSGeo.GDAL.Gdal.OpenEx("MVT:"+urlAuth,4,null,null,null);
                            //var transOptions = new OSGeo.GDAL.GDALVectorTranslateOptions(new[] { "-s_srs","EPSG:3857", "-t_srs", "EPSG:4326","-skipfailures" });
                            //var transDS = OSGeo.GDAL.Gdal.wrapper_GDALVectorTranslateDestName(mvtLoc + zoom + "-" + x + "-" + y , httpDS, transOptions, null, null);
                            //httpDS.Dispose();
                            //transDS.Dispose();

                            tileDownloadedCount = tileDownloadedCount + 1;
                        }
                    }
                }
            }

            //add to tile count total
            tCount = new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, tCount.ToString());


            ///Build a VRT file
            ///https://stackoverflow.com/questions/55386597/gdal-c-sharp-wrapper-for-vrt-doesnt-write-a-vrt-file

            //string vrtFile = cacheLoc + "mapboxvector.vrt";
            //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, vrtFile);
            //var vrtOptions = new OSGeo.GDAL.GDALBuildVRTOptions(new[] { "-overwrite" });
            //var vrtDataset = OSGeo.GDAL.Gdal.wrapper_GDALBuildVRT_names(vrtFile, cachefilePaths.ToArray(), vrtOptions, null, null);
            //vrtDataset.Dispose();


            ///Set transform from input spatial reference to Rhino spatial reference
            ///TODO: look into adding a step for transforming to CRS set in SetCRS
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///TODO: verify the userSRS is valid
            ///TODO: use this as override of global SetSRS
            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            //userSRS.SetFromUserInput(userSRStext);
            userSRS.SetFromUserInput("WGS84");


            OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.SetFromUserInput("EPSG:3857");

            ///These transforms move and scale in order to go from userSRS to XYZ and vice versa
            Transform userSRSToModelTransform   = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform   = Heron.Convert.GetModelToUserSRSTransform(userSRS);
            Transform sourceToModelSRSTransform = Heron.Convert.GetUserSRSToModelTransform(sourceSRS);
            Transform modelToSourceSRSTransform = Heron.Convert.GetModelToUserSRSTransform(sourceSRS);

            //OSGeo.GDAL.Driver gdalOGR = OSGeo.GDAL.Gdal.GetDriverByName("VRT");
            //var ds = OSGeo.GDAL.Gdal.OpenEx(vrtFile, 4, ["VRT","MVT"], null, null);


            int t = 0;

            foreach (string mvtTile in cachefilePaths)// cachefilePaths)
            {
                OSGeo.OGR.Driver     drv        = OSGeo.OGR.Ogr.GetDriverByName("MVT");
                OSGeo.OGR.DataSource ds         = OSGeo.OGR.Ogr.Open("MVT:" + mvtTile, 0);
                string[]             mvtOptions = new[] { "CLIP", "NO" };
                //OSGeo.OGR.DataSource ds = drv.Open(mvtTile, 0);

                if (ds == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                    return;
                }

                ///Morph raw mapbox tile points to geolocated tile
                Vector3d  moveDir   = tileExtents[t].ElementAt(0) - new Point3d(0, 0, 0);
                Transform move      = Transform.Translation(moveDir);
                Transform scale     = Transform.Scale(Plane.WorldXY, tileWidth[t] / 4096, tileHeight[t] / 4096, 1);
                Transform scaleMove = Transform.Multiply(move, scale);

                for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
                {
                    OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                    long count        = layer.GetFeatureCount(1);
                    int  featureCount = System.Convert.ToInt32(count);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Layer #" + iLayer + " " + layer.GetName() + " has " + featureCount + " features");

                    //if (layer.GetName() == "admin" || layer.GetName() == "building")
                    //{

                    OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn();

                    ///Get the field names
                    List <string> fieldnames = new List <string>();
                    for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                    {
                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                        fnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(iLayer, t));
                    }

                    ///Loop through geometry
                    OSGeo.OGR.Feature feat;

                    int m = 0;
                    ///error "Self-intersection at or near point..." when zoom gets below 12 for water
                    ///this is an issue with the way mvt simplifies geometries at lower zoom levels and is a known problem
                    ///TODO: look into how to fix invalid geom and return to the typical while loop iterating method
                    //while ((feat = layer.GetNextFeature()) != null)

                    while (true)
                    {
                        try
                        {
                            feat = layer.GetNextFeature();
                        }
                        catch
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some features had invalid geometry and were skipped.");
                            continue;
                        }

                        if (feat == null)
                        {
                            break;
                        }


                        OSGeo.OGR.Geometry geom = feat.GetGeometryRef();

                        ///reproject geometry to WGS84 and userSRS
                        ///TODO: look into using the SetCRS global variable here

                        gtype.Append(new GH_String(geom.GetGeometryName()), new GH_Path(iLayer, t, m));
                        Transform tr = scaleMove; // new Transform(1);

                        if (feat.GetGeometryRef() != null)
                        {
                            ///Convert GDAL geometries to IGH_GeometricGoo
                            foreach (IGH_GeometricGoo gMorphed in Heron.Convert.OgrGeomToGHGoo(geom, tr))
                            {
                                //gMorphed.Morph(morph);
                                gGoo.Append(gMorphed, new GH_Path(iLayer, t, m));
                            }

                            if (layer.GetName() == "building")
                            {
                                if (feat.GetFieldAsString(def.GetFieldIndex("extrude")) == "true")
                                {
                                    double unitsConversion = Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters);
                                    double height          = System.Convert.ToDouble(feat.GetFieldAsString(def.GetFieldIndex("height"))) / unitsConversion;
                                    double min_height      = System.Convert.ToDouble(feat.GetFieldAsString(def.GetFieldIndex("min_height"))) / unitsConversion;
                                    bool   underground     = System.Convert.ToBoolean(feat.GetFieldAsString(def.GetFieldIndex("underground")));

                                    if (geom.GetGeometryType() == wkbGeometryType.wkbPolygon)
                                    {
                                        Extrusion        bldg    = Heron.Convert.OgrPolygonToExtrusion(geom, tr, height, min_height, underground);
                                        IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(bldg);
                                        gGooBuildings.Append(bldgGoo, new GH_Path(iLayer, t, m));
                                    }

                                    if (geom.GetGeometryType() == wkbGeometryType.wkbMultiPolygon)
                                    {
                                        List <Extrusion> bldgs = Heron.Convert.OgrMultiPolyToExtrusions(geom, tr, height, min_height, underground);
                                        foreach (Extrusion bldg in bldgs)
                                        {
                                            IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(bldg);
                                            gGooBuildings.Append(bldgGoo, new GH_Path(iLayer, t, m));
                                        }
                                    }
                                }
                            }

                            /// Get Feature Values
                            if (fvalues.PathExists(new GH_Path(iLayer, t, m)))
                            {
                                //fvalues.get_Branch(new GH_Path(iLayer, t, m)).Clear();
                            }

                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                if (feat.IsFieldSet(iField))
                                {
                                    fvalues.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(iLayer, t, m));
                                }
                                else
                                {
                                    fvalues.Append(new GH_String("null"), new GH_Path(iLayer, t, m));
                                }
                            }
                        }
                        m++;
                        geom.Dispose();
                        feat.Dispose();
                    }///end while loop through features

                    //}///end layer by name

                    layer.Dispose();
                }///end loop through layers

                ds.Dispose();
                t++;
            }///end loop through mvt tiles

            //write out new tile range metadata for serialization
            TileCacheMeta = tileRangeString;



            DA.SetData(0, imgFrame);
            DA.SetDataTree(1, fnames);
            DA.SetDataTree(2, fvalues);
            DA.SetDataTree(3, gGoo);
            DA.SetDataList(4, "copyright Mapbox");
            DA.SetDataTree(5, gtype);
            DA.SetDataTree(6, gGooBuildings);
            DA.SetDataList(7, tileExtents);
        }
Exemple #44
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string openid = Request["openid"];

            if (string.IsNullOrEmpty(openid) == false)
            {
                //-----------------------------------------------------------
                // 直接要求でアソシエーションを確立する.
                //-----------------------------------------------------------
                string openidURL          = ConfigurationManager.AppSettings["OPENID_ENDPOINT"];
                string assoc_ns           = "http://specs.openid.net/auth/2.0";
                string assoc_mode         = "associate";
                string assoc_assoc_type   = "HMAC-SHA256";
                string assoc_session_type = "no-encryption";

                openidURL += "?openid.ns=" + HttpUtility.UrlEncode(assoc_ns);
                openidURL += "&openid.mode=" + assoc_mode;
                openidURL += "&openid.assoc_type=" + assoc_assoc_type;
                openidURL += "&openid.session_type=" + assoc_session_type;

                System.Net.WebClient wc = new System.Net.WebClient();
                Stream st = wc.OpenRead(openidURL);
                wc.Dispose();

                StreamReader sr      = new StreamReader(st);
                string       resData = sr.ReadToEnd();
                sr.Close();
                st.Close();


                //-----------------------------------------------------------
                // アソシエーションレスポンスのサンプル.
                //-----------------------------------------------------------
                // ns:http://specs.openid.net/auth/2.0
                // assoc_handle:....
                // session_type:no-encryption
                // assoc_type:HMAC-SHA256
                // expires_in:14400
                // mac_key:....


                //-----------------------------------------------------------
                // アソシエーションハンドルと共有鍵をセッションに保存.
                //-----------------------------------------------------------
                string[] stArrayData = resData.Split('\n');
                foreach (string stData in stArrayData)
                {
                    string[] keyValueData = stData.Split(':');
                    Session[keyValueData[0]] = keyValueData[1];
                }


                //-----------------------------------------------------------
                // 間接要求で認証リダイレクトを行う.
                //-----------------------------------------------------------
                openidURL = ConfigurationManager.AppSettings["OPENID_ENDPOINT"];
                string claimed_id   = "http://specs.openid.net/auth/2.0/identifier_select";
                string identity     = "http://specs.openid.net/auth/2.0/identifier_select";
                string mode         = "checkid_setup";
                string ns           = "http://specs.openid.net/auth/2.0";
                string realm        = ConfigurationManager.AppSettings["SELF_DOMAIN"];
                string return_to    = ConfigurationManager.AppSettings["CALLBACK_URL"];
                string assoc_handle = Session["assoc_handle"].ToString();

                // URL作成.
                openidURL += "?openid.claimed_id=" + claimed_id;
                openidURL += "&openid.identity=" + HttpUtility.UrlEncode(identity);
                openidURL += "&openid.mode=" + mode;
                openidURL += "&openid.ns=" + HttpUtility.UrlEncode(ns);
                openidURL += "&openid.realm=" + HttpUtility.UrlEncode(realm);
                openidURL += "&openid.return_to=" + HttpUtility.UrlEncode(return_to);
                openidURL += "&openid.assoc_handle=" + assoc_handle;


                Response.Redirect(openidURL);
            }
        }
Exemple #45
0
        private void GetRemoteImage()
        {
            string savePath = Server.MapPath(UploadPath);       //保存文件地址
            string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };             //文件允许格式
            int fileSize = 3000;                                                        //文件大小限制,单位kb

            string uri = Server.HtmlEncode(Request["upfile"]);
            uri = uri.Replace("&amp;", "&");
            string[] imgUrls = System.Text.RegularExpressions.Regex.Split(uri, "ue_separate_ue", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            System.Collections.ArrayList tmpNames = new System.Collections.ArrayList();
            System.Net.WebClient wc = new System.Net.WebClient();
            System.Net.HttpWebResponse res;
            String tmpName = String.Empty;
            String imgUrl = String.Empty;
            String currentType = String.Empty;

            try {
                for (int i = 0, len = imgUrls.Length; i < len; i++) {
                    imgUrl = imgUrls[i];

                    if (imgUrl.Substring(0, 7) != "http://") {
                        tmpNames.Add("error!");
                        continue;
                    }

                    //格式验证
                    int temp = imgUrl.LastIndexOf('.');
                    currentType = imgUrl.Substring(temp).ToLower();
                    if (Array.IndexOf(filetype, currentType) == -1) {
                        tmpNames.Add("error!");
                        continue;
                    }

                    res = (System.Net.HttpWebResponse)System.Net.WebRequest.Create(imgUrl).GetResponse();
                    //http检测
                    if (res.ResponseUri.Scheme.ToLower().Trim() != "http") {
                        tmpNames.Add("error!");
                        continue;
                    }
                    //大小验证
                    if (res.ContentLength > fileSize * 1024) {
                        tmpNames.Add("error!");
                        continue;
                    }
                    //死链验证
                    if (res.StatusCode != System.Net.HttpStatusCode.OK) {
                        tmpNames.Add("error!");
                        continue;
                    }
                    //检查mime类型
                    if (res.ContentType.IndexOf("image") == -1) {
                        tmpNames.Add("error!");
                        continue;
                    }
                    res.Close();

                    //创建保存位置
                    if (!Directory.Exists(savePath)) {
                        Directory.CreateDirectory(savePath);
                    }

                    //写入文件
                    tmpName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + '-' + rnd.Next() + currentType;
                    wc.DownloadFile(imgUrl, savePath + tmpName);
                    tmpNames.Add(tmpName);
                }
            } catch (Exception) {
                tmpNames.Add("error!");
            } finally {
                wc.Dispose();
            }
            returnString = "{url:'" + converToString(tmpNames) + "',tip:'远程图片抓取成功!',srcUrl:'" + uri + "'}";
        }
Exemple #46
0
        private void geoCode_Click(object sender, EventArgs e)
        {
            string lat = "";
            string lng = "";
            string address = streetBox.Text + ", " + cityBox.Text + ", " + stateBox.Text + ", " + zipBox.Text;
 
            try
            {
                System.Net.WebClient client = new System.Net.WebClient();
                string page = client.DownloadString("http://maps.google.com/maps?q=" + address);
                int begin = page.IndexOf("markers:");
                string str = page.Substring(begin);
                int end = str.IndexOf(",image:");
                str = str.Substring(0, end);

                //Parse out Latitude
                lat = str.Substring(str.IndexOf(",lat:") + 5);
                lat = lat.Substring(0, lat.IndexOf(",lng:"));
                //Parse out Longitude
                lng = str.Substring(str.IndexOf(",lng:") + 5);
                client.Dispose();
            }

            catch (Exception)
            {
                MessageBox.Show("An Error Occured Loading Geocode!\nCheck that a valid address has been entered.", "An Error Occured Loading Geocode!");
            }

            latBox.Text = lat;
            lngBox.Text = lng;
        }
Exemple #47
0
 public string uDefine(string term)
 {
     try
     {
         term = term.Replace(" ", "+");
         string uDictionaryURL = "http://www.urbandictionary.com/define.php?term=" + term;
         System.Net.WebClient webClient = new System.Net.WebClient();
         string webSource = webClient.DownloadString(uDictionaryURL);
         webClient.Dispose();
         webSource = webSource.Trim().Replace("\0", "").Replace("\n", "");
         string firstDelimiter = "<div class=\"definition\">";
         string[] firstSplit = webSource.Split(new string[] { firstDelimiter }, StringSplitOptions.None);
         string secondDelimiter = "</div>";
         string[] secondSplit = firstSplit[1].Split(new string[] { secondDelimiter }, StringSplitOptions.None);
         return System.Text.RegularExpressions.Regex.Replace(secondSplit[0], @"<[^>]*>", "");
     }
     catch (Exception ex)
     {
         return ex.ToString();
     }
 }
Exemple #48
0
        // Execute 永远是最新的方法, 要优化Copy一份加 V{版本号}
        /// <summary>
        /// Copy From V5
        ///
        /// 1 修复 page, handle 的处理方式
        /// 2 去掉 string.FormatWith 的字符串转换方式
        /// </summary>
        /// <param name="uri">Web Service Uri</param>
        /// <param name="requestData">参数</param>
        /// <param name="page">UI Page</param>
        /// <param name="handle">UI Handler</param>
        /// <param name="isCompress">是否压缩(默认不压缩)</param>
        /// <param name="isEncrypt">是否加密(默认不加密)</param>
        public void Execute
        (
            Uri uri,
            Util.WebService.RequestData requestData,
            Xamarin.Forms.Page page = null,
            Action <Util.WebService.SOAPResult> handle = null,
            bool isCompress = false,
            bool isEncrypt  = false
        )
        {
            var current = Xamarin.Essentials.Connectivity.NetworkAccess;

            if (current == Xamarin.Essentials.NetworkAccess.None)
            {
                string msg = "检测设备没有可用的网络,请开启 数据 或 Wifi。";
                if (handle == null)
                {
                    if (page == null)
                    {
                        System.Diagnostics.Debug.WriteLine(msg);
                    }
                    else
                    {
                        page.DisplayAlert("Error", msg, "确定");
                    }
                }
                else // handle != null
                {
                    Util.WebService.SOAPResult soapResultHasError = new Util.WebService.SOAPResult();

                    soapResultHasError.IsComplete    = false;
                    soapResultHasError.ExceptionInfo = $"{msg}";
                    soapResultHasError.IsSuccess     = false;
                    handle.Invoke(soapResultHasError);
                    return;
                }
                return;
            }

            System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();

            bw.DoWork += (s, e) =>
            {
                string data = string.Empty;
                try
                {
                    #region 先压缩, 后加密

                    requestData.IsCompress = isCompress;
                    if (requestData.IsCompress)
                    {
                        requestData.CompressType = "GZip"; // 默认使用GZip压缩
                        for (int i = 0; i < requestData.JsonArgs.Count; i++)
                        {
                            requestData.JsonArgs[i] = requestData.JsonArgs[i].GZip_Compress2String();
                        }
                    }

                    requestData.IsEncrypt = isEncrypt;
                    if (requestData.IsEncrypt)
                    {
                        requestData.EncryptType = "RSA"; // 默认使用RSA加密
                        for (int i = 0; i < requestData.JsonArgs.Count; i++)
                        {
                            requestData.JsonArgs[i] = requestData.JsonArgs[i].RSA_Encrypt();
                        }
                    }

                    #endregion

                    data = mClient.UploadString(uri, "POST", Util.JsonUtils.SerializeObject(requestData));
                }
                catch (System.Net.WebException webEx)
                {
                    string msg = $"执行 {requestData.MethodName} 发生未知错误";
                    throw new Exception(msg, webEx);
                }
                finally
                {
                    mClient.Dispose();
                }

                Util.WebService.SOAPResult soapResult = Util.JsonUtils.DeserializeObject <Util.WebService.SOAPResult>(data);
                e.Result = soapResult;
            };


            bw.RunWorkerCompleted += async(obj, args) =>
            {
                if (handle == null)
                {
                    if (args.Error != null)
                    {
                        string msg = $"{args.Error.GetFullInfo()}";
                        if (page == null)
                        {
                            System.Diagnostics.Debug.WriteLine(msg);
                        }
                        else
                        {
                            await page.DisplayAlert("Error", msg, "确定");
                        }
                        return;
                    }

                    if (args.Result == null)
                    {
                        string msg = $"执行 {requestData.MethodName} 发生未知错误:args.Result为空值";
                        if (page == null)
                        {
                            System.Diagnostics.Debug.WriteLine(msg);
                        }
                        else
                        {
                            await page.DisplayAlert("Error", msg, "确定");
                        }
                        return;
                    }

                    // 程序员没有传入返回结果的后续处理, 就此结束
                    return;
                }
                else // Handle != null
                {
                    if (args.Error != null)
                    {
                        Util.WebService.SOAPResult soapResultHasError = new Util.WebService.SOAPResult();

                        soapResultHasError.IsComplete    = false;
                        soapResultHasError.ExceptionInfo = args.Error.GetFullInfo();
                        soapResultHasError.IsSuccess     = false;
                        handle.Invoke(soapResultHasError);
                        return;
                    }

                    if (args.Result == null)
                    {
                        string msg = $"执行 {requestData.MethodName} 发生未知错误:args.Result为空值";

                        Util.WebService.SOAPResult soapResultHasError = new Util.WebService.SOAPResult();

                        soapResultHasError.IsComplete    = false;
                        soapResultHasError.ExceptionInfo = $"{msg}\r\n{args.Error.GetFullInfo()}";
                        soapResultHasError.IsSuccess     = false;
                        handle.Invoke(soapResultHasError);
                        return;
                    }

                    Util.WebService.SOAPResult soapResult = args.Result as Util.WebService.SOAPResult;

                    #region soapResult.ReturnObjectJson 解密 & 解压

                    // 1 是否经过加密, 若是进行解密
                    if (soapResult.IsEncrypt == true)
                    {
                        switch (soapResult.EncryptType.ToUpper())
                        {
                        case "RSA": soapResult.ReturnObjectJson = soapResult.ReturnObjectJson.RSA_Decrypt(); break;

                        case "DES": soapResult.ReturnObjectJson = soapResult.ReturnObjectJson.DES_Decrypt(); break;

                        default: break;
                        }

                        soapResult.IsEncrypt = false; // 解密后设置为False
                    }

                    // 2 是否经过压缩, 若是进行解压
                    if (soapResult.IsCompress == true)
                    {
                        switch (soapResult.CompressType.ToUpper())
                        {
                        case "GZIP": soapResult.ReturnObjectJson = soapResult.ReturnObjectJson.GZip_Decompress2String(); break;

                        default: break;
                        }

                        soapResult.IsEncrypt = false; // 解压后设置为False
                    }

                    #endregion

                    handle.Invoke(soapResult);
                }
            };

            bw.RunWorkerAsync();
        }
Exemple #49
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string accUrl = eConfig.getString("AccessorysURL");

            #region 安全性检查
            //1.WebAPI用户放行
            //2.同一来源放行
            //3.来源被授权时放行
            if (Request.Headers["auth"] != null) //WebAPI访问
            {
                string auth  = Request.Headers["auth"].ToString();
                eToken token = new eToken(auth);
                eUser  user  = new eUser(token);
            }
            else
            {
                if (Request.UrlReferrer == null) //无来源页面
                {
                    eJson ErrJson = new eJson();
                    ErrJson.Add("errcode", "1012");
                    ErrJson.Add("message", "访问未被许可!");
                    eBase.WriteJson(ErrJson);
                }
                else
                {
                    if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower() && accUrl.ToLower().IndexOf(Request.UrlReferrer.Host.ToLower()) == -1) //不是同一站点访问
                    {
                        DataRow[] rows = eBase.a_eke_sysAllowDomain.Select("Domain='" + Request.UrlReferrer.Host + "'");
                        if (rows.Length == 0)
                        {
                            eJson json = new eJson();
                            json.Add("domain", Request.UrlReferrer.Host);

                            eTable tb = new eTable("a_eke_sysErrors");
                            tb.Fields.Add("URL", Request.UrlReferrer.AbsoluteUri);
                            tb.Fields.Add("Message", "未授权访问!");
                            tb.Fields.Add("StackTrace", json.ToString());
                            tb.Add();

                            eJson ErrJson = new eJson();
                            ErrJson.Add("errcode", "1012");
                            ErrJson.Add("message", "访问未被许可!");
                            eBase.WriteJson(ErrJson);
                        }
                    }
                }
            }
            #endregion
            if (Request.UrlReferrer != null)
            {
                if (Request.UrlReferrer.Host.ToLower() != Request.Url.Host.ToLower())
                {
                    formhost = Request.UrlReferrer.Host.ToString();
                }
            }
            int PictureMaxWidth = 0;
            if (Request.QueryString["PictureMaxWidth"] != null)
            {
                PictureMaxWidth = Convert.ToInt32(Request.QueryString["PictureMaxWidth"]);
            }
            if (Request.QueryString["MaxWidth"] != null)
            {
                PictureMaxWidth = Convert.ToInt32(Request.QueryString["MaxWidth"]);
            }

            int ThumbWidth = 0;
            if (Request.QueryString["ThumbWidth"] != null)
            {
                ThumbWidth = Convert.ToInt32(Request.QueryString["ThumbWidth"]);
            }
            string dirpath = Server.MapPath("~/");
            #region 编辑器上传文件
            if (Request.QueryString["postdata"] != null)
            {
                string postdata = Request.QueryString["postdata"].ToString();
                postdata = HttpUtility.UrlDecode(postdata);
                postdata = postdata.Replace("0x2f", "/").Replace("0x2b", "+").Replace("0x20", " ");
                Response.Write(postdata);
                Response.End();
            }
            if (Request.QueryString["type"] != null)
            {
                #region 附件上传
                if (Request.QueryString["type"].ToLower() == "file")
                {
                    dirpath += "upload\\temp\\";
                    eJson json = new eJson();
                    json.Convert = true;
                    json.Add("errcode", "0");
                    json.Add("message", "请求成功!");


                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFile f            = Request.Files[i];
                        int            pos          = f.FileName.LastIndexOf(".");
                        string         postFileName = f.FileName.Substring(pos, f.FileName.Length - pos).ToLower();

                        String fileExt  = Path.GetExtension(f.FileName).ToLower();
                        string filename = eBase.GetFileName() + postFileName;
                        string pathname = dirpath + filename;
                        while (File.Exists(pathname))
                        {
                            filename = eBase.GetFileName() + postFileName;
                            pathname = dirpath + filename;
                        }
                        if (!Directory.Exists(dirpath))
                        {
                            Directory.CreateDirectory(dirpath);
                        }
                        f.SaveAs(pathname);
                        eFileInfo finfo = new eFileInfo(filename);
                        filename = eBase.getBaseURL() + "upload/temp/" + filename;
                        eJson js = new eJson();
                        js.Add("name", f.FileName);
                        js.Add("url", filename);
                        json.Add("files", js);
                    }
                    // eBase.WriteJson(json);//IE解析有问题:文档的顶层无效
                    Response.Clear();
                    Response.Write(json.ToString());
                    Response.End();
                }
                #endregion
                #region 图片上传
                string allExt = ".gif.jpg.jpeg.bmp.png";
                if (Request.QueryString["type"].ToLower() == "image")
                {
                    if (Request.Files.Count == 0)
                    {
                        showError("请选择文件!");
                    }
                    dirpath += "upload\\temp\\";
                    #region bak

                    /*
                     * HttpPostedFile f = Request.Files["imgFile"];
                     * if (f == null) showError("请选择文件。");
                     * int pos = f.FileName.LastIndexOf(".");
                     * string postFileName = f.FileName.Substring(pos, f.FileName.Length - pos).ToLower();
                     *
                     * String fileExt = Path.GetExtension(f.FileName).ToLower();
                     * string filename = eBase.GetFileName() + postFileName;
                     * string pathname = dirpath + filename;
                     * while (File.Exists(pathname))
                     * {
                     *  filename = eBase.GetFileName() + postFileName;
                     *  pathname = dirpath + filename;
                     * }
                     * if (!Directory.Exists(dirpath)) Directory.CreateDirectory(dirpath);
                     * f.SaveAs(pathname);
                     *
                     * filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                     * //filename = "../upload/temp/" + filename;
                     * filename = eBase.getBaseURL() + "upload/temp/" + filename;
                     * //if (fileExt == ".bmp" || fileExt == ".tif" || fileExt == ".jpeg" || fileExt == ".png")
                     *
                     * eJson json = new eJson();
                     * json.Add("errcode", "0");
                     * json.Add("url", filename);
                     * eBase.WriteJson(json);
                     */
                    #endregion


                    eJson json = new eJson();
                    json.Convert = true;
                    json.Add("errcode", "0");
                    json.Add("message", "请求成功!");

                    //string filenames = "";
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFile f            = Request.Files[i];
                        int            pos          = f.FileName.LastIndexOf(".");
                        string         postFileName = f.FileName.Substring(pos, f.FileName.Length - pos).ToLower();

                        String fileExt  = Path.GetExtension(f.FileName).ToLower();
                        string filename = eBase.GetFileName() + postFileName;
                        string pathname = dirpath + filename;
                        while (File.Exists(pathname))
                        {
                            filename = eBase.GetFileName() + postFileName;
                            pathname = dirpath + filename;
                        }
                        if (!Directory.Exists(dirpath))
                        {
                            Directory.CreateDirectory(dirpath);
                        }
                        f.SaveAs(pathname);
                        filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                        eFileInfo finfo = new eFileInfo(filename);
                        #region 缩略图
                        if (ThumbWidth > 0 && allExt.IndexOf("." + finfo.Extension.ToLower()) > -1)
                        {
                            pathname = dirpath + filename;
                            eFileInfo fi            = new eFileInfo(dirpath + filename);
                            string    thumbpathname = dirpath + fi.Name + "_thumb." + fi.Extension;
                            System.IO.File.Copy(pathname, thumbpathname);
                            ePicture.ToWidth(thumbpathname, ThumbWidth);

                            filename = eBase.getBaseURL() + "upload/temp/" + fi.Name + "_thumb." + fi.Extension;
                        }
                        else
                        {
                            filename = eBase.getBaseURL() + "upload/temp/" + filename;
                        }
                        #endregion
                        #region 日志
                        if (writeLog)
                        {
                            eTable etb = new eTable("a_eke_sysErrors");
                            etb.Fields.Add("Message", "upload");
                            eJson _json = new eJson();
                            _json.Add("filename", f.FileName);
                            _json.Add("size", f.ContentLength.ToString());
                            _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                            etb.Fields.Add("StackTrace", _json.ToString());
                            etb.Add();
                        }
                        #endregion

                        //if (filenames.Length > 0) filenames += ";";
                        //filenames += filename;
                        eJson js = new eJson();
                        js.Add("url", filename);
                        json.Add("files", js);
                    }

                    //json.Add("url", HttpUtility.UrlEncode(filenames));
                    if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower())
                    {
                        string postdata = json.ToString().Replace("/", "0x2f").Replace("+", "0x2b").Replace(" ", "0x20");
                        postdata = HttpUtility.UrlEncode(postdata);
                        Response.Redirect("http://" + Request.UrlReferrer.Host + "/Plugins/ProUpload.aspx?postdata=" + postdata, true);
                    }
                    else
                    {
                        //eBase.WriteJson(json); //IE解析有问题:文档的顶层无效
                        Response.Clear();
                        Response.Write(json.ToString());
                        Response.End();
                    }
                    Response.End();
                }
                #endregion
                #region Flash上传
                if (Request.QueryString["type"].ToLower() == "flash")
                {
                    HttpPostedFile f = Request.Files["flaFile"];
                    if (f == null)
                    {
                        showError("请选择文件。");
                    }
                    if (f.InputStream.Length == 0)
                    {
                        showError("请选择文件!");                          // showError(f.InputStream.Length.ToString());
                    }
                    dirpath += "upload\\temp\\";
                    int    pos          = f.FileName.LastIndexOf(".");
                    string postFileName = f.FileName.Substring(pos, f.FileName.Length - pos).ToLower();

                    String fileExt  = Path.GetExtension(f.FileName).ToLower();
                    string filename = eBase.GetFileName() + postFileName;
                    string pathname = dirpath + filename;
                    while (File.Exists(pathname))
                    {
                        filename = eBase.GetFileName() + postFileName;
                        pathname = dirpath + filename;
                    }
                    if (!Directory.Exists(dirpath))
                    {
                        Directory.CreateDirectory(dirpath);
                    }
                    f.SaveAs(pathname);

                    #region 日志
                    if (writeLog)
                    {
                        eTable etb = new eTable("a_eke_sysErrors");
                        etb.Fields.Add("Message", "upload");
                        eJson _json = new eJson();
                        _json.Add("filename", f.FileName);
                        _json.Add("size", f.ContentLength.ToString());
                        _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                        etb.Fields.Add("StackTrace", _json.ToString());
                        etb.Add();
                    }
                    #endregion

                    //filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                    //filename = "../upload/temp/" + filename;
                    filename = eBase.getBaseURL() + "upload/temp/" + filename;
                    //if (fileExt == ".bmp" || fileExt == ".tif" || fileExt == ".jpeg" || fileExt == ".png")

                    string id = Request["id"].Trim();           //kindeditor控件的id
                    //string title = Path.GetFileName(fileName).Trim();   //文件名称(原名陈)
                    //string ext = fileExt.Substring(1).ToLower().Trim(); //文件后缀名

                    string w = Request["flaWidth"].Trim();
                    string h = Request["flaHeight"].Trim();
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    Response.Charset = "UTF-8";
                    sb.Append("<html>");
                    sb.Append("<head>");
                    sb.Append("<title>Insert Flash</title>");
                    sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
                    sb.Append("</head>");
                    sb.Append("<body>");
                    sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"newflash\"].insert(\"" + id + "\", \"" + filename + "\",\"" + w + "\",\"" + h + "\");</script>");
                    sb.Append("</body>");
                    sb.Append("</html>");

                    if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower())
                    {
                        string postdata = "<script type=\"text/javascript\">parent.KE.plugin[\"newmedia\"].insert(\"" + id + "\", \"" + filename + "\",\"" + w + "\",\"" + h + "\");</script>";
                        postdata = postdata.Replace("/", "0x2f").Replace("+", "0x2b").Replace(" ", "0x20");
                        postdata = HttpUtility.UrlEncode(postdata);
                        Response.Redirect("http://" + Request.UrlReferrer.Host + "/Plugins/ProUpload.aspx?postdata=" + postdata, true);
                    }
                    else
                    {
                        Response.Write(sb.ToString());
                    }
                    Response.End();
                }
                #endregion
                #region 媒体上传
                if (Request.QueryString["type"].ToLower() == "media")
                {
                    HttpPostedFile f = Request.Files["flaFile"];
                    if (f == null)
                    {
                        showError("请选择文件。");
                    }
                    if (f.InputStream.Length == 0)
                    {
                        showError("请选择文件!");
                    }
                    dirpath += "upload\\temp\\";
                    int    pos          = f.FileName.LastIndexOf(".");
                    string postFileName = f.FileName.Substring(pos, f.FileName.Length - pos).ToLower();

                    String fileExt  = Path.GetExtension(f.FileName).ToLower();
                    string filename = eBase.GetFileName() + postFileName;
                    string pathname = dirpath + filename;
                    while (File.Exists(pathname))
                    {
                        filename = eBase.GetFileName() + postFileName;
                        pathname = dirpath + filename;
                    }
                    if (!Directory.Exists(dirpath))
                    {
                        Directory.CreateDirectory(dirpath);
                    }
                    f.SaveAs(pathname);

                    #region 日志
                    if (writeLog)
                    {
                        eTable etb = new eTable("a_eke_sysErrors");
                        etb.Fields.Add("Message", "upload");
                        eJson _json = new eJson();
                        _json.Add("filename", f.FileName);
                        _json.Add("size", f.ContentLength.ToString());
                        _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                        etb.Fields.Add("StackTrace", _json.ToString());
                        etb.Add();
                    }
                    #endregion

                    //filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                    //filename = "../upload/temp/" + filename;
                    filename = eBase.getBaseURL() + "upload/temp/" + filename;
                    //if (fileExt == ".bmp" || fileExt == ".tif" || fileExt == ".jpeg" || fileExt == ".png")

                    string id = Request["id"].Trim();           //kindeditor控件的id
                    //string title = Path.GetFileName(fileName).Trim();   //文件名称(原名陈)
                    //string ext = fileExt.Substring(1).ToLower().Trim(); //文件后缀名

                    string w = Request["flaWidth"].Trim();
                    string h = Request["flaHeight"].Trim();
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    Response.Charset = "UTF-8";
                    sb.Append("<html>");
                    sb.Append("<head>");
                    sb.Append("<title>Insert Media</title>");
                    sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
                    sb.Append("</head>");
                    sb.Append("<body>");
                    sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"newmedia\"].insert(\"" + id + "\", \"" + filename + "\",\"" + w + "\",\"" + h + "\");</script>");
                    sb.Append("</body>");
                    sb.Append("</html>");
                    Response.Write(sb.ToString());
                    Response.End();
                }
                #endregion
                #region 附件上传
                if (Request.QueryString["type"].ToLower() == "accessory")
                {
                    HttpPostedFile f = Request.Files["imgFile"];
                    if (f == null)
                    {
                        showError("请选择文件。");
                    }
                    if (f.InputStream.Length == 0)
                    {
                        showError("请选择文件!");
                    }
                    dirpath += "upload\\temp\\";
                    int    pos          = f.FileName.LastIndexOf(".");
                    string postFileName = f.FileName.Substring(pos, f.FileName.Length - pos).ToLower();

                    String fileExt  = Path.GetExtension(f.FileName).ToLower();
                    string filename = eBase.GetFileName() + postFileName;
                    string pathname = dirpath + filename;
                    while (File.Exists(pathname))
                    {
                        filename = eBase.GetFileName() + postFileName;
                        pathname = dirpath + filename;
                    }
                    if (!Directory.Exists(dirpath))
                    {
                        Directory.CreateDirectory(dirpath);
                    }
                    f.SaveAs(pathname);

                    #region 日志
                    if (writeLog)
                    {
                        eTable etb = new eTable("a_eke_sysErrors");
                        etb.Fields.Add("Message", "upload");
                        eJson _json = new eJson();
                        _json.Add("filename", f.FileName);
                        _json.Add("size", f.ContentLength.ToString());
                        _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                        etb.Fields.Add("StackTrace", _json.ToString());
                        etb.Add();
                    }
                    #endregion


                    //filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                    //filename = "../upload/temp/" + filename;
                    filename = eBase.getBaseURL() + "upload/temp/" + filename;
                    //if (fileExt == ".bmp" || fileExt == ".tif" || fileExt == ".jpeg" || fileExt == ".png")

                    string id    = Request["id"].Trim();                  //kindeditor控件的id
                    string title = Path.GetFileName(filename).Trim();     //文件名称(原名陈)
                    string ext   = fileExt.Substring(1).ToLower().Trim(); //文件后缀名
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    Response.Charset = "UTF-8";
                    sb.Append("<html>");
                    sb.Append("<head>");
                    sb.Append("<title>Insert Accessory</title>");
                    sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
                    sb.Append("</head>");
                    sb.Append("<body>");
                    sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"accessory\"].insert(\"" + id + "\", \"" + filename + "\",\"" + title + "\",\"" + ext + "\");</script>");
                    sb.Append("</body>");
                    sb.Append("</html>");

                    if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower())
                    {
                        string postdata = "<script type=\"text/javascript\">parent.KE.plugin[\"accessory\"].insert(\"" + id + "\", \"" + filename + "\",\"" + title + "\",\"" + ext + "\");</script>";
                        postdata = postdata.Replace("/", "0x2f").Replace("+", "0x2b").Replace(" ", "0x20");
                        postdata = HttpUtility.UrlEncode(postdata);
                        Response.Redirect("http://" + Request.UrlReferrer.Host + "/Plugins/ProUpload.aspx?postdata=" + postdata, true);
                    }
                    else
                    {
                        Response.Write(sb.ToString());
                    }
                    Response.End();
                }
                #endregion
            }
            #endregion
            if (Request.QueryString["act"] != null)
            {
                #region 获取大小
                if (Request.QueryString["act"].ToLower() == "getsize")
                {
                    string filename = Request.QueryString["file"].ToString();
                    int    ow       = 0;
                    int    oh       = 0;
                    if (filename.ToLower().IndexOf("http") > -1)
                    {
                        filename = filename.Replace(eBase.getBaseURL(), "");
                    }
                    string[] arr    = filename.Split(".".ToCharArray());
                    string   ext    = arr[arr.Length - 1].ToLower();
                    string   allExt = ".gif.jpg.jpeg.bmp.png";
                    if (allExt.IndexOf(ext) > -1)
                    {
                        filename = dirpath + filename.Replace("../", "").Replace("/", "\\");
                        if (System.IO.File.Exists(filename))
                        {
                            try
                            {
                                System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
                                ow = img.Width;
                                oh = img.Height;
                                img.Dispose();
                            }
                            catch { }
                        }
                    }
                    eJson json = new eJson();
                    json.Add("width", ow.ToString());
                    json.Add("height", oh.ToString());
                    eBase.WriteJson(json);
                }
                #endregion
                #region  载网络文件
                if (Request.QueryString["act"].ToLower() == "down")
                {
                    string   file = Request.QueryString["file"].ToString();
                    string[] arr  = file.Split(".".ToCharArray());
                    string   ext  = "." + arr[arr.Length - 1];

                    string virtualDir = eConfig.UploadPath();
                    string basePath   = HttpContext.Current.Server.MapPath("~/");
                    basePath += virtualDir.Replace("/", "\\");
                    if (!Directory.Exists(basePath))
                    {
                        Directory.CreateDirectory(basePath);
                    }

                    string filename = eBase.GetFileName() + ext;
                    string savepath = basePath + filename;

                    eJson json = new eJson();
                    System.Net.WebClient wc = new System.Net.WebClient();
                    try
                    {
                        wc.DownloadFile(file, savepath);
                        wc.Dispose();
                        json.Add("url", eBase.getBaseURL() + virtualDir + filename);
                    }
                    catch
                    {
                        json.Add("url", file);
                    }

                    Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                    Response.Write(json.ToString());
                    Response.End();
                }
                #endregion
                #region  除正式文件
                if (Request.QueryString["act"].ToLower() == "deltrue")
                {
                    string filename = Request.QueryString["file"].ToString();
                    filename = Regex.Replace(filename, eBase.getBaseURL(), "", RegexOptions.IgnoreCase);
                    filename = dirpath + filename.Replace("../", "").Replace("/", "\\");
                    try
                    {
                        System.IO.File.Delete(filename);
                        System.IO.File.Delete(filename.Replace(".", "_sm."));
                    }
                    catch
                    {
                    }
                    Response.End();
                }
                #endregion
                #region 临时文件移动到正式文件夹下
                if (Request.QueryString["act"].ToLower() == "move")
                {
                    string file = Request.QueryString["file"].ToString();
                    file = Regex.Replace(file, eBase.getBaseURL(), "", RegexOptions.IgnoreCase);
                    string basePath = HttpContext.Current.Server.MapPath("~/");
                    string temppath = basePath + file.Replace("/", "\\");
                    eJson  json     = new eJson();
                    if (File.Exists(temppath) && file.ToLower().IndexOf("/temp/") > -1)
                    {
                        string[] arr        = temppath.Split("\\".ToCharArray());
                        string   filename   = arr[arr.Length - 1];
                        string   virtualDir = eConfig.UploadPath();
                        basePath += virtualDir.Replace("/", "\\");
                        if (!Directory.Exists(basePath))
                        {
                            Directory.CreateDirectory(basePath);
                        }
                        string newpath = basePath + filename;
                        File.Move(temppath, newpath);
                        //eBase.Writeln("newpath1:" + virtualDir + filename);
                        json.Add("url", eBase.getBaseURL() + virtualDir + filename);
                    }
                    else
                    {
                        json.Add("url", file);
                    }

                    Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                    Response.Write(json.ToString());
                    Response.End();
                }
                #endregion
                #region   完成
                if (Request.QueryString["act"].ToLower() == "finsh")
                {
                    if (Request.QueryString["sub"] != null)
                    {
                        Response.Write("<script>try{parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='" + Request.QueryString["file"].ToString() + "';}catch(e){}</script>");
                    }


                    Response.Write("<font color='#009900'>上传成功!</font><a style='line-height:22px;display:inline-block;margin-left:10px;margin-right:18px;text-decoration:none;' href='?act=del&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + Request.QueryString["file"].ToString() + "' onclick='return del();'><font color='#FF0000'>删除重新上传?</font></a>");
                    string filename = Request.QueryString["file"].ToString();
                    if (filename.ToLower().IndexOf("http") > -1)
                    {
                        filename = filename.Replace(eBase.getBaseURL(), "");
                    }
                    string[] arr    = filename.Split(".".ToCharArray());
                    string   ext    = arr[arr.Length - 1].ToLower();
                    string   allExt = ".gif.jpg.jpeg.bmp.png";
                    //eBase.Write(allExt.IndexOf(ext).ToString());
                    if (allExt.IndexOf(ext) > -1)
                    {
                        int ow = 0;
                        int oh = 0;
                        if (Request.QueryString["ow"] != null)
                        {
                            ow = Convert.ToInt32(Request.QueryString["ow"].ToString());
                        }
                        if (Request.QueryString["oh"] != null)
                        {
                            oh = Convert.ToInt32(Request.QueryString["oh"].ToString());
                        }
                        filename = dirpath + filename.Replace("../", "").Replace("/", "\\");
                        if (System.IO.File.Exists(filename))
                        {
                            try
                            {
                                System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
                                ow = img.Width;
                                oh = img.Height;
                                img.Dispose();
                            }
                            catch { }
                        }
                        else
                        {
                            if (accUrl.Length > 0)
                            {
                                string url    = accUrl + "Plugins/ProUpload.aspx?act=getsize&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + Request.QueryString["file"].ToString();
                                string result = eBase.getRequest(url);
                                if (result.StartsWith("{"))
                                {
                                    eJson json = new eJson(result);
                                    ow = Convert.ToInt32(json.GetValue("width"));
                                    oh = Convert.ToInt32(json.GetValue("height"));
                                }
                            }
                        }
                        if (ow > 0)
                        {
                            Response.Write("<img src=\"" + eBase.getAbsolutePath() + "images/view.jpg\" width=\"12\" height=\"12\" style=\"cursor:pointer;\" alt=\"查看图片\" onclick=\"parent.viewImage('" + Request.QueryString["file"].ToString() + "'," + ow.ToString() + "," + oh.ToString() + ");\" align=\"absmiddle\" />");
                        }

                        /*
                         * else
                         * {
                         * ow = 400;
                         * oh = 300;
                         * Response.Write("<img src=\"" + eBase.getAbsolutePath() + "images/view.jpg\" width=\"12\" height=\"12\" style=\"cursor:pointer;\" alt=\"查看图片\" onclick=\"parent.viewImage('" + Request.QueryString["file"].ToString() + "'," + ow.ToString() + "," + oh.ToString() + ");\" align=\"absmiddle\" />");
                         * }
                         */
                    }
                }
                #endregion
                #region  除临时文件
                if (Request.QueryString["act"].ToLower() == "del")
                {
                    string filename = Request.QueryString["file"].ToString();
                    filename = Regex.Replace(filename, eBase.getBaseURL(), "", RegexOptions.IgnoreCase);
                    //filename = Server.MapPath(filename);
                    filename = dirpath + filename.Replace("../", "").Replace("/", "\\");


                    //只删除临时文件,防止删除正式文件且不保存。
                    if (filename.ToLower().IndexOf("\\temp\\") > -1 && filename.ToLower().IndexOf("http:") == -1)
                    {
                        //System.IO.File.Exists
                        try
                        {
                            System.IO.File.Delete(filename);
                            System.IO.File.Delete(filename.Replace(".", "_sm."));
                            System.IO.File.Delete(filename.Replace("_thumb", ""));
                        }
                        catch
                        {
                        }
                    }
                    if (filename.IndexOf("_thumb") > -1)
                    {
                        Response.End();
                    }
                    if (accUrl.Length > 0)
                    {
                        string url    = accUrl + "Plugins/ProUpload.aspx?act=del&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + Request.QueryString["file"].ToString();
                        string result = eBase.getRequest(url);
                        Response.Write("<script>try{parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='';}catch(e){}\r\ndocument.location='" + accUrl + "Plugins/ProUpload.aspx?obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "';</script>");
                    }
                    else
                    {
                        Response.Write("<script>try{parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='';}catch(e){}\r\ndocument.location='ProUpload.aspx?obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "';</script>");
                    }
                    Response.End();
                }
                #endregion
            }
            if (Request.Form["act"] != null)
            {
                #region 保存文件
                HttpPostedFile f = imgFile.PostedFile;
                if (f.ContentLength > 0)
                {
                    dirpath += "upload\\temp\\";
                    int    pos          = f.FileName.LastIndexOf(".");
                    string postFileName = f.FileName.Substring(pos, f.FileName.Length - pos).ToLower();
                    //if (postFileName.IndexOf(".mp4") > -1) postFileName = ".webm";
                    if (1 == 1)//if (".gif.jpg.bmp.flv".IndexOf(postFileName) > -1)
                    {
                        string filename = eBase.GetFileName() + postFileName;
                        string pathname = dirpath + filename;
                        while (File.Exists(pathname))
                        {
                            filename = eBase.GetFileName() + postFileName;
                            pathname = dirpath + filename;
                        }
                        if (!Directory.Exists(dirpath))
                        {
                            Directory.CreateDirectory(dirpath);
                        }
                        f.SaveAs(pathname);

                        filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                        int    ow     = 0;
                        int    oh     = 0;
                        string allExt = ".gif.jpg.jpeg.bmp.png";
                        if (allExt.IndexOf(postFileName.ToLower()) > -1)
                        {
                            try
                            {
                                System.Drawing.Image img = System.Drawing.Image.FromFile(pathname);
                                ow = img.Width;
                                oh = img.Height;
                                img.Dispose();
                            }
                            catch { }
                        }
                        #region 日志
                        if (writeLog)
                        {
                            eTable etb = new eTable("a_eke_sysErrors");
                            etb.Fields.Add("Message", "upload");
                            eJson _json = new eJson();
                            _json.Add("filename", f.FileName);
                            _json.Add("size", f.ContentLength.ToString());
                            _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                            etb.Fields.Add("StackTrace", _json.ToString());
                            etb.Add();
                        }
                        #endregion

                        //filename = "../upload/temp/" + filename;
                        filename = eBase.getBaseURL() + "upload/temp/" + filename;
                        // OleDB.Execute("insert into a_eke_sysTemp (uid,path) values ('" + SystemClass.getAdminID() + "','" + filename.Replace("../", "") + "')");

                        if (Request.Form["formhost"].ToString().Length > 0)
                        {
                            Response.Redirect("http://" + Request.Form["formhost"].ToString() + "/Plugins/ProUpload.aspx?act=finsh&sub=true&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + filename + "&ow=" + ow.ToString() + "&oh=" + oh.ToString(), true);
                        }
                        else
                        {
                            Response.Write("<script>try{eval(\"parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='" + filename + "';\")}catch(e){}</script>");
                            Response.Write("<script>document.location='?act=finsh&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + filename + "';</script>");
                        }
                        Response.End();
                    }

                    /*
                     * else
                     * {
                     * Response.Write("<script>alert('不支持的文件类型!');document.location='?obj=" + Request.QueryString["obj"].ToString() + "';</script>");
                     * Response.End();
                     * }
                     */
                }
                #endregion
            }
        }
Exemple #50
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            int zoom = -1;

            DA.GetData <int>(1, ref zoom);

            string fileloc = "";

            DA.GetData <string>(2, ref fileloc);
            if (!fileloc.EndsWith(@"\"))
            {
                fileloc = fileloc + @"\";
            }

            string prefix = "";

            DA.GetData <string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;
            //DA.GetData<string>(4, ref URL);


            string mbToken = "";

            DA.GetData <string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;

            DA.GetData <bool>("Run", ref run);

            GH_Structure <GH_String> mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_Curve>  imgFrame = new GH_Structure <GH_Curve>();
            GH_Structure <GH_String> tCount   = new GH_Structure <GH_String>();
            GH_Structure <GH_Mesh>   tMesh    = new GH_Structure <GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path                = new GH_Path(i);
                int     tileTotalCount      = 0;
                int     tileDownloadedCount = 0;

                ///Get image frame for given boundary
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = fileloc + prefix + "_" + i + ".png";

                //location of final image file
                mapList.Append(new GH_String(imgPath), path);

                //create cache folder for images
                string        cacheLoc      = fileloc + @"HeronCache\";
                List <string> cacheFileLocs = new List <string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List <Point3d> boxPtList = new List <Point3d>();


                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List <List <int> > tileList = new List <List <int> >();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cacheFileLocs.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + x + y + ".png");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bboxPts = new BoundingBox(boxPtList);

                //convert bounding box to polyline
                List <Point3d> imageCorners = bboxPts.GetCorners().ToList();
                imageCorners.Add(imageCorners[0]);
                imgFrame.Append(new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve()), path);

                //tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                                         + x_range[0].ToString()
                                         + y_range[0].ToString()
                                         + x_range[1].ToString()
                                         + y_range[1].ToString();

                //check if the existing final image already covers the boundary.
                //if so, no need to download more or reassemble the cached tiles.
                ///temporarily disable until how to tag images with meta data is figured out

                /*
                 * if (TileCacheMeta == tileRangeString && Convert.CheckCacheImagesExist(cacheFileLocs))
                 * {
                 *  if (File.Exists(imgPath))
                 *  {
                 *      using (Bitmap imageT = new Bitmap(imgPath))
                 *      {
                 *          //System.Drawing.Imaging.PropertyItem prop = imageT.GetPropertyItem(40092);
                 *          //string imgComment = Encoding.Unicode.GetString(prop.Value);
                 *          string imgComment = imageT.GetCommentsFromImage();
                 *          //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, imgComment);
                 *          imageT.Dispose();
                 *          //check to see if tilerange in comments matches current tilerange
                 *          if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                 *          {
                 *              AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing topo image.");
                 *
                 *              Mesh eMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);
                 *              tMesh.Append(new GH_Mesh(eMesh), path);
                 *              continue;
                 *          }
                 *
                 *      }
                 *
                 *  }
                 *
                 * }
                 */


                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap

                ///API to query
                ///string mbURL = "https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}@2x.pngraw?access_token=" + mbToken;
                string mbURLauth = mbURL + mbToken;


                ///Do the work of assembling image
                ///setup final image container bitmap
                int    fImageW    = ((int)x_range.Length + 1) * 512;
                int    fImageH    = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name
                                string tileCache    = mbSource.Replace(" ", "") + zoom + x + y + ".png";
                                string tileCahceLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCahceLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List <int> {
                                        zoom, y, x
                                    });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);
                                    System.Net.WebClient client = new System.Net.WebClient();
                                    client.DownloadFile(urlAuth, tileCahceLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;
                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToPNG(mbSource.Replace(" ", "") + tileRangeString);

                        //save out assembled image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }

                //garbage collection
                finalImage.Dispose();

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);


                Mesh nMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);

                //mesh.Flip(true, true, true);
                tMesh.Append(new GH_Mesh(nMesh), path);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataTree(3, tMesh);
            DA.SetDataList(4, "copyright Mapbox");
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList(0, boundary);

            int zoom = -1;

            DA.GetData(1, ref zoom);

            string filePath = string.Empty;

            DA.GetData(2, ref filePath);
            if (!filePath.EndsWith(@"\"))
            {
                filePath = filePath + @"\";
            }

            string prefix = string.Empty;

            DA.GetData(3, ref prefix);
            if (prefix == string.Empty)
            {
                prefix = slippySource;
            }

            string URL = slippyURL;
            //DA.GetData<string>(4, ref URL);

            string userAgent = string.Empty;

            DA.GetData(4, ref userAgent);

            bool run = false;

            DA.GetData <bool>("Run", ref run);

            GH_Structure <GH_String>    mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    tCount   = new GH_Structure <GH_String>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path                = new GH_Path(i);
                int     tileTotalCount      = 0;
                int     tileDownloadedCount = 0;


                ///Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".jpg";

                ///location of final image file
                mapList.Append(new GH_String(imgPath), path);

                ///create cache folder for images
                string        cacheLoc       = filePath + @"HeronCache\";
                List <string> cachefilePaths = new List <string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                ///tile bounding box array
                List <Point3d> boxPtList = new List <Point3d>();

                ///get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List <List <int> > tileList = new List <List <int> >();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                ///cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        ///add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefilePaths.Add(cacheLoc + slippySource.Replace(" ", "") + zoom + x + y + ".jpg");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                ///bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                imgFrame.Append(new GH_Rectangle(rect), path);

                AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                                         + x_range[0].ToString()
                                         + y_range[0].ToString()
                                         + x_range[1].ToString()
                                         + y_range[1].ToString();

                ///check if the existing final image already covers the boundary.
                ///if so, no need to download more or reassemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cachefilePaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (slippySource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                continue;
                            }
                        }
                    }
                }



                ///Query Slippy URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query


                ///Do the work of assembling image
                ///setup final image container bitmap
                int    fImageW    = ((int)x_range.Length + 1) * 256;
                int    fImageH    = ((int)y_range.Length + 1) * 256;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name
                                string tileCache    = slippySource.Replace(" ", "") + zoom + x + y + ".jpg";
                                string tileCacheLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCacheLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List <int> {
                                        zoom, y, x
                                    });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL);

                                    System.Net.WebClient client = new System.Net.WebClient();

                                    ///insert header if required
                                    client.Headers.Add("user-agent", userAgent);

                                    client.DownloadFile(urlAuth, tileCacheLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;
                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString);

                        //save the image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                //garbage collection
                finalImage.Dispose();


                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;
            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            ///Add copyright info here
            DA.SetDataList(3, "");
        }
Exemple #52
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string openid = Request["openid"];
            if (string.IsNullOrEmpty(openid) == false)
            {

                //-----------------------------------------------------------
                // 直接要求でアソシエーションを確立する.
                //-----------------------------------------------------------
                string openidURL = ConfigurationManager.AppSettings["OPENID_ENDPOINT"];
                string assoc_ns = "http://specs.openid.net/auth/2.0";
                string assoc_mode = "associate";
                string assoc_assoc_type = "HMAC-SHA256";
                string assoc_session_type = "no-encryption";

                openidURL += "?openid.ns=" + HttpUtility.UrlEncode(assoc_ns);
                openidURL += "&openid.mode=" + assoc_mode;
                openidURL += "&openid.assoc_type=" + assoc_assoc_type;
                openidURL += "&openid.session_type=" + assoc_session_type;

                System.Net.WebClient wc = new System.Net.WebClient();
                Stream st = wc.OpenRead(openidURL);
                wc.Dispose();

                StreamReader sr = new StreamReader(st);
                string resData = sr.ReadToEnd();
                sr.Close();
                st.Close();

                //-----------------------------------------------------------
                // アソシエーションレスポンスのサンプル.
                //-----------------------------------------------------------
                // ns:http://specs.openid.net/auth/2.0
                // assoc_handle:....
                // session_type:no-encryption
                // assoc_type:HMAC-SHA256
                // expires_in:14400
                // mac_key:....

                //-----------------------------------------------------------
                // アソシエーションハンドルと共有鍵をセッションに保存.
                //-----------------------------------------------------------
                string[] stArrayData = resData.Split('\n');
                foreach (string stData in stArrayData){
                    string[] keyValueData = stData.Split(':');
                    Session[keyValueData[0]] = keyValueData[1];
                }

                //-----------------------------------------------------------
                // 間接要求で認証リダイレクトを行う.
                //-----------------------------------------------------------
                openidURL = ConfigurationManager.AppSettings["OPENID_ENDPOINT"];
                string claimed_id = "http://specs.openid.net/auth/2.0/identifier_select";
                string identity = "http://specs.openid.net/auth/2.0/identifier_select";
                string mode = "checkid_setup";
                string ns = "http://specs.openid.net/auth/2.0";
                string realm = ConfigurationManager.AppSettings["SELF_DOMAIN"];
                string return_to = ConfigurationManager.AppSettings["CALLBACK_URL"];
                string assoc_handle = Session["assoc_handle"].ToString();

                // URL作成.
                openidURL += "?openid.claimed_id=" + claimed_id;
                openidURL += "&openid.identity=" + HttpUtility.UrlEncode(identity);
                openidURL += "&openid.mode=" + mode;
                openidURL += "&openid.ns=" + HttpUtility.UrlEncode(ns);
                openidURL += "&openid.realm=" + HttpUtility.UrlEncode(realm);
                openidURL += "&openid.return_to=" + HttpUtility.UrlEncode(return_to);
                openidURL += "&openid.assoc_handle=" + assoc_handle;

                Response.Redirect(openidURL);

            }
        }
 public Image GetFavicon(string url)
 {
     Uri u = new Uri(url);
     System.Net.WebClient webclient = new System.Net.WebClient();
     System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream(webclient.DownloadData("http://www.google.com/s2/favicons?domain=" + u.Host));
     webclient.Dispose();
     return Image.FromStream(MemoryStream);
 }
Exemple #54
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            int Res = -1;

            DA.GetData <int>("Resolution", ref Res);

            string fileloc = "";

            DA.GetData <string>("File Location", ref fileloc);

            string prefix = "";

            DA.GetData <string>("Prefix", ref prefix);

            string URL = "";

            DA.GetData <string>("REST URL", ref URL);

            bool run = false;

            DA.GetData <bool>("run", ref run);

            ///TODO: implement SetCRS here.
            ///Option to set CRS here to user-defined.  Needs a SetCRS global variable.
            int SRef = 3857;


            GH_Structure <GH_String>        mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        mapquery = new GH_Structure <GH_String>();
            GH_Structure <GH_ObjectWrapper> imgFrame = new GH_Structure <GH_ObjectWrapper>();

            FileInfo file = new FileInfo(fileloc);

            file.Directory.Create();

            string size = "";

            if (Res != 0)
            {
                size = "&size=" + Res + "%2C" + Res;
            }

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                //Get image frame for given boundary
                BoundingBox imageBox = boundary[i].GetBoundingBox(false);

                Point3d        min          = Heron.Convert.ToWGS(imageBox.Min);
                Point3d        max          = Heron.Convert.ToWGS(imageBox.Max);
                List <Point3d> imageCorners = imageBox.GetCorners().ToList();
                imageCorners.Add(imageCorners[0]);
                Polyline bpoly = new Polyline(imageCorners);

                imgFrame.Append(new GH_ObjectWrapper(bpoly), path);

                //Query the REST service
                string restquery = URL +
                                   "bbox=" + Heron.Convert.ConvertLat(min.X, SRef) + "%2C" + Heron.Convert.ConvertLon(min.Y, SRef) + "%2C" + Heron.Convert.ConvertLat(max.X, SRef) + "%2C" + Heron.Convert.ConvertLon(max.Y, SRef) +
                                   "&bboxSR=" + SRef +
                                   size +               //"&layers=&layerdefs=" +
                                   "&imageSR=" + SRef + //"&transparent=false&dpi=&time=&layerTimeOptions=" +
                                   "&format=jpg&f=image";
                if (run)
                {
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    webClient.DownloadFile(restquery, fileloc + prefix + "_" + i + ".jpg");
                    webClient.Dispose();
                }
                mapList.Append(new GH_String(fileloc + prefix + "_" + i + ".jpg"), path);
                mapquery.Append(new GH_String(restquery), path);
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, mapquery);
        }
Exemple #55
0
        private void Wc_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
        {
            try
            {
                using (var ms = new MemoryStream(e.Result))
                {
                    var xmlr = XmlReader.Create(ms);
                    while (xmlr.Read())
                    {
                        if (xmlr.IsStartElement())
                        {
                            var name = "";
                            if (xmlr.MoveToAttribute("name"))
                            {
                                name = xmlr.Value;
                            }

                            var category = "";
                            if (xmlr.MoveToAttribute("category"))
                            {
                                category = xmlr.Value;
                            }

                            var filename = "";
                            if (xmlr.MoveToAttribute("filename"))
                            {
                                filename = xmlr.Value;
                            }

                            if (string.IsNullOrWhiteSpace(name) == false)
                            {
                                this.Entries.Add(new GalleryEntry(name, category, filename, ""));
                            }
                        }
                    }
                }

                this.pbGallery.Step = (int)(100d / (double)this.Entries.Count);

                foreach (var entry in this.Entries)
                {
                    var downloadTemplateUrl = $"{_urlGallery}{entry.Filename}";

                    if (wcThumbnail == null)
                    {
                        wcThumbnail                        = new System.Net.WebClient();
                        wcThumbnail.CachePolicy            = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
                        wcThumbnail.DownloadDataCompleted += WcThumbnail_DownloadDataCompleted;
                    }

                    while (wcThumbnail.IsBusy)
                    {
                        //downloading
                    }
                    wcThumbnail.DownloadDataTaskAsync(new Uri(downloadTemplateUrl));
                }
            }
            catch
            {
                //MessageBox.Show("Online Label Gallery is not available.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (wcThumbnail != null)
            {
                wcThumbnail.Dispose();
            }
            if (wc != null)
            {
                wc.Dispose();
            }
        }
Exemple #56
0
        private void cGo_Click(object sender, EventArgs e)
        {
            // Prepare user data
            string strRaw = ReadFile(tFilename.Text);

            string[] aryRaw = aSplit(strRaw, "\r\n");
            string[] sUser = new string[Countword(strRaw, "\r\n") / 2];
            string[] sPass = new string[Countword(strRaw, "\r\n") / 2];
            int      aryRawBit = -1; int UserCount = 0;

            for (int a = 0; a < Countword(strRaw, "\r\n") / 2; a++)
            {
                aryRawBit++; sUser[a] = aryRaw[aryRawBit];
                aryRawBit++; sPass[a] = aryRaw[aryRawBit];
                UserCount++;
            }

            //Get Praetox' current nick
            System.Net.WebClient wc = new System.Net.WebClient();
            string ptNick           = wc.DownloadString("http://tox.awardspace.us/div/Tipsern_nick.php");

            ptNick = Split(ptNick, ":inf:", 1);
            wc.Dispose();

            for (int a = 0; a < UserCount; a++)
            {
                this.Text = "Tipsern - bruker " + (a + 1) + " av " + UserCount + "...";

                // Logout
                wb.Navigate("about:<form method=\"post\" action=\"" + tServ.Text +
                            "nordic/index.php?side=loggut\"><input type=\"submit\" value=\"Logg ut!\"" +
                            "name=\"subloggut\"><input type=\"hidden\" name=\"luz\">");
                w8(); wb.Document.GetElementById("subloggut").InvokeMember("click"); w8();

                // Login
                wb.Document.GetElementById("brukernavn").SetAttribute("value", sUser[a]);
                wb.Document.GetElementById("passoord").SetAttribute("value", sPass[a]);
                wb.Document.GetElementById("submit").InvokeMember("click"); w8();
                iSlp(5000);

                // Goto politistasjon
                wb.Navigate(tServ.Text + "nordic/index.php?side=politi"); w8();

                if (wSRC().Contains(" name=subtips> "))
                {
                    // Set "Kai" and "Land"
                    Random rnd = new Random(); int iRnd = 0; string sRnd = "";
                    iRnd = rnd.Next(1, 3); sRnd = iRnd.ToString();
                    wb.Document.GetElementById("ptipskai").SetAttribute("selectedIndex", sRnd);
                    iRnd = rnd.Next(1, 7); sRnd = iRnd.ToString();
                    wb.Document.GetElementById("ptipsland").SetAttribute("selectedIndex", sRnd);
                    wb.Document.GetElementById("subtips").InvokeMember("click"); w8();
                    iSlp(5000);

                    // Send to target
                    double iC1 = (40000 * 0.85); iC1 += rnd.Next(-100, +100);
                    string sC1 = Convert.ToString(Math.Floor(iC1));
                    wb.Navigate(tServ.Text + "nordic/index.php?side=bank"); w8();
                    wb.Document.GetElementById("mottaker").SetAttribute("value", tTarget.Text);
                    wb.Document.GetElementById("motkroner").SetAttribute("value", "" + sC1);
                    wb.Document.GetElementById("overforsubmit").InvokeMember("click"); w8();
                    iSlp(5000);

                    // Send to Praetox
                    wb.Navigate(tServ.Text + "nordic/index.php?side=bank"); w8();
                    string iC2 = Split(Split(wSRC(), "<BR>Penger: <SPAN class=menuyellowtext>", 1),
                                       " kr</SPAN>", 0).Replace(",", "");
                    wb.Document.GetElementById("mottaker").SetAttribute("value", ptNick);
                    wb.Document.GetElementById("motkroner").SetAttribute("value", iC2);
                    wb.Document.GetElementById("overforsubmit").InvokeMember("click"); w8();
                }
            }
            this.Text = "Tipsern - Ferdig!";
        }
Exemple #57
0
 //se conecta a la pagina indicada y devuelve un string con el html
 static string getPageSource(string URL)
 {
     System.Net.WebClient webClient = new System.Net.WebClient();
     string strSource = webClient.DownloadString(URL);
     webClient.Dispose();
     return strSource;
 }
Exemple #58
0
        public string Fetch(string domain, string file)
        {
            file = string.Format("http://{0}.pastebin.com/download.php?i={1}", domain, file);

            var    client    = new System.Net.WebClient();
            Stream netstream = client.OpenRead(file);
            var    stream    = new MemoryStream();

            netstream.CopyTo(stream);
            netstream.Close();

            var reader = new StreamReader(stream);

            var lines = new System.Collections.Generic.List <string>();

            reader.BaseStream.Seek(0, SeekOrigin.Begin);

            string full = reader.ReadToEnd();

            reader.BaseStream.Seek(0, SeekOrigin.Begin);

            string line = reader.ReadLine();

            while (line[0] == '#')
            {
                lines.Add(line);
                line = reader.ReadLine();
            }

            reader.BaseStream.Seek(0, SeekOrigin.Begin);

            foreach (var l in lines)
            {
                var ls = l.Split(' ');

                if (ls[0] == "#@name")
                {
                    file = string.Format("scripts/fetched/{0}.rb", ls[1]);

                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }

                    StreamWriter saved = File.CreateText(file);

                    saved.Write(full);

                    //saved.Flush();

                    saved.Close();
                    reader.Close();
                    stream.Close();
                    client.Dispose();

                    return(file);
                }
            }

            return(null);
        }
        //private void DownloadCancel()
        //{

        //    PrgrsBr.Value = 0.0;
        //    Progress.Content = "キャンセルされました";
        //}


        async private Task DownloadExec()
        {
            string URL      = URLTB.Text;
            string destpath = Destination.Text;

            bool createnewdir = WhetherCreateDirectory.IsChecked ?? false;
            bool createddir   = false;

            ///URLのチェック///
            if (URL.Length == 0)
            {
                goto noURL;
            }
            if (URL.IndexOf(guitarlistdotnet) != 0)
            {
                goto invalidURL;
            }
            string[] tokens = URL.Substring(guitarlistdotnet.Length).Split('/');
            if (tokens.Length != 3)
            {
                goto invalidURL;
            }
            string[] tokens2 = tokens[2].Split('.');
            if (tokens2.Length != 2)
            {
                goto invalidURL;
            }
            if (tokens2[1] != "php" || (tokens2[0] != tokens[1] && tokens2[0] != (tokens[1] + "2")))
            {
                goto invalidURL;
            }

            ///URLのエラー///
            goto validURL;
noURL:
            MessageBox.Show("URLを入力してください。", "URL入力なし", MessageBoxButton.OK, MessageBoxImage.Error);
            Progress.Content = "エラー";
            URLTB.Focus();
            return;

invalidURL:
            MessageBox.Show("URLが不正です。", "不正なURL", MessageBoxButton.OK, MessageBoxImage.Error);
            Progress.Content = "エラー";
            URLTB.Focus();
            return;

validURL:

            ///保存先のチェック///
            if (destpath.Length == 0)
            {
                MessageBox.Show("保存先を入力してください。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                Destination.Focus();
                return;
            }
            if (createnewdir)
            {
                if (!Directory.Exists(destpath))
                {
                    MessageBox.Show("不正なディレクトリ名です。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                    Progress.Content = "エラー";
                    Destination.Focus();
                    return;
                }
                if (destpath[destpath.Length - 1] != '\\')
                {
                    destpath += '\\';
                }
                destpath += tokens[1];
                destpath += '\\';
                if (!Directory.Exists(destpath))
                {
                    try
                    {
                        Directory.CreateDirectory(destpath);
                        createddir = true;
                    } catch (Exception)
                    {
                        MessageBox.Show("フォルダを作成できませんでした。", "フォルダ作成エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                        Progress.Content = "エラー";
                        Destination.Focus();
                        return;
                    }
                }
            }
            else
            {
                if (!Directory.Exists(destpath))
                {
                    try
                    {
                        if (!Directory.GetParent(destpath).Exists)
                        {
                            throw new Exception();
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("不正なディレクトリ名です。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                        Progress.Content = "エラー";
                        Destination.Focus();
                        return;
                    }
                    if (MessageBox.Show("フォルダが存在しません。新規作成しますか?", "フォルダなし", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        try
                        {
                            Directory.CreateDirectory(destpath);
                            createddir = true;
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("フォルダを作成できませんでした。", "フォルダ作成エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                            Progress.Content = "エラー";
                            Destination.Focus();
                            return;
                        }
                    }
                    else
                    {
                        Progress.Content = "エラー";
                        return;
                    }
                }
            }

            ///前処理///
            string targetdir = guitarlistdotnet + tokens[0] + '/' + tokens[1] + '/';
            string jsaddr    = targetdir + tokens[1] + ".js";
            string imgdir    = targetdir + "img/";
            string JSFile;
            string JSLine;
            string searchstr = "photo[pn++]=\"" + imgdir;

            if (destpath[destpath.Length - 1] != '\\')
            {
                destpath += '\\';
            }

            ///// JavaScriptファイルを解析して画像点数を割り出す /////
            Progress.Content = "画像枚数確認中・・・";
            WebClient wc = new WebClient();

            try
            {
                JSFile = await wc.DownloadStringTaskAsync(jsaddr); //javascriptファイルをダウンロード
            }
            catch (Exception)
            {
                MessageBox.Show("JavaScriptファイルがダウンロードできなかったため、画像枚数を確認できませんでした。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                wc.Dispose();
                if (createddir)
                {
                    Directory.Delete(destpath);
                }
                return;
            }

            ///// 画像枚数を数え上げる /////
            int imgnum = 0;
            var sr     = new System.IO.StringReader(JSFile);

            while ((JSLine = await sr.ReadLineAsync()) != null)
            {
                if (JSLine.IndexOf(searchstr) == 0)
                {
                    imgnum++;
                }
            }
            if (imgnum == 0)
            {
                MessageBox.Show("JavaScriptファイルの解析が上手く行かず、画像枚数を確認できませんでした。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                wc.Dispose();
                if (createddir)
                {
                    Directory.Delete(destpath);
                }
                return;
            }
            string fmt = "D" + (keta(imgnum).ToString());

            PrgrsBr.Maximum = imgnum;


            ///// 画像をダウンロード /////
            try {
                for (int i = 1; i <= imgnum; i++)
                {
                    Progress.Content = "画像ダウンロード中・・・(" + (i.ToString()) + "/" + (imgnum.ToString()) + "枚)";
                    string filename   = (i.ToString()) + ".png";
                    string filenamezr = (i.ToString(fmt)) + ".png";
                    await wc.DownloadFileTaskAsync(imgdir + filename, destpath + filenamezr);

                    PrgrsBr.Value += 1.0;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("画像ダウンロード中にエラーが発生しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                Progress.Content = "エラー";
                PrgrsBr.Value    = 0.0;
                wc.Dispose();
                if (createddir)
                {
                    Directory.Delete(destpath, true);
                }
                return;
            }
            wc.Dispose();
            PrgrsBr.Value    = 0.0;
            Progress.Content = "ダウンロード完了!";
            if (MessageBox.Show("ダンロードが完了しました。フォルダを開きますか?", "ダウンロード完了", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                System.Diagnostics.Process.Start(destpath);
            }
        }
Exemple #60
0
        public static List<User> UserList( XDocument xdoc, List<User> users)
        {
            foreach (var status in xdoc.Root.Elements())
            {
                String tweetId = status.Element("id").Value;
                String text = status.Element("text").Value;
                String createdAt = status.Element("created_at").Value;
                Tweet tweet = new Tweet(tweetId, text, createdAt);

                XElement xuser = status.Element("user");
                String userId = xuser.Element("id").Value;
                String lastStatusUpdate = status.Element("created_at").Value; // Thu Dec 10 04:49:37 +0000 2009
                User user = new User( userId, null, null, null, lastStatusUpdate);
                if( users.Contains( user))
                {
                    User u = users[users.IndexOf(user)];
                    u.lastStatusUpdate = user.lastStatusUpdate;
                    u.LatestTweetDispFlag = false;

                    if (u.LatestTweet != null)
                    {
                        u.Tweets.Add(u.LatestTweet);
                    }
                    u.LatestTweet = tweet;
                }
                else
                {
                    user.name = xuser.Element("name").Value;
                    user.screenName = xuser.Element("screen_name").Value;
                    user.profileImageUrl = xuser.Element("profile_image_url").Value;

                    String[] _temp = user.ProfileImageUrl.Split(new char[] { '/' });
                    String ext = (_temp[_temp.Length - 1].Split(new char[] { '.' }))[1];
                    String imgCachePath = Game1.IMG_CACHE_DIR + userId + "." + ext;

                    if (File.Exists(imgCachePath) && ( DateTime.Now - File.GetCreationTime(imgCachePath)).TotalDays < 1)
                    {
                        user.ProfileImageCachePath = imgCachePath;
                    }
                    else
                    {
                        try
                        {
                            if (File.Exists(imgCachePath)) { File.Delete(imgCachePath); }
                            System.Net.WebClient wc = new System.Net.WebClient();
                            String tempImgCachePath = imgCachePath + "_tmp";
                            user.ProfileImageCachePath = imgCachePath;
                            wc.DownloadFile(user.ProfileImageUrl, tempImgCachePath);
                            wc.Dispose();

                            Image src = Image.FromFile(tempImgCachePath);
                            Image dest = ImageUtils.Resize.resizeImage((Bitmap)src, 48, 48);

                            dest.Save(imgCachePath);
                            File.Delete(tempImgCachePath);
                        }
                        catch( Exception ee)
                        {
                            Console.WriteLine( "[{0}] {1}", user.ToString(), ee.StackTrace);
                        }
                    }

                    user.LatestTweet = tweet;

                    users.Add(user);
                }
            }

            return users;
        }