Пример #1
0
        public async Task Handle(OnlinePushEvent p_event)
        {
            StringCache sc = new StringCache(p_event.PrefixKey);

            if (p_event.Receivers != null && p_event.Receivers.Count > 0)
            {
                foreach (var id in p_event.Receivers)
                {
                    if (Online.All.TryGetValue(id, out var ls) &&
                        ls != null &&
                        ls.Count > 0)
                    {
                        // 在线推送,直接放入推送队列
                        if (p_event.PushFirstSession)
                        {
                            ls[0].AddMsg(p_event.Msg);
                            await sc.Set(null, true);
                        }
                        else
                        {
                            foreach (var ci in ls)
                            {
                                ci.AddMsg(p_event.Msg);
                            }

                            // 设置处理标志: msg:Push:6位id前缀:userid = true
                            await sc.Set(id, true);
                        }
                    }
                }
            }
            // 统计总数+1
            await sc.Increment("cnt");
        }
Пример #2
0
        public async Task <string> CacheStr(string p_key, string p_val)
        {
            var cache = new StringCache("Test:Str");
            await cache.Set(p_key, p_val);

            return(await cache.Get <string>(p_key));
        }
Пример #3
0
        /// <summary>
        /// Insert a ingle row
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connection"></param>
        /// <param name="param">object</param>
        /// <param name="table">Optional table name</param>
        /// <param name="commandTimeout">commandTimeout</param>
        /// <param name="transaction">transaction</param>
        /// <returns>Numbers of rows affected</returns>
        public static int InsertSingle <T>(this IDbConnection connection, T param, int?commandTimeout = null, IDbTransaction transaction = null)
        {
            if (param == null)
            {
                throw new ArgumentNullException("param can not be null.");
            }

            if (param is IEnumerable)
            {
                throw new ArgumentException("param can not be a IEnumerable. Call InsertMany instead.");
            }

            var type = typeof(T);

            string cachedCommand;
            var    value = StringCache.TryGetCommand(type, Operation.Insert, out cachedCommand);

            if (string.IsNullOrEmpty(cachedCommand))
            {
                cachedCommand = InsertGenerator.GenerateSingle(param);
                StringCache.Add(type, Operation.Insert, cachedCommand);
            }

            return(connection.Execute(cachedCommand, param, commandTimeout: commandTimeout, transaction: transaction));
        }
Пример #4
0
        public void GetOrAdd_DisposesReleasedReferencesOnExpand()
        {
            // Arrange
            var cache = new StringCache(2);

            // Act
            StringArea();

            // Force a collection
            GC.Collect();
            var str1   = $"{1}";
            var result = cache.GetOrAddValue(str1);

            // Assert
            Assert.Equal(1, cache.ApproximateSize);
            Assert.Same(result, str1);

            void StringArea()
            {
                var first = $"{1}";
                var test  = cache.GetOrAddValue(first);

                Assert.Same(first, test);
                Assert.Equal(1, cache.ApproximateSize);
                GC.KeepAlive(first);
            }
        }
Пример #5
0
        public BindingEntry(int errorCode, Match match, StringCache stringCache)
        {
            this.stringCache = stringCache;
            this.ErrorCode   = errorCode;
            this.Count       = 1;

            if (Constants.IsXamlDesigner)
            {
                this.Description        = nameof(this.Description);
                this.SourceProperty     = nameof(this.SourceProperty);
                this.SourcePropertyType = nameof(this.SourcePropertyType);
                this.SourcePropertyName = nameof(this.SourcePropertyName);
                this.BindingPath        = nameof(this.BindingPath);
                this.DataItemType       = nameof(this.DataItemType);
                this.DataItemName       = nameof(this.DataItemName);
                this.TargetElementType  = nameof(this.TargetElementType);
                this.TargetElementName  = nameof(this.TargetElementName);
                this.TargetProperty     = nameof(this.TargetProperty);
                this.TargetPropertyType = nameof(this.TargetPropertyType);
            }
            else
            {
                this.Description        = stringCache.Get(match.Value);
                this.SourceProperty     = stringCache.Get(match.Groups[nameof(this.SourceProperty)].Value);
                this.SourcePropertyType = stringCache.Get(match.Groups[nameof(this.SourcePropertyType)].Value);
                this.SourcePropertyName = stringCache.Get(match.Groups[nameof(this.SourcePropertyName)].Value);
                this.BindingPath        = stringCache.Get(match.Groups[nameof(this.BindingPath)].Value);
                this.DataItemType       = stringCache.Get(match.Groups[nameof(this.DataItemType)].Value);
                this.DataItemName       = stringCache.Get(match.Groups[nameof(this.DataItemName)].Value);
                this.TargetElementType  = stringCache.Get(match.Groups[nameof(this.TargetElementType)].Value);
                this.TargetElementName  = stringCache.Get(match.Groups[nameof(this.TargetElementName)].Value);
                this.TargetProperty     = stringCache.Get(match.Groups[nameof(this.TargetProperty)].Value);
                this.TargetPropertyType = stringCache.Get(match.Groups[nameof(this.TargetPropertyType)].Value);
            }
        }
Пример #6
0
        public static void ExecuteAsync(
            string cacheKey,
            string queueName,
            string executeable
            )
        {
            // Get Cache to see if we already did this
            var cachedValues = StringCache.getCache(cacheKey);

            if (cachedValues == null)
            {
                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results = executeable;
                            StringCache.setCache(cacheKey, results);
                        }
                        catch (Exception e)
                        {
                            //StringCache.AppendCache(this.InstanceGuid.ToString(), e.ToString() + "\n");
                        }

                        StringCache.setCache(queueName, "");
                    });
                    //ExpireSolution(true);
                }
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var launch = false;

            if (!DA.GetData(0, ref launch))
            {
                return;
            }
            DA.DisableGapLogic();
            const string url = "https://energyplus.net/weather";

            if (launch)
            {
                QueueManager.addToQueue(url, () =>
                {
                    try
                    {
                        Process.Start(url);
                    }
                    catch (Exception e)
                    {
                        StringCache.setCache(InstanceGuid.ToString(), e.Message);
                    }
                });
            }

            var errors = StringCache.getCache(InstanceGuid.ToString());

            if (errors != null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errors);
            }
        }
        /// <summary>
        /// UploadXML in string string Cache
        /// </summary>
        /// <param name="companyCode"></param>
        /// <param name="userId"></param>
        /// <param name="fnolParametersXml"></param>
        /// <param name="serviceName"></param>
        private static void UploadXML(string companyCode, string userId, string fnolParametersXml, string serviceName)
        {
            string message             = string.Empty;
            string zippedfnolXmlString = string.Empty;
            string stringCachekey      = string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(companyCode) && !string.IsNullOrEmpty(fnolParametersXml))
                {
                    //creating string cache key
                    stringCachekey = companyCode.ToUpper() + "_" + userId.ToUpper() + "_" + serviceName.ToUpper();
                    StringCache stringCache = new StringCache();
                    zippedfnolXmlString = FNOLHelper.GZip(fnolParametersXml);
                    stringCache.SetString(stringCachekey, cacheVersion, zippedfnolXmlString);
                }
                else
                {
                    throw new Exception("Either Company Code or User Id is empty.");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #9
0
        public void GetOrAdd(string input)
        {
            StringCache stringCache = new StringCache();
            string      added       = stringCache.GetOrAdd(input);

            Assert.AreEqual(added, input);
        }
Пример #10
0
        public void SetUp()
        {
            containingObject = new GameObject();
#pragma warning disable 0618
            subject = containingObject.AddComponent <StringCache>();
#pragma warning restore 0618
        }
Пример #11
0
        private void PollDownloadContent(
            string inputJson,
            string downloadPath,
            string localPath,
            string overrides,
            bool reload,
            string cacheKey
            )
        {
            var queueName = "Download" + cacheKey;

            // Get queue lock
            var queueLock  = StringCache.getCache(queueName);
            var downloaded = false;
            var inputData  = new Inputs().FromJson(inputJson);

            if (reload)
            {
                StringCache.setCache(InstanceGuid.ToString(), "");
            }

            if (queueLock != "true" && inputData.Task != null)
            {
                StringCache.setCache(queueName, "true");
                StringCache.setCache(cacheKey, null);
                QueueManager.addToQueue(queueName, () => {
                    try
                    {
                        while (!downloaded)
                        {
                            StringCache.setCache(cacheKey + "progress", "Downloading...");
                            ExpireSolutionThreadSafe(true);

                            downloaded = DownloadContent.Download(inputJson, downloadPath, localPath, overrides);
                            StringCache.setCache(cacheKey, downloaded.ToString());

                            if (!downloaded)
                            {
                                StringCache.setCache(cacheKey + "progress", "Waiting for results...");
                                ExpireSolutionThreadSafe(true);
                                Thread.Sleep(60000);
                            }
                            else
                            {
                                StringCache.setCache(cacheKey + "progress", "Downloaded files");
                            }
                            ExpireSolutionThreadSafe(true);
                        }
                    }
                    catch (Exception e)
                    {
                        StringCache.setCache(InstanceGuid.ToString(), e.Message);
                        StringCache.setCache(cacheKey, "error");
                    }
                    ExpireSolutionThreadSafe(true);
                    Thread.Sleep(2000);
                    StringCache.setCache(queueName, "");
                });
            }
        }
Пример #12
0
        internal RouteHandler Find(string httpMethod, char[] buffer, int len, out RouteMatch routeMatch)
        {
            RouteHandler handler;
            var          reqHash = StringCache.CalcHash(httpMethod, buffer, len);
            int          askSign = -1;

            for (int i = 0; i < len; i++)
            {
                if (buffer[i] == '?')
                {
                    askSign = i;
                    break;
                }
            }
            if (askSign == -1 && Cache.TryGetValue(reqHash, out handler))
            {
                if (handler.Pattern.IsStatic)
                {
                    routeMatch = handler.Pattern.ExtractMatch(handler.Url, 0);
                    return(handler);
                }
            }
            var rawUrl = new string(buffer, 0, len);

            return(FindRoute(httpMethod, rawUrl, reqHash, out routeMatch));
        }
Пример #13
0
        public void GetOrAdd(string?input)
        {
            var stringCache = new StringCache();
            var added       = stringCache.GetOrAdd(input);

            Assert.AreEqual(added, input);
        }
Пример #14
0
        public void StringCacheRemembersItemsUniquely()
        {
            StringCache cache = new StringCache(2000000, 10);

            cache.Add(key0, value0);
            cache.Add(key1, value1);
            cache.Add(key2, value2);
            cache.Add(key3, value3);
            Assert.AreEqual(value0, cache.Get(key0));
            Assert.AreEqual(value1, cache.Get(key1));
            Assert.AreEqual(value2, cache.Get(key2));
            Assert.AreEqual(value3, cache.Get(key3));

            // Test unmapped inputs
            Assert.IsNull(cache.Get(null));
            Assert.IsNull(cache.Get(""));
            Assert.IsNull(cache.Get("I Do Not Exist as a Key"));

            // Test that null can be used as a key or as a value
            cache.Add(null, "I'm with null");
            cache.Add("I have a null value", null);
            Assert.AreEqual("I'm with null", cache.Get(null));
            Assert.IsNull(cache.Get("I have a null value"));

            // Test that null can be used as a key and as a value
            cache.Add(null, null);
            Assert.IsNull(cache.Get(null));

            // Test that adding a key after failing to retrieve it causes correct behavior
            cache.Add("", "I am a new value");
            Assert.AreEqual("I am a new value", cache.Get(""));
        }
Пример #15
0
        public async Task <long> CacheLong(string p_key, long p_val)
        {
            var cache = new StringCache("Test:Long");
            await cache.Set(p_key, p_val);

            return(await cache.Get <long>(p_key));
        }
Пример #16
0
        public void GetStringCachingMultipleStrings()
        {
            string[] expected = new[]
            {
                "Hello",
                "hello",
                "World",
                "World ",
                "foo",
                "bar",
                "baz",
                "qux",
                "0",
                "1",
                " ",
                String.Empty,
            };
            string[] actual = new string[expected.Length];

            for (int i = 0; i < expected.Length; ++i)
            {
                byte[] buffer = Encoding.Unicode.GetBytes(expected[i]);
                actual[i] = StringCache.GetString(buffer, 0, buffer.Length);
                Assert.AreEqual(expected[i], actual[i], "First conversion is incorrect");
            }

            for (int i = 0; i < expected.Length; ++i)
            {
                byte[] buffer = Encoding.Unicode.GetBytes(expected[i]);
                string cached = StringCache.GetString(buffer, 0, buffer.Length);
                Assert.AreEqual(expected[i], cached, "Cached value is incorrect");
                Assert.AreSame(actual[i], cached, "Value {0} was not cached", expected[i]);
            }
        }
Пример #17
0
        public void GetStringCaching()
        {
            byte[] buffer = Encoding.Unicode.GetBytes("Hello");
            string s1     = StringCache.GetString(buffer, 0, buffer.Length);
            string s2     = StringCache.GetString(buffer, 0, buffer.Length);

            Assert.AreSame(s1, s2);
        }
Пример #18
0
        public void GetOrAdd_NullReturnsNull()
        {
            // Arrange
            var cache = new StringCache();

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => cache.GetOrAddValue(null));
        }
Пример #19
0
        /// <summary>
        /// Adds the string point.
        /// </summary>
        /// <param name="stringCache">The string cache.</param>
        /// <param name="index">The index.</param>
        /// <param name="stringPointNumericVal">The string point numeric val.</param>
        protected static void AddStringPoint(StringCache stringCache, int index, string stringPointNumericVal)
        {
            StringPoint stringPoint = new StringPoint();

            stringPoint.Index        = new UInt32Value((uint)index);
            stringPoint.NumericValue = new NumericValue(stringPointNumericVal);
            stringCache.Append(stringPoint);
        }
Пример #20
0
 public Search(IEnumerable <TreeNode> roots, IEnumerable <string> strings, int maxResults, bool markResultsInTree, StringCache stringTable = null)
 {
     this.roots             = roots;
     this.strings           = strings;
     this.maxResults        = maxResults;
     this.markResultsInTree = markResultsInTree;
     this.stringTable       = stringTable;
 }
Пример #21
0
 public void Adds_and_retrieves_short_content_safely()
 {
     const string input = "This will not compress";
     var cache = new StringCache();
     var added = cache.Add("short", input);
     Assert.IsTrue(added);
     var retrieved = cache.Get("short");
     Assert.AreEqual(input, retrieved);
 }
 public BindingPaneViewModel(Telemetry telemetry, StringCache stringCache)
 {
     this.Telemetry                  = telemetry;
     this.stringCache                = stringCache;
     this.countedEntries             = new HashSet <ICountedTableEntry>(new CountedTableEntryComparer());
     this.entries                    = new ObservableCollection <ITableEntry>();
     this.entries.CollectionChanged += this.OnEntryCollectionChanged;
     this.traceLevel                 = nameof(SourceLevels.Error);
 }
Пример #23
0
        //public override GH_Exposure Exposure => GH_Exposure.hidden;

        //public override bool Obsolete => true;

        protected void HandleErrors()
        {
            var errors = StringCache.getCache(InstanceGuid.ToString());

            if (!string.IsNullOrEmpty(errors))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errors);
            }
        }
Пример #24
0
 private void Init(int bufferSize)
 {
     _max    = bufferSize - 1;
     _starts = new int[bufferSize];
     _lens   = new int[bufferSize];
     if (_tagCache == null)
     {
         _tagCache = new StringCache(); // unit testing
     }
 }
Пример #25
0
        public RouteMatch?Find(string httpMethod, string rawUrl, string absolutePath, out RouteHandler handler)
        {
            var reqHash = StringCache.CalcHash(httpMethod, absolutePath);

            if (Cache.TryGetValue(reqHash, out handler))
            {
                return(handler.Pattern.ExtractMatch(rawUrl, handler.Service.Length));
            }
            return(FindRoute(httpMethod, rawUrl, reqHash, out handler));
        }
Пример #26
0
        public void ClearStrCache()
        {
            var cache = new StringCache("Test:Str");
            int cnt   = cache.Count();

            if (cnt > 0)
            {
                cache.Clear();
            }
        }
Пример #27
0
        public void VerifyLongStringIsNotCached()
        {
            string expected = Any.StringOfLength(8192);

            byte[] buffer = Encoding.Unicode.GetBytes(expected);
            string actual = StringCache.GetString(buffer, 0, buffer.Length);

            Assert.AreEqual(expected, actual);
            Assert.AreNotSame(actual, StringCache.GetString(buffer, 0, buffer.Length));
        }
Пример #28
0
 public void GetStringCachingRandomStrings()
 {
     for (int i = 0; i < 250000; ++i)
     {
         string expected = Any.String;
         byte[] buffer   = Encoding.Unicode.GetBytes(expected);
         string actual   = StringCache.GetString(buffer, 0, buffer.Length);
         Assert.AreEqual(expected, actual);
         Assert.AreSame(actual, StringCache.GetString(buffer, 0, buffer.Length));
     }
 }
Пример #29
0
        public BindingEntryParser(StringCache stringCache)
        {
            this.stringCache = stringCache;

            this.processTextRegex = new Regex(@"^System.Windows.Data Error: (?<code>\d+) : (?<text>.+?)$",
                                              RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.Singleline | RegexOptions.Multiline);

            // BindingEntryType.PathError
            this.pathErrorRegex = new Regex($@"BindingExpression path error: '(?<{nameof(BindingEntry.SourceProperty)}>.+?)' property not found on '(object|current item of collection)' '{BindingEntryParser.CaptureItem(nameof(BindingEntry.SourcePropertyType), nameof(BindingEntry.SourcePropertyName))}'. BindingExpression:Path=(?<{nameof(BindingEntry.BindingPath)}>.+?); DataItem={BindingEntryParser.CaptureItem(nameof(BindingEntry.DataItemType), nameof(BindingEntry.DataItemName))}; target element is {BindingEntryParser.CaptureItem(nameof(BindingEntry.TargetElementType), nameof(BindingEntry.TargetElementName))}; target property is '(?<{nameof(BindingEntry.TargetProperty)}>.+?)' \(type '(?<{nameof(BindingEntry.TargetPropertyType)}>.+?)'\)",
                                            RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
        }
        // used for last string from console text
        static string tryCompleteString(string str, StringCache stringCache)
        {
            var matched = stringCache.findByPrefix(str);

            if (matched.Count > 1)
            {
                showMessages(matched, L10n.str("ids_matched"));
            }

            return(getCommonPrefix(matched, str));
        }
Пример #31
0
        /// <summary>
        /// Modify/Add series into chart XML
        /// </summary>
        /// <param name="column_index">Corresponds to the column index that needs to be modified in chart spreadsheet (Ex: A, B, C, ...)</param>
        /// <param name="row_index">Corresponds to the column index that needs to be modified in excel </param>
        /// <param name="new_value">Corresponds to the new value we need to insert to the cell </param>
        protected override void ModifyChartXML_Series(string column_index, uint row_index, string new_value)
        {
            LineChartSeries linechart_series = chart_part.ChartSpace.Descendants <LineChartSeries>().Where(s => string.Compare(s.InnerText, worksheet_name + "!$" + column_index + "$1", true) > 0).FirstOrDefault();

            if (linechart_series != null)    // There exists data on the series --> We only need to modify it
            {
                SeriesText      st = linechart_series.Descendants <SeriesText>().FirstOrDefault();
                StringReference sr = st.Descendants <StringReference>().First();
                StringCache     sc = sr.Descendants <StringCache>().First();
                StringPoint     sp = sc.Descendants <StringPoint>().First();
                NumericValue    nv = sp.Descendants <NumericValue>().First();
                nv.Text = new_value;
            }
            else    // No such series exists --> Consider create a new series
            {
                /*
                 * // Find location in XML to append the BarChartSeries
                 * Chart chart = chart_part.ChartSpace.Descendants<Chart>().FirstOrDefault();
                 * PlotArea plot = chart.PlotArea;
                 *
                 * // Create new BarChartSeries
                 * barchart_series = new BarChartSeries();
                 * uint index = (uint)plot.Descendants<BarChartSeries>().ToList().Count;
                 *
                 * barchart_series.Append(new Index() { Val = index });
                 * barchart_series.Append(new Order() { Val = index });
                 *
                 * SeriesText seriesText = new SeriesText();
                 * seriesText.Append(new NumericValue() { Text = new_value });
                 *
                 * barchart_series.Append(seriesText);
                 *
                 *
                 * // Append data
                 * Bar3DChart bar_3dchart = plot.Descendants<Bar3DChart>().FirstOrDefault();
                 * if (bar_3dchart != null)       // Chart is 3D
                 *  bar_3dchart.Append(barchart_series);
                 * else    // Chart is not 3d
                 * {
                 *  BarChart barchart = plot.Descendants<BarChart>().FirstOrDefault();
                 *  barchart.Append(barchart_series);
                 * }
                 *
                 * // Append other settings
                 * BarChartSeries barchart_series_template = chart_part.ChartSpace.Descendants<BarChartSeries>().LastOrDefault();
                 *
                 * CategoryAxisData cateAxisData = new CategoryAxisData();
                 * StringReference string_ref = new StringReference();
                 * string_ref.Append(new DocumentFormat.OpenXml.Drawing.Charts.Formula() { Text = barchart_series.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Formula>().FirstOrDefault().Text});
                 * StringCache string_cache = new StringCache();
                 * string_cache.Append(new PointCount() { Val = count });
                 */
            }
        }
Пример #32
0
 private void  Init()
 {
     lock (this)
     {
         caches = new HashMap<Type, Cache>(7);
         caches[typeof(sbyte)] = new ByteCache(this);
         caches[typeof(short)] = new ShortCache(this);
         caches[typeof(int)] = new IntCache(this);
         caches[typeof(float)] = new FloatCache(this);
         caches[typeof(long)] = new LongCache(this);
         caches[typeof(double)] = new DoubleCache(this);
         caches[typeof(string)] = new StringCache(this);
         caches[typeof(StringIndex)] = new StringIndexCache(this);
     }
 }
Пример #33
0
        public void Adds_and_retrieves_long_content_safely()
        {
            var sb = new StringBuilder();
            for(var i = 0; i < 1000; i++)
            {
                sb.Append("I will not write loops in unit tests.");
            }
            var input = sb.ToString();

            var cache = new StringCache();
            var added = cache.Add("long", input);
            Assert.IsTrue(added);
            var retrieved = cache.Get("long");
            Assert.AreEqual(input, retrieved);
        }
Пример #34
0
		private void  Init()
		{
			lock (this)
			{
                Support.Dictionary<Type, Cache> caches2 = new Support.Dictionary<Type, Cache>();
                caches2[typeof(sbyte)] = new ByteCache(this);
                caches2[typeof(short)] = new ShortCache(this);
                caches2[typeof(int)] = new IntCache(this);
                caches2[typeof(float)] = new FloatCache(this);
                caches2[typeof(long)] = new LongCache(this);
                caches2[typeof(double)] = new DoubleCache(this);
                caches2[typeof(string)] = new StringCache(this);
                caches2[typeof(StringIndex)] = new StringIndexCache(this);
                caches2[typeof(System.IComparable)] = new CustomCache(this);
                caches2[typeof(System.Object)] = new AutoCache(this);
                caches = caches2;
			}
		}