GetValues() public method

public GetValues ( 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(),
                BoostFactor = query.Get("boostFactor").ToNullableFloat(),
                MaximumNumberOfTokensParsed = query.Get("maxNumTokens").ToNullableInt(),
                MaximumQueryTerms = query.Get("maxQueryTerms").ToNullableInt(),
                MaximumWordLength = query.Get("maxWordLen").ToNullableInt(),
                MinimumDocumentFrequency = query.Get("minDocFreq").ToNullableInt(),
                MaximumDocumentFrequency = query.Get("maxDocFreq").ToNullableInt(),
                MaximumDocumentFrequencyPercentage = query.Get("maxDocFreqPct").ToNullableInt(),
                MinimumTermFrequency = query.Get("minTermFreq").ToNullableInt(),
                MinimumWordLength = query.Get("minWordLen").ToNullableInt(),
                StopWordsDocumentId = query.Get("stopWords"),
                AdditionalQuery= query.Get("query")
            };

            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;
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            SortedList sl = new SortedList();
            sl.Add("Stack", "Represents a LIFO collection of objects.");
            sl.Add("Queue", "Represents a FIFO collection of objects.");
            sl.Add("SortedList", "Represents a collection of key/value pairs.");

            foreach (DictionaryEntry de in sl)
            {
                Console.WriteLine("{0,12}: {1}", de.Key, de.Value);
            }

            Console.WriteLine("\n" + sl["Queue"]);
            Console.WriteLine(sl.GetByIndex(1));

            Console.WriteLine("\nName Value Collection:");
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("Stack", "Represents a LIFO collection of objects.");
            nvc.Add("Stack", "A pile of pancakes.");
            nvc.Add("Queue", "Represents a FIFO collection of objects.");
            nvc.Add("Queue", "In England, a line.");
            nvc.Add("SortedList", "Represents a collection of key/value pairs.");

            foreach (string s in nvc.GetValues(0))
                Console.WriteLine(s);

            foreach (string s in nvc.GetValues("Queue"))
                Console.WriteLine(s);
        }
Beispiel #3
0
        public virtual MARC.HI.EHRS.CR.Messaging.FHIR.Util.DataUtil.ClientRegistryFhirQuery ParseQuery(System.Collections.Specialized.NameValueCollection parameters, List <Everest.Connectors.IResultDetail> dtls)
        {
            MARC.HI.EHRS.CR.Messaging.FHIR.Util.DataUtil.ClientRegistryFhirQuery retVal = new Util.DataUtil.ClientRegistryFhirQuery();
            retVal.ActualParameters   = new System.Collections.Specialized.NameValueCollection();
            retVal.MinimumDegreeMatch = 0.8f;
            int  page      = 0;
            bool hasFormat = false;

            for (int i = 0; i < parameters.Count; i++)
            {
                try
                {
                    switch (parameters.GetKey(i))
                    {
                    case "stateid":
                    case "_stateid":
                        try
                        {
                            retVal.QueryId = Guid.Parse(parameters.GetValues(i)[0]);
                            retVal.ActualParameters.Add("stateid", retVal.QueryId.ToString());
                        }
                        catch (Exception e)
                        {
                            dtls.Add(new ResultDetail(ResultDetailType.Error, "State identifiers must be issued from the registry and must be a valid GUID", null, e));
                        }
                        break;

                    case "count":
                    case "_count":      // TODO: CP
                        retVal.Quantity = Int32.Parse(parameters.GetValues(i)[0]);
                        retVal.ActualParameters.Add("count", retVal.Quantity.ToString());
                        break;

                    case "page":
                    case "_page":
                        page = Int32.Parse(parameters.GetValues(i)[0]);
                        retVal.ActualParameters.Add("page", page.ToString());
                        break;

                    case "_format":
                        hasFormat = true;
                        //retVal.ActualParameters.Add("_format", parameters.GetValues(i)[0]);
                        break;
                    }
                }
                catch (Exception e)
                {
                    Trace.TraceError(e.ToString());
                    dtls.Add(new ResultDetail(ResultDetailType.Error, e.Message, e));
                }
            }

            //if (!hasFormat)
            //    throw new InvalidOperationException("Missing _format parameter");

            retVal.Start = page * retVal.Quantity;

            return(retVal);
        }
		public void GetValues ()
		{
			NameValueCollection col = new NameValueCollection ();
			col.Add ("foo1", "bar1");
			Assertion.AssertEquals ("#1", null, col.GetValues (null));
			Assertion.AssertEquals ("#2", null, col.GetValues (""));
			Assertion.AssertEquals ("#3", null, col.GetValues ("NotExistent"));
		}
		public void GetValues ()
		{
			NameValueCollection col = new NameValueCollection ();
			col.Add ("foo1", "bar1");
			Assert.AreEqual (null, col.GetValues (null), "#1");
			Assert.AreEqual (null, col.GetValues (""), "#2");
			Assert.AreEqual (null, col.GetValues ("NotExistent"), "#3");
			Assert.AreEqual (1, col.GetValues (0).Length, "#4");
		}
Beispiel #6
0
        public void TestNameValueCollectionValuesAreNotUnique()
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("a", "value a1");
            nvc.Add("a", "value a1"); //the same values again

            Assert.AreEqual(1, nvc.AllKeys.Count());
            Assert.AreEqual(2, nvc.GetValues("a").Count(), "If there was only 1 value, NameValueCollection would enforce uniqueness. Apparently it does not.");
            Assert.AreEqual(1, nvc.GetValues("a").Distinct().Count(), "If we apply a Distinct afterwards, I would expect to have only one value left.");
        }
Beispiel #7
0
        /// <summary>
        /// Query data from the client registry
        /// </summary>
        public SVC.Messaging.FHIR.FhirQueryResult Query(System.Collections.Specialized.NameValueCollection parameters)
        {
            FhirQueryResult result = new FhirQueryResult();

            result.Details = new List <IResultDetail>();

            // Get query parameters
            var resourceProcessor = FhirMessageProcessorUtil.GetMessageProcessor(this.ResourceName);

            // Process incoming request

            NameValueCollection goodParameters = new NameValueCollection();

            for (int i = 0; i < parameters.Count; i++)
            {
                for (int v = 0; v < parameters.GetValues(i).Length; v++)
                {
                    if (!String.IsNullOrEmpty(parameters.GetValues(i)[v]))
                    {
                        goodParameters.Add(parameters.GetKey(i), MessageUtil.Escape(parameters.GetValues(i)[v]));
                    }
                }
            }
            parameters = goodParameters;

            var queryObject = resourceProcessor.ParseQuery(goodParameters, result.Details);

            result.Query = queryObject;

            // sanity check
#if !DEBUG
            if (result.Query.ActualParameters.Count == 0)
            {
                result.Outcome = ResultCode.Rejected;
                result.Details.Add(new ValidationResultDetail(ResultDetailType.Error, ApplicationContext.LocalizationService.GetString("MSGE077"), null, null));
            }
            else
#endif
            if (result.Details.Exists(o => o.Type == ResultDetailType.Error))
            {
                result.Outcome = ResultCode.Error;
                result.Details.Add(new ResultDetail(ResultDetailType.Error, ApplicationContext.LocalizationService.GetString("MSGE00A"), null, null));
            }
            else if (queryObject.Filter == null || result.Outcome != ResultCode.Accepted)
            {
                throw new InvalidOperationException("Could not process query parameters!");
            }
            else
            {
                result = DataUtil.Query(queryObject, result.Details);
            }

            return(result);
        }
Beispiel #8
0
    public static string GetValueFromAppSettings(string key)
    {
        string strValue = string.Empty;

        System.Collections.Specialized.NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings;
        if (appSettings.GetValues(key) != null)
        {
            strValue = appSettings.GetValues(key)[0].ToString();
        }
        return(strValue);
    }
Beispiel #9
0
 void DumpNvc(NameValueCollection nvc)
 {
     foreach (string key in nvc.Keys)
     {
         string[] values = nvc.GetValues(key);
         foreach (string value in nvc.GetValues(key))
         {
             AddDebug(string.Format("'{0}' : '{1}'", key, value));
         }
     }
 }
Beispiel #10
0
    protected void btn_Tj_Click(object sender, EventArgs e)
    {
        System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(Request.Form);
        string txt_Begin = nc.GetValues("txt_Begin")[0].ToString();
        string txt_End   = nc.GetValues("txt_End")[0].ToString();

        LVWEIBA.Model.Reservation model = new LVWEIBA.Model.Reservation();
        model.Place1 = txt_Place1.Value;
        model.Place2 = txt_Place2.Value;
        model.Place3 = txt_Place3.Value;
        openid       = Request.Form["uid"];
        if (!string.IsNullOrEmpty(txt_Begin))
        {
            model.BeginTime = Convert.ToDateTime(txt_Begin);
        }
        else
        {
            model.BeginTime = DateTime.Now;
        }
        if (!string.IsNullOrEmpty(txt_End))
        {
            model.EndTime = Convert.ToDateTime(txt_End);
        }
        else
        {
            model.EndTime = DateTime.Now;
        }
        model.Mobile = txt_Mobile.Value;
        model.Member = openid;

        LVWEIBA.BLL.Reservation bll = new LVWEIBA.BLL.Reservation();
        bool isOK = false;

        isOK = bll.Add(model) > 0 ? true : false;

        //if (bll.Exists(userId))
        //{
        //    model.Id = int.Parse(hid_id.Value);
        //    isOK = bll.Update(model);
        //}
        //else
        //{
        //    isOK = bll.Add(model) > 0 ? true : false;
        //}
        if (isOK)
        {
            string rdd = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + GetWeiXinInf.appid + "&redirect_uri=http://wx.lvwei8.com/index/myindex.aspx&response_type=code&scope=snsapi_base&state=123#wechat_redirect";

            BaseClass.Common.Jscript.AlertAndRedirect("提交成功!谢谢您的参与!", rdd);
        }
    }
Beispiel #11
0
 public void PostMethod(string url, NameValueCollection prms)
 {
     string req = "";
     for (int i = 0; i < prms.Count; i++)
     {
         if (i == 0)
             req += prms.GetKey(i) + "=" + Utility.URLEncode(prms.GetValues(i).GetValue(0).ToString());
         else
             req += "&" + prms.GetKey(i) + "=" + Utility.URLEncode(prms.GetValues(i).GetValue(0).ToString());
     }
     if (authObject != null)
         this.Navigate(url, null, ASCIIEncoding.ASCII.GetBytes(req), (string)authObject);
     else
         this.Navigate(url, null, ASCIIEncoding.ASCII.GetBytes(req), null);
 }
Beispiel #12
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));
     }
 }
 private static string GetValueFromAppSettings(NameValueCollection appSettings, string key, string defaultValue)
 {
     if (appSettings == null) return defaultValue;
     var values = appSettings.GetValues(key);
     if (values == null) return defaultValue;
     return values.FirstOrDefault() ?? defaultValue;
 }
Beispiel #14
0
        /// <summary>
        ///     To register the app:
        ///     1) Go to appregnew.aspx to create the client ID and client secret
        ///     2) Copy the client ID and client secret to app.config
        ///     3) Go to appinv.aspx to lookup by client ID and add permission XML below
        ///     /*
        ///      <AppPermissionRequests AllowAppOnlyPolicy="true">
        ///        <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="Write" />
        ///      </AppPermissionRequests>
        ///     */
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            //Read site collections to apply policy to from app.config file
            configSites = (NameValueCollection)ConfigurationManager.GetSection("Sites");
            configContentTypeRetentionPolicyPeriods =
                (NameValueCollection)ConfigurationManager.GetSection("ContentTypeRetentionPolicyPeriod");

            //Iterate through site collections
            foreach (var key in configSites.Keys)
            {
                var siteUrls = configSites.GetValues(key as string);
                if (siteUrls != null)
                {
                    //Build ClientContext with AppOnly Token
                    var sitetUri = new Uri(siteUrls[0]);
                    var siteRealm = TokenHelper.GetRealmFromTargetUrl(sitetUri);
                    var tenantAccessToken = TokenHelper.GetAppOnlyAccessToken
                        (TokenHelper.SharePointPrincipal, sitetUri.Authority, siteRealm).AccessToken;

                    using (var clientContext = TokenHelper.GetClientContextWithAccessToken
                            (sitetUri.ToString(), tenantAccessToken))
                    {
                        //Retrieve root web.
                        var rootWeb = clientContext.Site.RootWeb;
                        clientContext.Load(rootWeb);
                        clientContext.ExecuteQueryWithExponentialRetry(5, 30000);

                        ProcessWebRecursively(clientContext, rootWeb);
                    }
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Beispiel #15
0
        protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            if (connection == null) {
                connection = new Http2Connection (request.RequestUri.Host, (uint)request.RequestUri.Port, request.RequestUri.Scheme == Uri.UriSchemeHttps);
            } else {
                // TODO: Check if they tried to use a new host/port
            }

            await connection.Connect ();

            var resetComplete = new ManualResetEventSlim (false);

            var stream = await connection.CreateStream ();
            stream.OnFrameReceived += frame => {
                if (frame.IsEndStream)
                    resetComplete.Set ();
            };

            var headersFrame = new HeadersFrame (stream.StreamIdentifer);
            headersFrame.Headers.Add (":method", request.Method.Method.ToUpperInvariant ());
            headersFrame.Headers.Add (":path", request.RequestUri.PathAndQuery);
            headersFrame.Headers.Add (":scheme", request.RequestUri.Scheme);
            headersFrame.Headers.Add (":authority", request.RequestUri.Authority);
            headersFrame.EndHeaders = true;
            headersFrame.EndStream = true;

            await connection.SendFrame (headersFrame);

            resetComplete.Wait (connection.ConnectionTimeout);

            var responseData = new List<byte> ();
            var responseHeaders = new NameValueCollection ();

            foreach (var f in stream.Frames) {
                if (f.Type == FrameType.Headers) {                    
                    responseHeaders = (f as HeadersFrame)?.Headers ?? new NameValueCollection ();
                } else if (f.Type == FrameType.Data) {
                    responseData.AddRange ((f as DataFrame).Data);
                    //responseData += Encoding.ASCII.GetString ((f as DataFrame).Data);
                } else if (f.Type == FrameType.Continuation) {
                    // TODO:
                }
            }

            var httpStatusStr = responseHeaders.GetValues (":status")?.FirstOrDefault ();
            var httpStatus = HttpStatusCode.InternalServerError;

            Enum.TryParse<HttpStatusCode> (httpStatusStr, out httpStatus);

            var httpResponseMsg = new HttpResponseMessage (httpStatus);

            foreach (var h in responseHeaders.AllKeys) {
                if (!h.StartsWith (":"))
                    httpResponseMsg.Headers.TryAddWithoutValidation (h, responseHeaders [h]);
            }

            httpResponseMsg.Content = new ByteArrayContent (responseData.ToArray ());

            return httpResponseMsg;
        }
Beispiel #16
0
        private static Dictionary<string, object> NvcToDictionary(NameValueCollection nvc, bool handleMultipleValuesPerKey)
        {
            var result = new Dictionary<string, object>();
            foreach (string key in nvc.Keys)
            {
                if (handleMultipleValuesPerKey)
                {
                    string[] values = nvc.GetValues(key);
                    if (values.Length == 1)
                    {
                        result.Add(key, values[0]);
                    }
                    else
                    {
                        result.Add(key, values);
                    }
                }
                else
                {
                    result.Add(key, nvc[key]);
                }
            }

            return result;
        }
        public static string ToQueryString(NameValueCollection collection, bool startWithQuestionMark = true)
        {
            if (collection == null || !collection.HasKeys())
                return String.Empty;

            var sb = new StringBuilder();
            if (startWithQuestionMark)
                sb.Append("?");

            var j = 0;
            var keys = collection.Keys;
            foreach (string key in keys)
            {
                var i = 0;
                var values = collection.GetValues(key);
                foreach (var value in values)
                {
                    sb.Append(key)
                        .Append("=")
                        .Append(value);

                    if (++i < values.Length)
                        sb.Append("&");
                }
                if (++j < keys.Count)
                    sb.Append("&");
            }
            return sb.ToString();
        }
        /// <internalonly/>
        // Parse the WML posted data appropriately.
        protected virtual bool LoadPostData(String key, NameValueCollection data) {
            bool dataChanged = false;            
            String[] selectedItems = data.GetValues(key);

            if (String.IsNullOrEmpty(selectedItems)) {
                // This shouldn't happen if we're posting back from the form that
                // contains the checkbox. It could happen when being called 
                // as the result of a postback from another form on the page,
                // so we just return quietly.
                return false;
            }

            // For a checkbox, our selection list
            // has only one item.

            Debug.Assert(selectedItems.Length == 1, "Checkbox selection " + 
                         "list has more than one value");

            string selectedItem = selectedItems[0];
            if (selectedItem != null && selectedItem.Length == 0) {
                dataChanged = Control.Checked == true;
                Control.Checked = false;
            }

            else if (StringUtil.EqualsIgnoreCase(selectedItem, "1")) {
                dataChanged = Control.Checked == false;
                Control.Checked = true;
            }

            return dataChanged;

        }
        public LocalReportAssemblyResourceLoader(NameValueCollection queryString, bool isEncrypted)
        {
            var urlParam1 = queryString[UriParameters.ReportAssemblyName];
            AssemblyName = isEncrypted ? SecurityUtil.Decrypt(urlParam1) : urlParam1;

            var urlParam2 = queryString[UriParameters.ReportResourceName];
            MainReportResourceName = isEncrypted ? SecurityUtil.Decrypt(urlParam2) : urlParam2;

            var subReportValues = queryString.GetValues(UriParameters.SubReportResourceNames);

            if (subReportValues == null || !subReportValues.Any()) return;

            var subReportList = new List<SubReportResourceName>();

            foreach(var subReportResourceName in subReportValues)
            {
                var sr = subReportResourceName.Split(':');
                var reportName = sr[0];
                var resourceName = sr[1];

                subReportList.Add(new SubReportResourceName(reportName, resourceName));
            }

            SubReportResourceNames = subReportList;
        }
        public static IDictionary<string,IEnumerable<string>> Parse(Stream stream)
        {
            var headers = new NameValueCollection();
            var bytes = ReadHeaderBytes(stream);

            var text = Encoding.Default.GetString(bytes);
            var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.None);
            foreach (var line in lines)
            {
                if (line == "")
                {
                    break;
                }
                var colonIndex = line.IndexOf(':');
                headers.Add(line.Substring(0, colonIndex), line.Substring(colonIndex + 1).TrimStart());
            }

            var dict = new Dictionary<string, IEnumerable<string>>(headers.Keys.Count);
            foreach (var key in headers.Keys.Cast<string>())
            {
                dict.Add(key, headers.GetValues(key));
            }

            return dict;
        }
        //---------------------------------------------------------------------------------------------------------------------

        #region IOpenSearchable implementation

        //---------------------------------------------------------------------------------------------------------------------

        public OpenSearchRequest Create(QuerySettings querySettings, System.Collections.Specialized.NameValueCollection parameters)
        {
            UriBuilder url = new UriBuilder(context.BaseUrl);

            url.Path += "/remoteresource/" + this.Identifier;
            var array = (from key in parameters.AllKeys
                         from value in parameters.GetValues(key)
                         select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)))
                        .ToArray();

            url.Query = string.Join("&", array);

            /*if (!String.IsNullOrEmpty(parameters["grouped"]) && parameters["grouped"] == "true") {
             *  return new MultiAtomGroupedOpenSearchRequest(ose, GetOpenSearchableArray(), type, new OpenSearchUrl(url.ToString()), true);
             * }*/
            //TODO: if only one result dont use Multi
            var entities = GetOpenSearchableArray();
            OpenSearchableFactorySettings settings = new OpenSearchableFactorySettings(ose)
            {
                Credentials = querySettings.Credentials
            };

            settings.MergeFilters = Terradue.Metadata.EarthObservation.Helpers.GeoTimeOpenSearchHelper.MergeGeoTimeFilters;
            return(new MultiOpenSearchRequest <AtomFeed, AtomItem>(settings, entities, querySettings.PreferredContentType, new OpenSearchUrl(url.ToString()), true, this));
        }
 protected object[] Read(NameValueCollection collection)
 {
     object[] objArray = new object[this.paramInfos.Length];
     for (int i = 0; i < this.paramInfos.Length; i++)
     {
         ParameterInfo info = this.paramInfos[i];
         if (info.ParameterType.IsArray)
         {
             string[] values = collection.GetValues(info.Name);
             Type elementType = info.ParameterType.GetElementType();
             Array array = Array.CreateInstance(elementType, values.Length);
             for (int j = 0; j < values.Length; j++)
             {
                 string str = values[j];
                 array.SetValue(ScalarFormatter.FromString(str, elementType), j);
             }
             objArray[i] = array;
         }
         else
         {
             string str2 = collection[info.Name];
             if (str2 == null)
             {
                 throw new InvalidOperationException(Res.GetString("WebMissingParameter", new object[] { info.Name }));
             }
             objArray[i] = ScalarFormatter.FromString(str2, info.ParameterType);
         }
     }
     return objArray;
 }
 protected virtual string GetExplicitResourceString(string attributeName, string defaultValue, bool throwIfNotFound, NameValueCollection explicitResourceKeys)
 {
     if (attributeName == null)
     {
         throw new ArgumentNullException("attributeName");
     }
     string globalResourceObject = null;
     if (explicitResourceKeys != null)
     {
         string[] values = explicitResourceKeys.GetValues(attributeName);
         if ((values == null) || (values.Length <= 1))
         {
             return globalResourceObject;
         }
         var httpContext = mvcContextFactory.CreateHttpContext();
         try
         {
             globalResourceObject = httpContext.GetGlobalResourceObject(values[0], values[1]) as string;
         }
         catch (System.Resources.MissingManifestResourceException)
         {
             if (defaultValue != null)
             {
                 return defaultValue;
             }
         }
         if ((globalResourceObject == null) && throwIfNotFound)
         {
             throw new InvalidOperationException(string.Format(Resources.Messages.ResourceNotFoundWithClassAndKey, values[0], values[1]));
         }
     }
     return globalResourceObject;
 }
        public static bool NameValueCollections(NameValueCollection left, NameValueCollection right)
        {
            if(left == null)
                return right == null;
            if(right == null)
                return false;
            if(left.Count != right.Count)
                return false;

            foreach(var key in left.AllKeys) {
                IList<string> leftValues = left.GetValues(key);
                IList<string> rightValues = right.GetValues(key);

                if(leftValues == null)
                if(rightValues == null)
                    continue;
                else
                    return false;
                if(rightValues == null)
                    return false;

                if(!leftValues.All(rightValues.Contains) || !rightValues.All(leftValues.Contains))
                    return false;
            }
            return true;
        }
Beispiel #25
0
		public void PopulateTree(CompositeNode root, NameValueCollection nameValueCollection)
		{
			foreach (String key in nameValueCollection.Keys)
			{
				if (key == null) continue;
				string singleKeyName = NormalizeKey(key);
				String[] values = nameValueCollection.GetValues(key);

				if (values == null) continue;

				if (values.Length == 1 && key.EndsWith("[]"))
				{
					if (values[0] == string.Empty)
					{
						ProcessNode(root, typeof (String[]), singleKeyName, new string[0]);
					}
					else
					{
						values = values[0].Split(',');
						ProcessNode(root, typeof (String[]), singleKeyName, values);
					}
				}
				else if (values.Length == 1)
				{
					ProcessNode(root, typeof (String), key, values[0]);
				}
				else
				{
					ProcessNode(root, typeof (String[]), singleKeyName, values);
				}
			}
		}
    private static void DumpEnvironmentSettings(NameValueCollection environment)
    {
      Debug.Print("Begin Dump environment settings:");
      Debug.Indent();

      foreach (var key in environment.AllKeys)
      {
        var values = environment.GetValues(key);
        if (values.Length == 0)
        {
          continue;
        }
        if (values.Length == 1)
        {
          Debug.Print("{0}: {1}", key, values[0]);
        }
        else
        {
          Debug.Print("{0}:", key);

          Debug.Indent();
          foreach (var value in values)
          {
            Debug.Print(value);
          }
          Debug.Unindent();
          Debug.Print(String.Empty);
        }
      }
      Debug.Unindent();
      Debug.Print("End Dump environment settings");
    }
Beispiel #27
0
        public static bool KeyExists(NameValueCollection nameValueCollection, string key)
        {
            if(nameValueCollection.GetValues(key) != null)
                return(true);

            return(false);
        }
Beispiel #28
0
    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        //
        // see if args were passed
        int loop1, loop2;

        BOL = "";
        // Load NameValueCollection object.
        System.Collections.Specialized.NameValueCollection coll = Request.QueryString;
        // Get names of all keys into a string array.
        String[] arr1 = coll.AllKeys;
        for (loop1 = 0; loop1 < arr1.Length; loop1++)
        {
            //Response.Write("Key: " + Server.HtmlEncode(arr1[loop1]) + "<br>");
            String[] arr2 = coll.GetValues(arr1[loop1]);
            for (loop2 = 0; loop2 < arr2.Length; loop2++)
            {
                //Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
            }
            if (arr1[loop1] == "BOL")
            {
                BOL = arr2[0];
            }
        }
        if (BOL != "")
        {
            BindBOLData(BOL);
            BOLNumberBox.Visible    = false;
            FindBOLButt.Visible     = false;
            BOLLabel.Visible        = false;
            CloseButton.PostBackUrl = "javascript:window.close();";
            lblSuccessMessage.Text  = "";
        }
    }
Beispiel #29
0
 public string buildQueryString(NameValueCollection input)
 {
     var array = (from key in input.AllKeys
                  from value in input.GetValues(key)
                  select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)))
       .ToArray();
     return "?" + string.Join("&", array);
 }
 public static string ToQueryString(NameValueCollection source)
 {
     //return HttpUtility.UrlEncode(string.Join("&", source.AllKeys
     return string.Join("&", source.AllKeys
                                   .SelectMany(key => source.GetValues(key)
                                                            .Select(value => string.Format("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value))))
                                   .ToArray());
 }
Beispiel #31
0
 private static string GetQuery(NameValueCollection queryString, string except)
 {
     var array = (from key in queryString.AllKeys
                  from value in queryString.GetValues(key)
                  where key != except
                  select string.Format("{0}={1}", key, value)).ToArray();
     return string.Join("&", array);
 }
Beispiel #32
0
 private static string ToQueryString(NameValueCollection nvc)
 {
     var array = (from key in nvc.AllKeys
                  from value in nvc.GetValues(key)
                  select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)))
         .ToArray();
     return "?" + string.Join("&", array);
 }
 public static void BuildQuery(this UriBuilder uriBuilder, NameValueCollection nameValueCollection)
 {
     uriBuilder.Query = string.Join("&", nameValueCollection.AllKeys.Select(
         k =>
             string.Join("&", nameValueCollection.GetValues(k).Select(
             v =>
                 string.Format("{0}={1}", HttpUtility.UrlEncode(k), HttpUtility.UrlEncode(v))))));
 }
Beispiel #34
0
 public static string GetFromConfig(NameValueCollection config, string attrName)
 {
     string[] values = config.GetValues(attrName);
     if (values != null && values.Length > 0 && !string.IsNullOrEmpty(values[0]))
         return values[0];
     else
         return (string) null;
 }
Beispiel #35
0
        public void TestNameValueCollectionWithMultipleValuesOnOneKey()
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("a", "value a1");
            nvc.Add("a", "value a2");

            Assert.AreEqual(1, nvc.AllKeys.Count());
            Assert.AreEqual(2, nvc.GetValues("a").Count());
        }
Beispiel #36
0
        public static string GetParameter(Uri requestUri, string keyParam)
        {
            System.Collections.Specialized.NameValueCollection nvp = System.Web.HttpUtility.ParseQueryString(requestUri.OriginalString);

            if (nvp.HasKeys())
            {
                return(nvp.GetValues(keyParam).FirstOrDefault());
            }
            return(null);
        }
Beispiel #37
0
 public static string ExtractValue(string key, NameValueCollection formData)
 {
     if (formData == null) return null;
     if (formData.AllKeys.Contains(key))
     {
         var result = formData.GetValues(key);
         return result == null ? null : result[0];
     }
     return null;
 }
Beispiel #38
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        LVWEIBA.BLL.MemberHotel bllhotel = new LVWEIBA.BLL.MemberHotel();
        System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(Request.Form);
        MemberHotel m = new MemberHotel();

        m.Member = member;
        m.Mobile = nc.GetValues("Mobile")[0].ToString();
        m.Name   = nc.GetValues("hotelname")[0].ToString();
        m.Card   = nc.GetValues("card")[0].ToString();
        m.Type   = nc.GetValues("type")[0].ToString();
        m.Sj     = DateTime.Now;
        int id = bllhotel.GetMaxId();

        if (bllhotel.Add(m) > 0)
        {
            string strhotel = string.Format("<li id='{0}'>{1}<span>{2}</span><i class='iconfont' id='{3}'>&#xe63d;</i></li>", m.Id, m.Name, m.Card, m.Id);
            Literal1.Text += strhotel;
        }
    }
    protected void addContactPerson_Click(object sender, EventArgs e)
    {
        LVWEIBA.BLL.MemberHotel bllhotel = new LVWEIBA.BLL.MemberHotel();
        System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(Request.Form);
        MemberHotel m = new MemberHotel();

        m.Member = member;
        m.Mobile = nc.GetValues("mobile")[0].ToString();
        m.Name   = nc.GetValues("userName")[0].ToString();
        m.Card   = nc.GetValues("identityCard")[0].ToString();
        m.Sj     = DateTime.Now;
        m.Type   = "0";
        int id = bllhotel.GetMaxId();

        if (bllhotel.Add(m) > 0)
        {
            string strhotel = string.Format(" <input id='Checkbox1' name='hotel' checked class='hotel' type='checkbox' value='{0}' />{1}", id, m.Name);
            contactPersonsLiteral.Text += strhotel;
        }
    }
 internal static string[] GetValues(System.Collections.Specialized.NameValueCollection data, string key, string prefix)
 {
     string[] value = data.GetValues(key);
     if (string.IsNullOrEmpty(prefix))
     {
         return(value);
     }
     if (value.Length == 0)
     {
         value = data.GetValues(prefix + "." + key);
     }
     if (value.Length == 0)
     {
         value = data.GetValues(prefix + "_" + key);
     }
     if (value.Length == 0)
     {
         value = data.GetValues(prefix + key);
     }
     return(value);
 }
Beispiel #41
0
    protected void btn_Tj_Click(object sender, EventArgs e)
    {
        openid = Session["openid"].ToString();
        DBCLASSFORWEIXIN.DAL.LocalWeixinUser   ld    = new DBCLASSFORWEIXIN.DAL.LocalWeixinUser();
        DBCLASSFORWEIXIN.Model.LocalWeixinUser wxmdl = ld.GetModel(openid);

        LVWEIBA.BLL.MemberList   mbll = new LVWEIBA.BLL.MemberList();
        LVWEIBA.Model.MemberList mmm  = new LVWEIBA.Model.MemberList();

        System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(Request.Form);
        string txt_user = nc.GetValues("txt_user")[0].ToString();
        string txt_tel  = nc.GetValues("txt_tel")[0].ToString();
        string txt_xm   = nc.GetValues("txt_xm")[0].ToString();
        string txt_card = nc.GetValues("txt_card")[0].ToString();
        string txt_mail = nc.GetValues("txt_mail")[0].ToString();
        string txt_pwd  = nc.GetValues("txt_pwd")[0].ToString();
        string txt_pwd2 = nc.GetValues("txt_pwd2")[0].ToString();

        bool isexists = false;

        if (mbll.Exists(openid))
        {
            mmm      = mbll.GetModel(openid);
            isexists = true;
        }
        wxmdl.nickname = txt_user;
        wxmdl.Tel      = txt_tel;
        mmm.MemberName = txt_xm;
        wxmdl.sex      = int.Parse(ddl_sex.SelectedValue);
        mmm.Card       = txt_card;
        mmm.Mail       = txt_mail;
        mmm.UserPwd    = txt_pwd;
        mmm.UserPwd    = txt_pwd2;
        mmm.MemberId   = openid;
        bool isok = false;

        try
        {
            isok = ld.Update(wxmdl);
            if (isexists)
            {
                isok = mbll.Update(mmm);
            }
            else
            {
                isok = mbll.Add(mmm);
            }
            Response.Write(String.Format("<script>alert('个人信息修改成功');window.location='myindex.aspx';</script>"));
        }
        catch (Exception ex)
        {
            log4netHelper.WriteExceptionLog(typeof(aboutme), "aboutme异常", ex);
        }
    }
Beispiel #42
0
        /// <summary>
        /// Encodes an XML representation for a
        /// <see cref="NameValueCollection" /> object.
        /// </summary>

        private static void Encode(NameValueCollection collection, XmlWriter writer)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (collection.Count == 0)
            {
                return;
            }

            //
            // Write out a named multi-value collection as follows
            // (example here is the ServerVariables collection):
            //
            //      <item name="HTTP_URL">
            //          <value string="/myapp/somewhere/page.aspx" />
            //      </item>
            //      <item name="QUERY_STRING">
            //          <value string="a=1&amp;b=2" />
            //      </item>
            //      ...
            //

            foreach (string key in collection.Keys)
            {
                writer.WriteStartElement("item");
                writer.WriteAttributeString("name", key);

                string[] values = collection.GetValues(key);

                if (values != null)
                {
                    foreach (string value in values)
                    {
                        writer.WriteStartElement("value");
                        writer.WriteAttributeString("string", value);
                        writer.WriteEndElement();
                    }
                }

                writer.WriteEndElement();
            }
        }
Beispiel #43
0
    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        //
        // see if args were passed
        int loop1, loop2;

        BOL = "";
        // Load NameValueCollection object.
        System.Collections.Specialized.NameValueCollection coll = Request.QueryString;
        // Get names of all keys into a string array.
        String[] arr1 = coll.AllKeys;
        for (loop1 = 0; loop1 < arr1.Length; loop1++)
        {
            //Response.Write("Key: " + Server.HtmlEncode(arr1[loop1]) + "<br>");
            String[] arr2 = coll.GetValues(arr1[loop1]);
            for (loop2 = 0; loop2 < arr2.Length; loop2++)
            {
                //Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
            }
            if (arr1[loop1] == "BOL")
            {
                BOL = arr2[0];
            }
        }
        //lblSuccessMessage.Text = "Go PLC" + BOL;
        //FamilyPanel.Update();
        if (BOL != "")
        {
            ViewState["Header"] = "true";
            dtBillLoad.Clear();
            GridVisible(dgBillLoad.ID);
            DataSet ds = ger.GetBOLDetail(BOL);
            dtBillLoad            = ds.Tables[0];
            ViewState["BillData"] = dtBillLoad;
            BindBillData();
            plBillLoad.Update();
            HiddenPassedBOL.Value = BOL;
            DataSet dsGERList       = ger.GetBOLDetailList("BOLNo='" + BOL + "'");
            string  strHeaderValues = dsGERList.Tables[0].Rows[0]["VendNo"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["VendName"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["PFCLocCd"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["PFCLocName"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["BOLNo"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["PortofLading"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["BOLDate"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["VesselName"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["BrokerInvTot"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["RcptTypeDesc"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["ProcDt"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["BrokerInvBOLCount"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["CustomsEntryNo"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["CustomsPortofEntry"].ToString() + "~" + dsGERList.Tables[0].Rows[0]["CustomsEntryDt"].ToString();
            BOLHeader.SetBOLHeaderValues = strHeaderValues;
        }
    }
Beispiel #44
0
    // </snippet20>


    // <snippet21>
    // Displays the header information that accompanied a request.
    public static void DisplayWebHeaderCollection(HttpListenerRequest request)
    {
        System.Collections.Specialized.NameValueCollection headers = request.Headers;
        // Get each header and display each value.
        foreach (string key in headers.AllKeys)
        {
            string[] values = headers.GetValues(key);
            if (values.Length > 0)
            {
                Console.WriteLine("The values of the {0} header are: ", key);
                foreach (string value in values)
                {
                    Console.WriteLine("   {0}", value);
                }
            }
            else
            {
                Console.WriteLine("There is no value associated with the header.");
            }
        }
    }
Beispiel #45
0
        /// <summary>
        /// Retrieve all the parameters from the Request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="excludeParameters">Do not include any parameters from the provided collection</param>
        /// <returns></returns>
        public static IEnumerable <KeyValuePair <string, string> > TupledParameters(Uri requestUri, string[] excludeParameters = null)
        {
            var list = new List <KeyValuePair <string, string> >();

            System.Collections.Specialized.NameValueCollection nvp = System.Web.HttpUtility.ParseQueryString(requestUri.OriginalString);

            if (nvp.HasKeys())
            {
                foreach (string key in nvp.Keys)
                {
                    if (excludeParameters == null || !excludeParameters.Contains(key))
                    {
                        foreach (string val in nvp.GetValues(key))
                        {
                            list.Add(new KeyValuePair <string, string>(key, val));
                        }
                    }
                }
            }
            return(list);
        }
Beispiel #46
0
        /// <summary>
        /// Determines whether the NameValueCollection contains a specific value.
        /// </summary>
        /// <param name="d">The dictionary to check for the value.</param>
        /// <param name="obj">The object to locate in the SortedList.</param>
        /// <returns>Returns true if the value is contained in the NameValueCollection, false otherwise.</returns>
        public static bool ContainsValue(System.Collections.Specialized.NameValueCollection d, Object obj)
        {
            bool contained = false;
            Type type      = d.GetType();

            for (int i = 0; i < d.Count && !contained; i++)
            {
                String[] values = d.GetValues(i);
                if (values != null)
                {
                    foreach (String val in values)
                    {
                        if (val.Equals(obj))
                        {
                            contained = true;
                            break;
                        }
                    }
                }
            }
            return(contained);
        }
        /// <summary>
        /// 生成QueryString
        /// </summary>
        /// <param name="args">键值对</param>
        /// <param name="encoding">URL编码</param>
        /// <returns>生成的QueryString</returns>
        public static string GenerateQueryString(System.Collections.Specialized.NameValueCollection args, Encoding encoding)
        {
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < args.Count; i++)
            {
                string key = args.GetKey(i);
                key = ((key != null) && (key.Length > 0)) ? (HttpUtility.UrlEncode(key, encoding) + "=") : "";

                string[] values = args.GetValues(i);


                if (i > 0)
                {
                    builder.Append("&");
                }

                if (values.Length == 0)
                {
                    builder.Append(key);
                }
                else
                {
                    for (int j = 0; j < values.Length; j++)
                    {
                        if (j > 0)
                        {
                            builder.Append("&");
                        }

                        builder.Append(key);
                        builder.Append(HttpUtility.UrlEncode(values[j], encoding));
                    }
                }
            }

            return(builder.ToString());
        }
Beispiel #48
0
        public static string Serialize(this System.Collections.Specialized.NameValueCollection collection)
        {
            if (collection.Count == 0)
            {
                return(string.Empty);
            }

            StringBuilder str = new();

            str.Append('{');
            foreach (string key in collection.AllKeys)
            {
                bool     isArray = false;
                string[] values  = collection.GetValues(key).Select(a => {
                    string[] temp = a.Split(',');
                    if (temp.Length > 1)
                    {
                        isArray = true;
                    }

                    for (int i = 0; i < temp.Length; i++)
                    {
                        try
                        {
                            if (int.TryParse(temp[i], out int result))
                            {
                                temp[i] = result.ToString();
                            }
                            else if (double.TryParse(temp[i], out double dresult))
                            {
                                temp[i] = dresult.ToString();
                            }
                            else if (float.TryParse(temp[i], out float fresult))
                            {
                                temp[i] = fresult.ToString();
                            }
                            else if (bool.TryParse(temp[i], out bool bresult))
                            {
                                temp[i] = bresult ? "true" : "false";
                            }
                            else
                            {
                                temp[i] = temp[i][0] == '"' && temp[i][temp[i].Length - 1] == '"' ? temp[i] : '"' + temp[i] + '"';
                            }
                        }
                        catch { }
                    }
                    return(string.Join(',', temp));
                }).ToArray();
                if (values.Length == 0)
                {
                    continue;
                }
                else if (isArray)
                {
                    str.Append($"\"{key}\"").Append(':').Append('[')
                    .Append(string.Join(',', values)).Append(']').Append(',');
                }
                else
                {
                    str.Append($"\"{key}\"").Append(':').Append(values[0]).Append(',');
                }
            }
            string w = str.ToString()[..^ 1] + '}';
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        decimal order_Price = int.Parse(hid_price_yh.Value);
        string  order_id    = DateTime.Now.ToString("yyyyMMdd") + "0000" + "MP" + BaseClass.Common.Common.getSuijiString(2);

        //明细
        LVWEIBA.Model.order_Mx modelMx = null;

        LVWEIBA.BLL.order_Mx bllMx = new LVWEIBA.BLL.order_Mx();
        modelMx                   = new LVWEIBA.Model.order_Mx();
        modelMx.order_id          = order_id;
        modelMx.productNum        = hid_ticket_id.Value;
        modelMx.market_price      = int.Parse(hid_price_sc.Value); //市场价
        modelMx.Transaction_price = int.Parse(hid_price_yh.Value); //优惠价
        modelMx.Transfer_price    = int.Parse(hid_price_jj.Value); //交接价
        modelMx.ProCount          = int.Parse(this.hid_count.Value);
        //商品类型(电子票)
        modelMx.ProType = "DZP";
        //成人和小孩数量(门票默认为0)
        modelMx.adultCount = 0;
        modelMx.puppyCount = 0;

        bllMx.Add(modelMx);

        //订单
        LVWEIBA.Model.order_list model = new LVWEIBA.Model.order_list();
        model.order_id    = order_id;
        model.user_id     = member;
        model.order_sj    = DateTime.Now;
        model.order_zt    = "DZF";//待支付
        model.order_Price = order_Price;
        model.bz          = HiddenFieldBZ.Value;

        LVWEIBA.BLL.order_list bll = new LVWEIBA.BLL.order_list();
        if (bll.Add(model))
        {        //给订单添加旅客信息
            System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection(Request.Form);
            string[] arrhotel = nc.GetValues("hotel");
            LVWEIBA.BLL.MemberHotelMx bllhotel = new LVWEIBA.BLL.MemberHotelMx();
            if (arrhotel != null && arrhotel.Length > 0)
            {
                for (int i = 0; i < arrhotel.Length; i++)
                {
                    if (arrhotel[i] == "")
                    {
                        break;
                    }
                    MemberHotelMx m = new MemberHotelMx();
                    m.Member  = member;
                    m.OrderID = order_id;
                    m.Hotel   = int.Parse(arrhotel[i]);
                    m.Sj      = DateTime.Now;
                    bllhotel.Add(m);
                }
            }
            else
            {
                Jscript.NorefLocation(this.Page, "请选择联系用户!", "showTicket.aspx");
            }
            //1代表门票0代表尾单
            Response.Redirect("indent_pay.aspx?ddbm=" + order_id + "&lineid=" + ViewState["ticketId"] + "&type='mp'");
        }
    }
Beispiel #50
0
        private static void Member(JsonTextWriter writer, string name, NameValueCollection collection)
        {
            Debug.Assert(writer != null);
            Debug.AssertStringNotEmpty(name);

            //
            // Bail out early if the collection is null or empty.
            //

            if (collection == null || collection.Count == 0)
            {
                return;
            }

            //
            // Save the depth, which we'll use to lazily emit the collection.
            // That is, if we find that there is nothing useful in it, then
            // we could simply avoid emitting anything.
            //

            int depth = writer.Depth;

            //
            // For each key, we get all associated values and loop through
            // twice. The first time round, we count strings that are
            // neither null nor empty. If none are found then the key is
            // skipped. Otherwise, second time round, we encode
            // strings that are neither null nor empty. If only such string
            // exists for a key then it is written directly, otherwise
            // multiple strings are naturally wrapped in an array.
            //

            foreach (string key in collection.Keys)
            {
                string[] values = collection.GetValues(key);

                if (values == null || values.Length == 0)
                {
                    continue;
                }

                int count = 0; // Strings neither null nor empty.

                for (int i = 0; i < values.Length; i++)
                {
                    string value = values[i];
                    if (value != null && value.Length > 0)
                    {
                        count++;
                    }
                }

                if (count == 0) // None?
                {
                    continue;   // Skip key
                }
                //
                // There is at least one value so now we emit the key.
                // Before doing that, we check if the collection member
                // was ever started. If not, this would be a good time.
                //

                if (depth == writer.Depth)
                {
                    writer.Member(name);
                    writer.Object();
                }

                writer.Member(key);

                if (count > 1)
                {
                    writer.Array(); // Wrap multiples in an array
                }
                for (int i = 0; i < values.Length; i++)
                {
                    string value = values[i];
                    if (value != null && value.Length > 0)
                    {
                        writer.String(value);
                    }
                }

                if (count > 1)
                {
                    writer.Pop();   // Close multiples array
                }
            }

            //
            // If we are deeper than when we began then the collection was
            // started so we terminate it here.
            //

            if (writer.Depth > depth)
            {
                writer.Pop();
            }
        }
Beispiel #51
0
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // elab cmd
        if (!IsPostBack)
        {
            html_blocks hb = new html_blocks();

            StringBuilder sb = new StringBuilder();
            try {
                string cmd = qry_val("cmd");
                if (string.IsNullOrEmpty(cmd))
                {
                    return;
                }

                deepanotes.cmd c = master.check_cmd(cmd);
                if (c == null)
                {
                    throw new Exception("Comando '" + cmd + "' non riconosciuto!");
                }

                // filtro type
                if (c.type != "" && !c.type.Split(new char[] { ',' }).Contains(_user.type.ToString()))
                {
                    throw new Exception("Comando '" + cmd + "' non riconosciuto!");
                }

                // page
                if (!string.IsNullOrEmpty(c.page))
                {
                    master.redirect_to(c.page); return;
                }

                if (c.action == "view" && c.obj == "cmds")
                {
                    foreach (config.table_row gr in _core.config.get_table("cmds.cmds-groups").rows_ordered("title"))
                    {
                        StringBuilder sb2 = null;
                        foreach (config.table_row tr in _core.config.get_table("cmds.base-cmds")
                                 .rows_ordered("action", "object", "subobj").Where(r => r.field("group") == gr.field("name")))
                        {
                            // filtro type
                            string type = tr.field("type");
                            if (type != "" && !type.Split(new char[] { ',' }).Contains(_user.type.ToString()))
                            {
                                continue;
                            }

                            // gruppo
                            if (sb2 == null)
                            {
                                sb.Append(hb.section_title(gr.field("title"), gr.field("des")));
                                sb2 = new StringBuilder(hb.open_list());
                            }

                            // comando
                            bool   action_opt = tr.fld_bool("action-opt");
                            string action = !action_opt?tr.field("action") : string.Format("<i>[{0}]</i>", tr.field("action"))
                                                , cc = action + " " + tr.field("object") + (tr.field("subobj") != "" ? " " + tr.field("subobj") : "")
                                                , cc_ref = tr.field("action") + " " + tr.field("object") + (tr.field("subobj") != "" ? " " + tr.field("subobj") : "")
                                                , href = "", syns = tr.field("syn-object") != "" ? string.Join(", ", tr.field("syn-object").Split(new char[] { ',' })
                                                                                                               .Select(x => action + " " + x + (tr.field("subobj") != "" ? " " + tr.field("subobj") : ""))) : "";

                            if (tr.fld_bool("call"))
                            {
                                href = get_url_cmd(cc_ref);
                            }
                            else if (tr.fld_bool("compile"))
                            {
                                href = "javascript:compile('" + cc.Replace("'", "") + "')";
                            }

                            sb2.Append(hb.list_item(cc, href: href, sub_items: new string[] { syns != "" ? "sinonimi: " + syns : ""
                                                                                              , action_opt ? "<p class='mt-1'><u>nota: l'azione è facoltativa</u></p>" : "", tr.field("des") }));
                        }
                        if (sb2 != null)
                        {
                            sb2.Append(hb.close_list()); sb.Append(sb2);
                        }
                    }
                }
                else if (c.action == "exit")
                {
                    log_out("login.aspx");
                }
                else if (c.action == "crypt")
                {
                    if (!string.IsNullOrEmpty(c.obj) && !string.IsNullOrEmpty(c.sub_obj()))
                    {
                        sb.AppendFormat(@"<span class='h1'><span class='badge badge-primary d-block' style='white-space:normal;font-weight:normal;'>parola criptata</span></span>
              <input type='text' class='form-control mt-3' value=""{0}"">", cry.encrypt(c.obj, c.sub_obj()));
                    }
                    else if (!string.IsNullOrEmpty(c.obj))
                    {
                        sb.AppendFormat(@"<span class='h1'><span class='badge badge-primary d-block' style='white-space:normal;font-weight:normal;'>parola criptata</span></span>
              <input type='text' class='form-control mt-3' value=""{0}"">", cry.encode_tobase64(c.obj));
                    }
                }
                else if (c.action == "decrypt")
                {
                    if (!string.IsNullOrEmpty(c.obj) && !string.IsNullOrEmpty(c.sub_obj()))
                    {
                        sb.AppendFormat(@"<span class='h3'><span class='badge badge-primary d-block' style='white-space:normal;font-weight:normal;'>parola de-criptata</span></span>
              <input type='text' style='width:100%' value=""{0}"">", cry.decrypt(c.obj, c.sub_obj()));
                    }
                }
                else if (c.action == "check" && c.obj == "conn")
                {
                    string err = ""; bool ok = false; try { ok = db_reconn(true); } catch (Exception ex) { err = ex.Message; }
                    sb.AppendFormat("<h3 style='color:white;text-transform:uppercase;background-color:royalblue;'>Check DB connection</h3>");
                    sb.Append("<div class='list-group'>");
                    string row = @"<a class='list-group-item list-group-item-action flex-column align-items-start'>
            <div class='d-flex w-90 justify-content-between'>
              <h5 class='mb-1'>{0}</h5></div><p class='mb-1'>{1}</p></a>";
                    sb.AppendFormat(row, "Provider", cfg_conn.provider);
                    sb.AppendFormat(row, "Stringa di connessione", cfg_conn.conn_string.Replace(";", "; "));
                    sb.AppendFormat(row, "Data format", cfg_conn.date_format);
                    sb.Append("</div><div style='height:40px;'>&nbsp;</div>");
                    sb.AppendFormat(@"<h3 style='text-transform: uppercase;'>
            <span class='badge badge-{1} d-block' style='white-space:normal;'>{0}</span></h3>"
                                    , ok ? "CONNESSIONE AVVENUTA CON SUCCESSO" : "CONNESSIONE NON AVVENUTA!"
                                    , ok ? "success" : "warning");

                    if (err != "")
                    {
                        sb.AppendFormat(@"<h3 style='text-transform: uppercase;'>
            <span class='badge badge-danger d-block' style='white-space:normal;'>{0}</span></h3>", err);
                    }
                }
                else if (c.action == "view" && c.obj == "vars")
                {
                    sb.AppendFormat("<h3 style='color:white;text-transform:uppercase;background-color:royalblue;'>Variabili di sistema</h3>");
                    sb.Append("<div class='list-group'>");
                    string row_var = "<li class='list-group-item'><b style='text-transform: uppercase;'>{0}</b>: {1}</li>";
                    sb.AppendFormat(row_var, "machine name", sys.machine_name());
                    sb.AppendFormat(row_var, "machine ip", sys.machine_ip());
                    sb.Append("</div>");

                    // browser capabilities
                    System.Web.HttpBrowserCapabilities browser = Request.Browser;
                    sb.AppendFormat(@"<div style='height:40px;'>&nbsp;</div>
            <h3 style='color:white;text-transform:uppercase;background-color:royalblue;'>Browser Capabilities</h3>");
                    sb.Append("<div class='list-group'>");
                    sb.AppendFormat(row_var, "Type", browser.Type);
                    sb.AppendFormat(row_var, "Name", browser.Browser);
                    sb.AppendFormat(row_var, "Version", browser.Version);
                    sb.AppendFormat(row_var, "Major Version", browser.MajorVersion);
                    sb.AppendFormat(row_var, "Minor Version", browser.MinorVersion);
                    sb.AppendFormat(row_var, "Platform", browser.Platform);
                    sb.AppendFormat(row_var, "Is Beta", browser.Beta);
                    sb.AppendFormat(row_var, "Is Crawler", browser.Crawler);
                    sb.AppendFormat(row_var, "Is AOL", browser.AOL);
                    sb.AppendFormat(row_var, "Is Win16", browser.Win16);
                    sb.AppendFormat(row_var, "Is Win32", browser.Win32);
                    sb.AppendFormat(row_var, "Supports Frames", browser.Frames);
                    sb.AppendFormat(row_var, "Supports Tables", browser.Tables);
                    sb.AppendFormat(row_var, "Supports Cookies", browser.Cookies);
                    sb.AppendFormat(row_var, "Supports VBScript", browser.VBScript);
                    sb.AppendFormat(row_var, "Supports JavaScript", browser.EcmaScriptVersion.ToString());
                    sb.AppendFormat(row_var, "Supports Java Applets", browser.JavaApplets);
                    sb.AppendFormat(row_var, "Supports ActiveX Controls", browser.ActiveXControls);
                    sb.AppendFormat(row_var, "Supports JavaScript Version", browser["JavaScriptVersion"]);
                    sb.Append("</div>");

                    // server variables
                    sb.AppendFormat(@"<div style='height:40px;'>&nbsp;</div>
            <h3 style='color:white;text-transform:uppercase;background-color:royalblue;'>Server Variables</h3>");
                    sb.Append("<div class='list-group'>");
                    System.Collections.Specialized.NameValueCollection coll = Request.ServerVariables;
                    String[] arr1 = coll.AllKeys;
                    for (int loop1 = 0; loop1 < arr1.Length; loop1++)
                    {
                        string val = ""; String[] arr2 = coll.GetValues(arr1[loop1]);
                        for (int loop2 = 0; loop2 < arr2.Length; loop2++)
                        {
                            val += (loop2 > 0 ? ", " : "") + Server.HtmlEncode(arr2[loop2]);
                        }
                        sb.AppendFormat(row_var, "Key - " + arr1[loop1], val);
                    }
                    sb.Append("</div>");

                    // db factories
                    sb.AppendFormat(@"<div style='height:40px;'>&nbsp;</div>
            <h3 style='color:white;text-transform:uppercase;background-color:royalblue;'>Db Factory classes</h3>");

                    sb.Append("<ul class='list-group'>");
                    foreach (DataRow dr in System.Data.Common.DbProviderFactories.GetFactoryClasses().Rows)
                    {
                        sb.AppendFormat(@"<li class='list-group-item' style='padding-left:5px;border-right:0px;padding-right:0px;'>
              <h5 style='text-transform: uppercase;'>{0}&nbsp;<small>{1}</small></h5></li>"
                                        , dr["NAME"].ToString(), dr["DESCRIPTION"].ToString());
                        sb.Append("<ul class='list-group'>");
                        foreach (DataColumn col in dr.Table.Columns)
                        {
                            if (col.ColumnName.ToLower() != "name" && col.ColumnName.ToLower() != "description" &&
                                dr[col.ColumnName] != DBNull.Value)
                            {
                                sb.AppendFormat(row_var, col.ColumnName, dr[col.ColumnName].ToString());
                            }
                        }
                        sb.Append("</ul>");
                    }
                    sb.Append("</ul>");
                }
                else if (c.action == "view" && c.obj == "logs")
                {
                    sb.AppendFormat("<div class='list-group'>");
                    string fn = log.file_name();
                    if (!string.IsNullOrEmpty(fn))
                    {
                        string dir = Path.GetDirectoryName(fn);
                        if (Directory.Exists(dir))
                        {
                            foreach (file f in file.dir(dir, "*" + Path.GetExtension(fn), true))
                            {
                                sb.AppendFormat(@"<a class='list-group-item list-group-item-action flex-column align-items-start' href=""{2}"">
                  <div class='d-flex w-90 justify-content-between'>
                    <h5 class='mb-1'>{0}</h5></div>
                  <p class='mb-1'>{1}</p></a>", f.file_name
                                                , "data: " + f.lw.ToString("yyyy/MM/dd") + ", size: " + ((int)(f.size / 1024)).ToString("N0", new System.Globalization.CultureInfo("it-IT")) + " Kb"
                                                , master.url_cmd("view log '" + f.file_name + "'"));
                            }
                        }
                        sb.AppendFormat("</div>");
                    }
                    else
                    {
                        throw new Exception("NON È IMPOSTATO IL LOG!");
                    }
                }
                else if (c.action == "view" && c.obj == "log")
                {
                    view_log(Path.Combine(log.dir_path(), c.sub_obj()), sb);
                }
                else if (c.action == "view" && c.obj == "log-today")
                {
                    view_log(log.file_name(), sb);
                }
                else
                {
                    throw new Exception("COMANDO NON RICONOSCIUTO!");
                }
            } catch (Exception ex) {
                master.err_txt(ex.Message);
            }
            div_contents.InnerHtml = sb.ToString();
        }
    }