protected void VerifyParameters()
		{
			if ( actualNamedParameters.Count != namedParameters.Count + namedParameterLists.Count )
			{
				Set missingParams = new ListSet( actualNamedParameters );
				missingParams.RemoveAll( namedParameterLists.Keys );
				missingParams.RemoveAll( namedParameters.Keys );
				throw new QueryException( "Not all named parameters have been set: " + CollectionPrinter.ToString( missingParams ), QueryString );
			}

			if ( positionalParameterCount != values.Count ) 
			{
				throw new QueryException( string.Format( "Not all positional parameters have been set. Expected {0}, set {1}", positionalParameterCount, values.Count ),
					QueryString );
			}

			for ( int i = 0; i < values.Count; i++ )
			{
				if ( values[i] == UNSET_PARAMETER || types[i] == UNSET_TYPE ) 
				{
					throw new QueryException( string.Format( "Not all positional parameters have been set. Found unset parameter at position {0}", i),
						QueryString );
				}
			}
		}
        /// <summary>
        /// Given a string, returns all instances of @abc in an ordered set containing abc (the token without the @ sign). If a token is used more than once, it
        /// only appears in the list once. A different prefix may be used for certain databases.
        /// </summary>
        internal static ListSet<string> GetNamedParamList( DatabaseInfo info, string statement )
        {
            // We don't want to find parameters in quoted text.
            statement = statement.RemoveTextBetweenStrings( "'", "'" ).RemoveTextBetweenStrings( "\"", "\"" );

            var parameters = new ListSet<string>();
            foreach( Match match in Regex.Matches( statement, getParamRegex( info ) ) )
                parameters.Add( match.Value.Substring( 1 ) );

            return parameters;
        }
        public void FillTypeItems(
			ClassOrStructBlock callingClass,
			ICompletionListBuilder items)
        {
            ListSet<TextPictureInfo> result = new ListSet<TextPictureInfo>();
            FillTypeList(callingClass, result);
            foreach (TextPictureInfo t in result)
            {
                items.AddText(t.Text, t.Picture);
            }
        }
Beispiel #4
0
 /// <summary>
 /// A MultiPoint is simple if it has no repeated points.
 /// </summary>
 public bool IsSimple(IMultiPoint mp)
 {
     if (mp.IsEmpty) 
         return true;
     ISet points = new ListSet();
     for (int i = 0; i < mp.NumGeometries; i++)
     {
         IPoint pt = (IPoint) mp.GetGeometryN(i);
         ICoordinate p = pt.Coordinate;
         if (points.Contains(p))
             return false;
         points.Add(p);
     }
     return true;
 }   
        public void TestDifferentCollectionTypes()
        {
            const string xml = @"<?xml version='1.0' encoding='UTF-8' ?>
            <objects xmlns='http://www.springframework.net' xmlns:v='http://www.springframework.net/validation'>
          <v:group id='validatePerson' when='T(Spring.Objects.TestObject) == #this.GetType()'>
            <v:required id ='req' when='true' test='Name'/>
            <v:regex id ='reg' test='Name'>
              <v:property name='Expression' value='[a-z]*\s[a-z]*'/>
              <v:property name='Options' value='IgnoreCase'/>
              <v:message id='reg1' providers='regularni' when='true'>
                 <v:param value='#this.ToString()'/> 
              </v:message>
            </v:regex>
          </v:group>  
           <v:collection id='collectionValidator' validate-all='true'>
                <v:ref name='validatePerson'/>
           </v:collection>
           </objects>";

            MemoryStream stream = new MemoryStream(new UTF8Encoding().GetBytes(xml));
            IResource resource = new InputStreamResource(stream, "collectionValidator");

            XmlObjectFactory objectFactory = new XmlObjectFactory(resource, null);
            CollectionValidator validator = (CollectionValidator) objectFactory.GetObject("collectionValidator");
            
            IList listPersons = new ArrayList();
            IDictionary dictPersons = new Hashtable();
            ISet setPersons = new ListSet();  

            listPersons.Add(new TestObject("DAMJAN Tomic", 24));
            listPersons.Add(new TestObject("Goran Milosavljevic", 24));
            listPersons.Add(new TestObject("Ivan CIKIC", 28));

            dictPersons.Add(1, listPersons[0]);
            dictPersons.Add(2, listPersons[1]);
            dictPersons.Add(3, listPersons[2]);

            setPersons.AddAll(listPersons);
            IValidationErrors ve = new ValidationErrors();

            Assert.IsTrue(validator.Validate(listPersons, ve));                        
            Assert.IsTrue(ve.IsEmpty);                                    
            Assert.IsTrue(validator.Validate(dictPersons, ve));
            Assert.IsTrue(ve.IsEmpty);
            Assert.IsTrue(validator.Validate(setPersons, ve));
            Assert.IsTrue(ve.IsEmpty);
        }
        public override void FillItems(CustomItemsRequestEventArgs e)
        {
            LanguageService ls = LanguageService.Get(this);
            ClassOrStructBlock parent = ClassNavigator.FindContainingClassOrStruct(this);

            if (ls != null && parent != null)
            {
                ListSet<TextPictureInfo> result = new ListSet<TextPictureInfo>();
                AddItems(e.Items, ItemStrings);

                ls.FillTypeList(parent, result);
                foreach (TextPictureInfo s in result)
                {
                    CompletionListItem item = CreateItem(s.Text);
                    if (item.ShouldShow(this.Completion))
                    {
                        item.Picture = s.Picture;
                        e.Items.Add(item);
                    }
                }
            }
        }
Beispiel #7
0
        public IImage[] GetImages()
        {
            ListSet<IImage> images = new ListSet<IImage>();

            if (this.ShapeDef == null)
            {
                return new IImage[0];
            }

            foreach (IFillStyle fs in this.ShapeDef.FillStyles)
            {
                if (fs.Bitmap != null)
                {
                    images.AddIfNotAlredy(fs.Bitmap);
                }
            }

            foreach (IShapeRecord sr in this.ShapeDef.Records)
            {
                if (sr is StyleChange)
                {
                    StyleChange sc = (StyleChange)sr;
                    IFillStyle fs = sc.FillStyle0;
                    if (fs != null && fs.Bitmap != null)
                    {
                        images.AddIfNotAlredy(fs.Bitmap);
                    }

                    fs = sc.FillStyle1;
                    if (fs != null && fs.Bitmap != null)
                    {
                        images.AddIfNotAlredy(fs.Bitmap);
                    }
                }
            }

            return images.ToArray();
        }
Beispiel #8
0
        private void WriteCharacter(ICharacter ch, ListSet<Timeline> unboundClasses)
        {
            int cid;

            if (ch == null)
            {
                return;
            }

            if (this.characterMarshal.HasMarshalled(ch))
            {
                return;
            }

            int fontID = -1;

            if (ch is IFontUserProcessor)
            {
                IFontUserProcessor fup = (IFontUserProcessor)ch;
                fup.FontUserProc(delegate(IFontUser fu)
                {
                    if (fu.HasFont && !characterMarshal.HasMarshalled(fu.Font))
                    {
                        fontID = characterMarshal.GetIDFor(fu.Font);
                        this.WriteFont(fu.Font, fontID);
                    }
                    else
                    {
                        fontID = characterMarshal.GetExistingIDFor(fu.Font);
                    }
                });
            }

            if (ch is IShape)
            {
                IImage[] images = ((IShape)ch).GetImages();

                if (images != null)
                {
                    foreach (IImage image in images)
                    {
                        this.WriteImage(image);
                    }
                }

                Tag format;
                byte[] shapeBytes = ShapeWriter.ShapeToBytes((IShape)ch, out format);

                WriteBuffer shapeTag = this.OpenTag(format);
                cid = this.characterMarshal.GetIDFor(ch);
                shapeTag.WriteUI16((uint)cid);
                shapeTag.WriteBytes(shapeBytes);
            #if DEBUG
                this.LogMessage("char id=" + cid);
            #endif
                this.CloseTag();
            }
            else if (ch is Sprite)
            {
                this.WriteSprite((Sprite)ch, unboundClasses);
            }
            else if (ch is EditText)
            {
                this.WriteEditText((EditText)ch, fontID);
            }
            else if (ch is StaticText)
            {
                this.WriteStaticText((StaticText)ch);
            }
            else
            {
                /* ISSUE 73 */
                throw new SWFModellerException(
                            SWFModellerError.UnimplementedFeature,
                            "Character of type " + ch.GetType().ToString() + " not currently supported in writer");
            }

            if (ch is Timeline)
            {
                Timeline tl = (Timeline)ch;
                if (tl.HasClass && !(tl.Class is AdobeClass) && !unboundClasses.Contains(tl))
                {
                    unboundClasses.Add(tl);
                }
            }
        }
        public void TestIntersectionOperator()
        {
            object o = ExpressionEvaluator.GetValue(null, "{111, 'ivan', 23, 24} * {111, 11, 'ivan'}");
            Assert.IsInstanceOf(typeof(ISet), o);
            ISet intersection = (ISet)o;
            Assert.AreEqual(2, intersection.Count);
            Assert.IsTrue(intersection.Contains(111));
            Assert.IsTrue(intersection.Contains("ivan"));

            o = ExpressionEvaluator.GetValue(null, "{24, 25, 'aaa' + 'bb'} * {date('2007/2/5').day * 5, 24 - 1}");
            Assert.IsInstanceOf(typeof(ISet), o);
            intersection = (ISet)o;
            Assert.AreEqual(1, intersection.Count);
            Assert.IsTrue(intersection.Contains(25));

            ISet testset = new ListSet();
            testset.AddAll(new int[] { 1, 2, 3, 5, 8 });
            o = ExpressionEvaluator.GetValue(testset, "#this * #{1:'one', 10:'ten'}");
            Assert.IsInstanceOf(typeof(ISet), o);
            intersection = (ISet)o;
            Assert.AreEqual(1, intersection.Count);
            Assert.IsTrue(intersection.Contains(1));

            o = ExpressionEvaluator.GetValue(null, "#{1:'one', 2:'two', 3:'three'} * #{1:'ivan', 5:'five'}");
            Assert.IsInstanceOf(typeof(IDictionary), o);
            IDictionary result = (IDictionary)o;
            Assert.AreEqual(1, result.Count);
            Assert.AreEqual("one", result[1]);

            o = ExpressionEvaluator.GetValue(null, "#{1:'one', 2:'two', 3:'three'} * {1, 2, 5, 7}");
            Assert.IsInstanceOf(typeof(IDictionary), o);
            result = (IDictionary)o;
            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("one", result[1]);
            Assert.AreEqual("two", result[2]);
        }
Beispiel #10
0
 /// <summary>
 /// Check that a ring does not self-intersect, except at its endpoints.
 /// Algorithm is to count the number of times each node along edge occurs.
 /// If any occur more than once, that must be a self-intersection.
 /// </summary>
 private void CheckNoSelfIntersectingRing(EdgeIntersectionList eiList)
 {
     ISet nodeSet = new ListSet();    
     bool isFirst = true;
     foreach(EdgeIntersection ei in eiList)
     {                
         if (isFirst)
         {
             isFirst = false;
             continue;
         }
         if (nodeSet.Contains(ei.Coordinate))
         {
             validErr = new TopologyValidationError(TopologyValidationErrors.RingSelfIntersection, ei.Coordinate);
             return;
         }
         else nodeSet.Add(ei.Coordinate);
     }
 }
 /// <summary>
 /// Return an array of object-type property names that are unsatisfied.
 /// </summary>
 /// <remarks>
 /// <p>
 /// These are probably unsatisfied references to other objects in the
 /// factory. Does not include simple properties like primitives or
 /// <see cref="System.String"/>s.
 /// </p>
 /// </remarks>
 /// <returns>
 /// An array of object-type property names that are unsatisfied.
 /// </returns>
 /// <param name="definition">
 /// The definition of the named object.
 /// </param>
 /// <param name="wrapper">
 /// The <see cref="Spring.Objects.IObjectWrapper"/> wrapping the target object.
 /// </param>
 protected string[] UnsatisfiedNonSimpleProperties(RootObjectDefinition definition, IObjectWrapper wrapper)
 {
     ListSet results = new ListSet();
     IPropertyValues pvs = definition.PropertyValues;
     PropertyInfo[] properties = wrapper.GetPropertyInfos();
     foreach (PropertyInfo property in properties)
     {
         string name = property.Name;
         if (property.CanWrite
             && !IsExcludedFromDependencyCheck(property)
             && !pvs.Contains(name)
             && !ObjectUtils.IsSimpleProperty(property.PropertyType))
         {
             results.Add(name);
         }
     }
     return (string[])CollectionUtils.ToArray(results, typeof(string));
 }
		public void ManyToManyUsingSet()
		{
			ActiveRecordStarter.Initialize(GetConfigSource(), 
				typeof(Order), typeof(Product)/*, typeof(LineItem)*/);
			Recreate();
			
			Order.DeleteAll();
			Product.DeleteAll();
			
			Order myOrder = new Order();
			myOrder.OrderedDate = DateTime.Parse("05/09/2004");
			Product coolGadget = new Product();
			coolGadget.Name = "PSP";
			coolGadget.Price = 250.39f;
			
			using (new SessionScope())
			{
				coolGadget.Save();
				ISet products = new ListSet();
				products.Add(coolGadget);
				myOrder.Products = products;
				myOrder.Save();
			}
			
			Order secondRef2Order = Order.Find(myOrder.ID);
			Assert.IsFalse(secondRef2Order.Products.IsEmpty);
			
			Product secondRef2Product = Product.Find(coolGadget.ID);
			Assert.AreEqual(1, secondRef2Product.Orders.Count);	
		}
        /// <summary>
        /// Runs the provided package by a set of rules
        /// </summary>
        /// <returns>null on success, or an IHttpActionResult on a failure</returns>
        private IHttpActionResult ValidatePackage(WorkPackageDTO package)
        {
            // get the list of child packages
            var allPackages = new ListSet<WorkPackageDTO>(package.AllChildren)
                              {
                                  package // include the root package to make coding life easier
                              };
            
            // load any existing packages from the context
            var childPackagesFromDb = this._workPackageRepository.GetAll(allPackages.Select(wp => wp.Id).Where(i => i > 0)).ToDictionary(wp => wp.Id);


            // first pass - replace non modifyable packages with their current data from the db
            var newPackageCount = -1;
            var newTaskCount = -1;
            for (var i = 0; i < allPackages.Count; i++)
            {
                var pkg = allPackages[i];

                if (childPackagesFromDb.ContainsKey(pkg.Id))
                {
                    // we're dealing with an existing package

                    var fromDb = childPackagesFromDb[pkg.Id];
                    if (fromDb.IsReadOnlyFor(this._currentUser))
                    {
                        // ignore any changes to packages the user has no right to change
                        allPackages[i] = Mapper.Map<WorkPackageDTO>(fromDb);
                        continue;
                    }
                    else
                    {
                        // note that we don't update the values here - it gets done by the repository
                    }
                }
                else
                {
                    // we're dealing with a new package

                    pkg.Id = newPackageCount--;
                    pkg.CreatedBy = this._currentUserDto;
                }

                // make sure each of the tasks have a unique Id
                foreach (var task in pkg.Tasks.Where(t => t.Id < 0))
                {
                    task.Id = newTaskCount--;
                }
            }


            // second pass - update the packages with correct references
            // note that whilst we don't update the read only package's content (tasks, name, etc) - we do have to make sure it has the correct package references
            //      so that EF doesn't try and add two of the same package
            var childDict = allPackages.ToDictionary(wp => wp.Id);
            var processedPackages = new HashSet<WorkPackageDTO>();
            foreach (var pkg in allPackages)
            {
                if (!Utilities.IsNullOrEmpty(pkg.ChildPackages) && // save a little time in processing packages with no children
                    !processedPackages.Contains(pkg)) // don't reprocess packages
                {
                    pkg.ChildPackages = new ListSet<WorkPackageDTO>(pkg.ChildPackages.Select(child => childDict[child.Id]));
                }
                processedPackages.Add(pkg);
            }

            // third pass - check for cycles
            // we do this last because we may remove a cycle when we clean up readonly packages
            var packageWithCycle = package.DetectCycles();
            if (packageWithCycle != null)
            {
                return this.BadRequest(string.Format(Resources.Error_CreatePackage_Cycles, packageWithCycle.Id));
            }
            return null;
        }
Beispiel #14
0
        private void WriteSprite(Sprite s, ListSet<Timeline> unboundClasses)
        {
            foreach (ICharacterReference cr in s.CharacterRefs)
            {
                this.WriteCharacter(cr.Character, unboundClasses);
            }

            if (s.HasClass && !(s.Class is AdobeClass) && !unboundClasses.Contains(s))
            {
                unboundClasses.Add(s);
            }

            int id = this.characterMarshal.GetIDFor(s);
            WriteBuffer tagWriter = this.OpenTag(Tag.DefineSprite, s.ToString() + ";id=" + id.ToString());
            tagWriter.WriteUI16((uint)id);
            tagWriter.WriteUI16(s.FrameCount);
            #if DEBUG
            this.LogMessage("char id=" + id);
            #endif

            foreach (Frame f in s.Frames)
            {
                if (f.HasLabel)
                {
            #if DEBUG
                    this.LogMessage("frame label=" + f.Label);
            #endif
                    WriteBuffer labelWriter = this.OpenTag(Tag.FrameLabel);
                    labelWriter.WriteString(f.Label);
                    this.CloseTag();
                }

                foreach (IDisplayListItem dli in f.DisplayList)
                {
                    switch (dli.Type)
                    {
                        case DisplayListItemType.PlaceObjectX:
                            this.WritePlaceObjectTag((PlaceObject)dli);
                            break;

                        case DisplayListItemType.RemoveObjectX:
                            this.WriteRemoveObjectTag((RemoveObject)dli);
                            break;

                        default:
                            /* ISSUE 73 */
                            throw new SWFModellerException(
                                    SWFModellerError.UnimplementedFeature,
                                    "Unsupported tag in SWF sprite writer: " + dli.GetType().ToString());
                    }
                }

                this.WriteBodylessTag(Tag.ShowFrame);
            }

            this.WriteBodylessTag(Tag.End, id.ToString());

            this.CloseTag(); /* DefineSprite */
        }
    public void SetSensors(List<ISensor> sensors,
      IDictionary<ISensor, Color> colors) {
      this.model.Series.Clear();

      ListSet<SensorType> types = new ListSet<SensorType>();

      foreach (ISensor sensor in sensors) {
        var series = new LineSeries();
        if (sensor.SensorType == SensorType.Temperature) {
          series.ItemsSource = sensor.Values.Select(value => new DataPoint {
            X = (now - value.Time).TotalSeconds,
            Y = unitManager.TemperatureUnit == TemperatureUnit.Celsius ? 
              value.Value : UnitManager.CelsiusToFahrenheit(value.Value).Value
          });
        } else {
          series.ItemsSource = sensor.Values.Select(value => new DataPoint {
            X = (now - value.Time).TotalSeconds, Y = value.Value
          });
        }
        series.Color = colors[sensor].ToOxyColor();
        series.StrokeThickness = 1;
        series.YAxisKey = axes[sensor.SensorType].Key;
        series.Title = sensor.Hardware.Name + " " + sensor.Name;
        this.model.Series.Add(series);

        types.Add(sensor.SensorType);
      }

      foreach (var pair in axes.Reverse()) {
        var axis = pair.Value;
        var type = pair.Key;
        axis.IsAxisVisible = types.Contains(type);
      } 

      UpdateAxesPosition();
      InvalidatePlot();
    }
        public void TestDifferenceOperator()
        {
            object o = ExpressionEvaluator.GetValue(null, "{111, 11} - {14, 12, 11}");
            Assert.IsInstanceOf(typeof(ISet), o);
            ISet diff = (ISet)o;
            Assert.AreEqual(1, diff.Count);
            Assert.IsTrue(diff.Contains(111));

            o = ExpressionEvaluator.GetValue(null, "{111, 11} - {14, 12, 11} - {111}");
            Assert.IsInstanceOf(typeof(ISet), o);
            diff = (ISet)o;
            Assert.AreEqual(0, diff.Count);

            ISet testset = new ListSet();
            testset.AddAll(new int[] { 1, 2, 3, 5, 8 });
            o = ExpressionEvaluator.GetValue(testset, "#this - #{1:'one', 10:'ten'}");
            Assert.IsInstanceOf(typeof(ISet), o);
            diff = (ISet)o;
            Assert.AreEqual(4, diff.Count);
            Assert.IsFalse(diff.Contains(1));

            o = ExpressionEvaluator.GetValue(null, "#{1:'one', 2:'two', 3:'three'} - #{1:'ivan', 5:'five'}");
            Assert.IsInstanceOf(typeof(IDictionary), o);
            IDictionary result = (IDictionary)o;
            Assert.AreEqual(2, result.Count);
            Assert.IsNull(result[1]);
            Assert.AreEqual("three", result[3]);

            o = ExpressionEvaluator.GetValue(null, "#{1:'one', 2:'two', 3:'three'} - {1, 2, 3, 5, 7}");
            Assert.IsInstanceOf(typeof(IDictionary), o);
            result = (IDictionary)o;
            Assert.AreEqual(0, result.Count);
        }
Beispiel #17
0
        private void BindClasses(ListSet<Timeline> unboundClasses)
        {
            if (unboundClasses.Count > 0)
            {
                WriteBuffer symbolBuf = this.OpenTag(Tag.SymbolClass);

                symbolBuf.WriteUI16((uint)unboundClasses.Count);

                foreach (Timeline t in unboundClasses)
                {
                    symbolBuf.WriteUI16((uint)this.characterMarshal.GetIDFor((ICharacter)t));
                    symbolBuf.WriteString(t.Class.QualifiedName);
                    this.LogMessage(
                            "ID:" +
                            (uint)this.characterMarshal.GetIDFor((ICharacter)t) +
                            " => " +
                            t.Class.QualifiedName);
                }
                this.CloseTag();

                unboundClasses.Clear();
            }
        }
        public void TestSortProcessor()
        {
            int[] arr = new int[] { 24, 8, 14, 6 };
            Assert.AreEqual(new int[] { 6, 8, 14, 24 }, ExpressionEvaluator.GetValue(arr, "sort()"));
            Assert.AreEqual(new int[] { 6, 8, 14, 24 }, ExpressionEvaluator.GetValue(arr, "sort(true)"));
            Assert.AreEqual(new int[] { 24, 14, 8, 6 }, ExpressionEvaluator.GetValue(arr, "sort(false)"));

            string[] arr2 = new string[] { "abc", "xyz", "stuv", "efg", "dcb" };
            Assert.AreEqual(new string[] { "abc", "dcb", "efg", "stuv", "xyz" },
                            ExpressionEvaluator.GetValue(arr2, "sort()"));

            DateTime[] arr3 = new DateTime[] { DateTime.Today, DateTime.MaxValue, DateTime.MinValue };
            Assert.AreEqual(new DateTime[] { DateTime.MinValue, DateTime.Today, DateTime.MaxValue },
                            ExpressionEvaluator.GetValue(arr3, "sort()"));

            Assert.AreEqual(new object[] { -3.3, 1.2, 5.5 }, ExpressionEvaluator.GetValue(null, "{1.2, 5.5, -3.3}.sort()"));
            Assert.IsNull(ExpressionEvaluator.GetValue(null, "sort()"));

            ISet set = new ListSet(arr);
            Assert.AreEqual(new int[] { 6, 8, 14, 24 }, ExpressionEvaluator.GetValue(set, "sort()"));
        }
Beispiel #19
0
        private ListSet<ICharacterReference> PopulateCharacterRefList(ListSet<ICharacterReference> refs)
        {
            foreach (Frame f in FrameList)
            {
                foreach (IDisplayListItem dli in f.DisplayList)
                {
                    if (dli is ICharacterReference)
                    {
                        ICharacterReference cr = (ICharacterReference)dli;

                        refs.Add(cr);

                        if (cr.Character is Sprite && !refs.Contains(cr))
                        {
                            ((Sprite)cr.Character).PopulateCharacterRefList(refs);
                        }
                    }
                }
            }
            return refs;
        }
Beispiel #20
0
 public void GetAllInterfacesSunnyDay()
 {
     ImplementsTwoInterfaces instance = new ImplementsTwoInterfaces();
     Type[] interfaces = AopUtils.GetAllInterfaces(instance);
     Assert.IsNotNull(interfaces, "Must never return null.");
     Assert.AreEqual(2, interfaces.Length,
                     "Implements two interfaces.");
     ISet ifaces = new ListSet(interfaces);
     Assert.IsTrue(
         ifaces.ContainsAll(
             new Type [] {typeof(IDisposable), typeof(ICloneable)}),
         "Did not find the correct interfaces.");
 }
        public static void Main()
        {
            GlobalInitializationOps.InitStatics( new GlobalInitializer(), "Tester", false );

            EwlStatics.RunStandardLibraryTests();

            Console.WriteLine( new TimeSpan( 0, 0, 0, 0, 4861000 ).ToHourMinuteSecondString() );
            Console.WriteLine( new TimeSpan( 0, 0, 0, 0, 4861000 ).ToHourMinuteString() );
            Console.WriteLine( new TimeSpan( 0, 0, 0, 0, 104861000 ).ToHourMinuteSecondString() );
            Console.WriteLine( new TimeSpan( 0, 0, 0, 0, 104861000 ).ToHourMinuteString() );
            Console.WriteLine( new TimeSpan( 1, 2, 3, 4, 0 ).ToHourMinuteSecondString() );
            Console.WriteLine( new TimeSpan( 1, 2, 3, 4, 0 ).ToHourMinuteString() );
            Console.WriteLine( new TimeSpan( 0, 1, 32 ).ToHourMinuteSecondString() );

            Console.WriteLine( FormattingMethods.GetFormattedBytes( 64 ) );
            Console.WriteLine( FormattingMethods.GetFormattedBytes( 64000 ) );
            Console.WriteLine( FormattingMethods.GetFormattedBytes( 64000000 ) );
            Console.WriteLine( FormattingMethods.GetFormattedBytes( 64500000000 ) );

            Console.WriteLine( "fred".CapitalizeString() );
            Console.WriteLine( "".CapitalizeString() );
            Console.WriteLine( "\n".CapitalizeString() );
            Console.WriteLine( "f".CapitalizeString() );
            Console.WriteLine( "1234f".CapitalizeString() );
            Console.WriteLine( "1234".CapitalizeString() );
            Console.WriteLine( "       f".CapitalizeString() );
            Console.WriteLine( "       ".CapitalizeString() );
            Console.WriteLine( " fred".CapitalizeString() );
            Console.WriteLine( " fred died.".CapitalizeString() );
            Console.WriteLine( ".".CapitalizeString() );
            Console.WriteLine( " .".CapitalizeString() );
            Console.WriteLine( " .fred died.".CapitalizeString() );
            Console.WriteLine( " . fred died.".CapitalizeString() );
            Console.WriteLine( "\nfred".CapitalizeString() );
            Console.WriteLine( " \n fred".CapitalizeString() );
            Console.WriteLine( "\n------\nfred".CapitalizeString() );

            Console.WriteLine( "one two three.csv".ToSafeFileName() );

            Console.WriteLine( "One {one one } two {two}".RemoveTextBetweenStrings( "{", "}" ) );
            Console.WriteLine( "This 'quoted text'.".RemoveTextBetweenStrings( "'", "'" ) );
            Console.WriteLine( "A comments looks like /*A comment.*/.".RemoveTextBetweenStrings( "/*", "*/" ) );
            Console.WriteLine( "body.ewf div.ewfIeWarningBanner table a { font-size:1.5em; }".RemoveTextBetweenStrings( "{", "}" ) );

            Console.WriteLine( "one".ConcatenateWithSpace( "two" ) );
            Console.WriteLine( EnterpriseWebLibrary.StringTools.ConcatenateWithDelimiter( ", ", "one", "two", "three" ) );
            Console.WriteLine( EnterpriseWebLibrary.StringTools.ConcatenateWithDelimiter( "|", "", "one", "", "", "two", "", "three ", "   " ) );

            Console.WriteLine( "abcde".Truncate( 4 ) );
            Console.WriteLine( "abcde".TruncateStart( 4 ) );
            Console.WriteLine( NetTools.CombineUrls( @"http://www.redstapler.biz", "/Files", "Carriers", "Hancock/", "blabla.pdf" ) );
            Console.WriteLine( NetTools.CombineUrls( @"http://www.redstapler.biz", "//Files", "Carriers", "Hancock//", "blabla.pdf//" ) );
            Console.WriteLine( NetTools.CombineUrls( @"///http://www.redstapler.biz//", "/Files/", "Carriers/", "Hancock/", "/blabla.pdf/" ) );
            Console.WriteLine( NetTools.CombineUrls( @"http://localhost/ToddPublicWebSite/", "Carriers", "UP", "ComparisonLogo.jpg" ) );

            Console.WriteLine( EwlStatics.CombinePaths( @"C:\Inetpub\", "Files", "orgs", "box.txt" ) );
            Console.WriteLine( EwlStatics.CombinePaths( @"C:\Inetpub\", "Files", "orgs", "anotherFolder", "box.txt" ) );
            Console.WriteLine( EwlStatics.CombinePaths( @"C:\Inetpub\", "Files", @"orgs\" ) );
            Console.WriteLine( EwlStatics.CombinePaths( @"C:\Inetpub", @"\Files\", @"\orgs", "box.txt" ) );
            Console.WriteLine( EwlStatics.CombinePaths( @"Inetpub", @"Files" ) );
            Console.WriteLine( EwlStatics.CombinePaths( @"D:\Source Control Repository\Charette", @"", @"\Aspose.Words.lic" ) );

            Console.WriteLine( EnterpriseWebLibrary.StringTools.CamelToEnglish( null ) );
            Console.WriteLine( "".CamelToEnglish() );
            Console.WriteLine( "L".CamelToEnglish() );
            Console.WriteLine( "l".CamelToEnglish() );
            Console.WriteLine( "LeftLeg".CamelToEnglish() );
            Console.WriteLine( "hits you in the Head and the LeftLeg!  That hurts.".CamelToEnglish() );

            var mySet = new HashSet<string> { "a", "c", "", "b", "fred" };

            var list = new List<string>( mySet );
            foreach( var item in mySet )
                list.Add( item );

            //	mySet = new Set( list );

            var ls = new ListSet<string> { "one", "two", "one", "two" };
            foreach( var item in ls )
                Console.WriteLine( item );

            var validator = new Validator();
            var vp = new ValidationErrorHandler( errorWriter );

            Console.WriteLine( validator.GetUrl( vp, "hTTp://RedStapler.biZ/fRed", false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( validator.GetUrl( vp, "fred", true ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.Write( validator.GetNullableSqlSmallDateTimeExact( vp, "fred", "MM/dd/yyy", false ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( validator.GetInt( vp, "fred" ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter ); // "myGoodInt" );
            Console.WriteLine( validator.GetInt( vp, "-342" ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter ); // "myBadDate" );
            Console.WriteLine( validator.GetSqlSmallDateTimeFromParts( vp, "3", "", "" ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter ); // "myBadDate" );
            Console.WriteLine( validator.GetSqlSmallDateTimeFromParts( vp, "", "", "" ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter ); // "zip" );
            Console.WriteLine( validator.GetZipCode( vp, "14580", true ).FullZipCode );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter ); // "zip" );
            Console.WriteLine( validator.GetZipCode( vp, "14580-1234", true ).FullZipCode );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter ); // "badZip" );
            Console.WriteLine( validator.GetZipCode( vp, "123", false ).FullZipCode );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            Console.WriteLine( "---------------------------------\nPhone Numbers:\n------------------------------------\n" );
            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( validator.GetPhoneNumber( vp, "5854556476", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( validator.GetPhoneNumber( vp, "585 4556476", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( validator.GetPhoneNumber( vp, "( 585 )455-6476", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( validator.GetPhoneNumber( vp, "(585)455-6476", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( validator.GetPhoneNumber( vp, "585-455-6476", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "With lots of spaces: " + validator.GetPhoneNumber( vp, "585   872   0291  ", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "With x: " + validator.GetPhoneNumber( vp, "5854556476   x   12345", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "With space ext. allowed: " + validator.GetPhoneNumber( vp, "5854556476 12345", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "Toni example 1: " + validator.GetPhoneNumber( vp, "321-663-4810", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "Toni example 2: " + validator.GetPhoneNumber( vp, "585-336-7600 ext 65361", true, true, false ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "Gibberish, should fail^ " + validator.GetPhoneNumber( vp, "sodifuoisafdoiu", true, true, true ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "With space no ext. allowed, should fail^ " + validator.GetPhoneNumber( vp, "5854556476 12345", false, false, true ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "With extension and no delimeters, should fail^ " + validator.GetPhoneNumber( vp, "585455647612345", true, true, false ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine(
                "With extension and no delimeters, should succeed since allowGarbage is on. " + validator.GetPhoneNumber( vp, "585455647612345", true, true, true ) );
            Assert.IsFalse( vp.LastResult != ErrorCondition.NoError );

            vp = new ValidationErrorHandler( errorWriter );
            Console.WriteLine( "Should fail^ " + validator.GetPhoneNumber( vp, "02934", true, true, false ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            Console.WriteLine( "------------------------\nEnd phone numbers.\n-------------------------------\n" );

            vp = new ValidationErrorHandler( errorWriter ); // "badByte" );
            Console.WriteLine( validator.GetByte( vp, "234987234" ) );
            Assert.IsFalse( vp.LastResult == ErrorCondition.NoError );

            var key = Rijndael.Create().Key;
            Console.Write( "Encryption Key: { " );
            foreach( var b in key )
                Console.Write( b + ", " );
            Console.WriteLine();

            Console.WriteLine( "SSN length: " + EncryptionOps.EncryptString( EncryptionOps.GenerateInitVector(), "987654321" ).Length );
        }
        public IEnumerable<TextPictureInfo> GetTypeList(
			ClassOrStructBlock callingClass)
        {
            ListSet<TextPictureInfo> results = new ListSet<TextPictureInfo>();
            FillTypeList(callingClass, results);
            return results;
        }
        public void TestUnionOperator()
        {
            object o = ExpressionEvaluator.GetValue(null, "{1,2,3} + {3,4,5}");
            Assert.IsInstanceOf(typeof(ISet), o);
            ISet union = (ISet)o;
            Assert.AreEqual(5, union.Count);
            Assert.IsTrue(union.Contains(1));
            Assert.IsTrue(union.Contains(3));
            Assert.IsTrue(union.Contains(5));

            o = ExpressionEvaluator.GetValue(null, "{1,2,3} + {3,4,5} + {'ivan', 'gox', 'damjao', 5}");
            Assert.IsInstanceOf(typeof(ISet), o);
            union = (ISet)o;
            Assert.AreEqual(8, union.Count);
            Assert.IsTrue(union.Contains(1));
            Assert.IsTrue(union.Contains("ivan"));

            ISet testset = new ListSet();
            testset.AddAll(new int[] { 1, 2, 3, 5, 8 });
            o = ExpressionEvaluator.GetValue(testset, "#this + {1, 2, 13, 15}");
            Assert.IsInstanceOf(typeof(ISet), o);
            union = (ISet)o;
            Assert.AreEqual(7, union.Count);
            Assert.IsTrue(union.Contains(1));
            Assert.IsTrue(union.Contains(15));

            o = ExpressionEvaluator.GetValue(null, "#{1:'one', 2:'two', 3:'three'} + #{1:'ivan', 5:'five'}");
            Assert.IsInstanceOf(typeof(IDictionary), o);
            IDictionary result = (IDictionary)o;
            Assert.AreEqual(4, result.Count);
            Assert.AreEqual("one", result[1]);
            Assert.AreEqual("five", result[5]);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="g"></param>
 /// <returns></returns>
 public ICoordinate[] ExtractTargetCoordinates(IGeometry g)
 {
     // TODO: should do this more efficiently.  Use CoordSeq filter to get points, KDTree for uniqueness & queries
     ListSet<ICoordinate> ptSet = new ListSet<ICoordinate>(g.Coordinates);
     ICoordinate[] result = new ICoordinate[ptSet.Count];
     ptSet.CopyTo(result, 0);
     return result;
 }
Beispiel #25
0
        public void SetDefaults()
        {
            DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            StringSet = new HashedSet();
            StringSet.Add("foo");
            StringSet.Add("bar");
            StringSet.Add("baz");

            StringDateMap = new SortedList();
            StringDateMap.Add("now", DateTime.Now);
            StringDateMap.Add("never", null); // value is persisted since NH-2199
            // according to SQL Server the big bag happened in 1753 ;)
            StringDateMap.Add("big bang", new DateTime(1753, 01, 01));
            //StringDateMap.Add( "millenium", new DateTime( 2000, 01, 01 ) );
            ArrayList list = new ArrayList();
            list.AddRange(StringSet);
            StringList = list;
            IntArray = new int[] {1, 3, 3, 7};
            FooArray = new Foo[0];
            StringArray = (String[]) list.ToArray(typeof(string));
            Customs = new ArrayList();
            Customs.Add(new String[] {"foo", "bar"});
            Customs.Add(new String[] {"A", "B"});
            Customs.Add(new String[] {"1", "2"});

            FooSet = new HashedSet();
            Components = new FooComponent[]
                {
                    new FooComponent("foo", 42, null, null),
                    new FooComponent("bar", 88, null, new FooComponent("sub", 69, null, null))
                };
            TimeArray = new DateTime[]
                {
                    new DateTime(),
                    new DateTime(),
                    new DateTime(), // H2.1 has null here, but it's illegal on .NET
                    new DateTime(0)
                };

            Count = 667;
            Name = "Bazza";
            TopComponents = new ArrayList();
            TopComponents.Add(new FooComponent("foo", 11, new DateTime[] {today, new DateTime(2123, 1, 1)}, null));
            TopComponents.Add(
                new FooComponent("bar", 22, new DateTime[] {new DateTime(2007, 2, 3), new DateTime(1945, 6, 1)}, null));
            TopComponents.Add(null);
            Bag = new ArrayList();
            Bag.Add("duplicate");
            Bag.Add("duplicate");
            Bag.Add("duplicate");
            Bag.Add("unique");

            Cached = new ListSet();

            CompositeElement ce = new CompositeElement();
            ce.Foo = "foo";
            ce.Bar = "bar";
            CompositeElement ce2 = new CompositeElement();
            ce2.Foo = "fooxxx";
            ce2.Bar = "barxxx";
            Cached.Add(ce);
            Cached.Add(ce2);
            CachedMap = new SortedList();
            CachedMap.Add(this, ce);
        }
Beispiel #26
0
        /// <summary>
        /// Does the grunt-work of writing all the objects in the SWF file, tagging
        /// each of them with a record header.
        /// </summary>
        private void WriteTags()
        {
            /* Start with a file attributes tag */
            this.WriteFileAttributesTag();
            /* Despite background color being specified in the header, flash always puts this in too. */
            this.WriteBGColorTag();

            if (swf.ProtectHash != null)
            {
                /* ISSUE 45: This should be an option of some kind. */
                WriteBuffer protectTag = this.OpenTag(Tag.Protect);
                protectTag.WriteUI16(0); /* Reserved, always 0 */
                protectTag.WriteString(swf.ProtectHash);
                this.CloseTag();
            }

            if (this.options.EnableDebugger)
            {
                WriteBuffer dbugTag = this.OpenTag(Tag.EnableDebugger2);
                dbugTag.WriteUI16(0); /* Reserved, always 0 */
                dbugTag.WriteString("$1$ZH$B14iwyCzzcXcqLaJz0Mif0"); /* MD5-encoded password "abc"; http://devadraco.blogspot.com/2009/06/guide-to-cracking-enabledebugger2.html */
                this.CloseTag();
            }

            /* ISSUE 46: Write DefineSceneAndFrameLabelData tag */
            foreach (DoABC abc in this.swf.Scripts)
            {
                WriteBuffer abcOut = this.OpenTag(Tag.DoABC);

                abcOut.WriteUI32((uint)(abc.IsLazilyInitialized ? ABCValues.AbcFlagLazyInitialize : 0));
                abcOut.WriteString(abc.Name);

                AbcWriter abcWriter = new AbcWriter();
                abcWriter.AssembleIfNecessary(
                        abc,
                        this.options.EnableDebugger,
                        this.swf.Class == null ? null : this.swf.Class.QualifiedName,
                        this.abcWriteLog);

                abcOut.WriteBytes(abc.Bytecode);

                this.CloseTag();
            }

            ListSet<Timeline> writtenSymbolClasses = new ListSet<Timeline>();
            ListSet<Timeline> unboundClasses = new ListSet<Timeline>();

            foreach (Sprite exported in this.swf.ExportOnFirstFrame)
            {
                this.WriteSprite(exported, unboundClasses);
            }

            this.BindClasses(unboundClasses);

            if (this.swf.FrameCount > 0)
            {
                int writtenFrames = 0;

                if (this.swf.HasClass)
                {
                    WriteBuffer scbuf = this.OpenTag(Tag.SymbolClass);
                    scbuf.WriteUI16(1); /* Count */
                    scbuf.WriteUI16(0); /* Character ref */
                    scbuf.WriteString(this.swf.Class.QualifiedName); /* Name */
                    this.LogMessage(this.swf.Class.QualifiedName);
                    this.CloseTag();
                }

                foreach (Frame f in this.swf.Frames)
                {
                    if (f.HasLabel)
                    {
            #if DEBUG
                        this.LogMessage("frame label=" + f.Label);
            #endif
                        WriteBuffer labelWriter = this.OpenTag(Tag.FrameLabel);
                        labelWriter.WriteString(f.Label);
                        this.CloseTag();
                    }

                    foreach (IDisplayListItem dli in f.DisplayList)
                    {
                        switch (dli.Type)
                        {
                            case DisplayListItemType.PlaceObjectX:
                                this.WriteCharacter(((ICharacterReference)dli).Character, unboundClasses);
                                this.WritePlaceObjectTag((PlaceObject)dli);
                                break;

                            case DisplayListItemType.RemoveObjectX:
                            default:
                                this.WriteRemoveObjectTag((RemoveObject)dli);
                                break;
                        }
                    }

                    this.BindClasses(unboundClasses);

                    this.WriteBodylessTag(Tag.ShowFrame);

                    writtenFrames++;

                    List<SymbolClass> symbolClasses = new List<SymbolClass>();
                }
            }
            else
            {
                /* No SWF should be frameless. Awwww. */
                this.WriteBodylessTag(Tag.ShowFrame);
            }

            /* Finish with an end tag */
            this.WriteBodylessTag(Tag.End);
        }