Exemplo n.º 1
0
        public void get_on_dictionary()
        {
            var d = new Dictionary<string, string> { { "a", "hello" } };

            d.Get("a").MustHaveValue().Should().Be("hello");
            d.Get("b").Should().Be(Maybe<string>.None);
        }
 public void GetTest()
 {
     var dict = new Dictionary<string, string>();
     dict.Add("b", "b");
     Expect(dict.Get("a"), EqualTo(string.Empty));
     Expect(dict.Get("b"), EqualTo("b"));
 }
        public void ShouldBeAbleToInitializeBagWithSeveralObjects()
        {
            var url = new Url("/1");
            var identity = new GenericIdentity("name");

            var bag = new Dictionary<string, object>();
            bag.Add(identity).Add(url);
            Assert.That(bag.Get(typeof(GenericIdentity)), Is.EqualTo(identity));
            Assert.That(bag.Get(typeof(Url)), Is.EqualTo(url));
        }
        public void ShouldBeAbleToInitializeBagWithSeveralObjectsWithExplicitTypes()
        {
            var url = new Url("/1");
            var identity = new GenericIdentity("name");

            var bag = new Dictionary<string, object>();
            bag.Add<GenericIdentity>("first", identity);
            bag.Add<Url>("second", url);
            Assert.That(bag.Get<GenericIdentity>("first"), Is.EqualTo(identity));
            Assert.That(bag.Get<Url>("second"), Is.EqualTo(url));
        }
Exemplo n.º 5
0
        public void TestMiscDictionaryGet()
        {
            string key0 = "Blinky";

            var dict = new Dictionary<string, int>() { { key0, 42 } };

            int value0 = 0;
            dict.Get(key0, v => { value0 = v; return true; }, () => value0 = 0);
            Assert.Equal(42, value0);
            dict.Get(key0, v => { value0 = v; return false; }, () => value0 = 0);
            Assert.Equal(0, value0);
        }
Exemplo n.º 6
0
 internal Cookie(RemoteSession session, Dictionary dict) {
     _session = session;
     try {
         _name = (string)dict["name"];
         _value = (string)dict["value"];
         _path = (string)dict.Get("path", null);
         _domain = (string)dict.Get("domain", null);
         _expiry = (int?)dict.Get("expiry", null);
         _secure = (bool)dict.Get("secure", false);
     } catch (Errors.KeyNotFoundError ex) {
         throw new DeserializeException(typeof(Cookie), ex);
     }
 }
Exemplo n.º 7
0
 internal Cookie(RemoteSession session, Dictionary dict) {
     _session = session;
     try {
         _name = dict.GetValue("name", string.Empty);
         _value = dict.GetValue("value", string.Empty);
         _path = dict.GetValue("path", string.Empty);
         _domain = dict.GetValue("domain", string.Empty);
         _secure = Convert.ToBoolean(dict.Get("secure", false));
         _expiry = Convert.ToDouble(dict.Get("expiry", 0));
     } catch (Errors.KeyNotFoundError ex) {
         throw new DeserializeException(typeof(Cookie), ex);
     } catch (Exception ex) {
         throw new SeleniumException(ex);
     }
 }
Exemplo n.º 8
0
        public void GetTest()
        {
            var dict = new Dictionary<int, string>
            {
                [1] = "one",
                [2] = "two"
            };
            Assert.AreEqual("one", dict.Get(1));
            Assert.AreEqual("two", dict.Get(2));
            Assert.AreEqual(null, dict.Get(3));
            Assert.AreEqual(string.Empty, dict.Get(3, string.Empty));

            dict = null;
            Assert.AreEqual(null, dict.Get(1));
        }
        private static string Label(
            Context context,
            Column groupBy,
            string selectedValue,
            Dictionary <string, string> linkedLabelHash)
        {
            if (groupBy.UserColumn)
            {
                return(SiteInfo.UserName(
                           context: context,
                           userId: selectedValue.ToInt()));
            }
            else if (groupBy.HasChoices())
            {
                var label = linkedLabelHash != null
                    ? linkedLabelHash?.Get(selectedValue)
                    : groupBy.Choice(selectedValue).TextMini;

                return(label.IsNullOrEmpty()
                    ? NumericZero(groupBy, selectedValue)
                        ? Displays.NotSet(context: context)
                        : StringEmpty(groupBy, selectedValue)
                            ? Displays.NotSet(context: context)
                            : "? " + selectedValue
                    : label);
            }
            else
            {
                return(selectedValue);
            }
        }
Exemplo n.º 10
0
 private static string GenerateUrlFromTemplate(string template, Dictionary<string, object> routeValues)
 {
     var tokens = tokensCache.Get(template);
     if (tokens == null)
     {
         tokens = template.BraceTokenize().ToArray();
         tokensCache[template] = tokens;
     }
     var builder = new StringBuilder();
     foreach (var token in tokens)
     {
         if (token is BraceTokenizer.Literal)
         {
             builder.Append(token.Literal);
         }
         else
         {
             var id = token.VariableId;
             var value = routeValues.Get(id);
             builder.Append(value);
             routeValues.Remove(id);
         }
     }
     return builder.ToString();
 }
Exemplo n.º 11
0
    private static string _GetSource(int source)
    {
        var s = m_sourceMap?.Get(source, string.Empty);

        if (s != string.Empty)
        {
            return(s);
        }

        m_sourceMap = new Dictionary <int, string>();

        var p  = System.Text.RegularExpressions.Regex.Replace(UnityEngine.Application.dataPath.Replace("/Assets", "/XMLConfigs/"), @"Client\d+", "Client");
        var fs = System.IO.Directory.Exists(p) ? System.IO.Directory.GetFiles(p, "*", System.IO.SearchOption.AllDirectories) : new string[] { };

        foreach (var f in fs)
        {
            var ff = f.Substring(f.IndexOf("XMLConfigs") + 11).Replace("\\", "/");
            var ss = ff.GetHashCode();
            m_sourceMap.Set(ss, ff);

            if (ss == source)
            {
                s = ff;
            }
        }

        return(s);
    }
Exemplo n.º 12
0
        private IEnumerable<string> InternalGetAnagrams(Dictionary<char, int> tiles, List<string> path, Node root,
                                                    int minLength, int minWordLength)
        {
            if (final && depth >= minWordLength)
              {
            var word = string.Join("", path);
            var length = word.Replace(" ", "").Length;
            if (length >= minLength)
              yield return word;

            using (new Guard(() => path.Push(" "), path.Pop))
            {
              foreach (var anagram in root.InternalGetAnagrams(tiles, path, root, minLength, minWordLength))
            yield return anagram;
            }
              }

              foreach (var child in children)
              {
            var l = child.Key;

            var count = tiles.Get(l);
            if (count == 0)
              continue;

            using (new Guard(() => tiles[l] = count - 1, () => tiles[l] = count))
            using (new Guard(() => path.Push(l.ToString()), path.Pop))
            {
              var node = child.Value;
              foreach (var anagram in node.InternalGetAnagrams(tiles, path, root, minLength, minWordLength))
            yield return anagram;
            }
              }
        }
Exemplo n.º 13
0
        public IEnumerable<string> GetAnagrams(string letters, int minWordLength)
        {
            var counters = new Dictionary<char, int>();
              foreach (var l in letters)
            counters[l] = counters.Get(l) + 1;

              return InternalGetAnagrams(counters, new List<string>(), this, letters.Length, minWordLength);
        }
Exemplo n.º 14
0
        public void Get()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            string key = "a";
            string value = "myValue";
            string result = null;

            result = dictionary.Get(key);
            Assert.IsNull(result);

            dictionary.Add(key, value);
            result = dictionary.Get(key);
            Assert.AreEqual(value, result);

            dictionary = null;
            result = dictionary.Get(key);
            Assert.IsNull(result);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Executes s file and runs a callback
 /// </summary>
 /// <param name="cmd"></param>
 /// <param name="args"></param>
 /// <param name="opts"></param>
 /// <param name="callbackId"></param>
 /// <returns></returns>
 public Context _execFile(string cmd, string[] args, Dictionary<string, object> opts, string exitCallbackId)
 {
     Context context = new Context();
     if (opts != null) {
         context.setEncoding(opts.Get<string>("encoding"));
     }
     context.exitCallbackId = exitCallbackId;
     context.start(cmd, args);
     return context;
 }
Exemplo n.º 16
0
 /// <summary>
 /// Executes command synchronously
 /// </summary>
 /// <param name="cmd"></param>
 /// <param name="args"></param>
 /// <returns></returns>
 public Context _execSync(string cmd, string[] args, Dictionary<string, object> opts)
 {
     Context context = new Context();
     if (opts != null)
     {
         context.setEncoding(opts.Get<string>("encoding"));
     }
     context.execute(cmd, args);
     return context;
 }
Exemplo n.º 17
0
        public static void PrintGNU( string GNU,
            IEnumerable<Results> Results, IEnumerable<int> CompLimitTicks,
            IEnumerable<string> Algs, IEnumerable<string> Files)
        {
            if ( !Directory.Exists( GNU ) ) {
            Directory.CreateDirectory( GNU );
              } else {
            throw new ArgumentException( "GNU Folder Exists" );
              }
              Dictionary<string, double> DStarSol = new Dictionary<string, double>( );

              foreach ( string f in Files ) {
            var DSol = Results.First( r => r.Algorithm.Equals( "D*Lite" ) &&
                        f.Equals( r.File ) );
            DStarSol.Add( f, DSol.SubOptimality );

              }
              int NumFiles = Files.Count( );
              int Inc = 1; //      (int)( NumFiles*0.05 );
              Files = Files.OrderBy( x => DStarSol.Get( x ) );
              foreach ( string a in Algs ) {
            TextWriter W = new StreamWriter( new FileStream( GNU + "/" + a.Replace( "*", "Star" ),
              FileMode.CreateNew, FileAccess.Write ) );
            System.Console.Out.WriteLine( "Alg " + a );
            foreach ( int clt in CompLimitTicks ) {
              for ( int i = 0 ; i< NumFiles ; i += Inc ) {
            var FilesSet = new HashSet<string>( Files.Skip( i ).Take( Inc ) );
            List<double> Difficulties = new List<double>( );
            foreach ( var F in FilesSet ) {
              double d;
              if ( !DStarSol.TryGetValue( F, out d ) ) {
                throw new ArgumentException( "D* Solution Missing" );
              }
              Difficulties.Add( d );
            }
            double Difficulty = Difficulties.Average( );

            var all = ( from r in Results
                        where a.Equals( r.Algorithm ) &&
                        FilesSet.Contains( r.File ) && clt == r.ComputationLimit
                        select r );
            if ( all.Any( ) ) {
              double AvgSubOpt = all.Select( x => x.SubOptimality ).Average( );
              W.WriteLine( a + ", " + clt  + ", " + AvgSubOpt + ", " + Difficulty );
              W.Flush( );
            }
              }
              W.WriteLine( );
              W.Flush( );
            }
            W.WriteLine( );
            W.Flush( );
            W.Close( );
              }
        }
Exemplo n.º 18
0
 private NameValueCollection runFormReader(string formPost)
 {
     var bytes = System.Text.Encoding.UTF8.GetBytes(formPost);
     var stream = new MemoryStream(bytes);
     var environment = new Dictionary<string, object>();
     environment.Add(OwinConstants.MediaTypeKey, MimeType.HttpFormMimetype);
     environment.Add(OwinConstants.RequestBodyKey, stream);
     new FormReader().Read(environment);
     var form = environment.Get<NameValueCollection>(OwinConstants.RequestFormKey);
     return form;
 }
Exemplo n.º 19
0
        public void get_complex()
        {
            var leaf = new Dictionary<string, object>{
                {"a", 1},
                {"b", true},
                {"c", false}
            };

            var node = new Dictionary<string, object>{
                {"leaf", leaf}
            };

            var top = new Dictionary<string, object>{
                {"node", node}
            };

            top.Get<int>("node/leaf/a").ShouldEqual(1);
            top.Get<bool>("node/leaf/b").ShouldBeTrue();
            top.Get<bool>("node/leaf/c").ShouldBeFalse();
        }
Exemplo n.º 20
0
        public void Get_Callback()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            string key = "a";
            string value = "myValue";
            string result = null;
            Func<string> valueNeededCallback = () => { return value; };

            result = dictionary.Get(key, null);
            Assert.IsNull(result);

            result = dictionary.Get(key, valueNeededCallback);
            Assert.AreEqual(value, result);
            Assert.IsTrue(dictionary.ContainsKey(key));
            Assert.AreEqual(value, dictionary[key]);

            dictionary = null;
            result = dictionary.Get(key, valueNeededCallback);
            Assert.IsNull(result);
        }
Exemplo n.º 21
0
 /// <summary>
 /// Loads the contents of a cookie dictionary into a system cookie
 /// </summary>
 /// <param name="cookie"></param>
 /// <param name="data"></param>
 public static void Load(this Cookie cookie, Dictionary<string, object> data)
 {
     if (data != null)
     {
         cookie.Name = data.Get<string>("name");
         cookie.Value = data.Get<string>("value");
         cookie.Secure = data.Get<bool>("secure");
         cookie.Domain = data.Get<string>("domain");
         cookie.Path = String.IsNullOrEmpty(data.Get<string>("path")) ? "/" : data.Get<string>("path");
         cookie.Expires = data.Get<DateTime>("expires");
         cookie.HttpOnly = data.Get<bool>("httpOnly");
     }
 }
        public void TestMissingKey()
        {
            var data = new Dictionary<string, string>
            {
                {"a", "1"},
                {"b", "2"},
                {"d", "4"}
            };

            var expected = Maybe.Nothing<string>();
            var actual = data.Get("c");
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 23
0
        private async Task <IList <BestsellersReportLineModel> > GetBestsellersBriefReportModelAsync(List <BestsellersReportLine> report, bool includeFiles = false)
        {
            var productIds = report.Select(x => x.ProductId).Distinct().ToArray();
            var products   = await _db.Products
                             .AsNoTracking()
                             .Where(x => productIds.Contains(x.Id))
                             .ToDictionaryAsync(x => x.Id);

            Dictionary <int, MediaFileInfo> files = null;

            if (includeFiles)
            {
                var fileIds = products.Values
                              .Select(x => x.MainPictureId ?? 0)
                              .Where(x => x != 0)
                              .Distinct()
                              .ToArray();

                files = (await Services.MediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id);
            }

            var model = report.Select(x =>
            {
                var m = new BestsellersReportLineModel
                {
                    ProductId     = x.ProductId,
                    TotalAmount   = Services.CurrencyService.PrimaryCurrency.AsMoney(x.TotalAmount),
                    TotalQuantity = x.TotalQuantity.ToString("N0")
                };

                var product = products.Get(x.ProductId);
                if (product != null)
                {
                    var file = files?.Get(product.MainPictureId ?? 0);

                    m.ProductName          = product.Name;
                    m.ProductTypeName      = product.GetProductTypeLabel(Services.Localization);
                    m.ProductTypeLabelHint = product.ProductTypeLabelHint;
                    m.Sku                 = product.Sku;
                    m.StockQuantity       = product.StockQuantity;
                    m.Price               = product.Price;
                    m.PictureThumbnailUrl = Services.MediaService.GetUrl(file, _mediaSettings.CartThumbPictureSize, null, false);
                    m.NoThumb             = file == null;
                }

                return(m);
            })
                        .ToList();

            return(model);
        }
Exemplo n.º 24
0
        public void write_a_header_that_allows_multiple_values()
        {
            var settings = new OwinHeaderSettings();
            var environment = new Dictionary<string, object>
            {
                {OwinConstants.HeaderSettings, settings}
            };
            var response = new OwinHttpResponse(environment);

            response.AppendHeader(HttpGeneralHeaders.Allow, "application/json");
            response.AppendHeader(HttpGeneralHeaders.Allow, "text/json");

            var headers = environment.Get<IDictionary<string, string[]>>(OwinConstants.ResponseHeadersKey);
            headers[HttpGeneralHeaders.Allow].ShouldHaveTheSameElementsAs("application/json", "text/json");
        }
Exemplo n.º 25
0
        public void Get()
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
              d["foo"] = (double)1.0;
              d["bar"] = "test";

              Assert.DoesNotThrow(new TestDelegate(() => d.Get<double>("foo")));
              Assert.DoesNotThrow(new TestDelegate(() => d.Get<string>("bar")));
              Assert.Throws<KeyNotFoundException>(new TestDelegate(() => d.Get<string>("not here")));
              Assert.Throws<InvalidCastException>(new TestDelegate(() => d.Get<int>("foo")));
              Assert.Throws<InvalidCastException>(new TestDelegate(() => d.Get<int>("bar")));

              Assert.AreEqual(1.0, d.Get<double>("foo"));
              Assert.AreEqual("test", d.Get<string>("bar"));
        }
 private static bool Bold(
     Column groupBy, string key, Dictionary <string, string> linkedLabelHash)
 {
     return(groupBy?.HasChoices() == true
         ? groupBy.ChoiceHash.Get(key) != null ||
            linkedLabelHash?.Get(key) != null ||
            UserNotSet(
                groupBy: groupBy,
                key: key) ||
            NumericZero(
                groupBy: groupBy,
                key: key) ||
            StringEmpty(
                groupBy: groupBy,
                key: key)
         : true);
 }
Exemplo n.º 27
0
        public void write_a_header_that_does_not_allow_multiple_values()
        {
            var settings = new OwinHeaderSettings();
            var environment = new Dictionary<string, object>
            {
                {OwinConstants.HeaderSettings, settings}
            };
            var response = new OwinHttpResponse(environment);

            settings.DoNotAllowMultipleValues(HttpRequestHeaders.ContentLength);

            response.AppendHeader(HttpRequestHeaders.ContentLength, "1234");
            response.AppendHeader(HttpRequestHeaders.ContentLength, "1234");

            var headers = environment.Get<IDictionary<string, string[]>>(OwinConstants.ResponseHeadersKey);
            headers[HttpRequestHeaders.ContentLength].ShouldHaveTheSameElementsAs("1234");
        }
Exemplo n.º 28
0
        public void TryGet()
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
              d["foo"] = (double)1.0;
              d["bar"] = "test";

              Assert.DoesNotThrow(new TestDelegate(() => { double v; d.Get<double>("foo", out v); }));
              Assert.DoesNotThrow(new TestDelegate(() => { string v; d.Get<string>("bar", out v); }));
              Assert.DoesNotThrow(new TestDelegate(() => { string v; d.Get<string>("not here", out v); }));
              Assert.Throws<InvalidCastException>(new TestDelegate(() => { int v; d.Get<int>("foo", out v); }));
              Assert.Throws<InvalidCastException>(new TestDelegate(() => { int v; d.Get<int>("bar", out v); }));

              double value;
              string str;
              Assert.True(d.Get<double>("foo", out value));
              Assert.AreEqual(1.0, value);
              Assert.False(d.Get<double>("nothere", out value));

              Assert.True(d.Get<string>("bar", out str));
              Assert.AreEqual("test", str);
        }
Exemplo n.º 29
0
 public TypeDef getTypeDef(int def)
 {
     return(m_typeIdxs.Get(def));
 }
Exemplo n.º 30
0
 /// <exception cref="NGit.Errors.CorruptObjectException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 private void AssertIndex(Dictionary<string, string> i)
 {
     string expectedValue;
     string path;
     DirCache read = DirCache.Read(db.GetIndexFile(), db.FileSystem);
     NUnit.Framework.Assert.AreEqual(i.Count, read.GetEntryCount(), "Index has not the right size."
         );
     for (int j = 0; j < read.GetEntryCount(); j++)
     {
         path = read.GetEntry(j).PathString;
         expectedValue = i.Get(path);
         NUnit.Framework.Assert.IsNotNull(expectedValue, "found unexpected entry for path "
              + path + " in index");
         NUnit.Framework.Assert.IsTrue(Arrays.Equals(db.Open(read.GetEntry(j).GetObjectId(
             )).GetCachedBytes(), Sharpen.Runtime.GetBytesForString(i.Get(path))), "unexpected content for path "
              + path + " in index. Expected: <" + expectedValue + ">");
     }
 }
Exemplo n.º 31
0
 /// <summary>
 /// Get a registerd Type by module name
 /// </summary>
 /// <param name="name">The class name</param>
 /// <returns>The resgisterd runtime Type</returns>
 /// <remarks>See RegisterTypes</remarks>
 public static Type GetType(string name)
 {
     return(m_types.Get(name, true));
 }
        internal override void ProcessInbox(RevisionList inbox)
        {
            if (Status == ReplicationStatus.Offline) {
                Log.V(TAG, "Offline, so skipping inbox process");
                return;
            }

            if(_requests.Count > ManagerOptions.Default.MaxOpenHttpConnections) {
                Task.Delay(1000).ContinueWith(t => ProcessInbox(inbox), CancellationToken.None, TaskContinuationOptions.None, WorkExecutor.Scheduler);
                return;
            }

            // Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
            // <http://wiki.apache.org/couchdb/HttpPostRevsDiff>
            var diffs = new Dictionary<String, IList<String>>();
            foreach (var rev in inbox) {
                var docID = rev.GetDocId();
                var revs = diffs.Get(docID);
                if (revs == null) {
                    revs = new List<String>();
                    diffs[docID] = revs;
                }
                revs.Add(rev.GetRevId());
                AddPending(rev);
            }

            // Call _revs_diff on the target db:
            Log.D(TAG, "posting to /_revs_diff: {0}", String.Join(Environment.NewLine, new[] { Manager.GetObjectMapper().WriteValueAsString(diffs) }));
            SendAsyncRequest(HttpMethod.Post, "/_revs_diff", diffs, (response, e) =>
            {
                try {
                    if(!LocalDatabase.IsOpen) {
                        return;
                    }

                    var results = response.AsDictionary<string, object>();

                    Log.D(TAG, "/_revs_diff response: {0}\r\n{1}", response, results);

                    if (e != null) {
                        LastError = e;
                        RevisionFailed();
                    } else {
                        if (results.Count != 0)  {
                            // Go through the list of local changes again, selecting the ones the destination server
                            // said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
                            var docsToSend = new List<object> ();
                            var revsToSend = new RevisionList();
                            foreach (var rev in inbox) {
                                // Is this revision in the server's 'missing' list?
                                IDictionary<string, object> properties = null;
                                var revResults = results.Get(rev.GetDocId()).AsDictionary<string, object>(); 
                                if (revResults == null) {
                                    //SafeIncrementCompletedChangesCount();
                                    continue;
                                }

                                var revs = revResults.Get("missing").AsList<string>();
                                if (revs == null || !revs.Any( id => id.Equals(rev.GetRevId(), StringComparison.OrdinalIgnoreCase))) {
                                    RemovePending(rev);
                                    //SafeIncrementCompletedChangesCount();
                                    continue;
                                }

                                // Get the revision's properties:
                                var contentOptions = DocumentContentOptions.IncludeAttachments;
                                if (!_dontSendMultipart && RevisionBodyTransformationFunction == null)
                                {
                                    contentOptions |= DocumentContentOptions.BigAttachmentsFollow;
                                }

                                RevisionInternal loadedRev;
                                try {
                                    loadedRev = LocalDatabase.LoadRevisionBody (rev);
                                    if(loadedRev == null) {
                                        throw new CouchbaseLiteException("DB is closed", StatusCode.DbError);
                                    }

                                    properties = new Dictionary<string, object>(rev.GetProperties());
                                } catch (Exception e1) {
                                    Log.W(TAG, String.Format("{0} Couldn't get local contents of", rev), e);
                                    RevisionFailed();
                                    continue;
                                }

                                var populatedRev = TransformRevision(loadedRev);
                                IList<string> possibleAncestors = null;
                                if (revResults.ContainsKey("possible_ancestors")) {
                                    possibleAncestors = revResults["possible_ancestors"].AsList<string>();
                                }

                                properties = new Dictionary<string, object>(populatedRev.GetProperties());

                                try {
                                    var history = LocalDatabase.GetRevisionHistory(populatedRev, possibleAncestors);
                                    if(history == null) {
                                        throw new CouchbaseLiteException("DB closed", StatusCode.DbError);
                                    }

                                    properties["_revisions"] = Database.MakeRevisionHistoryDict(history);
                                } catch(Exception e1) {
                                    Log.W(TAG, "Error getting revision history", e1);
                                    RevisionFailed();
                                    continue;
                                }

                                populatedRev.SetProperties(properties);
                                if(properties.GetCast<bool>("_removed")) {
                                    RemovePending(rev);
                                    continue;
                                }

                                // Strip any attachments already known to the target db:
                                if (properties.ContainsKey("_attachments")) {
                                    // Look for the latest common ancestor and stuf out older attachments:
                                    var minRevPos = FindCommonAncestor(populatedRev, possibleAncestors);
                                    try {
                                        LocalDatabase.ExpandAttachments(populatedRev, minRevPos + 1, !_dontSendMultipart, false);
                                    } catch(Exception ex) {
                                        Log.W(TAG, "Error expanding attachments!", ex);
                                        RevisionFailed();
                                        continue;
                                    }

                                    properties = populatedRev.GetProperties();
                                    if (!_dontSendMultipart && UploadMultipartRevision(populatedRev)) {
                                        continue;
                                    }
                                }

                                if (properties == null || !properties.ContainsKey("_id")) {
                                    throw new InvalidOperationException("properties must contain a document _id");
                                }

                                // Add the _revisions list:
                                revsToSend.Add(rev);

                                //now add it to the docs to send
                                docsToSend.Add (properties);
                            }

                            UploadBulkDocs(docsToSend, revsToSend);
                        } else {
                            foreach (var revisionInternal in inbox) {
                                RemovePending(revisionInternal);
                            }

                            SafeAddToCompletedChangesCount(inbox.Count);
                        }
                    }
                } catch (Exception ex) {
                    Log.E(TAG, "Unhandled exception in Pusher.ProcessInbox", ex);
                }
            });
        }
Exemplo n.º 33
0
 public void Execute(Dictionary<string, object> bundle)
 {
     System.Console.WriteLine(String.Format("A:{0}", bundle.Get<DateTime>("A")));
 }
Exemplo n.º 34
0
        public bool Encode(IoBuffer buffer, object obj)
        {
            //类型
            byte type;

            //System.Type t = obj != null ? obj.GetType():null;
            if (obj == null)
            {
                type = Types.NULL;
            }
            else if (obj is byte || obj is short || obj is int || obj is long || obj is float || obj is double)
            {
                type = Types.NUMBER;
            }
            else if (obj is string)
            {
                type = Types.STRING;
            }
            else if (obj is bool)
            {
                type = Types.BOOLEAN;
            }
            else if (obj is System.Enum)//t.IsEnum
            {
                type = Types.ENUM;
            }
            else if (obj is System.DateTime)
            {
                type = Types.DATE_TIME;
            }
            else if (obj is IDictionary)
            {
                type = Types.MAP;
            }
            else if (obj is System.Array)//t.IsArray
            {
                type = Types.ARRAY;
            }
            else if (obj is IList)
            {
                type = Types.COLLECTION;
            }
            else
            {
                System.Type t = obj.GetType();
                if (IsObjectType(t))//这里不能序列化模板类型、c#原生类型、继承自其他类的类型,不然可能会序列化一些不想要的东西
                {
                    type = Types.OBJECT;
                }
                else
                {
                    Debuger.LogError("不能序列化的类型,不能序列化模板类型、c#原生类型、继承自其他类的类型:" + obj.GetType().Name);
                    return(false);
                }
            }


            Proxy proxy = m_proxys.Get(type);

            if (proxy == null)
            {
                Debuger.LogError("找不到序列化类。{0}", obj.GetType().ToString());
                return(false);
            }

            if (!proxy.setValue(buffer, obj))
            {
                return(false);
            }
            return(true);
        }
        private async Task MapProductSummaryItem(Product product, MapProductSummaryItemContext ctx)
        {
            var contextProduct = product;
            var finalPrice     = default(Money);
            var model          = ctx.Model;
            var settings       = ctx.MappingSettings;
            var options        = ctx.CalculationOptions;
            var slug           = await product.GetActiveSlugAsync();

            var item = new ProductSummaryModel.SummaryItem(ctx.Model)
            {
                Id        = product.Id,
                Name      = product.GetLocalized(x => x.Name),
                SeName    = slug,
                DetailUrl = _urlHelper.RouteUrl("Product", new { SeName = slug })
            };

            if (model.ShowDescription)
            {
                item.ShortDescription = product.GetLocalized(x => x.ShortDescription);
            }

            if (settings.MapFullDescription)
            {
                item.FullDescription = product.GetLocalized(x => x.FullDescription, detectEmptyHtml: true);
            }

            // Price
            if (settings.MapPrices)
            {
                (finalPrice, contextProduct) = await MapSummaryItemPrice(product, item, ctx);
            }

            // (Color) Attributes
            if (settings.MapColorAttributes || settings.MapAttributes)
            {
                var attributes = await ctx.BatchContext.Attributes.GetOrLoadAsync(contextProduct.Id);

                var cachedAttributeNames = new Dictionary <int, LocalizedValue <string> >();

                // Color squares
                if (attributes.Any() && settings.MapColorAttributes)
                {
                    var colorAttributes = attributes
                                          .Where(x => x.IsListTypeAttribute())
                                          .SelectMany(x => x.ProductVariantAttributeValues)
                                          .Where(x => x.Color.HasValue() && !x.Color.EqualsNoCase("transparent"))
                                          .Distinct()
                                          .Take(20) // limit results
                                          .Select(x =>
                    {
                        var attr     = x.ProductVariantAttribute.ProductAttribute;
                        var attrName = cachedAttributeNames.Get(attr.Id) ?? (cachedAttributeNames[attr.Id] = attr.GetLocalized(l => l.Name));

                        return(new ProductSummaryModel.ColorAttributeValue
                        {
                            Id = x.Id,
                            Color = x.Color,
                            Alias = x.Alias,
                            FriendlyName = x.GetLocalized(l => l.Name),
                            AttributeId = x.ProductVariantAttributeId,
                            AttributeName = attrName,
                            ProductAttributeId = attr.Id,
                            ProductUrl = _productUrlHelper.GetProductUrl(product.Id, item.SeName, 0, x)
                        });
                    })
                                          .ToList();

                    item.ColorAttributes = colorAttributes;

                    // TODO: (mc) Resolve attribute value images also
                }

                // Variant Attributes
                if (attributes.Any() && settings.MapAttributes)
                {
                    if (item.ColorAttributes != null && item.ColorAttributes.Any())
                    {
                        var processedIds = item.ColorAttributes.Select(x => x.AttributeId).Distinct().ToArray();
                        attributes = attributes.Where(x => !processedIds.Contains(x.Id)).ToList();
                    }

                    foreach (var attr in attributes)
                    {
                        var pa = attr.ProductAttribute;
                        item.Attributes.Add(new ProductSummaryModel.Attribute
                        {
                            Id    = attr.Id,
                            Alias = pa.Alias,
                            Name  = cachedAttributeNames.Get(pa.Id) ?? (cachedAttributeNames[pa.Id] = pa.GetLocalized(l => l.Name))
                        });
                    }
                }
            }

            // Picture
            if (settings.MapPictures)
            {
                var thumbSize = model.ThumbSize ?? _mediaSettings.ProductThumbPictureSize;

                ctx.MediaFiles.TryGetValue(product.MainPictureId ?? 0, out var file);

                item.Image = new ImageModel
                {
                    File       = file,
                    ThumbSize  = thumbSize,
                    Title      = file?.File?.GetLocalized(x => x.Title)?.Value.NullEmpty() ?? string.Format(ctx.Resources["Media.Product.ImageLinkTitleFormat"], item.Name),
                    Alt        = file?.File?.GetLocalized(x => x.Alt)?.Value.NullEmpty() ?? string.Format(ctx.Resources["Media.Product.ImageAlternateTextFormat"], item.Name),
                    NoFallback = _catalogSettings.HideProductDefaultPictures
                };

                _services.DisplayControl.Announce(file?.File);
            }

            // Brands
            if (settings.MapManufacturers)
            {
                item.Brand = (await PrepareBrandOverviewModelAsync(
                                  await ctx.BatchContext.ProductManufacturers.GetOrLoadAsync(product.Id),
                                  ctx.CachedBrandModels,
                                  _catalogSettings.ShowManufacturerLogoInLists && settings.ViewMode == ProductSummaryViewMode.List)).FirstOrDefault();
            }

            // Spec Attributes
            if (settings.MapSpecificationAttributes)
            {
                item.SpecificationAttributes.AddRange(MapProductSpecificationModels(await ctx.BatchContext.SpecificationAttributes.GetOrLoadAsync(product.Id)));
            }

            item.MinPriceProductId = contextProduct.Id;
            item.Sku = contextProduct.Sku;

            // Measure Dimensions
            if (model.ShowDimensions && (contextProduct.Width != 0 || contextProduct.Height != 0 || contextProduct.Length != 0))
            {
                item.Dimensions = ctx.Resources["Products.DimensionsValue"].Value.FormatCurrent(
                    contextProduct.Width.ToString("N2"),
                    contextProduct.Height.ToString("N2"),
                    contextProduct.Length.ToString("N2")
                    );
                item.DimensionMeasureUnit = (await _db.MeasureDimensions.FindByIdAsync(_measureSettings.BaseDimensionId, false))?.SystemKeyword;
            }

            // Delivery Times.
            item.HideDeliveryTime = product.ProductType == ProductType.GroupedProduct;
            if (!item.HideDeliveryTime && model.DeliveryTimesPresentation != DeliveryTimesPresentation.None)
            {
                // We cannot include ManageInventoryMethod.ManageStockByAttributes because it's only functional with MergeWithCombination.
                // INFO: (core) Don't uncomment this part
                //item.StockAvailablity = contextProduct.FormatStockMessage(_localizationService);
                //item.DisplayDeliveryTimeAccordingToStock = contextProduct.DisplayDeliveryTimeAccordingToStock(_catalogSettings);

                //var deliveryTime = _deliveryTimeService.GetDeliveryTime(contextProduct);
                //if (deliveryTime != null)
                //{
                //	item.DeliveryTimeName = deliveryTime.GetLocalized(x => x.Name);
                //	item.DeliveryTimeHexValue = deliveryTime.ColorHexValue;
                //}

                var deliveryTimeId = product.DeliveryTimeId ?? 0;
                if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock && product.StockQuantity <= 0 && _catalogSettings.DeliveryTimeIdForEmptyStock.HasValue)
                {
                    deliveryTimeId = _catalogSettings.DeliveryTimeIdForEmptyStock.Value;
                }

                var deliveryTime = await _db.DeliveryTimes.FindByIdAsync(deliveryTimeId, false);

                if (deliveryTime != null)
                {
                    item.DeliveryTimeName     = deliveryTime.GetLocalized(x => x.Name);
                    item.DeliveryTimeHexValue = deliveryTime.ColorHexValue;

                    // Due to lack of space, the grid view does not show a date for the delivery time.
                    if (settings.ViewMode >= ProductSummaryViewMode.List &&
                        (model.DeliveryTimesPresentation == DeliveryTimesPresentation.DateOnly || model.DeliveryTimesPresentation == DeliveryTimesPresentation.LabelAndDate))
                    {
                        item.DeliveryTimeDate = _deliveryTimeService.GetFormattedDeliveryDate(deliveryTime);
                    }
                }

                item.DisplayDeliveryTimeAccordingToStock = product.ManageInventoryMethod == ManageInventoryMethod.ManageStock
                    ? product.StockQuantity > 0 || (product.StockQuantity <= 0 && _catalogSettings.DeliveryTimeIdForEmptyStock.HasValue)
                    : true;

                if (product.DisplayStockAvailability && product.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
                {
                    if (product.StockQuantity > 0)
                    {
                        item.StockAvailablity = product.DisplayStockQuantity
                            ? T("Products.Availability.InStockWithQuantity", product.StockQuantity)
                            : T("Products.Availability.InStock");
                    }
                    else
                    {
                        item.StockAvailablity = product.BackorderMode == BackorderMode.NoBackorders || product.BackorderMode == BackorderMode.AllowQtyBelow0
                            ? T("Products.Availability.OutOfStock")
                            : T("Products.Availability.Backordering");
                    }
                }
            }

            item.LegalInfo         = ctx.LegalInfo;
            item.RatingSum         = product.ApprovedRatingSum;
            item.TotalReviews      = product.ApprovedTotalReviews;
            item.IsShippingEnabled = contextProduct.IsShippingEnabled;

            if (finalPrice != decimal.Zero && model.ShowBasePrice)
            {
                item.BasePriceInfo = _priceCalculationService.GetBasePriceInfo(contextProduct, finalPrice, options.TargetCurrency);
            }

            if (settings.MapPrices)
            {
                var addShippingPrice = ToWorkingCurrency(contextProduct.AdditionalShippingCharge, ctx);
                if (addShippingPrice > 0)
                {
                    item.TransportSurcharge = addShippingPrice.WithPostFormat(ctx.Resources["Common.AdditionalShippingSurcharge"]);
                }

                item.PriceDisplayStyle        = _catalogSettings.PriceDisplayStyle;
                item.DisplayTextForZeroPrices = _catalogSettings.DisplayTextForZeroPrices;
            }

            if (model.ShowWeight && contextProduct.Weight > 0)
            {
                var measureWeightName = (await _db.MeasureWeights.FindByIdAsync(_measureSettings.BaseWeightId, false))?.GetLocalized(x => x.Name) ?? string.Empty;
                item.Weight = "{0} {1}".FormatCurrent(contextProduct.Weight.ToString("N2"), measureWeightName);
            }

            // New Badge
            if (product.IsNew(_catalogSettings))
            {
                item.Badges.Add(new ProductSummaryModel.Badge
                {
                    Label = T("Common.New"),
                    Style = BadgeStyle.Success
                });
            }

            model.Items.Add(item);
        }
Exemplo n.º 36
0
 private string GetUrl()
 {
     return(links.Get <InputField>("UrlToLoadInput").text);
 }
Exemplo n.º 37
0
        private void WriteHeader(BinaryWriter file)
        {
            file.BaseStream.Seek(0L, SeekOrigin.Begin);
            file.Write(IDString);
            file.Write(FileVersion);
            file.Write(unk2);
            file.Write(unk3);
            file.Write(unk4);
            file.Write(unk5);
            file.Write(cr2wsize);
            file.Write(buffersize);
            file.Write(unk6);
            file.Write(unk7);
            for (var index = 0; index < 10; ++index)
            {
                headers[index].Write(file);
            }
            var position = (uint)file.BaseStream.Position;

            headers[0].offset = position;
            var dic1 = new Dictionary <string, uint>();
            var dic2 = new Dictionary <string, uint>();

            for (var index = 0; index < strings.Count; ++index)
            {
                dic1.AddUnique(strings[index].str, strings[index].offset);
            }
            for (var index = 0; index < handles.Count; ++index)
            {
                dic1.AddUnique(handles[index].str, handles[index].offset);
            }
            for (var index = 0; index < block7.Count; ++index)
            {
                foreach (var handle in block7[index].handles)
                {
                    dic1.AddUnique(handle, block7[index].handle_name_offset);
                }
            }
            foreach (var keyValuePair in dic1)
            {
                var num = (uint)file.BaseStream.Position - position;
                dic2.Add(keyValuePair.Key, num);
                file.WriteCR2WString(keyValuePair.Key);
            }

            headers[0].size = (uint)file.BaseStream.Position - position;
            for (var index = 0; index < strings.Count; ++index)
            {
                var num = dic2.Get(strings[index].str);
                if ((int)strings[index].offset != (int)num)
                {
                    strings[index].offset = num;
                }
            }

            for (var index = 0; index < handles.Count; ++index)
            {
                var num = dic2.Get(handles[index].str);
                if ((int)num != (int)handles[index].offset)
                {
                    handles[index].offset = num;
                }
            }

            for (var index1 = 0; index1 < block7.Count; ++index1)
            {
                for (var index2 = 0; index2 < block7[index1].handles.Count; ++index2)
                {
                    var num = dic2.Get(block7[index1].handles[index2]);
                    if ((int)num != (int)block7[index1].handle_name_offset)
                    {
                        block7[index1].handle_name_offset = num;
                    }
                }
            }

            headers[1].size   = (uint)strings.Count;
            headers[1].offset = (uint)file.BaseStream.Position;
            for (var index = 0; index < strings.Count; ++index)
            {
                strings[index].Write(file);
            }
            headers[2].size   = (uint)handles.Count;
            headers[2].offset = (uint)file.BaseStream.Position;
            for (var index = 0; index < handles.Count; ++index)
            {
                handles[index].Write(file);
            }
            headers[3].size   = (uint)block4.Count;
            headers[3].offset = (uint)file.BaseStream.Position;
            for (var index = 0; index < block4.Count; ++index)
            {
                block4[index].Write(file);
            }
            headers[4].size   = (uint)chunks.Count;
            headers[4].offset = (uint)file.BaseStream.Position;
            for (var index = 0; index < chunks.Count; ++index)
            {
                chunks[index].offset += headerOffset;
                chunks[index].Write(file);
            }

            headers[5].size   = (uint)block6.Count;
            headers[5].offset = (uint)file.BaseStream.Position;
            for (var index = 0; index < block6.Count; ++index)
            {
                block6[index].Write(file);
            }
            headers[6].size   = (uint)block7.Count;
            headers[6].offset = (uint)file.BaseStream.Position;
            for (var index = 0; index < block7.Count; ++index)
            {
                block7[index].offset += headerOffset;
                block7[index].Write(file);
            }
        }
Exemplo n.º 38
0
        private void WriteHeader(BinaryWriter file)
        {
            file.BaseStream.Seek(0, SeekOrigin.Begin);
            file.Write(IDString);

            file.Write(FileVersion);
            file.Write(unk2);
            file.Write(unk3);

            file.Write(unk4);
            file.Write(unk5);

            file.Write(cr2wsize);
            file.Write(buffersize);

            file.Write(unk6);
            file.Write(unk7);

            for (var i = 0; i < 10; i++)
            {
                headers[i].Write(file);
            }

            var stringbuffer_offset = (uint)file.BaseStream.Position;

            headers[0].offset = stringbuffer_offset;

            // Write string buffers
            var string_offsets     = new Dictionary <string, uint>();
            var new_string_offsets = new Dictionary <string, uint>();

            // Add all strings to dictionary
            for (var i = 0; i < strings.Count; i++)
            {
                string_offsets.AddUnique(strings[i].str, strings[i].offset);
            }
            for (var i = 0; i < handles.Count; i++)
            {
                string_offsets.AddUnique(handles[i].str, handles[i].offset);
            }
            for (var i = 0; i < block7.Count; i++)
            {
                foreach (var str in block7[i].handles)
                {
                    string_offsets.AddUnique(str, block7[i].handle_name_offset);
                }
            }

            // Write all strings
            foreach (var str in string_offsets)
            {
                var newoffset = ((uint)file.BaseStream.Position) - stringbuffer_offset;
                new_string_offsets.Add(str.Key, newoffset);
                file.WriteCR2WString(str.Key);
            }

            headers[0].size = ((uint)file.BaseStream.Position - stringbuffer_offset);

            // Update all offsets
            for (var i = 0; i < strings.Count; i++)
            {
                var newoffset = new_string_offsets.Get(strings[i].str);
                if (strings[i].offset != newoffset)
                {
                    strings[i].offset = newoffset;
                }
            }
            for (var i = 0; i < handles.Count; i++)
            {
                var newoffset = new_string_offsets.Get(handles[i].str);
                if (newoffset != handles[i].offset)
                {
                    handles[i].offset = newoffset;
                }
            }
            for (var i = 0; i < block7.Count; i++)
            {
                for (var j = 0; j < block7[i].handles.Count; j++)
                {
                    var newoffset = new_string_offsets.Get(block7[i].handles[j]);
                    if (newoffset != block7[i].handle_name_offset)
                    {
                        block7[i].handle_name_offset = newoffset;
                    }
                }
            }


            headers[1].size   = (uint)strings.Count;
            headers[1].offset = (uint)file.BaseStream.Position;
            for (var i = 0; i < strings.Count; i++)
            {
                strings[i].Write(file);
            }

            headers[2].size   = (uint)handles.Count;
            headers[2].offset = (uint)file.BaseStream.Position;
            for (var i = 0; i < handles.Count; i++)
            {
                handles[i].Write(file);
            }

            headers[3].size   = (uint)block4.Count;
            headers[3].offset = (uint)file.BaseStream.Position;
            for (var i = 0; i < block4.Count; i++)
            {
                block4[i].Write(file);
            }

            headers[4].size   = (uint)chunks.Count;
            headers[4].offset = (uint)file.BaseStream.Position;
            for (var i = 0; i < chunks.Count; i++)
            {
                chunks[i].offset += headerOffset;
                chunks[i].Write(file);
            }

            headers[5].size   = (uint)block6.Count;
            headers[5].offset = (uint)file.BaseStream.Position;
            for (var i = 0; i < block6.Count; i++)
            {
                block6[i].Write(file);
            }

            headers[6].size   = (uint)block7.Count;
            headers[6].offset = (uint)file.BaseStream.Position;
            for (var i = 0; i < block7.Count; i++)
            {
                block7[i].offset += headerOffset;
                block7[i].Write(file);
            }
        }
Exemplo n.º 39
0
 public InputField NameUi()
 {
     return(links.Get <InputField>("Name"));
 }
Exemplo n.º 40
0
        public static void Reflesh(Context context, bool force = false)
        {
            SetAnonymousId(context: context);
            if (context.TenantId == 0)
            {
                return;
            }
            var tenantCache = TenantCaches.Get(context.TenantId);
            var monitor     = tenantCache.GetUpdateMonitor(context: context);

            if (monitor.DeptsUpdated || monitor.GroupsUpdated || monitor.UsersUpdated || force)
            {
                var dataSet = Repository.ExecuteDataSet(
                    context: context,
                    statements: new SqlStatement[]
                {
                    Rds.SelectDepts(
                        dataTableName: "Depts",
                        column: Rds.DeptsColumn()
                        .TenantId()
                        .DeptId()
                        .DeptCode()
                        .DeptName()
                        .Body()
                        .Disabled(),
                        where : Rds.DeptsWhere().TenantId(context.TenantId),
                        _using: monitor.DeptsUpdated || force),
                    Rds.SelectGroups(
                        dataTableName: "Groups",
                        column: Rds.GroupsColumn()
                        .TenantId()
                        .GroupId()
                        .GroupName()
                        .Body()
                        .Disabled(),
                        where : Rds.GroupsWhere().TenantId(context.TenantId),
                        _using: monitor.GroupsUpdated || force),
                    Rds.SelectUsers(
                        dataTableName: "Users",
                        column: Rds.UsersColumn()
                        .TenantId()
                        .UserId()
                        .DeptId()
                        .LoginId()
                        .Name()
                        .UserCode()
                        .Body()
                        .TenantManager()
                        .ServiceManager()
                        .AllowCreationAtTopSite()
                        .AllowGroupAdministration()
                        .AllowGroupCreation()
                        .AllowApi()
                        .Disabled(),
                        where : Rds.UsersWhere().TenantId(context.TenantId),
                        _using: monitor.UsersUpdated || force)
                });
                if (monitor.DeptsUpdated || force)
                {
                    tenantCache.DeptHash = dataSet.Tables["Depts"]
                                           .AsEnumerable()
                                           .ToDictionary(
                        dataRow => dataRow.Int("DeptId"),
                        dataRow => new Dept(dataRow));
                }
                if (monitor.GroupsUpdated || force)
                {
                    tenantCache.GroupHash = dataSet.Tables["Groups"]
                                            .AsEnumerable()
                                            .ToDictionary(
                        dataRow => dataRow.Int("GroupId"),
                        dataRow => new Group(dataRow));
                }
                if (monitor.UsersUpdated || force)
                {
                    tenantCache.UserHash = dataSet.Tables["Users"]
                                           .AsEnumerable()
                                           .ToDictionary(
                        dataRow => dataRow.Int("UserId"),
                        dataRow => new User(
                            context: context,
                            dataRow: dataRow));
                }
            }
            if (monitor.PermissionsUpdated || monitor.GroupsUpdated || monitor.UsersUpdated || force)
            {
                tenantCache.SiteDeptHash  = new Dictionary <long, List <int> >();
                tenantCache.SiteGroupHash = new Dictionary <long, List <int> >();
                tenantCache.SiteUserHash  = new Dictionary <long, List <int> >();
            }
            SetSites(
                context: context,
                tenantCache: tenantCache);
            if (monitor.Updated || force)
            {
                monitor.Update();
            }
        }
Exemplo n.º 41
0
        private static void SetLinks(
            Context context,
            TenantCache tenantCache,
            DateTime sitesUpdatedTime)
        {
            var dataRows = Rds.ExecuteTable(
                context: context,
                statements: Rds.SelectLinks(
                    column: Rds.LinksColumn()
                    .DestinationId()
                    .SourceId(),
                    join: new SqlJoinCollection(
                        new SqlJoin(
                            tableBracket: "\"Sites\"",
                            joinType: SqlJoin.JoinTypes.Inner,
                            joinExpression: "\"DestinationSites\".\"SiteId\"=\"Links\".\"DestinationId\"",
                            _as: "DestinationSites"),
                        new SqlJoin(
                            tableBracket: "\"Sites\"",
                            joinType: SqlJoin.JoinTypes.Inner,
                            joinExpression: "\"SourceSites\".\"SiteId\"=\"Links\".\"SourceId\"",
                            _as: "SourceSites")),
                    where : Rds.SitesWhere()
                    .TenantId(context.TenantId, tableName: "DestinationSites")
                    .TenantId(context.TenantId, tableName: "SourceSites")
                    .ReferenceType("Wikis", tableName: "DestinationSites", _operator: "<>")
                    .ReferenceType("Wikis", tableName: "SourceSites", _operator: "<>")
                    .Or(or: Rds.SitesWhere()
                        .UpdatedTime(sitesUpdatedTime, tableName: "DestinationSites", _operator: ">")
                        .UpdatedTime(sitesUpdatedTime, tableName: "SourceSites", _operator: ">"))))
                           .AsEnumerable();

            if (dataRows.Any())
            {
                var destinationKeyValues = new Dictionary <long, List <long> >();
                var sourceKeyValues      = new Dictionary <long, List <long> >();
                tenantCache.Links?.DestinationKeyValues.ForEach(data =>
                                                                destinationKeyValues.Add(data.Key, data.Value));
                tenantCache.Links?.SourceKeyValues.ForEach(data =>
                                                           sourceKeyValues.Add(data.Key, data.Value));
                foreach (var data in dataRows.GroupBy(dataRow => dataRow.Long("DestinationId")))
                {
                    destinationKeyValues.AddOrUpdate(
                        data.Key,
                        (destinationKeyValues.Get(data.Key) ?? new List <long>())
                        .Concat(data.Select(dataRow => dataRow.Long("SourceId")))
                        .Distinct()
                        .ToList());
                }
                foreach (var data in dataRows.GroupBy(dataRow => dataRow.Long("SourceId")))
                {
                    sourceKeyValues.AddOrUpdate(
                        data.Key,
                        (sourceKeyValues.Get(data.Key) ?? new List <long>())
                        .Concat(data.Select(dataRow => dataRow.Long("DestinationId")))
                        .Distinct()
                        .ToList());
                }
                if (tenantCache.Links == null)
                {
                    tenantCache.Links = new LinkKeyValues();
                }
                tenantCache.Links.DestinationKeyValues = destinationKeyValues;
                tenantCache.Links.SourceKeyValues      = sourceKeyValues;
            }
        }
Exemplo n.º 42
0
 public TouchPoint GetPrimaryTouch(Dictionary <int, TouchPoint> Touches)
 {
     return(Touches.Get(DraggingTouchIds[0]));
 }
        /// <summary>
        ///     アセットのイメージをスライスする
        ///     戻り地は、変換リザルトメッセージ
        /// </summary>
        /// <param name="outputPath"></param>
        /// <param name="sourceImagePath"></param>
        /// <returns></returns>
        public static string SliceSprite(string outputPath, string sourceImagePath)
        {
            // オプションJSONの読み込み
            Dictionary <string, object> json = null;
            var imageJsonPath = sourceImagePath + ".json";

            if (File.Exists(imageJsonPath))
            {
                var text = File.ReadAllText(imageJsonPath);
                json = Json.Deserialize(text) as Dictionary <string, object>;
            }

            // PNGを読み込み、同じサイズのTextureを作成する
            var sourceTexture   = CreateTextureFromPng(sourceImagePath);
            var optionJson      = json.GetDic("copy_rect");
            var readableTexture = CreateReadableTexture2D(sourceTexture,
                                                          optionJson?.GetInt("offset_x"),
                                                          optionJson?.GetInt("offset_y"),
                                                          optionJson?.GetInt("width"),
                                                          optionJson?.GetInt("height")
                                                          );

            if (readableTexture == null)
            {
                Debug.LogError($"readableTextureがNULLです{sourceImagePath}");
            }

            // LoadAssetAtPathをつかったテクスチャ読み込み サイズが2のべき乗になる JPGも読める
            // var texture = CreateReadableTexture2D(AssetDatabase.LoadAssetAtPath<Texture2D>(asset));
            if (PreprocessTexture.SlicedTextures == null)
            {
                PreprocessTexture.SlicedTextures = new Dictionary <string, SlicedTexture>();
            }

            var slice = json?.Get("slice").ToLower();

            switch (slice)
            {
            case null:
            case "auto":
            {
                var slicedTexture = TextureSlicer.Slice(readableTexture);
                return(CheckWriteSpriteFromTexture(outputPath, slicedTexture.Texture, slicedTexture.Boarder));
            }

            case "none":
            {
                return(CheckWriteSpriteFromTexture(outputPath, readableTexture, new Boarder(0, 0, 0, 0)));
            }

            case "border":
            {
                var border = json.GetDic("slice_border");
                if (border == null)
                {
                    break;                     // borderパラメータがなかった
                }
                // 上・右・下・左の端から内側へのオフセット量
                var top    = border.GetInt("top") ?? 0;
                var right  = border.GetInt("right") ?? 0;
                var bottom = border.GetInt("bottom") ?? 0;
                var left   = border.GetInt("left") ?? 0;

                return(CheckWriteSpriteFromTexture(outputPath, readableTexture, new Boarder(left, bottom, right, top)));
            }
            }
            Debug.LogError($"[{Importer.NAME}] SliceSpriteの処理ができませんでした");
            return(null);
        }
Exemplo n.º 44
0
        private static void ParseWay(XmlReader rd, Dictionary <long, Waypoint> wps, OsmStreetSystem strt)
        {
            if (rd.IsEmptyElement)
            {
                return;
            }

            var wpIds = new ArrayList(2000);
            Dictionary <string, string> tags = new Dictionary <string, string>();

            while (rd.Read() && rd.NodeType != XmlNodeType.EndElement)
            {
                if (rd.NodeType == XmlNodeType.Element)
                {
                    switch (rd.Name)
                    {
                    case "nd":
                        wpIds.Add(long.Parse(rd.GetAttribute("ref")));
                        break;

                    case "tag":
                        tags.Add(
                            rd.GetAttribute("k"),
                            rd.GetAttribute("v")
                            );
                        break;
                    }
                }
            }

            if (!Defaults.HighwayWhitelist.Contains(tags.Get("highway", "-")))
            {
                return;
            }

            bool oneWay = (tags.Get("oneway", "no") == "yes") ||
                          (tags.Get("junction", "-") == "roundabout");

            var info = MakeConnectionInfo(tags);

            Waypoint last = wps[(long)wpIds[0]];

            if (!strt.Waypoints.ContainsKey(last.Id))
            {
                strt.Waypoints.Add(last.Id, last);
            }

            for (int i = 1; i < wpIds.Count; i++)
            {
                Waypoint current = wps[(long)wpIds[i]];
                if (!strt.Waypoints.ContainsKey(current.Id))
                {
                    strt.Waypoints.Add(current.Id, current);
                }

                last.ConnectTo(current, info);

                if (!oneWay)
                {
                    current.ConnectTo(last, info);
                }

                last = current;
            }
        }
Exemplo n.º 45
0
 public EnumDef getEnumDef(int def)
 {
     return(m_enumIdxs.Get(def));
 }
Exemplo n.º 46
0
 public virtual void InitFromParameters(Dictionary <string, string> requestParameters)
 {
     TransactionId = requestParameters.Get <string>(CommandsKeys.TransactionId);
 }
Exemplo n.º 47
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="assignments">the list of variable assignments</param>
        /// <param name="variableService">variable service</param>
        /// <param name="eventAdapterService">event adapters</param>
        /// <throws><seealso cref="ExprValidationException" /> when variables cannot be found</throws>
        public VariableReadWritePackage(IList <OnTriggerSetAssignment> assignments, VariableService variableService, EventAdapterService eventAdapterService)
        {
            _metaData             = new VariableMetaData[assignments.Count];
            _readersForGlobalVars = new VariableReader[assignments.Count];
            _mustCoerce           = new bool[assignments.Count];
            _writers = new WriteDesc[assignments.Count];

            _variableTypes       = new Dictionary <String, Object>();
            _eventAdapterService = eventAdapterService;
            _variableService     = variableService;

            IDictionary <EventTypeSPI, CopyMethodDesc> eventTypeWrittenProps = new Dictionary <EventTypeSPI, CopyMethodDesc>();
            var count = 0;
            IList <VariableTriggerSetDesc> assignmentList = new List <VariableTriggerSetDesc>();

            foreach (var expressionWithAssignments in assignments)
            {
                var possibleVariableAssignment = ExprNodeUtility.CheckGetAssignmentToVariableOrProp(expressionWithAssignments.Expression);
                if (possibleVariableAssignment == null)
                {
                    throw new ExprValidationException("Missing variable assignment expression in assignment number " + count);
                }
                assignmentList.Add(new VariableTriggerSetDesc(possibleVariableAssignment.First, possibleVariableAssignment.Second.ExprEvaluator));

                var    fullVariableName = possibleVariableAssignment.First;
                var    variableName     = fullVariableName;
                String subPropertyName  = null;

                var indexOfDot = variableName.IndexOf('.');
                if (indexOfDot != -1)
                {
                    subPropertyName = variableName.Substring(indexOfDot + 1);
                    variableName    = variableName.Substring(0, indexOfDot);
                }

                VariableMetaData variableMetadata = variableService.GetVariableMetaData(variableName);
                _metaData[count] = variableMetadata;
                if (variableMetadata == null)
                {
                    throw new ExprValidationException("Variable by name '" + variableName + "' has not been created or configured");
                }
                if (variableMetadata.IsConstant)
                {
                    throw new ExprValidationException("Variable by name '" + variableName + "' is declared constant and may not be set");
                }
                if (variableMetadata.ContextPartitionName == null)
                {
                    _readersForGlobalVars[count] = variableService.GetReader(variableName, EPStatementStartMethodConst.DEFAULT_AGENT_INSTANCE_ID);
                }

                if (subPropertyName != null)
                {
                    if (variableMetadata.EventType == null)
                    {
                        throw new ExprValidationException("Variable by name '" + variableName + "' does not have a property named '" + subPropertyName + "'");
                    }
                    var type = variableMetadata.EventType;
                    if (!(type is EventTypeSPI))
                    {
                        throw new ExprValidationException("Variable by name '" + variableName + "' event type '" + type.Name + "' not writable");
                    }
                    var spi    = (EventTypeSPI)type;
                    var writer = spi.GetWriter(subPropertyName);
                    var getter = spi.GetGetter(subPropertyName);
                    if (writer == null)
                    {
                        throw new ExprValidationException("Variable by name '" + variableName + "' the property '" + subPropertyName + "' is not writable");
                    }

                    _variableTypes.Put(fullVariableName, spi.GetPropertyType(subPropertyName));
                    var writtenProps = eventTypeWrittenProps.Get(spi);
                    if (writtenProps == null)
                    {
                        writtenProps = new CopyMethodDesc(variableName, new List <String>());
                        eventTypeWrittenProps.Put(spi, writtenProps);
                    }
                    writtenProps.PropertiesCopied.Add(subPropertyName);

                    _writers[count] = new WriteDesc(spi, variableName, writer, getter);
                }
                else
                {
                    // determine types
                    var expressionType = possibleVariableAssignment.Second.ExprEvaluator.ReturnType;

                    if (variableMetadata.EventType != null)
                    {
                        if ((expressionType != null) && (!TypeHelper.IsSubclassOrImplementsInterface(expressionType, variableMetadata.EventType.UnderlyingType)))
                        {
                            throw new VariableValueException("Variable '" + variableName
                                                             + "' of declared event type '" + variableMetadata.EventType.Name + "' underlying type '" + variableMetadata.EventType.UnderlyingType.GetCleanName() +
                                                             "' cannot be assigned a value of type '" + expressionType.GetCleanName() + "'");
                        }
                        _variableTypes.Put(variableName, variableMetadata.EventType.UnderlyingType);
                    }
                    else
                    {
                        var variableType = variableMetadata.VariableType;
                        _variableTypes.Put(variableName, variableType);

                        // determine if the expression type can be assigned
                        if (variableType != typeof(object))
                        {
                            if ((TypeHelper.GetBoxedType(expressionType) != variableType) &&
                                (expressionType != null))
                            {
                                if ((!TypeHelper.IsNumeric(variableType)) ||
                                    (!TypeHelper.IsNumeric(expressionType)))
                                {
                                    throw new ExprValidationException(VariableServiceUtil.GetAssigmentExMessage(variableName, variableType, expressionType));
                                }

                                if (!(TypeHelper.CanCoerce(expressionType, variableType)))
                                {
                                    throw new ExprValidationException(VariableServiceUtil.GetAssigmentExMessage(variableName, variableType, expressionType));
                                }

                                _mustCoerce[count] = true;
                            }
                        }
                    }
                }

                count++;
            }

            _assignments = assignmentList.ToArray();

            if (eventTypeWrittenProps.IsEmpty())
            {
                _copyMethods = new Dictionary <EventTypeSPI, EventBeanCopyMethod>();
                return;
            }

            _copyMethods = new Dictionary <EventTypeSPI, EventBeanCopyMethod>();
            foreach (var entry in eventTypeWrittenProps)
            {
                var propsWritten = entry.Value.PropertiesCopied;
                var props        = propsWritten.ToArray();
                var copyMethod   = entry.Key.GetCopyMethod(props);
                if (copyMethod == null)
                {
                    throw new ExprValidationException("Variable '" + entry.Value.VariableName
                                                      + "' of declared type " + entry.Key.UnderlyingType.GetCleanName() +
                                                      "' cannot be assigned to");
                }
                _copyMethods.Put(entry.Key, copyMethod);
            }
        }
Exemplo n.º 48
0
		private void Reflect(Scriptable scope, bool includeProtected, bool includePrivate)
		{
			// We reflect methods first, because we want overloaded field/method
			// names to be allocated to the NativeJavaMethod before the field
			// gets in the way.
			MethodInfo[] methods = DiscoverAccessibleMethods(cl, includeProtected, includePrivate);
			foreach (MethodInfo method in methods)
			{
				int mods = method.Attributes;
				bool isStatic = Modifier.IsStatic(mods);
				IDictionary<string, object> ht = isStatic ? staticMembers : members;
				string name = method.Name;
				object value = ht.Get(name);
				if (value == null)
				{
					ht.Put(name, method);
				}
				else
				{
					ObjArray overloadedMethods;
					if (value is ObjArray)
					{
						overloadedMethods = (ObjArray)value;
					}
					else
					{
						if (!(value is MethodInfo))
						{
							Kit.CodeBug();
						}
						// value should be instance of Method as at this stage
						// staticMembers and members can only contain methods
						overloadedMethods = new ObjArray();
						overloadedMethods.Add(value);
						ht.Put(name, overloadedMethods);
					}
					overloadedMethods.Add(method);
				}
			}
			// replace Method instances by wrapped NativeJavaMethod objects
			// first in staticMembers and then in members
			for (int tableCursor = 0; tableCursor != 2; ++tableCursor)
			{
				bool isStatic = (tableCursor == 0);
				IDictionary<string, object> ht = isStatic ? staticMembers : members;
				foreach (KeyValuePair<string, object> entry in ht.EntrySet())
				{
					MemberBox[] methodBoxes;
					object value = entry.Value;
					if (value is MethodInfo)
					{
						methodBoxes = new MemberBox[1];
						methodBoxes[0] = new MemberBox((MethodInfo)value);
					}
					else
					{
						ObjArray overloadedMethods = (ObjArray)value;
						int N = overloadedMethods.Size();
						if (N < 2)
						{
							Kit.CodeBug();
						}
						methodBoxes = new MemberBox[N];
						for (int i = 0; i != N; ++i)
						{
							MethodInfo method_1 = (MethodInfo)overloadedMethods.Get(i);
							methodBoxes[i] = new MemberBox(method_1);
						}
					}
					NativeJavaMethod fun = new NativeJavaMethod(methodBoxes);
					if (scope != null)
					{
						ScriptRuntime.SetFunctionProtoAndParent(fun, scope);
					}
					ht.Put(entry.Key, fun);
				}
			}
			// Reflect fields.
			FieldInfo[] fields = GetAccessibleFields(includeProtected, includePrivate);
			foreach (FieldInfo field in fields)
			{
				string name = field.Name;
				int mods = field.Attributes;
				try
				{
					bool isStatic = Modifier.IsStatic(mods);
					IDictionary<string, object> ht = isStatic ? staticMembers : members;
					object member = ht.Get(name);
					if (member == null)
					{
						ht.Put(name, field);
					}
					else
					{
						if (member is NativeJavaMethod)
						{
							NativeJavaMethod method_1 = (NativeJavaMethod)member;
							FieldAndMethods fam = new FieldAndMethods(scope, method_1.methods, field);
							IDictionary<string, FieldAndMethods> fmht = isStatic ? staticFieldAndMethods : fieldAndMethods;
							if (fmht == null)
							{
								fmht = new Dictionary<string, FieldAndMethods>();
								if (isStatic)
								{
									staticFieldAndMethods = fmht;
								}
								else
								{
									fieldAndMethods = fmht;
								}
							}
							fmht.Put(name, fam);
							ht.Put(name, fam);
						}
						else
						{
							if (member is FieldInfo)
							{
								FieldInfo oldField = (FieldInfo)member;
								// If this newly reflected field shadows an inherited field,
								// then replace it. Otherwise, since access to the field
								// would be ambiguous from Java, no field should be
								// reflected.
								// For now, the first field found wins, unless another field
								// explicitly shadows it.
								if (oldField.DeclaringType.IsAssignableFrom(field.DeclaringType))
								{
									ht.Put(name, field);
								}
							}
							else
							{
								// "unknown member type"
								Kit.CodeBug();
							}
						}
					}
				}
				catch (SecurityException)
				{
					// skip this field
					Context.ReportWarning("Could not access field " + name + " of class " + cl.FullName + " due to lack of privileges.");
				}
			}
			// Create bean properties from corresponding get/set methods first for
			// static members and then for instance members
			for (int tableCursor_1 = 0; tableCursor_1 != 2; ++tableCursor_1)
			{
				bool isStatic = (tableCursor_1 == 0);
				IDictionary<string, object> ht = isStatic ? staticMembers : members;
				IDictionary<string, BeanProperty> toAdd = new Dictionary<string, BeanProperty>();
				// Now, For each member, make "bean" properties.
				foreach (string name in ht.Keys)
				{
					// Is this a getter?
					bool memberIsGetMethod = name.StartsWith("get");
					bool memberIsSetMethod = name.StartsWith("set");
					bool memberIsIsMethod = name.StartsWith("is");
					if (memberIsGetMethod || memberIsIsMethod || memberIsSetMethod)
					{
						// Double check name component.
						string nameComponent = Sharpen.Runtime.Substring(name, memberIsIsMethod ? 2 : 3);
						if (nameComponent.Length == 0)
						{
							continue;
						}
						// Make the bean property name.
						string beanPropertyName = nameComponent;
						char ch0 = nameComponent[0];
						if (System.Char.IsUpper(ch0))
						{
							if (nameComponent.Length == 1)
							{
								beanPropertyName = nameComponent.ToLower();
							}
							else
							{
								char ch1 = nameComponent[1];
								if (!System.Char.IsUpper(ch1))
								{
									beanPropertyName = System.Char.ToLower(ch0) + Sharpen.Runtime.Substring(nameComponent, 1);
								}
							}
						}
						// If we already have a member by this name, don't do this
						// property.
						if (toAdd.ContainsKey(beanPropertyName))
						{
							continue;
						}
						object v = ht.Get(beanPropertyName);
						if (v != null)
						{
							// A private field shouldn't mask a public getter/setter
							if (!includePrivate || !(v is MemberInfo) || !Modifier.IsPrivate(((MemberInfo)v).Attributes))
							{
								continue;
							}
						}
						// Find the getter method, or if there is none, the is-
						// method.
						MemberBox getter = null;
						getter = FindGetter(isStatic, ht, "get", nameComponent);
						// If there was no valid getter, check for an is- method.
						if (getter == null)
						{
							getter = FindGetter(isStatic, ht, "is", nameComponent);
						}
						// setter
						MemberBox setter = null;
						NativeJavaMethod setters = null;
						string setterName = System.String.Concat("set", nameComponent);
						if (ht.ContainsKey(setterName))
						{
							// Is this value a method?
							object member = ht.Get(setterName);
							if (member is NativeJavaMethod)
							{
								NativeJavaMethod njmSet = (NativeJavaMethod)member;
								if (getter != null)
								{
									// We have a getter. Now, do we have a matching
									// setter?
									Type type = getter.Method().ReturnType;
									setter = ExtractSetMethod(type, njmSet.methods, isStatic);
								}
								else
								{
									// No getter, find any set method
									setter = ExtractSetMethod(njmSet.methods, isStatic);
								}
								if (njmSet.methods.Length > 1)
								{
									setters = njmSet;
								}
							}
						}
						// Make the property.
						BeanProperty bp = new BeanProperty(getter, setter, setters);
						toAdd.Put(beanPropertyName, bp);
					}
				}
				// Add the new bean properties.
				foreach (string key in toAdd.Keys)
				{
					object value = toAdd.Get(key);
					ht.Put(key, value);
				}
			}
			// Reflect constructors
			ConstructorInfo<object>[] constructors = GetAccessibleConstructors(includePrivate);
			MemberBox[] ctorMembers = new MemberBox[constructors.Length];
			for (int i_1 = 0; i_1 != constructors.Length; ++i_1)
			{
				ctorMembers[i_1] = new MemberBox(constructors[i_1]);
			}
			ctors = new NativeJavaMethod(ctorMembers, cl.Name);
		}
Exemplo n.º 49
0
        private async Task HandleShellLibraryMessage(Dictionary <string, object> message)
        {
            switch ((string)message["action"])
            {
            case "Enumerate":
                // Read library information and send response to UWP
                var enumerateResponse = await Win32API.StartSTATask(() =>
                {
                    var response = new ValueSet();
                    try
                    {
                        var libraryItems = new List <ShellLibraryItem>();
                        // https://docs.microsoft.com/en-us/windows/win32/search/-search-win7-development-scenarios#library-descriptions
                        var libFiles = Directory.EnumerateFiles(ShellLibraryItem.LibrariesPath, "*" + ShellLibraryItem.EXTENSION);
                        foreach (var libFile in libFiles)
                        {
                            using var shellItem = new ShellLibrary2(Shell32.ShellUtil.GetShellItemForPath(libFile), true);
                            if (shellItem is ShellLibrary2 library)
                            {
                                libraryItems.Add(ShellFolderExtensions.GetShellLibraryItem(library, libFile));
                            }
                        }
                        response.Add("Enumerate", JsonConvert.SerializeObject(libraryItems));
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Warn(e);
                    }
                    return(response);
                });

                await Win32API.SendMessageAsync(connection, enumerateResponse, message.Get("RequestID", (string)null));

                break;

            case "Create":
                // Try create new library with the specified name and send response to UWP
                var createResponse = await Win32API.StartSTATask(() =>
                {
                    var response = new ValueSet();
                    try
                    {
                        using var library = new ShellLibrary2((string)message["library"], Shell32.KNOWNFOLDERID.FOLDERID_Libraries, false);
                        library.Folders.Add(ShellItem.Open(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));     // Add default folder so it's not empty
                        library.Commit();
                        library.Reload();
                        response.Add("Create", JsonConvert.SerializeObject(ShellFolderExtensions.GetShellLibraryItem(library, library.GetDisplayName(ShellItemDisplayString.DesktopAbsoluteParsing))));
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Warn(e);
                    }
                    return(response);
                });

                await Win32API.SendMessageAsync(connection, createResponse, message.Get("RequestID", (string)null));

                break;

            case "Update":
                // Update details of the specified library and send response to UWP
                var updateResponse = await Win32API.StartSTATask(() =>
                {
                    var response = new ValueSet();
                    try
                    {
                        var folders           = message.ContainsKey("folders") ? JsonConvert.DeserializeObject <string[]>((string)message["folders"]) : null;
                        var defaultSaveFolder = message.Get("defaultSaveFolder", (string)null);
                        var isPinned          = message.Get("isPinned", (bool?)null);

                        bool updated      = false;
                        var libPath       = (string)message["library"];
                        using var library = new ShellLibrary2(Shell32.ShellUtil.GetShellItemForPath(libPath), false);
                        if (folders != null)
                        {
                            if (folders.Length > 0)
                            {
                                var foldersToRemove = library.Folders.Where(f => !folders.Any(folderPath => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase)));
                                foreach (var toRemove in foldersToRemove)
                                {
                                    library.Folders.Remove(toRemove);
                                    updated = true;
                                }
                                var foldersToAdd = folders.Distinct(StringComparer.OrdinalIgnoreCase)
                                                   .Where(folderPath => !library.Folders.Any(f => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase)))
                                                   .Select(ShellItem.Open);
                                foreach (var toAdd in foldersToAdd)
                                {
                                    library.Folders.Add(toAdd);
                                    updated = true;
                                }
                                foreach (var toAdd in foldersToAdd)
                                {
                                    toAdd.Dispose();
                                }
                            }
                        }
                        if (defaultSaveFolder != null)
                        {
                            library.DefaultSaveFolder = ShellItem.Open(defaultSaveFolder);
                            updated = true;
                        }
                        if (isPinned != null)
                        {
                            library.PinnedToNavigationPane = isPinned == true;
                            updated = true;
                        }
                        if (updated)
                        {
                            library.Commit();
                            library.Reload();     // Reload folders list
                            response.Add("Update", JsonConvert.SerializeObject(ShellFolderExtensions.GetShellLibraryItem(library, libPath)));
                        }
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Warn(e);
                    }
                    return(response);
                });

                await Win32API.SendMessageAsync(connection, updateResponse, message.Get("RequestID", (string)null));

                break;
            }
        }
Exemplo n.º 50
0
 private PackageItem GetPackageItem(string packageUniqueId)
 {
     return(string.IsNullOrEmpty(packageUniqueId) ? null : m_PackageItemsLookup.Get(packageUniqueId));
 }
Exemplo n.º 51
0
        public void Register(System.Type clz)
        {
            if (clz.IsEnum)
            {
                if (m_enumDefs.Get(clz) == null)
                {
                    EnumDef def = EnumDef.valueOf(clz);
                    if (def == null)
                    {
                        return;
                    }
                    m_enumIdxs.Add(def.code, def);
                    m_enumDefs.Add(clz, def);
                    m_log.AppendFormat("Protocol注册了枚举:{0} code:{1} \n", clz.Name, def.code);
                }
            }
            else if (!clz.IsClass)
            {
                Debuger.LogError("不能注册的类型:{0}", clz.Name);
            }
            else if (clz.IsArray)
            {
                System.Type elemType = clz.GetElementType();
                if (ProtocolCoder.CanRegister(elemType))
                {
                    ProtocolCoder.instance.Register(elemType);
                }
            }
            else if (clz.GetInterface("System.Collections.IList") != null)
            {
                if (m_collectionDefs.Get(clz) == null)
                {
                    CollectionDef def = CollectionDef.valueOf(clz);
                    if (def == null)
                    {
                        return;
                    }
                    m_collectionIdxs.Add(def.code, def);
                    m_collectionDefs.Add(clz, def);
                    m_log.AppendFormat("Protocol注册了list:{0} code:{1} element:{2} \n", clz.Name, def.code, def.elementType.Name);
                }
            }
            else if (clz.GetInterface("System.Collections.IDictionary") != null)
            {
                if (m_mapDefs.Get(clz) == null)
                {
                    MapDef def = MapDef.valueOf(clz);
                    if (def == null)
                    {
                        return;
                    }
                    m_mapIdxs.Add(def.code, def);
                    m_mapDefs.Add(clz, def);
                    m_log.AppendFormat("Protocol注册了map:{0} code:{1} key:{2} value:{3} \n", clz.Name, def.code, def.keyType.Name, def.valueType.Name);
                }
            }
            else
            {
                if (m_typeDefs.Get(clz) == null)
                {
                    if (!IsObjectType(clz))
                    {
                        Debuger.LogError("不能序列化的类型,不能序列化模板类型、c#原生类型、继承自其他类的类型:{0}", clz.Name);
                        return;
                    }
                    TimeCheck check = new TimeCheck();
                    TypeDef   def   = TypeDef.valueOf(clz, m_typeDefs);
                    if (def == null)
                    {
                        return;
                    }
                    m_typeIdxs.Add(def.code, def);

                    m_log.AppendFormat("Protocol注册了类:{0} code:{1} 耗时:{2} \n", clz.Name, def.code, check.delayMS);
                }
            }
        }
Exemplo n.º 52
0
 public CollectionDef getCollectionDef(int def)
 {
     return(m_collectionIdxs.Get(def));
 }
Exemplo n.º 53
0
        /// <exception cref="NGit.Errors.CorruptObjectException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void AssertWorkDir(Dictionary<string, string> i)
        {
            TreeWalk walk = new TreeWalk(db);
            walk.Recursive = true;
            walk.AddTree(new FileTreeIterator(db));
            string expectedValue;
            string path;
            int nrFiles = 0;
            FileTreeIterator ft;
            while (walk.Next())
            {
                ft = walk.GetTree<FileTreeIterator>(0);
                path = ft.EntryPathString;
                expectedValue = i.Get(path);
                NUnit.Framework.Assert.IsNotNull(expectedValue, "found unexpected file for path "
                     + path + " in workdir");
                FilePath file = new FilePath(db.WorkTree, path);
                NUnit.Framework.Assert.IsTrue(file.Exists());
                if (file.IsFile())
                {
                    FileInputStream @is = new FileInputStream(file);
                    byte[] buffer = new byte[(int)file.Length()];
                    int offset = 0;
                    int numRead = 0;
                    while (offset < buffer.Length && (numRead = @is.Read(buffer, offset, buffer.Length
                         - offset)) >= 0)
                    {
                        offset += numRead;
                    }
                    @is.Close();

                    CollectionAssert.AreEqual (buffer, Sharpen.Runtime.GetBytesForString(i.Get(path)),
                        "unexpected content for path " + path + " in workDir. ");
                    nrFiles++;
                }
            }
            NUnit.Framework.Assert.AreEqual(i.Count, nrFiles, "WorkDir has not the right size."
                );
        }
Exemplo n.º 54
0
 public MapDef getMapDef(int def)
 {
     return(m_mapIdxs.Get(def));
 }
Exemplo n.º 55
0
        private void MapProductSummaryItem(Product product, MapProductSummaryItemContext ctx)
        {
            var contextProduct = product;
            var finalPrice     = decimal.Zero;
            var model          = ctx.Model;
            var settings       = ctx.Settings;

            var item = new ProductSummaryModel.SummaryItem(ctx.Model)
            {
                Id     = product.Id,
                Name   = product.GetLocalized(x => x.Name).EmptyNull(),
                SeName = product.GetSeName()
            };

            if (model.ShowDescription)
            {
                item.ShortDescription = product.GetLocalized(x => x.ShortDescription);
            }

            if (settings.MapFullDescription)
            {
                item.FullDescription = product.GetLocalized(x => x.FullDescription);
            }

            // Price
            if (settings.MapPrices)
            {
                finalPrice = MapSummaryItemPrice(product, ref contextProduct, item, ctx);
            }

            // (Color) Attributes
            if (settings.MapColorAttributes || settings.MapAttributes)
            {
                #region Map (color) attributes

                var attributes = ctx.BatchContext.Attributes.GetOrLoad(contextProduct.Id);

                var cachedAttributeNames = new Dictionary <int, string>();

                // Color squares
                if (attributes.Any() && settings.MapColorAttributes)
                {
                    var colorAttributes = attributes
                                          .Where(x => x.IsListTypeAttribute())
                                          .SelectMany(x => x.ProductVariantAttributeValues)
                                          .Where(x => x.Color.HasValue() && !x.Color.IsCaseInsensitiveEqual("transparent"))
                                          .Distinct()
                                          .Take(20)       // limit results
                                          .Select(x =>
                    {
                        var attr     = x.ProductVariantAttribute.ProductAttribute;
                        var attrName = cachedAttributeNames.Get(attr.Id) ?? (cachedAttributeNames[attr.Id] = attr.GetLocalized(l => l.Name));

                        return(new ProductSummaryModel.ColorAttributeValue
                        {
                            Id = x.Id,
                            Color = x.Color,
                            Alias = x.Alias,
                            FriendlyName = x.GetLocalized(l => l.Name),
                            AttributeId = x.ProductVariantAttributeId,
                            AttributeName = attrName,
                            ProductAttributeId = attr.Id,
                            ProductUrl = _productUrlHelper.GetProductUrl(product.Id, item.SeName, 0, x)
                        });
                    })
                                          .ToList();

                    item.ColorAttributes = colorAttributes;

                    // TODO: (mc) Resolve attribute value images also
                }

                // Variant Attributes
                if (attributes.Any() && settings.MapAttributes)
                {
                    if (item.ColorAttributes != null && item.ColorAttributes.Any())
                    {
                        var processedIds = item.ColorAttributes.Select(x => x.AttributeId).Distinct().ToArray();
                        attributes = attributes.Where(x => !processedIds.Contains(x.Id)).ToList();
                    }

                    foreach (var attr in attributes)
                    {
                        var pa = attr.ProductAttribute;
                        item.Attributes.Add(new ProductSummaryModel.Attribute
                        {
                            Id    = attr.Id,
                            Alias = pa.Alias,
                            Name  = cachedAttributeNames.Get(pa.Id) ?? (cachedAttributeNames[pa.Id] = pa.GetLocalized(l => l.Name))
                        });
                    }
                }

                #endregion
            }

            // Picture
            if (settings.MapPictures)
            {
                #region Map product picture

                // If a size has been set in the view, we use it in priority
                int pictureSize = model.ThumbSize.HasValue ? model.ThumbSize.Value : _mediaSettings.ProductThumbPictureSize;

                // Prepare picture model
                var defaultProductPictureCacheKey = string.Format(
                    ModelCacheEventConsumer.PRODUCT_DEFAULTPICTURE_MODEL_KEY,
                    product.Id,
                    pictureSize,
                    true,
                    _services.WorkContext.WorkingLanguage.Id,
                    ctx.Store.Id);

                item.Picture = _services.Cache.Get(defaultProductPictureCacheKey, () =>
                {
                    if (!ctx.BatchContext.Pictures.FullyLoaded)
                    {
                        ctx.BatchContext.Pictures.LoadAll();
                    }

                    var picture      = ctx.BatchContext.Pictures.GetOrLoad(product.Id).FirstOrDefault();
                    var pictureModel = new PictureModel
                    {
                        Size             = pictureSize,
                        ImageUrl         = _pictureService.GetPictureUrl(picture, pictureSize, !_catalogSettings.HideProductDefaultPictures),
                        FullSizeImageUrl = _pictureService.GetPictureUrl(picture, 0, !_catalogSettings.HideProductDefaultPictures),
                        Title            = string.Format(ctx.Resources["Media.Product.ImageLinkTitleFormat"], item.Name),
                        AlternateText    = string.Format(ctx.Resources["Media.Product.ImageAlternateTextFormat"], item.Name),
                        PictureId        = picture == null ? 0 : picture.Id
                    };

                    return(pictureModel);
                }, TimeSpan.FromHours(6));

                #endregion
            }

            // Manufacturers
            if (settings.MapManufacturers)
            {
                item.Manufacturer = PrepareManufacturersOverviewModel(
                    ctx.BatchContext.ProductManufacturers.GetOrLoad(product.Id),
                    ctx.CachedManufacturerModels,
                    _catalogSettings.ShowManufacturerLogoInLists && settings.ViewMode == ProductSummaryViewMode.List).FirstOrDefault();
            }

            // Spec Attributes
            if (settings.MapSpecificationAttributes)
            {
                item.SpecificationAttributes.AddRange(MapProductSpecificationModels(ctx.BatchContext.SpecificationAttributes.GetOrLoad(product.Id)));
            }

            item.MinPriceProductId = contextProduct.Id;
            item.Sku = contextProduct.Sku;

            // Measure Dimensions
            if (model.ShowDimensions && (contextProduct.Width != 0 || contextProduct.Height != 0 || contextProduct.Length != 0))
            {
                item.Dimensions = ctx.Resources["Products.DimensionsValue"].Text.FormatCurrent(
                    contextProduct.Width.ToString("N2"),
                    contextProduct.Height.ToString("N2"),
                    contextProduct.Length.ToString("N2")
                    );
                item.DimensionMeasureUnit = _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId).SystemKeyword;
            }

            // Delivery Times
            item.HideDeliveryTime = (product.ProductType == ProductType.GroupedProduct);
            if (model.ShowDeliveryTimes && !item.HideDeliveryTime)
            {
                #region Delivery Time

                // We cannot include ManageInventoryMethod.ManageStockByAttributes because it's only functional with MergeWithCombination.
                //item.StockAvailablity = contextProduct.FormatStockMessage(_localizationService);
                //item.DisplayDeliveryTimeAccordingToStock = contextProduct.DisplayDeliveryTimeAccordingToStock(_catalogSettings);

                //var deliveryTime = _deliveryTimeService.GetDeliveryTime(contextProduct);
                //if (deliveryTime != null)
                //{
                //	item.DeliveryTimeName = deliveryTime.GetLocalized(x => x.Name);
                //	item.DeliveryTimeHexValue = deliveryTime.ColorHexValue;
                //}

                var deliveryTimeId = product.DeliveryTimeId ?? 0;
                if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock && product.StockQuantity <= 0 && _catalogSettings.DeliveryTimeIdForEmptyStock.HasValue)
                {
                    deliveryTimeId = _catalogSettings.DeliveryTimeIdForEmptyStock.Value;
                }

                var deliveryTime = _deliveryTimeService.GetDeliveryTimeById(deliveryTimeId);
                if (deliveryTime != null)
                {
                    item.DeliveryTimeName     = deliveryTime.GetLocalized(x => x.Name);
                    item.DeliveryTimeHexValue = deliveryTime.ColorHexValue;
                }

                if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
                {
                    item.DisplayDeliveryTimeAccordingToStock = product.StockQuantity > 0 || (product.StockQuantity <= 0 && _catalogSettings.DeliveryTimeIdForEmptyStock.HasValue);
                }
                else
                {
                    item.DisplayDeliveryTimeAccordingToStock = true;
                }

                if (product.DisplayStockAvailability && product.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
                {
                    if (product.StockQuantity > 0)
                    {
                        if (product.DisplayStockQuantity)
                        {
                            item.StockAvailablity = T("Products.Availability.InStockWithQuantity", product.StockQuantity);
                        }
                        else
                        {
                            item.StockAvailablity = T("Products.Availability.InStock");
                        }
                    }
                    else
                    {
                        if (product.BackorderMode == BackorderMode.NoBackorders || product.BackorderMode == BackorderMode.AllowQtyBelow0)
                        {
                            item.StockAvailablity = T("Products.Availability.OutOfStock");
                        }
                        else if (product.BackorderMode == BackorderMode.AllowQtyBelow0AndNotifyCustomer)
                        {
                            item.StockAvailablity = T("Products.Availability.Backordering");
                        }
                    }
                }

                #endregion
            }

            item.LegalInfo         = ctx.LegalInfo;
            item.RatingSum         = product.ApprovedRatingSum;
            item.TotalReviews      = product.ApprovedTotalReviews;
            item.IsShippingEnabled = contextProduct.IsShipEnabled;

            if (finalPrice != decimal.Zero && model.ShowBasePrice)
            {
                item.BasePriceInfo = contextProduct.GetBasePriceInfo(finalPrice, _localizationService, _priceFormatter, ctx.Currency);
            }

            if (settings.MapPrices)
            {
                var addShippingPrice = _currencyService.ConvertCurrency(contextProduct.AdditionalShippingCharge, ctx.Store.PrimaryStoreCurrency, ctx.Currency);

                if (addShippingPrice > 0)
                {
                    item.TransportSurcharge = ctx.Resources["Common.AdditionalShippingSurcharge"].Text.FormatCurrent(_priceFormatter.FormatPrice(addShippingPrice, true, false));
                }
            }

            if (model.ShowWeight && contextProduct.Weight > 0)
            {
                item.Weight = "{0} {1}".FormatCurrent(contextProduct.Weight.ToString("N2"), _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).Name);
            }

            // New Badge
            if (product.IsNew(_catalogSettings))
            {
                item.Badges.Add(new ProductSummaryModel.Badge
                {
                    Label = T("Common.New"),
                    Style = BadgeStyle.Success
                });
            }

            model.Items.Add(item);
        }
Exemplo n.º 56
0
 /// <summary>
 /// Get a registerd type name by type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static string GetDefaultName(Type type)
 {
     return(m_typeNames.Get(type.GetHashCode()));
 }
        private IEnumerable<BrowseFacet> FilterByKeys(IEnumerable<BrowseFacet> facets, char separator, int numFacetsPerKey, string[] values) {
            var keyOccurences = new Dictionary<string, AtomicInteger>();
            var editable = facets.ToList();
            string separatorString = Convert.ToString(separator);
            for (int i = 0; i < facets.Count(); i++)
            {
                BrowseFacet facet = facets.ElementAt(i);
                string value = facet.Value;
                if (!value.Contains(separatorString)) {
                    editable.Remove(facet);
                    continue;
                }

                if (values != null && values.Length > 0)
                {
                    bool belongsToKeys = false;
                    foreach (var val in values)
                    {
                        if (value.StartsWith(val))
                        {
                            belongsToKeys = true;
                            break;
                        }
                    }
                    if (!belongsToKeys)
                    {
                        editable.Remove(facet);
                        continue;
                    }
                }
                string key = value.Substring(0, value.IndexOf(separatorString));
                AtomicInteger numOfKeys = keyOccurences.Get(key);
                if (numOfKeys == null)
                {
                    numOfKeys = new AtomicInteger(0);
                    keyOccurences.Put(key, numOfKeys);
                }
                int count = numOfKeys.IncrementAndGet();
                if (count > numFacetsPerKey)
                {
                    editable.Remove(facet);
                }
            }
            return editable;
        }
Exemplo n.º 58
0
        public override GameObject Render(Renderer renderer, GameObject parentObject)
        {
            var go = CreateUIGameObject(renderer);

            var rect = go.GetComponent <RectTransform>();

            if (parentObject)
            {
                //親のパラメータがある場合、親にする 後のAnchor定義のため
                rect.SetParent(parentObject.transform);
            }

            var image = go.AddComponent <Image>();

            if (spriteName != null)
            {
                image.sprite = renderer.GetSprite(spriteName);
            }

            image.color = new Color(1.0f, 1.0f, 1.0f, opacity != null ? opacity.Value / 100.0f : 0);
            var raycastTarget = imageJson.GetBool("raycast_target");

            if (raycastTarget != null)
            {
                image.raycastTarget = raycastTarget.Value;
            }

            image.type = Image.Type.Sliced;
            var imageType = imageJson.Get("image_type");

            if (imageType != null)
            {
                switch (imageType.ToLower())
                {
                case "sliced":
                    image.type = Image.Type.Sliced;
                    break;

                case "filled":
                    image.type = Image.Type.Filled;
                    break;

                case "tiled":
                    image.type = Image.Type.Tiled;
                    break;

                case "simple":
                    image.type = Image.Type.Simple;
                    break;

                default:
                    Debug.LogAssertion("[Baum2+] unknown image_type:" + imageType);
                    break;
                }
            }

            var preserveAspect = imageJson.GetBool("preserve_aspect");

            if (preserveAspect != null)
            {
                // アスペクト比を保つ場合はSimpleにする
                image.type           = Image.Type.Simple;
                image.preserveAspect = preserveAspect.Value;
            }

            SetAnchor(go, renderer);

            return(go);
        }
Exemplo n.º 59
0
        /**
         * /// Computes the composition of two Fsts. Assuming no epsilon transitions.
         * ///
         * /// Input Fsts are not modified.
         * ///
         * /// @param fst1 the first Fst
         * /// @param fst2 the second Fst
         * /// @param semiring the semiring to use in the operation
         * /// @param sorted
         * /// @return the composed Fst
         */
        public static Fst compose(Fst fst1, Fst fst2, Semiring semiring, Boolean sorted)
        {
            if (!Arrays.AreEqual(fst1.Osyms, fst2.Isyms))
            {
                // symboltables do not match
                return(null);
            }

            Fst res = new Fst(semiring);

            Dictionary <Pair <State, State>, State> stateMap = new Dictionary <Pair <State, State>, State>();
            Queue <Pair <State, State> >            queue    = new Queue <Pair <State, State> >();

            State s1 = fst1.Start;
            State s2 = fst2.Start;

            if ((s1 == null) || (s2 == null))
            {
                Logger.LogInfo <Compose>("Cannot find initial state.");
                return(null);
            }

            Pair <State, State> p = new Pair <State, State>(s1, s2);
            State s = new State(semiring.Times(s1.FinalWeight,
                                               s2.FinalWeight));

            res.AddState(s);
            res.SetStart(s);
            if (stateMap.ContainsKey(p))
            {
                stateMap[p] = s;
            }
            else
            {
                stateMap.Add(p, s);
            }
            queue.Enqueue(p);

            while (queue.Count != 0)
            {
                p  = queue.Dequeue();
                s1 = p.GetLeft();
                s2 = p.GetRight();
                s  = stateMap[p];
                int numArcs1 = s1.GetNumArcs();
                int numArcs2 = s2.GetNumArcs();
                for (int i = 0; i < numArcs1; i++)
                {
                    Arc a1 = s1.GetArc(i);
                    for (int j = 0; j < numArcs2; j++)
                    {
                        Arc a2 = s2.GetArc(j);
                        if (sorted && a1.Olabel < a2.Ilabel)
                        {
                            break;
                        }
                        if (a1.Olabel == a2.Ilabel)
                        {
                            State nextState1             = a1.NextState;
                            State nextState2             = a2.NextState;
                            Pair <State, State> nextPair = new Pair <State, State>(
                                nextState1, nextState2);
                            State nextState = stateMap.Get(nextPair);
                            if (nextState == null)
                            {
                                nextState = new State(semiring.Times(
                                                          nextState1.FinalWeight,
                                                          nextState2.FinalWeight));
                                res.AddState(nextState);
                                if (stateMap.ContainsKey(nextPair))
                                {
                                    stateMap[nextPair] = nextState;
                                }
                                else
                                {
                                    stateMap.Add(nextPair, nextState);
                                }

                                queue.Enqueue(nextPair);
                            }
                            Arc a = new Arc(a1.Ilabel, a2.Olabel,
                                            semiring.Times(a1.Weight, a2.Weight),
                                            nextState);
                            s.AddArc(a);
                        }
                    }
                }
            }

            res.Isyms = fst1.Isyms;
            res.Osyms = fst2.Osyms;

            return(res);
        }
Exemplo n.º 60
0
 public void ShouldGetMeaningfulExceptionIfObjectDoesntExistByKey()
 {
     var bag = new Dictionary <string, object>();
     var url = bag.Get <Url>("foobar");
 }