Example #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));
        }
Example #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);
        }
Example #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);
     }
 }
Example #7
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));
        }
Example #8
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);
     }
 }
Example #9
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;
            }
              }
        }
Example #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();
 }
Example #11
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);
        }
        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);
        }
Example #13
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;
 }
Example #14
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;
 }
Example #15
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( );
              }
        }
        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);
        }
Example #17
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");
     }
 }
 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;
 }
        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();
        }
        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);
        }
        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");
        }
Example #22
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"));
        }
        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");
        }
Example #24
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);
        }
        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;
        }
Example #26
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);
		}
Example #27
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 + ">");
     }
 }
Example #28
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."
                );
        }
Example #29
0
 public void Execute(Dictionary<string, object> bundle)
 {
     System.Console.WriteLine(String.Format("A:{0}", bundle.Get<DateTime>("A")));
 }
        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);
                }
            });
        }