Get() public method

public Get ( String name ) : String
name String
return String
		public static MoreLikeThisQuery GetParametersFromPath(string path, NameValueCollection query)
		{
			var results = new MoreLikeThisQuery
			{
				IndexName = query.Get("index"),
				Fields = query.GetValues("fields"),
				Boost = query.Get("boost").ToNullableBool(),
				MaximumNumberOfTokensParsed = query.Get("maxNumTokens").ToNullableInt(),
				MaximumQueryTerms = query.Get("maxQueryTerms").ToNullableInt(),
				MaximumWordLength = query.Get("maxWordLen").ToNullableInt(),
				MinimumDocumentFrequency = query.Get("minDocFreq").ToNullableInt(),
				MinimumTermFrequency = query.Get("minTermFreq").ToNullableInt(),
				MinimumWordLength = query.Get("minWordLen").ToNullableInt(),
				StopWordsDocumentId = query.Get("stopWords"),
			};

			var keyValues = query.Get("docid").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (var keyValue in keyValues)
			{
				var split = keyValue.IndexOf('=');

				if (split >= 0)
				{
					results.MapGroupFields.Add(keyValue.Substring(0, split), keyValue.Substring(split + 1));
				}
				else
				{
					results.DocumentId = keyValue;
				}
			}

			return results;
		}
        public frmMain(NameValueCollection args)
        {
            InitializeComponent();

            cboDevices.DataSource = _service.Devices(DeviceType.Imputed);
            cboDevices.ValueMember = "Id";
            cboDevices.DisplayMember = "Name";

            var i = args.Get("a");
            var u = args.Get("b");

            long.TryParse(i, out _imputed);
            long.TryParse(u, out _user);

            if (_imputed == 0 || _user == 0)
            {
                MessageBox.Show(this, @"La herramienta para enrolamiento de imputados únicamente puede ser usado desde la entrevista de encuadre.", @"Enrolamiento de imputados", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                End();
            }

            _service.GetImputedFromDb(_imputed);

            lblName.Text = _service.ImputedInfo.Name;

            foreach (var fingerPrint in _service.ImputedInfo.FingerPrints)
            {
                var chk = ((CheckBox)Controls["chk" + Encoding.ASCII.GetString(new[] { (byte)(65 + fingerPrint.Finger) })]);
                CheckBoxState(chk, true);
            }
        }
Beispiel #3
0
        static public System.Collections.Specialized.NameValueCollection ReadIni(string sFileName)
        {
            System.Collections.Specialized.NameValueCollection coll = null;
            string sTxt = cc.Util.readAll(sFileName);

            if (sTxt != null)
            {
                coll = new System.Collections.Specialized.NameValueCollection();
                string[] lines = sTxt.Replace("\n", "").Split('\r');
                for (int i = 0; i < lines.Length; i++)
                {
                    string line = lines[i].Trim();
                    if (line.Equals("") || line.StartsWith("#") || line.StartsWith(";"))
                    {
                        continue;
                    }

                    int npos;
                    npos = line.IndexOf("=");
                    if (npos > 0)
                    {
                        string skey = line.Substring(0, npos);
                        if (coll.Get(skey) != null)
                        {
                            coll.Set(skey, coll.Get(skey) + "\r\n" + line.Substring(npos + 1));
                        }
                        else
                        {
                            coll.Set(skey, line.Substring(npos + 1));
                        }
                    }
                }
            }
            return(coll);
        }
        protected new void InitFromRequest(NameValueCollection authResult)
        {
            base.InitFromRequest(authResult);

            Code = authResult.Get(OpenIdConnectParameterNames.Code);
            State = authResult.Get(OpenIdConnectParameterNames.State);
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            throw new NotImplementedException();

            if (config == null)
                throw new ArgumentNullException("config");

            if (String.IsNullOrEmpty(name))
                name = PROVIDER_NAME;

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "db4o ASP.NET Buffered Event provider");
            }

            base.Initialize(name, config);

            connectionString = ConnectionStringStore.GetConnectionString(config["connectionStringName"]);
            if (connectionString == null)
                throw new ProviderException("Connection string cannot be blank.");

            customInfo = new StringBuilder();

            providerName = name;
            buffer = config.Get("buffer");
            bufferMode = config.Get("bufferMode");

            customInfo.AppendLine(string.Format("Provider name: {0}", providerName));
            customInfo.AppendLine(string.Format("Buffering: {0}", buffer));
            customInfo.AppendLine(string.Format("Buffering modality: {0}", bufferMode));
        }
Beispiel #6
0
        /// <summary>
        /// 将键值集合转换成get url字符串
        /// </summary>
        /// <param name="Palist">键值集合</param>
        /// <param name="key">需要排除的key值</param>
        /// <returns>返回返回string字符串(格式:a=a&b=b&c=c)</returns>
        public static string GetStrNvNotKey(System.Collections.Specialized.NameValueCollection Palist, string key)
        {
            string str = "";

            if (string.IsNullOrEmpty(key))
            {
                for (int i = 0; i < Palist.Count; i++)
                {
                    str += Palist.GetKey(i) + "=" + Palist.Get(i) + "&";
                }
            }
            else
            {
                for (int k = 0; k < Palist.Count; k++)
                {
                    if (Palist.GetKey(k) != key)
                    {
                        str += Palist.GetKey(k) + "=" + Palist.Get(k) + "&";
                    }
                }
            }
            str = str.Substring(0, str.Length - 1);

            return(str);
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_queryStringCollection = m_request.QueryString;
            string location = m_queryStringCollection.Get("location");
            string quickDate = m_queryStringCollection.Get("time_scope");
            int categoryId = 1;
            string flags = "PT";
            string sort = "distance-asc";
            string backfill = "further";
            string upcomingEventQueryUri =
                Uri.EscapeUriString(
					String.Format("http://api.eventful.com/rest/events/search?app_key={0}&location={1}&date={2}&keywords=music&page_size=20",
                    m_yahooApiKey,
                    location,
                    quickDate,
                    categoryId,
                    flags,
                    sort,
                    backfill)
                );

            //XElement upcomingEventsXmlResult = XElement.Load(upcomingEventQueryUri);

            m_argList.AddParam("location", String.Empty, location);
            m_argList.AddParam("format", String.Empty, m_queryStringCollection.Get("format"));
            m_argList.AddParam("current-dateTime", String.Empty, DateTime.UtcNow);
            xslt.Transform(upcomingEventQueryUri, m_argList, m_response.Output);
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            m_asyncResult.CompleteCall();
            return m_asyncResult;

        }
        public NonEmptyDataContractCollectionBaseCollectionTypeValidator(NameValueCollection attributes) 
            : base(null, null) 
        {
            if (attributes == null)
                return;

            if(!String.IsNullOrEmpty(attributes.Get("propertyName")))
                propertyName = attributes.Get("propertyName");
       }
    public override void BeforeHTTPRequest(string qs, NameValueCollection parameters, IDictionary files, StreamWriter writer) {
      base.BeforeHTTPRequest(qs, parameters, files, writer);

      // Text to Speech
      String tts = parameters.Get("tts");
      if (tts != null) {
        AddOnManager.GetInstance().BeforeHandleVoice(tts, parameters.Get("sync") != null);
      }
    }
		public void Get ()
		{
			NameValueCollection col = new NameValueCollection (5);
			col.Add ("foo1", "bar1");
			Assert.AreEqual (null, col.Get (null), "#1");
			Assert.AreEqual (null, col.Get (""), "#2");
			Assert.AreEqual (null, col.Get ("NotExistent"), "#3");
			Assert.AreEqual ("bar1", col.Get ("foo1"), "#4");
			Assert.AreEqual ("bar1", col.Get (0), "#5");
		}
Beispiel #11
0
        public TimePeriod(NameValueCollection vals)
        {
            var startTimeString = vals.Get("StartTime") ?? "";
            if (!string.IsNullOrEmpty(startTimeString))
                StartTime = Util.ParseDateTime(startTimeString);

            var endTimeString = vals.Get("EndTime") ?? "";
            if (!string.IsNullOrEmpty(endTimeString))
                EndTime = Util.ParseDateTime(endTimeString);
        }
        protected new void InitFromRequest(NameValueCollection authResult)
        {
            base.InitFromRequest(authResult);

            ExpiresIn = authResult.Get(OpenIdConnectParameterNames.ExpiresIn);
            TokenType = authResult.Get(OpenIdConnectParameterNames.TokenType);

            IdToken = authResult.Get(OpenIdConnectParameterNames.IdToken);
            AccessToken = authResult.Get(OpenIdConnectParameterNames.AccessToken);
            RefreshToken = authResult.Get(Constants.OpenIdConnectParameterNames.RefreshToken);
        }
        public async Task<ValidationResult> ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject)
        {
            _validatedRequest.Raw = parameters;
            _validatedRequest.Subject = subject;

            if (!subject.Identity.IsAuthenticated)
            {
                return Invalid();
            }

            var idTokenHint = parameters.Get(Constants.EndSessionRequest.IdTokenHint);
            if (idTokenHint.IsPresent())
            {
                // validate id_token - no need to validate token life time
                var tokenValidationResult = await _tokenValidator.ValidateIdentityTokenAsync(idTokenHint, null, false);
                if (tokenValidationResult.IsError)
                {
                    return Invalid();
                }

                _validatedRequest.Client = tokenValidationResult.Client;

                // validate sub claim against currently logged on user
                var subClaim = tokenValidationResult.Claims.FirstOrDefault(c => c.Type == Constants.ClaimTypes.Subject);
                if (subClaim != null)
                {
                    if (subject.GetSubjectId() != subClaim.Value)
                    {
                        return Invalid();
                    }
                }

                var redirectUri = parameters.Get(Constants.EndSessionRequest.PostLogoutRedirectUri);
                if (redirectUri.IsPresent())
                {
                    if (await _uriValidator.IsPostLogoutRedirecUriValidAsync(redirectUri, _validatedRequest.Client) == true)
                    {
                        _validatedRequest.PostLogOutUri = redirectUri;
                    }
                    else
                    {
                        return Invalid();
                    }

                    var state = parameters.Get(Constants.EndSessionRequest.State);
                    if (state.IsPresent())
                    {
                        _validatedRequest.State = state;
                    }
                }
            }

            return Valid();
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="CrossDataContractModelTIandPMTValidator"/> class.
		/// </summary>
		/// <param name="attributes">The attributes.</param>
		public ImplementationTechnologyAndSerializerCrossModelValidator(NameValueCollection attributes)
			: base(attributes)
		{
			if(attributes == null)
			{
				return;
			}

			currentMessageTemplate = String.IsNullOrEmpty(attributes.Get(crossModelReferenceValidatorMessageKeyName)) ?
				Resources.ServiceAndServiceImplementationTechnologyCrossModelValidator :
				attributes.Get(crossModelReferenceValidatorMessageKeyName);
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="CrossDataContractModelTIandPMTValidator"/> class.
        /// </summary>
        /// <param name="attributes">The attributes.</param>
        public CrossServiceContractModelTIandPMTValidator(NameValueCollection attributes)
            : base(attributes)
        {
            if (attributes == null)
            {
                return;
            }

            currentMessageTemplate = String.IsNullOrEmpty(attributes.Get(crossModelReferenceValidatorMessageKeyName)) ?
                Resources.CrossServiceContractModelTIandPMTValidator :
                attributes.Get(crossModelReferenceValidatorMessageKeyName);
        }
 private void Parse(NameValueCollection queryString)
 {
     Keyword = queryString.Get("q");
     //TODO move this code to Parse or Converter method
     // tags=name1:value1,value2,value3;name2:value1,value2,value3
     SortBy = queryString.Get("sort_by");
     Terms = (queryString.GetValues("terms") ?? new string[0])
         .SelectMany(s => s.Split(';'))
         .Select(s => s.Split(':'))
         .Where(a => a.Length == 2)
         .SelectMany(a => a[1].Split(',').Select(v => new Term { Name = a[0], Value = v }))
         .ToArray();
 }
        protected void Page_Load(object sender, EventArgs e)
        {/* The Params property holds entries obtained from a form with 
                method="get" or method="post".  QueryString only holds method="get" 
                entries.
                */
            c = Request.Params;

            if (!IsPostBack)
            {
                nrecs = int.Parse(c.Get("nrecs"));
                Session["nrecs"] = nrecs;

                databasename = c.Get("databasename");
                Session["databasename"] = databasename;

                username = c.Get("username");
                Session["username"] = username;

                password = c.Get("password");
                Session["password"] = password;

                tablename = c.Get("tablename");
                Session["tablename"] = tablename;

                GetConn();

                string statement = "select * from " + tablename;
                SqlCommand cmd = new SqlCommand(statement, conn);
                SqlDataReader Read = cmd.ExecuteReader();

                for (int i = 0; i < Read.FieldCount; i++)
                {
                    fieldnames.Add(Read.GetName(i));
                    type.Add(Read.GetDataTypeName(i));
                }
                Session["fieldnames"] = fieldnames;
                Session["types"] = type;
                nfields = Read.FieldCount;
                Session["nfields"] = nfields;
            }
            else
            {
                GetConn();
                ExecuteInsertStatements();
                Response.Write("<h1>Insert an additional batch below if requested, or click on the link provided below</h1>");
                Response.Write("<p><a href=mainmenup2.html>Click here to go back to the main menu</a></p>");
            }
        }
Beispiel #18
0
        // Initializes the provider.
        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);

            logFilePath = @"SampleEvent.log";

            customInfo = new StringBuilder();

            providerName = name;
            buffer = config.Get("buffer");
            bufferMode = config.Get("bufferMode");

            customInfo.AppendLine(string.Format("Provider name: {0}", providerName));
            customInfo.AppendLine(string.Format("Buffering: {0}", buffer));
            customInfo.AppendLine(string.Format("Buffering modality: {0}", bufferMode));
        }
Beispiel #19
0
 public NameValueList(NameValueCollection nvc)
 {
     _Keys = nvc.AllKeys;
     int n = _Keys.Length;
     _Values = new object[n];
     for (int i = 0; i < n; i++) _Values[i] = nvc.Get(i);
 }
        internal static void GetPositiveOrInfiniteAttribute(NameValueCollection config, string attrib, string providerName, ref int val) {
            string s = config.Get(attrib);
            int t;

            if (s == null) {
                return;
            }

            if (s == "Infinite") {
                t = ProviderUtil.Infinite;
            }
            else {
                try {
                    t = Convert.ToInt32(s, CultureInfo.InvariantCulture);
                }
                catch (Exception e){
                    if (e is ArgumentException || e is FormatException || e is OverflowException) {
                        throw new ConfigurationErrorsException(
                            SR.GetString(SR.Invalid_provider_positive_attributes, attrib, providerName));
                    }
                    else {
                        throw;
                    }
                    
                }
                
                if (t < 0) {
                    throw new ConfigurationErrorsException(
                        SR.GetString(SR.Invalid_provider_positive_attributes, attrib, providerName));

                }
            }

            val = t;
        }
Beispiel #21
0
 public AuthorizeRequest(NameValueCollection parameters)
 {
     foreach (var key in parameters.AllKeys)
     {
         Set(key, parameters.Get(key));
     }
 }
        public void CustomHashProviderDataTest()
        {
            try
            {
                string name = "testName2";
                Type type = typeof(CustomHashProviderNodeFixture);
                NameValueCollection attributes = new NameValueCollection();
                attributes.Add("test", "value");

                CustomHashProviderData data = new CustomHashProviderData();
                data.Name = name;
                data.Type = type;
                data.Attributes.Add(attributes.GetKey(0), attributes[attributes.GetKey(0)]);

                CustomHashProviderNode node = new CustomHashProviderNode(data);
                ApplicationNode.AddNode(node);
                Assert.AreEqual(name, node.Name);
                Assert.AreEqual(type, node.Type);

                Assert.AreEqual(attributes.AllKeys[0], node.Attributes[0].Key);
                Assert.AreEqual(attributes.Get(0), node.Attributes[0].Value);
            }
            finally
            {
                File.Delete("KeyedHashKey.file");
            }
        }
Beispiel #23
0
        private bool SerializeNameValueCollection(System.Collections.Specialized.NameValueCollection value)
        {
            if (value.Count == 0)
            {
                _jsonWriter.WriteStartObject();
                _jsonWriter.WriteEndObject();
                return(true);
            }

            _jsonWriter.WriteStartObject();
            try
            {
                string[] keys = value.AllKeys;
                int      len  = keys.Length;
                for (int i = 0; i < len; i++)
                {
                    var name = keys[i];
                    if (!name.IsNullOrEmpty())
                    {
                        _jsonWriter.WritePropertyName(name, true);
                        _jsonWriter.WriteStringNullable(value.Get(i));
                    }
                }
            }
            finally
            {
                _jsonWriter.WriteEndObject();
            }

            return(true);
        }
Beispiel #24
0
        public static string CreateURI(string strScheme, string strHost, string strPath, NameValueCollection queryColl)
        {
            bool bFirst = true;
             string strURI = strScheme + "://" + strHost + "/";
             if (!String.IsNullOrEmpty(strPath))
            strURI += strPath;

             string strQuery = String.Empty;
             if (queryColl != null)
             {
            for (int i = 0; i < queryColl.Count; i++)
            {
               if (!bFirst)
                  strQuery += "&";
               else
                  bFirst = false;

               strQuery += queryColl.GetKey(i) + "=" + HttpUtility.UrlEncode(queryColl.Get(i));
            }
             }

             if (strQuery != String.Empty)
            strURI += "?" + strQuery;

             return strURI;
        }
        internal async Task<IHttpActionResult> ProcessRequest(NameValueCollection parameters)
        {
            var token = parameters.Get("token");
            if (token.IsMissing())
            {
                var error = "token is missing";

                Logger.Error(error);
                await RaiseFailureEventAsync(error);
                return BadRequest(_localizationService.GetMessage(MessageIds.MissingToken));
            }

            var result = await _validator.ValidateAccessTokenAsync(token, parameters.Get("expectedScope"));

            if (result.IsError)
            {
                Logger.Info("Returning error: " + result.Error);
                await RaiseFailureEventAsync(result.Error);

                return BadRequest(result.Error);
            }

            var response = result.Claims.ToClaimsDictionary();

            Logger.Info("End access token validation request");
            await RaiseSuccessEventAsync();

            return Json(response);
        }
Beispiel #26
0
        /// <summary>
        /// Call the API method with additional, non-required params
        /// </summary>
        /// <param name="apiCall">The path to the API method call (/videos/list)</param>
        /// <param name="args">Additional, non-required arguments</param>
        /// <returns>The string response from the API call</returns>
        public string Call(string apiCall, NameValueCollection args) {

            _queryString = new NameValueCollection();

            //add the non-required args to the required args
            if (args != null)
            {
                foreach (string k in args.Keys)
                {
                    _queryString.Add(k, UrlEncodeUCase(args.Get(k), Encoding.UTF8));
                }
            }
            buildArgs();
            WebClient client = createWebClient();

            string callUrl = _apiURL + apiCall;

            try
            {
                return client.DownloadString(callUrl);
            }
            catch
            {
                return "";
            }                                                               
        }
        /// <summary>
        /// Determines if an incoming request is authentic.
        /// </summary>
        /// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param>
        /// <param name="shopifySecretKey">Your app's secret key.</param>
        /// <returns>A boolean indicating whether the request is authentic or not.</returns>
        public static bool IsAuthenticRequest(NameValueCollection querystring, string shopifySecretKey)
        {
            string signature = querystring.Get("signature");

            //Convert the querystring to a dictionary, which lets us query it with LINQ
            IDictionary<string, string> parameters = querystring
                .Cast<string>()
                .Select(s => new { Key = s, Value = querystring[s] })
                .ToDictionary(d => d.Key, d => d.Value);

            //To calculate signature, order all querystring parameters by alphabetical (exclude the signature itself), and append it to the secret key.
            string calculatedSignature = shopifySecretKey + string.Join(null, parameters
                .Where(x => x.Key != "signature")
                .OrderBy(x => x.Key)
                .Select(x => string.Format("{0}={1}", x.Key, x.Value)));

            //Convert calculated signature to bytes
            Byte[] sigBytes = Encoding.UTF8.GetBytes(calculatedSignature);

            //Runt hose bytes through an MD5 hash
            using (MD5 md5 = MD5.Create())
            {
                sigBytes = md5.ComputeHash(sigBytes);
            }

            //Convert bytes back to string, replacing dashes, to get the final signature.
            calculatedSignature = BitConverter.ToString(sigBytes).Replace("-", "");

            //Request is valid if the calculated signature matches the signature from the querystring.
            return calculatedSignature.ToUpper() == signature.ToUpper();
        }
        // ------------------------------------------------------------
        // Name: CUtilities
        // Abstract: Constructor
        // ------------------------------------------------------------
        static CExactTargetUtilities()
        {
            // Initialize our ET Client
            // Pass ClientID/ClientSecret
            NameValueCollection parameters = new NameValueCollection();
            //parameters.Add("clientId", "<InsertClientId>");
            //parameters.Add("clientSecret", "<InsertClientSecret>");

            // WORKS FOR Customer Unit Lists
            parameters.Add("clientId", "<InsertClientId>");
            parameters.Add("clientSecret", "<InsertClientSecret>");

            // WORKS FOR main subscribers and shared data extensions!!
            //parameters.Add("clientId", "<InsertClientId>");
            //parameters.Add("clientSecret", "<InsertClientSecret>");
            Console.WriteLine("ID: " + parameters.Get("clientID").ToString());
            m_etcTDClient = new ET_Client(parameters);

            // for shared data extensions
            NameValueCollection parametersShared = new NameValueCollection();
            parametersShared.Add("clientId", "<InsertClientId>");
            parametersShared.Add("clientSecret", "<InsertClientSecret>");
            m_etcTDClientShared = new ET_Client(parametersShared);
            Console.WriteLine("OK");
        }
Beispiel #29
0
 static void Main(string[] args)
 {
     // Create an empty NameValueCollection and add multiple values for each key.
     NameValueCollection nvCol = new NameValueCollection();
     nvCol.Add("Minnesota", "St. Paul");
     nvCol.Add("Minnesota", "Minneapolis");
     nvCol.Add("Minnesota", "Rochester");
     nvCol.Add("Florida", "Miami");
     nvCol.Add("Florida", "Orlando");
     nvCol.Add("Arizona", "Pheonix");
     nvCol.Add("Arizona", "Tucson");
     // Get the key at index position 0 (Minnesota).
     string key = nvCol.GetKey(0);
     Console.WriteLine("Key 0: {0}", key);
     // Remove the entry for Minnesota by its key.
     nvCol.Remove(key);
     // Get the values for Florida as a string array.
     foreach (string val in nvCol.GetValues("Florida"))
     {
         Console.WriteLine("A value for 'Florida': {0}", val);
     }
     // Iterate through the entries (Florida and Arizona) in the NameValueCollection.
     foreach (string k in nvCol)
     {
         // Get the values for an entry as a comma-separated list.
         Console.WriteLine("Key: {0} Values: {1}", k, nvCol.Get(k));
     }
 }
Beispiel #30
0
        /// <summary>
        /// HTTPでのPOST処理
        /// </summary>
        /// <param name="url">対象URL</param>
        /// <param name="querystring">POSTパラメータ</param>
        /// <param name="cookies">POST時に使用するCookie</param>
        /// <returns>HTTPのPOST結果</returns>
        public static string HttpPost(string url, NameValueCollection querystring, CookieContainer cookies)
        {
            string param = "";
            if (querystring != null)
            {
                foreach (string key in querystring.Keys)
                {
                    param += String.Format("{0}={1}&", key, querystring.Get(key));
                }
            }
            byte[] data = Encoding.GetEncoding("Shift-JIS").GetBytes(param);

            // リクエストの作成
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            req.CookieContainer = cookies;

            // ポスト・データの書き込み
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();

            WebResponse res = req.GetResponse();

            // レスポンスの読み取り
            Stream resStream = res.GetResponseStream();
            StreamReader sr = new StreamReader(resStream, Encoding.GetEncoding("Shift-JIS"));
            string result = sr.ReadToEnd();
            sr.Close();
            resStream.Close();

            return result;
        }
        public void CustomCacheStorageNodeTest()
        {
            string name = "testName1";
            Type type = typeof(CustomCacheStorageData);
            NameValueCollection attributes = new NameValueCollection();
            attributes.Add("test", "value");

            CustomCacheStorageNode node = new CustomCacheStorageNode();
            ApplicationNode.AddNode(node);
            Assert.AreEqual("Cache Storage", node.Name);

            node.Type = type;
            node.Name = name;
            node.Attributes.Add( new EditableKeyValue(attributes.GetKey(0), attributes[attributes.GetKey(0)]));

            Assert.AreEqual(attributes[0], node.Attributes[0].Value);
            Assert.AreEqual(type, node.Type);
            Assert.AreEqual(name, node.Name);

            CustomCacheStorageData nodeData = (CustomCacheStorageData)node.CacheStorageData;
            Assert.AreEqual(name, nodeData.Name);
            Assert.AreEqual(type, nodeData.Type);
            Assert.AreEqual(attributes.AllKeys[0], nodeData.Attributes.AllKeys[0]);
            Assert.AreEqual(attributes.Get(0), nodeData.Attributes.Get(0));

        }
Beispiel #32
0
        private void CreateConfiguration(Dictionary<string, object> defaultValues, NameValueCollection nameValues)
        {
            foreach (KeyValuePair<string, object> pair in defaultValues)
                UsedValues.Add(pair.Key, pair.Value.ToString());
            foreach (string key in nameValues.AllKeys)
            {
                string value = nameValues.Get(key);
                if (value != null)
                {
                    UsedValues.Remove(key);
                    UsedValues[key] = value;
                }
            }

            var allKeys = new List<string>(nameValues.AllKeys);
            allKeys.AddRange(defaultValues.Keys);

            foreach (string key in allKeys)
            {
                string value = ConfigurationManager.AppSettings[key];
                if (value != null)
                {
                    UsedValues.Remove(key);
                    UsedValues[key] = value;
                }
            }
        }
Beispiel #33
0
        public void getBytesTest()
        {
            //given

            NameValueCollection values = new NameValueCollection();
            values.Add("TestKey1", "TestValue1");
            values.Add("TestKey2", "TestValue2");

            byte[] expected = Encoding.ASCII.GetBytes("TestKey1=TestValue1&TestKey2=TestValue2");

            //when

            StringBuilder stringBuilder = new StringBuilder();
            foreach (String key in values)
            {
                stringBuilder.Append(key).Append("=").Append(values.Get(key)).Append("&");
            }

            stringBuilder.Remove(stringBuilder.Length - 1, 1);

            byte[] actual = Encoding.ASCII.GetBytes(stringBuilder.ToString());

            //then

            CollectionAssert.AreEqual(actual, expected);
        }
Beispiel #34
0
        public static Dictionary <string, string> getUrlParam(this string query, HttpContextBase httpContext)
        {
            System.Collections.Specialized.NameValueCollection coll = System.Web.HttpUtility.ParseQueryString(httpContext.Request.UrlReferrer.Query);
            Dictionary <string, string> keyValuePair = new Dictionary <string, string>();

            for (int i = 0; i < coll.Count; i++)
            {
                keyValuePair.Add(coll.GetKey(i), coll.Get(i));
            }
            return(keyValuePair);
        }
Beispiel #35
0
        /// <summary>
        /// 根据NameValueCollection键值集合组装url字符串
        /// </summary>
        /// <param name="st">NameValueCollection键值集合</param>
        /// <returns>返回返回string字符串(格式:a=a&b=b&c=c)</returns>
        public static string GetStrNV(System.Collections.Specialized.NameValueCollection nv)
        {
            string str = string.Empty;

            for (int i = 0; i < nv.Count; i++)
            {
                str += nv.GetKey(i) + "=" + nv.Get(i) + "&";
            }
            str = str.Substring(0, str.Length - 1);
            return(str);
        }
Beispiel #36
0
    public static void metaInclude(System.Collections.Specialized.NameValueCollection metaAttributes, System.Web.UI.MasterPage masterPage)
    {
        using (System.Web.UI.HtmlControls.HtmlMeta meta_tag = new System.Web.UI.HtmlControls.HtmlMeta())
        {
            foreach (string key in metaAttributes.AllKeys)
            {
                meta_tag.Attributes.Add(key, metaAttributes.Get(key));
            }

            masterPage.Page.Header.Controls.Add(meta_tag);
        }
    }
Beispiel #37
0
        /// <summary>
        /// Extracts queries from a <see cref="Collections.Specialized.NameValueCollection"/> and turns them into a string list
        /// </summary>
        /// <param name="collection">source</param>
        public static string ReadQuery(Collections.Specialized.NameValueCollection collection)
        {
            if (collection == null)
            {
                return("");
            }
            var ret = new StringBuilder().Append("[");

            foreach (var k in collection.AllKeys)
            {
                ret.Append($"{k} = {collection.Get(k)}, ");
            }
            return(ret.ToString().TrimEnd(new char[] { ',', ' ' }) + "]");
        }
        private void CancelEdit(object sender, EventArgs e)
        {
            Button current = (Button)sender;

            Label currentLabel = (Xamarin.Forms.Label)FindByName(current.ClassId + "Display");

            Button submitButton = (Button)FindByName(current.ClassId + "Submit");
            Button cancelButton = (Button)FindByName(current.ClassId + "Cancel");
            Button editButton   = (Button)FindByName(current.ClassId + "Edit");

            submitButton.IsVisible = false;
            cancelButton.IsVisible = false;
            editButton.IsVisible   = true;

            if (current.ClassId == "CampaignDescription")
            {
                Editor currentInputView = (Xamarin.Forms.Editor)FindByName(current.ClassId + "Entry");

                currentInputView.Text      = sendingData.Get("CampaignDescription").ToString();
                currentInputView.IsVisible = false;
            }
            else if (current.ClassId == "StartDate" || current.ClassId == "EndDate")
            {
                DatePicker currentItem = (DatePicker)FindByName(current.ClassId + "Entry");
                currentItem.Date      = DateTime.Parse(sendingData.Get(current.ClassId));
                currentItem.IsVisible = false;
            }
            else
            {
                Entry currentInputView = (Xamarin.Forms.Entry)FindByName(current.ClassId + "Entry");
                currentInputView.Text      = sendingData.Get(current.ClassId);
                currentInputView.IsVisible = false;
            }

            currentLabel.IsVisible = true;
        }
Beispiel #39
0
        public void Publish(Exception exception, System.Collections.Specialized.NameValueCollection additionalInfo, System.Collections.Specialized.NameValueCollection configSettings)
        {
            #region Thread abort exception
            //if(exception.GetType().Equals(typeof(System.Threading.ThreadAbortException)))
            //{
            //return;
            //}
            #endregion

            #region Publish Exception
            // Load Config values if they are provided.
            if (configSettings != null)
            {
                if (configSettings["fileName"] != null &&
                    configSettings["fileName"].Length > 0)
                {
                    m_LogName = configSettings["fileName"];
                }
            }
            // Create StringBuilder to maintain publishing information.
            StringBuilder strInfo = new StringBuilder();

            // Record the contents of the AdditionalInfo collection.
            if (additionalInfo != null)
            {
                // Record General information.
                strInfo.AppendFormat("{0}General Information{0}", Environment.NewLine);
                strInfo.AppendFormat("{0}Additonal Info:", Environment.NewLine);
                foreach (string i in additionalInfo)
                {
                    strInfo.AppendFormat("{0}{1}: {2}", Environment.NewLine, i, additionalInfo.Get(i));
                }
            }

            // Append the exception text
            strInfo.AppendFormat("{0}{0}Exception Information{0}{1}", Environment.NewLine, exception.ToString());
            strInfo.AppendFormat("{0}{0}", Environment.NewLine);

            if (m_LogName != "")
            {
                // Write the entry to the log file.
                WriteToFile(m_LogName, strInfo);
            }
            #endregion
        }
Beispiel #40
0
    public static string generateJson(System.Collections.Specialized.NameValueCollection nameval)
    {
        System.Text.StringBuilder string_builder = new System.Text.StringBuilder();

        string_builder.Append("[");

        foreach (string key in nameval.Keys)
        {
            string_builder.Append("{");
            string_builder.AppendFormat("\"{0}\":\"{1}\",", key, nameval.Get(key));
            string_builder.Remove(string_builder.Length - 1, 1);
            string_builder.Append("},");
        }

        string_builder.Remove(string_builder.Length - 1, 1);
        string_builder.Append("]");

        return(Convert.ToString(string_builder));
    }
    public override string[][] GetUnknownRequestHeaders()
    {
        string[][] unknownRequestHeaders;
        System.Collections.Specialized.NameValueCollection headers = _context.Request.Headers;
        int             count       = headers.Count;
        List <string[]> headerPairs = new List <string[]>(count);

        for (int i = 0; i < count; i++)
        {
            string headerName = headers.GetKey(i);
            if (GetKnownRequestHeaderIndex(headerName) == -1)
            {
                string headerValue = headers.Get(i);
                headerPairs.Add(new string[] { headerName, headerValue });
            }
        }
        unknownRequestHeaders = headerPairs.ToArray();
        return(unknownRequestHeaders);
    }
        private static string formatException(Exception ex, System.Collections.Specialized.NameValueCollection additionalInfo)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Sorry to inform you, but there was a programming exception in application " + _eventSource + ". Pls see info below:"
                      + Environment.NewLine + Environment.NewLine);
            sb.Append("Server Name=" + Environment.MachineName + Environment.NewLine);
            sb.Append("Exception Info" + Environment.NewLine);
            sb.Append(ex.ToString() + Environment.NewLine);

            if (additionalInfo != null)
            {
                foreach (string i in additionalInfo)
                {
                    sb.Append(Environment.NewLine + i + " " + additionalInfo.Get(i) + "" + Environment.NewLine);
                }
            }

            return(sb.ToString());
        }
Beispiel #43
0
    public static string rq(string keyName)
    {
        string sRetValue = "";
        string sKeyname  = keyName.ToLower();

        System.Web.HttpRequest r = System.Web.HttpContext.Current.Request;
        System.Collections.Specialized.NameValueCollection n = r.QueryString;
        if (n.HasKeys())
        {
            for (int i = 0; i < n.Count; i++)
            {
                if (n.GetKey(i) != null)
                {
                    string key = n.GetKey(i).ToLower();
                    if (key == sKeyname)
                    {
                        sRetValue = n.Get(i);
                        break;
                    }
                }
            }
        }
        return(sRetValue);
    }
Beispiel #44
0
        /// <summary>
        /// prepares Remote post by populate all the necessary fields to generate PayUMoney post request.
        /// </summary>
        /// <param name="order">order details.</param>
        /// <param name="returnUrl">return url.</param>
        /// <returns>return remote post.</returns>
        private static async Task <RemotePost> PrepareRemotePost(OrderViewModel order, string returnUrl)
        {
            string fname = string.Empty;
            string phone = string.Empty;
            string email = string.Empty;

            CustomerRegistrationRepository customerRegistrationRepository = new CustomerRegistrationRepository(ApplicationDomain.Instance);
            CustomerViewModel customerRegistrationInfo = await customerRegistrationRepository.RetrieveAsync(order.CustomerId).ConfigureAwait(false);

            if (customerRegistrationInfo == null)
            {
                Customer customer = await ApplicationDomain.Instance.PartnerCenterClient.Customers.ById(order.CustomerId).GetAsync().ConfigureAwait(false);

                fname = customer.BillingProfile.DefaultAddress.FirstName;
                phone = customer.BillingProfile.DefaultAddress.PhoneNumber;
                email = customer.BillingProfile.Email;
            }
            else
            {
                fname = customerRegistrationInfo.FirstName;
                phone = customerRegistrationInfo.Phone;
                email = customerRegistrationInfo.Email;
            }

            decimal       paymentTotal = 0;
            StringBuilder productSubs  = new StringBuilder();
            StringBuilder prodQuants   = new StringBuilder();

            foreach (OrderSubscriptionItemViewModel subscriptionItem in order.Subscriptions)
            {
                productSubs.Append(":").Append(subscriptionItem.SubscriptionId);
                prodQuants.Append(":").Append(subscriptionItem.Quantity.ToString(CultureInfo.InvariantCulture));
                paymentTotal += Math.Round(subscriptionItem.Quantity * subscriptionItem.SeatPrice, Resources.Culture.NumberFormat.CurrencyDecimalDigits);
            }

            productSubs.Remove(0, 1);
            prodQuants.Remove(0, 1);
            System.Collections.Specialized.NameValueCollection inputs = new System.Collections.Specialized.NameValueCollection();
            PaymentConfiguration payconfig = await GetAPaymentConfigAsync().ConfigureAwait(false);

            inputs.Add("key", payconfig.ClientId);
            inputs.Add("txnid", GenerateTransactionId());
            inputs.Add("amount", paymentTotal.ToString(CultureInfo.InvariantCulture));
            inputs.Add("productinfo", productSubs.ToString());
            inputs.Add("firstname", fname);
            inputs.Add("phone", phone);
            inputs.Add("email", email);
            inputs.Add("udf1", order.OperationType.ToString());
            inputs.Add("udf2", prodQuants.ToString());
            inputs.Add("surl", returnUrl + "&payment=success&PayerId=" + inputs.Get("txnid"));
            inputs.Add("furl", returnUrl + "&payment=failure&PayerId=" + inputs.Get("txnid"));
            inputs.Add("service_provider", Constant.PAYUPAISASERVICEPROVIDER);
            string hashString = inputs.Get("key") + "|" + inputs.Get("txnid") + "|" + inputs.Get("amount") + "|" + inputs.Get("productInfo") + "|" + inputs.Get("firstName") + "|" + inputs.Get("email") + "|" + inputs.Get("udf1") + "|" + inputs.Get("udf2") + "|||||||||" + payconfig.ClientSecret;
            string hash       = GenerateHash512(hashString);

            inputs.Add("hash", hash);

            RemotePost myremotepost = new RemotePost();

            myremotepost.SetUrl(GetPaymentUrl(payconfig.AccountType));
            myremotepost.SetInputs(inputs);
            return(myremotepost);
        }
        public void SendPdf()
        {
            string result = "";

            var Request = HttpContext.Current.Request;

            System.Collections.Specialized.NameValueCollection parameters = HttpContext.Current.Request.Params;
            HttpPostedFile file = HttpContext.Current.Request.Files["uploadFile"];
            //System.Diagnostics.Debug.WriteLine("---" + parameters.Get("requestId"));
            //System.Diagnostics.Debug.WriteLine("---" + file.FileName);
            //System.Diagnostics.Debug.WriteLine("---" + file.ContentLength);
            //System.Diagnostics.Debug.WriteLine("---" + file.ContentType);
            string agentId         = parameters.Get("agentId");
            string contactId       = parameters.Get("contactId");
            string contactPersonId = parameters.Get("contactPersonId");
            var    roomId          = 0;
            var    userId          = "";
            var    url             = ConfigurationManager.AppSettings["LINE_SERVICE_URL"] + "/contactUpload";

            if (contactPersonId != null)
            {
                url = ConfigurationManager.AppSettings["LINE_SERVICE_URL"] + "/upload";
                using (ISession session = NHibernateHelper.OpenSession())
                {
                    var models = session.CreateQuery("from LineChatRoom where ContactPersonId=? and ActiveFlag='1'")
                                 .SetParameter(0, Guid.Parse(contactPersonId)).List <LineChatRoom>();
                    if (models.Count > 0)
                    {
                        roomId = models[0].Id;
                    }

                    var lineContacts = session.CreateQuery("from LineContacts where ContactPersonId=? and ActiveFlag='1'")
                                       .SetParameter(0, Guid.Parse(contactPersonId)).List <LineContacts>();
                    if (lineContacts.Count > 0)
                    {
                        userId = lineContacts[0].LineId;
                    }
                }
            }
            else
            {
                contactPersonId = "";
            }

            using (var client = new HttpClient())
            {
                MultipartFormDataContent form = new MultipartFormDataContent();
                form.Add(new StringContent(contactId), "contactId");
                form.Add(new StringContent(contactPersonId), "contactPersonId");
                form.Add(new StringContent(roomId.ToString()), "id");
                form.Add(new StringContent(userId), "userId");
                form.Add(new StringContent(agentId), "agentId");
                //client.DefaultRequestHeaders.Add("Authorization", ConfigurationManager.AppSettings["TOKEN"]);
                var stream        = file.InputStream;
                var contentStream = new StreamContent(stream);
                contentStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name     = "uploadFile",
                    FileName = file.FileName
                };
                contentStream.Headers.ContentType   = new MediaTypeWithQualityHeaderValue(file.ContentType);
                contentStream.Headers.ContentLength = file.ContentLength;
                form.Add(contentStream, "uploadFile");
                var response = client.PostAsync(url, form).Result;

                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                    //Console.WriteLine(content);
                    // Access variables from the returned JSON object
                    //var appHref = content.links.applications.href;
                }
                else
                {
                    result = "{sucess:false , msg : \"" + response.Content.ReadAsStringAsync().Result + "\"}";
                }
            }
            Context.Response.Clear();
            Context.Response.ContentType = "text/html";
            Context.Response.Write(result);
            Context.Response.End();
        }
        public void Publish(Exception exception, System.Collections.Specialized.NameValueCollection AdditionalInfo, System.Collections.Specialized.NameValueCollection configSettings)
        {
            #region Thread abort exception
            //if(exception.GetType().Equals(typeof(System.Threading.ThreadAbortException)))
            //{
            //return;
            //}
            #endregion

            #region Publish Exception
            // Load Config values if they are provided.
            if (configSettings != null)
            {
                if (configSettings["operatorMail"] != null &&
                    configSettings["operatorMail"].Length > 0)
                {
                    m_OpMail = configSettings["operatorMail"];
                }
                if (configSettings["operatorMailFrom"] != null &&
                    configSettings["operatorMailFrom"].Length > 0)
                {
                    m_OpMailFrom = configSettings["operatorMailFrom"];
                }
                if (configSettings["MailServer"] != null &&
                    configSettings["MailServer"].Length > 0)
                {
                    m_MailServer = configSettings["MailServer"];
                }
            }
            // Create StringBuilder to maintain publishing information.
            StringBuilder strInfo = new StringBuilder();

            // Record the contents of the AdditionalInfo collection.
            if (AdditionalInfo != null)
            {
                // Record General information.
                strInfo.AppendFormat("{0}General Information{0}", Environment.NewLine);
                strInfo.AppendFormat("{0}Additonal Info:", Environment.NewLine);
                foreach (string i in AdditionalInfo)
                {
                    strInfo.AppendFormat("{0}{1}: {2}", Environment.NewLine, i, AdditionalInfo.Get(i));
                }
            }

            // Append the exception text
            strInfo.AppendFormat("{0}{0}Exception Information{0}{1}", Environment.NewLine, exception.ToString());

            strInfo.AppendFormat("{0}{0}", Environment.NewLine);

            #region construct the subject
            // format of subject. E.g. "Error on Regulus: (501) General processing error"
            StringBuilder subject = new StringBuilder();
            subject.Append("Error on ");
            subject.Append(Environment.MachineName);
            subject.Append(": ");
            subject.Append(exception.Message);
            #endregion

            // send notification email if operatorMail attribute was provided
            if (m_OpMail.Length > 0)
            {
                SendMail(m_OpMailFrom, m_OpMail, "", "", subject.ToString(), strInfo.ToString());
            }
            #endregion
        }