コード例 #1
0
        public void TestString(string str, string res)
        {
            var formater = new StringFormater();
            var calc     = formater.UniqueInOrder <char>(str);

            Assert.That(Enumerable.SequenceEqual(calc.OrderBy(t => t), res.OrderBy(t => t)));
        }
コード例 #2
0
 public TreemapParameters()
 {
     Indexes            = new List <TreemapIndex>();
     ShowLegend         = true;
     LegendPosition     = Position.Bottom;
     LegendTextFormater = new StringFormater();
 }
コード例 #3
0
        public void TestDecimal(List <double> sec, List <double> res)
        {
            var formater = new StringFormater();
            var calc     = formater.UniqueInOrder <double>(sec);

            Assert.That(Enumerable.SequenceEqual(calc.OrderBy(t => t), res.OrderBy(t => t)));
        }
コード例 #4
0
        public IEnumerable <IOAuthQueryParameter> GenerateApplicationParameters(
            IReadOnlyConsumerCredentials temporaryCredentials,
            IAuthenticationRequest authRequest = null,
            IEnumerable <IOAuthQueryParameter> additionalParameters = null)
        {
            var headers = GenerateConsumerParameters(temporaryCredentials).ToList();

            // Add Header for authenticated connection to a Twitter Application
            if (authRequest != null &&
                !string.IsNullOrEmpty(authRequest.AuthorizationKey) &&
                !string.IsNullOrEmpty(authRequest.AuthorizationSecret))
            {
                headers.Add(new OAuthQueryParameter("oauth_token", StringFormater.UrlEncode(authRequest.AuthorizationKey), true, true, false));
                headers.Add(new OAuthQueryParameter("oauth_token_secret", StringFormater.UrlEncode(authRequest.AuthorizationSecret), false, false, true));
            }
            else
            {
                headers.Add(new OAuthQueryParameter("oauth_token", "", false, false, true));
            }

            if (additionalParameters != null)
            {
                headers.AddRange(additionalParameters);
            }

            return(headers);
        }
コード例 #5
0
 public TreemapParameters()
 {
     Indexes = new List<TreemapIndex>();
     ShowLegend = true;
     LegendPosition = Position.Bottom;
     LegendTextFormater = new StringFormater();
 }
コード例 #6
0
        private void btn_classstatis_Click(object sender, EventArgs e)
        {
            #region 输入与输出路径条件判断

            string sImageInput = this.txt_ImageInput.Text.Trim();
            if (sImageInput.Equals(""))
            {
                MessageBox.Show("请选择待分类统计影像!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            #endregion
            this.btn_classstatis.Enabled = false;

            #region 调用IDL程序
            //IDLSav的路径
            string sIDLSavPath = FileManage.getApplicatonPath();
            sIDLSavPath = sIDLSavPath + "IDLSav\\GetFileHist.pro";
            string sCSVPath  = FileManage.getApplicatonPath();
            string sFullName = sCSVPath + "AllSense.csv";
            COM_IDL_connectLib.COM_IDL_connectClass oCom = new COM_IDL_connectLib.COM_IDL_connectClass();
            try
            {
                //初始化
                oCom.CreateObject(0, 0, 0);
                //参数设置
                oCom.SetIDLVariable("File", sImageInput);
                oCom.SetIDLVariable("CSVPath", sFullName);
                //oCom.SetIDLVariable("Background", "0");
                //编译IDL功能源码
                oCom.ExecuteString(".compile '" + sIDLSavPath + "'");
                //执行计算
                oCom.ExecuteString("GetFileHist,file,CSVPath,DataArray=DataArray");
                //获取计算结果
                object objArr = oCom.GetIDLVariable("DataArray");
                //MessageBox.Show(objArr.ToString());
                if (objArr == null)
                {
                    MessageBox.Show("输入影像有误,请重新选择分类后影像!");
                    return;
                }
                //将对象转为一维数组
                string[] arrStatistic = (string[])objArr;
                //表头
                string[] arrName = { "作物类型", "面积(亩)", "所占比例(%)" };
                //数组行按","拆分后转DataTable
                DataTable dt = StringFormater.Convert(arrName, arrStatistic);
                //数据绑定
                BindDataSource(dt);
                oCom.DestroyObject();
                //MessageBox.Show("影像裁剪完毕", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.btn_classstatis.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            #endregion
        }
コード例 #7
0
        public static string GetBearerTokenAuthorizationHeader(IReadOnlyConsumerCredentials credentials)
        {
            var concatenatedCredentials = StringFormater.UrlEncode(credentials.ConsumerKey) + ":" + StringFormater.UrlEncode(credentials.ConsumerSecret);
            var credBytes         = Encoding.UTF8.GetBytes(concatenatedCredentials);
            var base64Credentials = Convert.ToBase64String(credBytes);

            return("Basic " + base64Credentials);
        }
コード例 #8
0
        public void SetSearchByName(StringFormater <T> searchString, string search)
        {
            FilterName <T> filterByName = new FilterName <T>(searchString);

            filterByName.SetSearchText(search);

            listFilters.Add(filterByName);
        }
コード例 #9
0
        private static string CreateOAuthRequest(Uri uri, HttpMethod httpMethod, string urlParametersFormatted)
        {
            var url               = uri.Query == "" ? uri.AbsoluteUri : uri.AbsoluteUri.Replace(uri.Query, "");
            var encodedUrl        = StringFormater.UrlEncode(url);
            var encodedParameters = StringFormater.UrlEncode(urlParametersFormatted);

            return($"{httpMethod}&{encodedUrl}&{encodedParameters}");
        }
コード例 #10
0
        private static string CreateOAuthSecretKey(IEnumerable <IOAuthQueryParameter> oAuthQueryParameters)
        {
            var oAuthSecretKeyHeaders = oAuthQueryParameters.Where(x => x.IsPartOfOAuthSecretKey)
                                        .OrderBy(x => x.Key)
                                        .Select(x => StringFormater.UrlEncode(x.Value));

            return(string.Join("&", oAuthSecretKeyHeaders));
        }
コード例 #11
0
        /// <summary>
        /// 输出类型数据绑定,从XML文件中获取
        /// </summary>
        public void ComBoxDataBind(string strVectorFile)
        {
            char[]        strVectorFileList = strVectorFile.ToCharArray();
            StringBuilder sSBuilder         = new StringBuilder(300);

            GdalAlgInterface.GetVectorFields(strVectorFileList, sSBuilder, 300);
            //MessageBox.Show("sSBuilder=" + sSBuilder);
            List <string> list = StringFormater.getListByStringSplit(sSBuilder.ToString());

            this.cbx_FormatType.DataSource = list;
        }
コード例 #12
0
ファイル: UIFactory.cs プロジェクト: SehdiNassim/WeatherLab
        public static WrapPanel GeneratePredictionWrapPanel(int mode, String iconPath, String parameterKey, String Value, String error, String errorRatio)
        {
            WrapPanel panel = new WrapPanel()
            {
                Orientation = Orientation.Horizontal,
                Margin      = new System.Windows.Thickness(6),
            };
            Image icon = new Image()
            {
                Source  = SvgIcon(iconPath),
                Width   = 40,
                Height  = 40,
                Margin  = new System.Windows.Thickness(10),
                ToolTip = StringFormater.GetParameterFromKey(parameterKey),
                Effect  = shadowEffect,
            };

            panel.Children.Add(icon);

            TextBlock value = new TextBlock()
            {
                VerticalAlignment = System.Windows.VerticalAlignment.Center,
                Margin            = new System.Windows.Thickness(2),
                Text     = Value,
                FontSize = textSize,
                Effect   = shadowEffect
            };

            panel.Children.Add(value);
            if (mode == PredictionSystem.PredictionSystem.CEP)
            {
                TextBlock err = new TextBlock()
                {
                    VerticalAlignment = System.Windows.VerticalAlignment.Center,
                    Margin            = new System.Windows.Thickness(2),
                    Text     = " \u00B1" + error,
                    ToolTip  = "Varie de : " + errorRatio,
                    FontSize = textSize,
                    Effect   = shadowEffect
                };

                panel.Children.Add(err);
            }

            else
            {
                value.Margin = new System.Windows.Thickness(10, 0, 10, 0);
            }



            return(panel);
        }
コード例 #13
0
        public IEnumerable <IOAuthQueryParameter> GenerateConsumerParameters(IConsumerCredentials consumerCredentials)
        {
            var consumerHeaders = new List <IOAuthQueryParameter>();

            // Add Header for every connection to a Twitter Application
            if (consumerCredentials != null && !String.IsNullOrEmpty(consumerCredentials.ConsumerKey) && !String.IsNullOrEmpty(consumerCredentials.ConsumerSecret))
            {
                consumerHeaders.Add(new OAuthQueryParameter("oauth_consumer_key", StringFormater.UrlEncode(consumerCredentials.ConsumerKey), true, true, false));
                consumerHeaders.Add(new OAuthQueryParameter("oauth_consumer_secret", StringFormater.UrlEncode(consumerCredentials.ConsumerSecret), false, false, true));
            }

            return(consumerHeaders);
        }
コード例 #14
0
        public void FormatStringFormaterTest()
        {
            try
            {
                var f = new StringFormater {
                    Format = ""
                };
                f.Formate("");
                throw new Exception("TEST FAILED.");
            }
            catch (SpiderException se)
            {
                Assert.Equal("FormatString should not be null or empty.", se.Message);
            }
            try
            {
                var f = new StringFormater {
                    Format = null
                };
                f.Formate("");
                throw new Exception("TEST FAILED.");
            }
            catch (SpiderException se)
            {
                Assert.Equal("FormatString should not be null or empty.", se.Message);
            }
            try
            {
                var f = new StringFormater {
                    Format = "     "
                };
                f.Formate("");
                throw new Exception("TEST FAILED.");
            }
            catch (SpiderException se)
            {
                Assert.Equal("FormatString should not be null or empty.", se.Message);
            }

            StringFormater formatter1 = new StringFormater {
                Format = "http://{0}"
            };

            Assert.Equal("http://a", formatter1.Formate("a"));

            StringFormater formatter2 = new StringFormater {
                Format = "http://{0}/{1}"
            };

            Assert.Equal("http://a/b", formatter2.Formate(new[] { "a", "b" }));
        }
コード例 #15
0
        public Task <ITwitterResult> UpdateProfileBanner(IUpdateProfileBannerParameters parameters, ITwitterRequest request)
        {
            var query             = _accountSettingsQueryGenerator.GetUpdateProfileBannerQuery(parameters);
            var banner            = StringFormater.UrlEncode(Convert.ToBase64String(parameters.Binary));
            var bannerHttpContent = new StringContent($"banner={banner}", Encoding.UTF8, "application/x-www-form-urlencoded");

            request.Query.Url         = query;
            request.Query.HttpMethod  = HttpMethod.POST;
            request.Query.HttpContent = new ProgressableStreamContent(bannerHttpContent, parameters.UploadProgressChanged);
            request.Query.IsHttpContentPartOfQueryParams = true;
            request.Query.Timeout = parameters.Timeout ?? TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite);

            return(_twitterAccessor.ExecuteRequest(request));
        }
コード例 #16
0
ファイル: UIFactory.cs プロジェクト: SehdiNassim/WeatherLab
        public static Image PredictionOutlookImage(Result result)
        {
            return(new Image()
            {
                Source = SvgIcon(ImagePaths.GetOutlookImagePath(result)),

                MaxHeight = 50,
                MaxWidth = 50,

                Margin = new System.Windows.Thickness(20, 0, 20, 0)
                ,
                ToolTip = StringFormater.GetClimate(result),
                Effect = shadowEffect
            });
        }
コード例 #17
0
ファイル: UIFactory.cs プロジェクト: SehdiNassim/WeatherLab
        public static TextBlock Probabilityblock(Result result, int mode)
        {
            String tooltip = "degré de confiance sur la prédiction";

            return(new TextBlock()
            {
                Text = StringFormater.GetProbabiltyText(result),

                VerticalAlignment = System.Windows.VerticalAlignment.Center,
                HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                Margin = new System.Windows.Thickness(0, 0, 0, 0),
                FontSize = 18,
                ToolTip = tooltip,
                Effect = shadowEffect
            });
        }
コード例 #18
0
        private string GenerateSignature(
            Uri uri,
            HttpMethod httpMethod,
            IEnumerable <IOAuthQueryParameter> queryParameters,
            Dictionary <string, string> urlParameters)
        {
            var oAuthQueryParameters   = queryParameters.ToArray();
            var signatureParameters    = GetSignatureParameters(oAuthQueryParameters, urlParameters);
            var formattedUrlParameters = CreateFormattedUrlParameters(signatureParameters);
            var oAuthRequest           = CreateOAuthRequest(uri, httpMethod, formattedUrlParameters);
            var oAuthSecretKey         = CreateOAuthSecretKey(oAuthQueryParameters);

            var hmacsha1Generator = new HMACSHA1Generator();

            return(StringFormater.UrlEncode(Convert.ToBase64String(hmacsha1Generator.ComputeHash(oAuthRequest, oAuthSecretKey, Encoding.UTF8))));
        }
コード例 #19
0
        public static string GenerateFilterLocationRequest(List <ILocation> locations)
        {
            if (locations.IsNullOrEmpty())
            {
                return(String.Empty);
            }

            StringBuilder queryBuilder = new StringBuilder();

            // queryBuilder.Append("locations=");
            for (int i = 0; i < locations.Count - 1; ++i)
            {
                queryBuilder.Append(GenerateLocationParameters(locations[i], false));
            }

            queryBuilder.Append(GenerateLocationParameters(locations[locations.Count - 1], true));

            return(String.Format("locations={0}", StringFormater.UrlEncode(queryBuilder.ToString())));
        }
コード例 #20
0
        /// <summary>
        /// Method Allowing to initialize a SortedDictionnary to enable oAuth query to be generated with
        /// these parameters
        /// </summary>
        /// <param name="method_uri">This is the Uri that will be required for creating the oAuth WebRequest</param>
        /// <returns>Call the method defined in the _generateDelegate and return a string result
        /// This result will be the header of the WebRequest.</returns>
        private string generateParameters(Uri method_uri)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            string   oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();

            string oauth_nonce = new Random().Next(123400, 9999999).ToString();

            SortedDictionary <String, String> parameters = new SortedDictionary <string, string>();

            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_nonce", oauth_nonce);
            parameters.Add("oauth_timestamp", oauth_timestamp);
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_consumer_key", StringFormater.UrlEncode(this.ConsumerKey));
            parameters.Add("oauth_token", StringFormater.UrlEncode(this.AccessToken));
            parameters.Add("oauth_consumer_secret", StringFormater.UrlEncode(this.ConsumerSecret));
            parameters.Add("oauth_token_secret", StringFormater.UrlEncode(this.AccessTokenSecret));

            return(_generateDelegate != null?_generateDelegate(parameters, method_uri) : null);
        }
コード例 #21
0
        protected override async Task Execute(CancellationToken token)
        {
            log.LogInformation("Starting...");
            if (!client.Connect())
            {
                log.LogError("Connection failed");
                return;
            }

            var providers = await newsProvider.Request().FirstOrDefaultAsync();

            var contract = await contractManager.Request(ContractHelper.GetContract(config.Stock)).FirstOrDefaultAsync();

            var news = newsManager.Request(contract.ContractDetails.Contract.ConId,
                                           providers.NewsProviders[2].ProviderCode,
                                           StringFormater.StrToDate(config.From, client.TimeZone).DateToStr(),
                                           StringFormater.StrToDate(config.To, client.TimeZone).DateToStr(),
                                           100);
            var newsData = await news.ToArray();

            log.LogInformation("News request completed");
        }
コード例 #22
0
        public IEnumerable <IOAuthQueryParameter> GenerateParameters(IOAuthCredentials credentials, IEnumerable <IOAuthQueryParameter> additionalParameters = null)
        {
            var headers = GenerateConsumerParameters(credentials).ToList();

            // Add Header for authenticated connection to a Twitter Application
            if (credentials != null && !String.IsNullOrEmpty(credentials.AccessToken) && !String.IsNullOrEmpty(credentials.AccessTokenSecret))
            {
                headers.Add(new OAuthQueryParameter("oauth_token", StringFormater.UrlEncode(credentials.AccessToken), true, true, false));
                headers.Add(new OAuthQueryParameter("oauth_token_secret", StringFormater.UrlEncode(credentials.AccessTokenSecret), false, false, true));
            }
            else
            {
                headers.Add(new OAuthQueryParameter("oauth_token", "", false, false, true));
            }

            if (additionalParameters != null)
            {
                headers.AddRange(additionalParameters);
            }

            return(headers);
        }
コード例 #23
0
        /// <summary>
        /// Encryption of the data to be sent
        /// </summary>
        /// <param name="parameters">Parameters of the query</param>
        /// <param name="method_uri">Uri to be called</param>
        /// <returns>Header of the WebRequest</returns>
        private string generateSignature(SortedDictionary <String, String> parameters, Uri method_uri)
        {
            String[] secretParameters = new[] { "oauth_consumer_key", "oauth_nonce",
                                                "oauth_signature_method", "oauth_timestamp", "oauth_token", "oauth_version" };

            List <KeyValuePair <String, String> > orderedParams = new List <KeyValuePair <string, string> >();

            foreach (var query_param in _queryParameters)
            {
                orderedParams.Add(query_param);
            }

            foreach (var param in (from p in parameters orderby p.Key where (secretParameters.Contains(p.Key)) == true select p))
            {
                orderedParams.Add(param);
            }

            StringBuilder queryParameters = new StringBuilder();

            foreach (var param in (from p in orderedParams orderby p.Key select p))
            {
                if (queryParameters.Length > 0)
                {
                    queryParameters.Append("&");
                }
                queryParameters.Append(string.Format("{0}={1}", param.Key, param.Value));
            }

            string url          = method_uri.Query == "" ? method_uri.AbsoluteUri : method_uri.AbsoluteUri.Replace(method_uri.Query, "");
            string oAuthRequest = string.Format("{0}&{1}&{2}", _method.ToString(),
                                                StringFormater.UrlEncode(url), StringFormater.UrlEncode(queryParameters.ToString()));

            string oAuthSecretkey = string.Format("{0}&{1}",
                                                  StringFormater.UrlEncode(this.ConsumerSecret), StringFormater.UrlEncode(this.AccessTokenSecret));
            HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(oAuthSecretkey));

            return(StringFormater.UrlEncode(Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(oAuthRequest)))));
        }
コード例 #24
0
        /// <summary>
        /// Generates the most probable prédiction first parameters
        /// </summary>
        private void GenerateFirstPredictionParameters()
        {
            /// Determining the number of parameters to draw
            int nbParam = (int)Math.Round(predictionSystem.GetNbParameters() * 0.5) + 1;

            int i = 0;

            foreach (var item in predictionSystem.Result.Results[0].Predictions)
            {
                /// TODO : Change this to use resources
                Image img = UIFactory.CreatePredictionIcon(ImagePaths.GetImagePathForParameter(item));
                ///
                TextBlock text  = UIFactory.CreatePredictionText(StringFormater.GetParameterValue(item));
                WrapPanel panel = UIFactory.CreatePredictionWrapPanel(img, text, Orientation.Vertical);
                firstPrediction.Children.Add(panel);
                panel.BeginAnimation(OpacityProperty, animation);
                i++;
                if (i >= nbParam)
                {
                    break;
                }
            }
        }
コード例 #25
0
        public virtual IEnumerable <IOAuthQueryParameter> GenerateParameters()
        {
            List <IOAuthQueryParameter> headers = new List <IOAuthQueryParameter>();

            // Add Header for every connection to a Twitter Application
            if (!String.IsNullOrEmpty(Credentials.ConsumerKey) && !String.IsNullOrEmpty(Credentials.ConsumerSecret))
            {
                headers.Add(new OAuthQueryParameter("oauth_consumer_key", StringFormater.UrlEncode(Credentials.ConsumerKey), true, true, false));
                headers.Add(new OAuthQueryParameter("oauth_consumer_secret", StringFormater.UrlEncode(Credentials.ConsumerSecret), false, false, true));
            }

            // Add Header for authenticated connection to a Twitter Application
            if (!String.IsNullOrEmpty(Credentials.AccessToken) && !String.IsNullOrEmpty(Credentials.AccessTokenSecret))
            {
                headers.Add(new OAuthQueryParameter("oauth_token", StringFormater.UrlEncode(Credentials.AccessToken), true, true, false));
                headers.Add(new OAuthQueryParameter("oauth_token_secret", StringFormater.UrlEncode(Credentials.AccessTokenSecret), false, false, true));
            }
            else
            {
                headers.Add(new OAuthQueryParameter("oauth_token", "", false, false, true));
            }

            return(headers);
        }
コード例 #26
0
        private string GenerateSignature(
            Uri uri,
            HttpMethod httpMethod,
            IEnumerable <IOAuthQueryParameter> queryParameters,
            Dictionary <string, string> urlParameters)
        {
            List <KeyValuePair <String, String> > signatureParameters = urlParameters.OrderBy(x => x.Key).ToList();

            #region Store the paramaters that will be used

            // Add all the parameters that are required to generate a signature
            var oAuthQueryParameters = queryParameters as IList <IOAuthQueryParameter> ?? queryParameters.ToList();
            foreach (var header in (from h in oAuthQueryParameters
                                    where h.RequiredForSignature
                                    orderby h.Key
                                    select h))
            {
                signatureParameters.Add(new KeyValuePair <string, string>(header.Key, header.Value));
            }

            #endregion

            #region Generate OAuthRequest Parameters

            StringBuilder urlParametersFormatted = new StringBuilder();
            foreach (KeyValuePair <string, string> param in (from p in signatureParameters orderby p.Key select p))
            {
                if (urlParametersFormatted.Length > 0)
                {
                    urlParametersFormatted.Append("&");
                }

                urlParametersFormatted.Append(string.Format("{0}={1}", param.Key, param.Value));
            }

            #endregion

            #region Generate OAuthRequest

            string url = uri.Query == "" ? uri.AbsoluteUri : uri.AbsoluteUri.Replace(uri.Query, "");

            string oAuthRequest = string.Format("{0}&{1}&{2}",
                                                httpMethod,
                                                StringFormater.UrlEncode(url),
                                                StringFormater.UrlEncode(urlParametersFormatted.ToString()));

            #endregion

            #region Generate OAuthSecretKey
            // Generate OAuthSecret that is required to generate a signature
            IEnumerable <IOAuthQueryParameter> oAuthSecretKeyHeaders = from h in oAuthQueryParameters
                                                                       where h.IsPartOfOAuthSecretKey
                                                                       orderby h.Key
                                                                       select h;
            string oAuthSecretkey = "";

            for (int i = 0; i < oAuthSecretKeyHeaders.Count(); ++i)
            {
                oAuthSecretkey += String.Format("{0}{1}",
                                                StringFormater.UrlEncode(oAuthSecretKeyHeaders.ElementAt(i).Value),
                                                (i == oAuthSecretKeyHeaders.Count() - 1) ? "" : "&");
            }

            #endregion

            // Create and return signature

            HMACSHA1Generator hmacsha1Generator = new HMACSHA1Generator();
            return(StringFormater.UrlEncode(Convert.ToBase64String(hmacsha1Generator.ComputeHash(oAuthRequest, oAuthSecretkey, Encoding.UTF8))));
        }
コード例 #27
0
 public IOAuthQueryParameter GenerateParameter(string key, string value, bool requiredForSignature, bool requiredForHeader, bool isPartOfOAuthSecretKey)
 {
     return(new OAuthQueryParameter(key, StringFormater.UrlEncode(value), requiredForSignature, requiredForHeader, isPartOfOAuthSecretKey));
 }
コード例 #28
0
        private void btn_ok_Click(object sender, EventArgs e)
        {
            #region 输入与输出路径条件判断
            if (this.txt_ImageInput.Text.Equals(""))
            {
                MessageBox.Show("请输入影像目录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (this.txt_ReferenceImage.Text.Equals(""))
            {
                MessageBox.Show("请选择参考文件总目录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (this.txt_winrar.Text.Equals(""))
            {
                MessageBox.Show("请选择解压缩文件WinRAR目录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (this.txt_ImageOutPath.Text.Equals(""))
            {
                MessageBox.Show("请选择输出路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            #endregion
            this.btn_ok.Enabled = false;
            #region 界面参数获取
            string sInputDIR     = this.txt_ImageInput.Text.Trim();
            string sReferenceDIR = this.txt_ReferenceImage.Text.Trim();
            string sOuputDIR     = this.txt_ImageOutPath.Text.Trim();
            string sWinrarDIR    = this.txt_winrar.Text.Trim();
            sInputDIR     = StringFormater.GetMarkedDirectory(sInputDIR);
            sReferenceDIR = StringFormater.GetMarkedDirectory(sReferenceDIR);
            sOuputDIR     = StringFormater.GetMarkedDirectory(sOuputDIR);
            sWinrarDIR    = StringFormater.GetMarkedDirectory(sWinrarDIR);
            DirectoryInfo source = new DirectoryInfo(sInputDIR);
            if (!source.Exists)
            {
                MessageBox.Show("输入文件夹不存在:" + sInputDIR, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            source = new DirectoryInfo(sReferenceDIR);
            if (!source.Exists)
            {
                MessageBox.Show("参考文件夹不存在:" + sInputDIR, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            source = new DirectoryInfo(sOuputDIR);
            if (!source.Exists)
            {
                try
                {
                    source.Create();
                }
                catch (Exception)
                {
                    MessageBox.Show("输出文件夹不存在,而且不能创建:" + sOuputDIR, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            source = new DirectoryInfo(sWinrarDIR);
            if (!source.Exists)
            {
                MessageBox.Show("Winrar文件夹不存在:" + sWinrarDIR, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                string sWinrarEXE = StringFormater.GetMarkedDirectory(sWinrarDIR) + "WinRAR.exe";
                if (!System.IO.File.Exists(sWinrarEXE))
                {
                    MessageBox.Show("WinRAR.exe 不存在:" + sWinrarEXE, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            #endregion

            #region 调用IDL程序
            //IDLSav的路径
            string sIDLSavPath = FileManage.getApplicatonPath();
            sIDLSavPath = sIDLSavPath + "IDLSav\\HJPreProSysWinV3_1.pro";
            int iACTFlag    = this.checkBox2.Checked ? 1 : 0;
            int iDeleteFlag = this.checkBox1.Checked ? 1 : 0;
            COM_IDL_connectLib.COM_IDL_connectClass oCom = new COM_IDL_connectLib.COM_IDL_connectClass();
            try
            {
                //初始化
                oCom.CreateObject(0, 0, 0);
                //参数设置
                //oCom.SetIDLVariable("InputDIR", sInputDIR);
                //oCom.SetIDLVariable("OutPutDIR", sOuputDIR);
                //oCom.SetIDLVariable("WinrarDIR", sWinrarDIR);
                //oCom.SetIDLVariable("ATCFlag", iACTFlag);
                //oCom.SetIDLVariable("DeleteFlag", iDeleteFlag);
                oCom.ExecuteString(".compile '" + sIDLSavPath);
                this.toolStripStatusLabel2.Text = "运行中,请等候";
                this.statusStrip1.Refresh();
                string comstr = "HJPreProSysWinV3_1,'" + sInputDIR + "','" + sOuputDIR + "','" + sWinrarDIR + "','" + sReferenceDIR + "'," + iACTFlag.ToString() + "," + iDeleteFlag.ToString();

                oCom.ExecuteString(comstr);
                //oCom.ExecuteString("HJPreProSysWinV3_1,InputDIR,OutPutDIR,WinrarDIR,ATCFlag,DeleteFlag");
                this.toolStripStatusLabel2.Text = "运行完成";
                this.statusStrip1.Refresh();

                oCom.DestroyObject();
                MessageBox.Show("几何纠正完毕", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.btn_ok.Enabled         = true;
                this.btn_OpenOutPut.Visible = true;
                //写配置文件
                string       sCfgPath = System.AppDomain.CurrentDomain.BaseDirectory + "ExeConfig.txt";
                StreamWriter sw       = new StreamWriter(sCfgPath);
                sw.WriteLine(this.txt_ImageInput.Text);
                sw.WriteLine(this.txt_ReferenceImage.Text);
                sw.WriteLine(this.txt_winrar.Text);
                sw.WriteLine(this.txt_ImageOutPath.Text);
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            #endregion
        }
コード例 #29
0
        private void btn_classstatis_Click(object sender, EventArgs e)
        {
            #region 输入与输出路径条件判断

            string sImageInput = this.txt_ImageInput.Text.Trim();
            if (sImageInput.Equals(""))
            {
                MessageBox.Show("请选择待统计影像!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //string filename = sImageInput.Substring(sImageInput.LastIndexOf("\\") + 1);
            //res = filename.Split(new char[] { '_', '.' }, StringSplitOptions.RemoveEmptyEntries);
            string filename = Path.GetFileNameWithoutExtension(sImageInput);
            if (filename.Contains("-"))
            {
                res = filename.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            }
            else
            {
                res = filename.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            }
            string sMorTime     = res[4];
            string sResultTitle = this.cbx_VIType.Text.Trim();
            string sField       = this.cbx_FieldName.Text.Trim();
            string sStaType     = this.cbx_StaValueType.Text.Trim();
            #endregion

            //调用进度条界面线程
            //Thread t = new Thread(new ThreadStart(thread1));
            //t.Start();
            #region 执行统计

            try
            {
                ProgressFunc pd  = new ProgressFunc(this.ProgressBarInfo);
                IntPtr       pre = this.Handle;
                int          ire = 0;

                //string strInFile = @"D:\share\Hongxingtest\wxf\text_data\soil\soil_organic1.tif";
                char[] strInFileList = sImageInput.ToCharArray();

                string strRegionFile     = this.txt_SHPFile.Text.Trim();
                char[] strRegionFileList = strRegionFile.ToCharArray();

                char[] strFieldList = sField.ToCharArray();



                List <string> fielddatalist = ReadShape.getShapeFieldDataList(strRegionFile, sField);
                int           nCount        = fielddatalist.Count;

                List <int> intfdlist       = new List <int>(nCount);
                int[]      pRegionCodeList = new int[nCount];
                //for (int i = 0; i < nCount; i++)
                //{
                //    //转LIST出错
                //    intfdlist.Add(int.Parse(fielddatalist[i]));
                //}

                //int[] pRegionCodeList = intfdlist.ToArray();

                double[] padfResultList = new double[nCount];

                int iStatisticType = 2; //默认为平均值
                if (sStaType == "Max")
                {
                    iStatisticType = 1;
                }
                else if (sStaType == "Min")
                {
                    iStatisticType = 0;
                }

                ire = GdalAlgInterface.ImageStatisticalByVector(strInFileList, strRegionFileList, strFieldList, iStatisticType, pRegionCodeList, padfResultList, padfResultList.Length, pd, pre);
                //第三步
                //运行成功或失败,停止线程,即终止进度条。
                //t.Abort();
                string[,] arrStatistic = new string[nCount, 4];
                for (int i = 0; i < nCount; i++)
                {
                    arrStatistic[i, 0] = sMorTime;//文件名中的时间,从文件名中解析,此处获取的系统时间只为测试
                    arrStatistic[i, 1] = pRegionCodeList[i].ToString();
                    arrStatistic[i, 2] = padfResultList[i].ToString("0.00");
                    arrStatistic[i, 3] = sStaType;
                }
                //string sResultTitle = DataBaseOperate.getNUTRIENTTableTitleName(res[2]);

                //表头
                string[] arrName = { "监测时间", "标识字段", sResultTitle, "统计类型" };
                //数组行按","拆分后转DataTable
                dtInfo = StringFormater.Convert(arrName, arrStatistic);
                InitDataSet();
                //dgvInfo.DataSource = dt;
            }
            catch (Exception ex)
            {
                //第三步
                //运行成功或失败,停止线程,即终止进度条。
                //t.Abort();
                MessageBox.Show(ex.Message);
            }
            #endregion
        }
コード例 #30
0
        private void btn_classstatis_Click(object sender, EventArgs e)
        {
            #region 输入与输出路径条件判断

            string sImageInput = this.txt_ImageInput.Text.Trim();
            if (sImageInput.Equals(""))
            {
                MessageBox.Show("请选择待统计影像!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //string filename = sImageInput.Substring(sImageInput.LastIndexOf("\\") + 1);
            //res = filename.Split(new char[] { '_', '.' }, StringSplitOptions.RemoveEmptyEntries);
            string filename = Path.GetFileNameWithoutExtension(sImageInput);
            res = filename.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            string sMorTime     = res[4];
            string sResultTitle = this.cbx_VIType.Text.Trim();

            #endregion

            //调用进度条界面线程
            //Thread t = new Thread(new ThreadStart(thread1));
            //t.Start();
            #region 执行统计

            try
            {
                ProgressFunc pd  = new ProgressFunc(this.ProgressBarInfo);
                IntPtr       pre = this.Handle;
                int          ire = 0;

                //string strInFile = @"D:\share\Hongxingtest\wxf\text_data\soil\soil_organic1.tif";
                char[] strInFileList = sImageInput.ToCharArray();

                string strRegionFile     = this.txt_SHPFile.Text.Trim();
                char[] strRegionFileList = strRegionFile.ToCharArray();

                string strField     = "RASTERID";
                char[] strFieldList = strField.ToCharArray();

                int nCount = ReadShape.getShapeCount(strRegionFile);

                int[] pRegionCodeList = new int[nCount];

                double[] padfResultList = new double[nCount];
                ire = GdalAlgInterface.ImageStatisticalByVector(strInFileList, strRegionFileList, strFieldList, 2, pRegionCodeList, padfResultList, padfResultList.Length, pd, pre);
                //第三步
                //运行成功或失败,停止线程,即终止进度条。
                //t.Abort();
                string[,] arrStatistic = new string[nCount, 6];
                for (int i = 0; i < nCount; i++)
                {
                    string sRASTERID = pRegionCodeList[i].ToString();
                    arrStatistic[i, 0] = sMorTime;//文件名中的时间,从文件名中解析,此处获取的系统时间只为测试
                    arrStatistic[i, 1] = DataBaseOperate.getTownName(DataBaseOperate.getGLQ(sRASTERID));
                    //arrStatistic[i, 1] = sGLQName;
                    arrStatistic[i, 2] = DataBaseOperate.getVillName(DataBaseOperate.getJMZ(sRASTERID));
                    //arrStatistic[i, 2] = sJMZName;
                    //arrStatistic[i, 3] = sPlotName;
                    arrStatistic[i, 3] = DataBaseOperate.getPlotName(sRASTERID);
                    arrStatistic[i, 4] = DataBaseOperate.getPlotId(sRASTERID);
                    //arrStatistic[i, 4] = sRASTERID; "区域代码"
                    arrStatistic[i, 5] = padfResultList[i].ToString("0.00");
                }
                //string sResultTitle = DataBaseOperate.getNUTRIENTTableTitleName(res[2]);

                //表头
                string[] arrName = { "监测时间", "作业区", "作业站", "地块名称", "地块编号", sResultTitle };
                //数组行按","拆分后转DataTable
                dtInfo = StringFormater.Convert(arrName, arrStatistic);
                InitDataSet();
                //dgvInfo.DataSource = dt;
            }
            catch (Exception ex)
            {
                //第三步
                //运行成功或失败,停止线程,即终止进度条。
                //t.Abort();
                MessageBox.Show(ex.Message);
            }
            #endregion
        }
コード例 #31
0
        private void btn_ok_Click(object sender, EventArgs e)
        {
            #region 输入与输出路径条件判断
            if (this.listViewImage.Items.Count <= 0)
            {
                MessageBox.Show("请选择输入影像!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (this.txt_ReferenceImage.Text.Equals(""))
            {
                MessageBox.Show("请选择输出范围!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (this.txt_ImageOutPath.Text.Equals(""))
            {
                MessageBox.Show("请选择输出路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            #endregion
            this.btn_ok.Enabled = false;
            #region 界面参数获取
            List <string> list = new List <string>();
            foreach (ListViewItem item in this.listViewImage.Items)
            {
                string s = item.SubItems[0].Text.Trim();
                list.Add(s);
            }
            string[] sFilename       = (string[])list.ToArray();
            string   sReferenceImage = this.txt_ReferenceImage.Text.Trim();
            string   sImageOutPath   = this.txt_ImageOutPath.Text.Trim();

            #endregion

            #region 调用IDL程序
            //IDLSav的路径
            string sIDLSavPath = FileManage.getApplicatonPath();
            sIDLSavPath = sIDLSavPath + "IDLSav\\FileCut.pro";
            COM_IDL_connectLib.COM_IDL_connectClass oCom = new COM_IDL_connectLib.COM_IDL_connectClass();
            try
            {
                foreach (string sFile in sFilename)
                {
                    //初始化
                    oCom.CreateObject(0, 0, 0);
                    //参数设置
                    oCom.SetIDLVariable("File", sFile);
                    oCom.SetIDLVariable("ReferFile", sReferenceImage);
                    oCom.SetIDLVariable("OUTPUTDIR", sImageOutPath);
                    oCom.SetIDLVariable("TIFF", "/TIFF");
                    //string sName = sFilename[0].ToString();
                    string outputname = StringFormater.getNewName(sFile, sImageOutPath);
                    oCom.SetIDLVariable("OUTPUTFILE", outputname);
                    //编译IDL功能源码
                    oCom.ExecuteString(".compile '" + sIDLSavPath + "'");

                    oCom.ExecuteString("FileCut,File,OUTPUTDIR=OUTPUTDIR,ReferFile,/TIFF,OUTPUTFILE=OUTPUTFILE,Message=Message");

                    object objArr = oCom.GetIDLVariable("Message");
                    //MessageBox.Show(objArr.ToString());
                    if (objArr != null)
                    {
                        MessageBox.Show(objArr.ToString());
                        return;
                    }
                    oCom.DestroyObject();
                }
                MessageBox.Show("影像裁剪完毕", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.btn_ok.Enabled         = true;
                this.btn_OpenOutPut.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            #endregion
        }