예제 #1
0
 public StoresController(
     [ServiceDependency] IGeoLocationServiceAgent geocodeServiceAgent,
     [CreateNew] IUnitOfWork unitOfWork
     )
 {
     this.geocodeServiceAgent = geocodeServiceAgent;
     this.logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
     this.traceManager = new TraceManager(this.logWriter);
     this.unitOfWork = unitOfWork;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PersonalLocationsController"/> class.
 /// </summary>
 public PersonalLocationsController(
     [CreateNew] IDomainContext domainContext,
     [ServiceDependency] IGeoLocationServiceAgent geoLocationService
     )
 {
     this.logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
     this.traceManager = new TraceManager(this.logWriter);
     this.geoLocationService = geoLocationService;
     this.domainContext = domainContext;
 }
        public void GetTracerFromTraceManagerWithNoInstrumentation()
        {
            MockTraceListener.Reset();

            LogSource source = new LogSource("tracesource", new[] { new MockTraceListener() }, SourceLevels.All);

            List<LogSource> traceSources = new List<LogSource>(new LogSource[] { source });
            LogWriter lg = new LogWriter(new List<ILogFilter>(), new List<LogSource>(), source, null, new LogSource("errors"), "default", true, false);

            TraceManager tm = new TraceManager(lg);

            Assert.IsNotNull(tm);

            using (tm.StartTrace("testoperation"))
            {
                Assert.AreEqual(1, MockTraceListener.Entries.Count);
            }

            Assert.AreEqual(2, MockTraceListener.Entries.Count);
        }
        public void GetTracerFromTraceManagerWithInstrumentationEnabled()
        {
            MockTraceListener.Reset();

            LogSource source = new LogSource("tracesource", SourceLevels.All);
            source.Listeners.Add(new MockTraceListener());

            List<LogSource> traceSources = new List<LogSource>(new LogSource[] { source });
            LogWriter lg = new LogWriterImpl(new List<ILogFilter>(), new List<LogSource>(), source, null, new LogSource("errors"), "default", true, false);

            TracerInstrumentationProvider instrumentationProvider = new TracerInstrumentationProvider(true, false, "applicationname");
            TraceManager tm = new TraceManager(lg, instrumentationProvider);

            Assert.IsNotNull(tm);

            using (tm.StartTrace("testoperation"))
            {
                Assert.AreEqual(1, MockTraceListener.Entries.Count);
            }

            Assert.AreEqual(2, MockTraceListener.Entries.Count);
        }
예제 #5
0
 /// <summary>
 /// Register adapter's conflict handlers.
 /// </summary>
 /// <param name="conflictManager"></param>
 public override void RegisterConflictTypes(ConflictManager conflictManager)
 {
     TraceManager.TraceInformation("WSSVC:AP:RegisterConflictTypes");
     conflictManagementService = conflictManager;
     conflictManagementService.RegisterConflictType(new GenericConflictType());
 }
예제 #6
0
 static void debugger_OnTrace(string line)
 {
     TraceManager.AddAsync(line, 1);
 }
예제 #7
0
        private void generateDeltaTableForSnapshot(List <string> paths, int snapshotChangeset)
        {
            List <string> pathsToGet          = new List <string>();
            VersionSpec   snapshotVersionSpec = new ChangesetVersionSpec(snapshotChangeset);

            foreach (string mappingPath in paths)
            {
                // Always query at one level down the mapping
                ItemSet itemSet = m_tfsClient.GetItems(mappingPath, snapshotVersionSpec, RecursionType.OneLevel);
                Item[]  items   = itemSet.Items;
                foreach (Item childItem in items)
                {
                    // Avoid the item itself.
                    if (!VersionControlPath.Equals(childItem.ServerItem, mappingPath))
                    {
                        pathsToGet.Add(childItem.ServerItem);
                    }
                }
            }

            int         countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize;
            ChangeGroup batchGroup = createChangeGroupForSnapshot(snapshotChangeset, snapshotChangeset);

            foreach (string path in pathsToGet)
            {
                TraceManager.TraceInformation("Getting snapshot at changeset: {0}, path: {1}", snapshotChangeset, path);
                ItemSet itemSet = m_tfsClient.GetItems(path, snapshotVersionSpec, RecursionType.Full);
                Item[]  items   = itemSet.Items;
                itemSet = null;
                TraceManager.TraceInformation("Snapshot contains {0} items", items.Length);
                for (int i = 0; i < items.Length; i++)
                {
                    if (FindMappedPath(items[i].ServerItem) != null)
                    {
                        countDownToCreateNewChangeGroup--;
                        if (countDownToCreateNewChangeGroup == 0)
                        {
                            TraceManager.TraceInformation("Saving {0} change actions", m_snapshotCheckinBatchSize);
                            batchGroup.Save();

                            batchGroup.Actions.Clear();
                            batchGroup = null;

                            batchGroup = createChangeGroupForSnapshot(snapshotChangeset, snapshotChangeset);
                            countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize;
                            TraceManager.TraceInformation("Saved {0} change actions", snapshotChangeset);
                        }
                        batchGroup.CreateAction(
                            WellKnownChangeActionId.Add,
                            new TfsMigrationItem(items[i]),
                            null,
                            items[i].ServerItem,
                            null,
                            null,
                            TfsAnalysisAlgorithms.convertContentType(items[i].ItemType),
                            null);
                    }
                    items[i] = null; // Dispose this object to reduce memory consumption.
                }
            }

            if (batchGroup.Actions.Count > 0)
            {
                int numRemainingItems = batchGroup.Actions.Count;
                TraceManager.TraceInformation("Saving {0} change actions", numRemainingItems);
                batchGroup.Save();
                TraceManager.TraceInformation("Saved {0} change actions", numRemainingItems);
            }
        }
예제 #8
0
        public void FixtureSetUp()
        {
            SpanFactory = new ShapeSpanFactory();
            TraceManager = new TraceManager();
            var phonologicalFeatSys = new FeatureSystem
            {
                new SymbolicFeature("voc", new FeatureSymbol("voc+", "+"), new FeatureSymbol("voc-", "-")),
                new SymbolicFeature("cons", new FeatureSymbol("cons+", "+"), new FeatureSymbol("cons-", "-")),
                new SymbolicFeature("high", new FeatureSymbol("high+", "+"), new FeatureSymbol("high-", "-")),
                new SymbolicFeature("low", new FeatureSymbol("low+", "+"), new FeatureSymbol("low-", "-")),
                new SymbolicFeature("back", new FeatureSymbol("back+", "+"), new FeatureSymbol("back-", "-")),
                new SymbolicFeature("round", new FeatureSymbol("round+", "+"), new FeatureSymbol("round-", "-")),
                new SymbolicFeature("vd", new FeatureSymbol("vd+", "+"), new FeatureSymbol("vd-", "-")),
                new SymbolicFeature("asp", new FeatureSymbol("asp+", "+"), new FeatureSymbol("asp-", "-")),
                new SymbolicFeature("del_rel", new FeatureSymbol("del_rel+", "+"), new FeatureSymbol("del_rel-", "-")),
                new SymbolicFeature("ATR", new FeatureSymbol("ATR+", "+"), new FeatureSymbol("ATR-", "-")),
                new SymbolicFeature("strident", new FeatureSymbol("strident+", "+"), new FeatureSymbol("strident-", "-")),
                new SymbolicFeature("cont", new FeatureSymbol("cont+", "+"), new FeatureSymbol("cont-", "-")),
                new SymbolicFeature("nasal", new FeatureSymbol("nasal+", "+"), new FeatureSymbol("nasal-", "-")),
                new SymbolicFeature("poa", new FeatureSymbol("bilabial"), new FeatureSymbol("labiodental"), new FeatureSymbol("alveolar"), new FeatureSymbol("velar"))
            };
            phonologicalFeatSys.Freeze();

            var syntacticFeatSys = new SyntacticFeatureSystem
            {
                new SymbolicFeature("foo", new FeatureSymbol("foo+", "+"), new FeatureSymbol("foo-", "-")),
                new SymbolicFeature("baz", new FeatureSymbol("baz+", "+"), new FeatureSymbol("baz-", "-")),
                new SymbolicFeature("num", new FeatureSymbol("sg"), new FeatureSymbol("pl")),
                new SymbolicFeature("pers", new FeatureSymbol("1"), new FeatureSymbol("2"), new FeatureSymbol("3"), new FeatureSymbol("4")),
                new SymbolicFeature("tense", new FeatureSymbol("past"), new FeatureSymbol("pres")),
                new SymbolicFeature("evidential", new FeatureSymbol("witnessed")),
                new SymbolicFeature("aspect", new FeatureSymbol("perf"), new FeatureSymbol("impf")),
                new SymbolicFeature("mood", new FeatureSymbol("active"), new FeatureSymbol("passive")),
                new SymbolicFeature("fum", new FeatureSymbol("fum+", "+"), new FeatureSymbol("fum-", "-")),
                new SymbolicFeature("bar", new FeatureSymbol("bar+", "+"), new FeatureSymbol("bar-", "-"))
            };
            syntacticFeatSys.AddPartsOfSpeech(new FeatureSymbol("N", "Noun"), new FeatureSymbol("V", "Verb"), new FeatureSymbol("TV", "Transitive Verb"),
                new FeatureSymbol("IV", "Intransitive Verb"), new FeatureSymbol("A", "Adjective"));
            Head = syntacticFeatSys.AddHeadFeature();
            Foot = syntacticFeatSys.AddFootFeature();
            syntacticFeatSys.Freeze();

            Table1 = new CharacterDefinitionTable(SpanFactory) { Name = "table1" };
            AddSegDef(Table1, phonologicalFeatSys, "a", "cons-", "voc+", "high-", "low+", "back+", "round-", "vd+");
            AddSegDef(Table1, phonologicalFeatSys, "i", "cons-", "voc+", "high+", "low-", "back-", "round-", "vd+");
            AddSegDef(Table1, phonologicalFeatSys, "u", "cons-", "voc+", "high+", "low-", "back+", "round+", "vd+");
            AddSegDef(Table1, phonologicalFeatSys, "o", "cons-", "voc+", "high-", "low-", "back+", "round+", "vd+");
            AddSegDef(Table1, phonologicalFeatSys, "y", "cons-", "voc+", "high+", "low-", "back-", "round+", "vd+");
            AddSegDef(Table1, phonologicalFeatSys, "ɯ", "cons-", "voc+", "high+", "low-", "back+", "round-", "vd+");
            AddSegDef(Table1, phonologicalFeatSys, "p", "cons+", "voc-", "bilabial", "vd-", "asp-", "strident-", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "t", "cons+", "voc-", "alveolar", "vd-", "asp-", "del_rel-", "strident-", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "k", "cons+", "voc-", "velar", "vd-", "asp-", "strident-", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "ts", "cons+", "voc-", "alveolar", "vd-", "asp-", "del_rel+", "strident+", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "pʰ", "cons+", "voc-", "bilabial", "vd-", "asp+", "strident-", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "tʰ", "cons+", "voc-", "alveolar", "vd-", "asp+", "del_rel-", "strident-", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "kʰ", "cons+", "voc-", "velar", "vd-", "asp+", "strident-", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "tsʰ", "cons+", "voc-", "alveolar", "vd-", "asp+", "del_rel+", "strident+", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "b", "cons+", "voc-", "bilabial", "vd+", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "d", "cons+", "voc-", "alveolar", "vd+", "strident-", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "g", "cons+", "voc-", "velar", "vd+", "cont-", "nasal-");
            AddSegDef(Table1, phonologicalFeatSys, "m", "cons+", "voc-", "bilabial", "vd+", "cont-", "nasal+");
            AddSegDef(Table1, phonologicalFeatSys, "n", "cons+", "voc-", "alveolar", "vd+", "strident-", "cont-", "nasal+");
            AddSegDef(Table1, phonologicalFeatSys, "ŋ", "cons+", "voc-", "velar", "vd+", "cont-", "nasal+");
            AddSegDef(Table1, phonologicalFeatSys, "s", "cons+", "voc-", "alveolar", "vd-", "asp-", "del_rel-", "strident+", "cont+");
            AddSegDef(Table1, phonologicalFeatSys, "z", "cons+", "voc-", "alveolar", "vd+", "asp-", "del_rel-", "strident+", "cont+");
            AddSegDef(Table1, phonologicalFeatSys, "f", "cons+", "voc-", "labiodental", "vd-", "asp-", "strident+", "cont+");
            AddSegDef(Table1, phonologicalFeatSys, "v", "cons+", "voc-", "labiodental", "vd+", "asp-", "strident+", "cont+");

            Table2 = new CharacterDefinitionTable(SpanFactory) { Name = "table2" };
            AddSegDef(Table2, phonologicalFeatSys, "a", "cons-", "voc+", "high-", "low+", "back+", "round-", "vd+");
            AddSegDef(Table2, phonologicalFeatSys, "i", "cons-", "voc+", "high+", "low-", "back-", "round-", "vd+");
            AddSegDef(Table2, phonologicalFeatSys, "u", "cons-", "voc+", "high+", "low-", "back+", "round+", "vd+");
            AddSegDef(Table2, phonologicalFeatSys, "y", "cons-", "voc+", "high+", "low-", "back-", "round+", "vd+");
            AddSegDef(Table2, phonologicalFeatSys, "o", "cons-", "voc+", "high-", "low-", "back+", "round+", "vd+");
            AddSegDef(Table2, phonologicalFeatSys, "p", "cons+", "voc-", "bilabial", "vd-");
            AddSegDef(Table2, phonologicalFeatSys, "t", "cons+", "voc-", "alveolar", "vd-", "del_rel-", "strident-");
            AddSegDef(Table2, phonologicalFeatSys, "k", "cons+", "voc-", "velar", "vd-");
            AddSegDef(Table2, phonologicalFeatSys, "ts", "cons+", "voc-", "alveolar", "vd-", "del_rel+", "strident+");
            AddSegDef(Table2, phonologicalFeatSys, "b", "cons+", "voc-", "bilabial", "vd+");
            AddSegDef(Table2, phonologicalFeatSys, "d", "cons+", "voc-", "alveolar", "vd+", "strident-");
            AddSegDef(Table2, phonologicalFeatSys, "g", "cons+", "voc-", "velar", "vd+");
            AddSegDef(Table2, phonologicalFeatSys, "m", "cons+", "voc-", "bilabial", "vd+", "cont-", "nasal+");
            AddSegDef(Table2, phonologicalFeatSys, "n", "cons+", "voc-", "alveolar", "vd+", "cont-", "nasal+");
            AddSegDef(Table2, phonologicalFeatSys, "ŋ", "cons+", "voc-", "velar", "vd+", "cont-", "nasal+");
            AddSegDef(Table2, phonologicalFeatSys, "s", "cons+", "voc-", "alveolar", "vd-", "asp-", "del_rel-", "strident+", "cont+");
            AddSegDef(Table2, phonologicalFeatSys, "z", "cons+", "voc-", "alveolar", "vd+", "asp-", "del_rel-", "strident+", "cont+");
            AddSegDef(Table2, phonologicalFeatSys, "f", "cons+", "voc-", "labiodental", "vd-", "asp-", "strident+", "cont+");
            AddSegDef(Table2, phonologicalFeatSys, "v", "cons+", "voc-", "labiodental", "vd+", "asp-", "strident+", "cont+");
            AddBdryDef(Table2, "+");
            AddBdryDef(Table2, "#");
            AddBdryDef(Table2, "!");
            AddBdryDef(Table2, ".");
            AddBdryDef(Table2, "$");

            Table3 = new CharacterDefinitionTable(SpanFactory) { Name = "table3" };
            AddSegDef(Table3, phonologicalFeatSys, "a", "cons-", "voc+", "high-", "low+", "back+", "round-", "vd+", "ATR+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "a̘", "cons-", "voc+", "high-", "low+", "back+", "round-", "vd+", "ATR-", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "i", "cons-", "voc+", "high+", "low-", "back-", "round-", "vd+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "u", "cons-", "voc+", "high+", "low-", "back+", "round+", "vd+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "y", "cons-", "voc+", "high+", "low-", "back-", "round+", "vd+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "ɯ", "cons-", "voc+", "high+", "low-", "back+", "round-", "vd+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "o", "cons-", "voc+", "high-", "low-", "back+", "round+", "vd+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "p", "cons+", "voc-", "bilabial", "vd-", "cont-", "nasal-");
            AddSegDef(Table3, phonologicalFeatSys, "t", "cons+", "voc-", "alveolar", "vd-", "del_rel-", "strident-", "cont-", "nasal-");
            AddSegDef(Table3, phonologicalFeatSys, "k", "cons+", "voc-", "velar", "vd-", "cont-", "nasal-");
            AddSegDef(Table3, phonologicalFeatSys, "ts", "cons+", "voc-", "alveolar", "vd-", "del_rel+", "strident+", "cont-", "nasal-");
            AddSegDef(Table3, phonologicalFeatSys, "b", "cons+", "voc-", "bilabial", "vd+", "cont-", "nasal-");
            AddSegDef(Table3, phonologicalFeatSys, "d", "cons+", "voc-", "alveolar", "vd+", "strident-", "cont-", "nasal-");
            AddSegDef(Table3, phonologicalFeatSys, "g", "cons+", "voc-", "velar", "vd+", "cont-", "nasal-");
            AddSegDef(Table3, phonologicalFeatSys, "m", "cons+", "voc-", "bilabial", "vd+", "cont-", "nasal+");
            AddSegDef(Table3, phonologicalFeatSys, "n", "cons+", "voc-", "alveolar", "vd+", "strident-", "cont-", "nasal+");
            AddSegDef(Table3, phonologicalFeatSys, "ŋ", "cons+", "voc-", "velar", "vd+", "cont-", "nasal+");
            AddSegDef(Table3, phonologicalFeatSys, "s", "cons+", "voc-", "alveolar", "vd-", "asp-", "del_rel-", "strident+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "z", "cons+", "voc-", "alveolar", "vd+", "asp-", "del_rel-", "strident+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "f", "cons+", "voc-", "labiodental", "vd-", "asp-", "strident+", "cont+");
            AddSegDef(Table3, phonologicalFeatSys, "v", "cons+", "voc-", "labiodental", "vd+", "asp-", "strident+", "cont+");
            AddBdryDef(Table3, "+");
            AddBdryDef(Table3, "#");
            AddBdryDef(Table3, "!");
            AddBdryDef(Table3, ".");

            Latinate = new MprFeature { Name = "latinate" };
            Germanic = new MprFeature { Name = "germanic" };

            Morphophonemic = new Stratum(Table3) { Name = "Morphophonemic", MorphologicalRuleOrder = MorphologicalRuleOrder.Unordered };
            Allophonic = new Stratum(Table1) { Name = "Allophonic", MorphologicalRuleOrder = MorphologicalRuleOrder.Unordered };
            Surface = new Stratum(Table1) { Name = "Surface", MorphologicalRuleOrder = MorphologicalRuleOrder.Unordered };

            Entries = new Dictionary<string, LexEntry>();
            var fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("N")
                .Feature(Head).EqualTo(head => head
                    .Symbol("foo+").Symbol("baz-"))
                .Feature(Foot).EqualTo(foot => foot
                    .Symbol("fum-").Symbol("bar+")).Value;
            AddEntry("1", fs, Allophonic, "pʰit");
            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("N")
                .Feature(Head).EqualTo(head => head
                    .Symbol("foo+").Symbol("baz-"))
                .Feature(Foot).EqualTo(foot => foot
                    .Symbol("fum-").Symbol("bar+")).Value;
            AddEntry("2", fs, Allophonic, "pit");

            AddEntry("5", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "pʰut");
            AddEntry("6", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "kʰat");
            AddEntry("7", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "kʰut");

            AddEntry("8", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "dat");
            AddEntry("9", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Allophonic, "dat");

            AddEntry("10", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "ga̘p");
            AddEntry("11", FeatureStruct.New(syntacticFeatSys).Symbol("A").Value, Morphophonemic, "gab");
            AddEntry("12", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "ga+b");

            AddEntry("13", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bubabu");
            AddEntry("14", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bubabi");
            AddEntry("15", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bɯbabu");
            AddEntry("16", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bibabi");
            AddEntry("17", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bubi");
            AddEntry("18", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bibu");
            AddEntry("19", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "b+ubu");
            AddEntry("20", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bubababi");
            AddEntry("21", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bibababu");
            AddEntry("22", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bubabababi");
            AddEntry("23", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bibabababu");
            AddEntry("24", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bubui");
            AddEntry("25", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "buibu");
            AddEntry("26", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "buibui");
            AddEntry("27", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "buiibuii");
            AddEntry("28", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "buitibuiti");
            AddEntry("29", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "iibubu");

            AddEntry("30", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "bu+ib");
            AddEntry("31", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "buib");

            AddEntry("32", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "sag");
            AddEntry("33", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "sas");
            AddEntry("34", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "saz");
            AddEntry("35", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "sat");
            AddEntry("36", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "sasibo");
            AddEntry("37", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "sasibut");
            AddEntry("38", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "sasibud");

            AddEntry("39", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "ab+ba");
            AddEntry("40", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "abba");

            AddEntry("41", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Allophonic, "pip");
            AddEntry("42", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "bubibi");
            AddEntry("43", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "bubibu");

            AddEntry("44", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "gigigi");

            AddEntry("45", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "nbinding");

            AddEntry("46", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "bupu");

            AddEntry("47", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "tag");
            AddEntry("48", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "pag");
            AddEntry("49", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "ktb");
            AddEntry("50", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Allophonic, "suupu");
            AddEntry("51", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "miu");
            AddEntry("52", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "pu");
            AddEntry("53", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "mi");
            AddEntry("54", FeatureStruct.New().Value, Morphophonemic, "pi");
            AddEntry("55", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "mim+ɯɯ");

            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("V")
                .Feature(Head).EqualTo(head => head
                    .Feature("num").EqualTo("pl")).Value;
            AddEntry("Perc0", fs, Morphophonemic, "ssag");
            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("V")
                .Feature(Head).EqualTo(head => head
                    .Feature("pers").EqualTo("1")
                    .Feature("num").EqualTo("pl")).Value;
            AddEntry("Perc1", fs, Morphophonemic, "ssag");
            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("V")
                .Feature(Head).EqualTo(head => head
                    .Feature("pers").EqualTo("3")
                    .Feature("num").EqualTo("pl")).Value;
            AddEntry("Perc2", fs, Morphophonemic, "ssag");
            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("V")
                .Feature(Head).EqualTo(head => head
                    .Feature("pers").EqualTo("2", "3")
                    .Feature("num").EqualTo("pl")).Value;
            AddEntry("Perc3", fs, Morphophonemic, "ssag");
            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("V")
                .Feature(Head).EqualTo(head => head
                    .Feature("pers").EqualTo("1", "3")
                    .Feature("num").EqualTo("pl")).Value;
            AddEntry("Perc4", fs, Morphophonemic, "ssag");

            var seeFamily = new LexFamily { Name = "SEE" };
            seeFamily.Entries.Add(AddEntry("bl1", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "si"));
            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("V")
                .Feature(Head).EqualTo(head => head
                    .Feature("tense").EqualTo("past")).Value;
            seeFamily.Entries.Add(AddEntry("bl2", fs, Morphophonemic, "sau"));
            fs = FeatureStruct.New(syntacticFeatSys)
                .Symbol("V")
                .Feature(Head).EqualTo(head => head
                    .Feature("tense").EqualTo("pres")).Value;
            seeFamily.Entries.Add(AddEntry("bl3", fs, Morphophonemic, "sis"));

            LexEntry entry = AddEntry("pos1", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "ba");
            entry.MprFeatures.Add(Latinate);
            entry = AddEntry("pos2", FeatureStruct.New(syntacticFeatSys).Symbol("N").Value, Morphophonemic, "ba");
            entry.MprFeatures.Add(Germanic);

            var vowel = FeatureStruct.New(phonologicalFeatSys).Symbol(HCFeatureSystem.Segment).Symbol("voc+").Value;
            entry = AddEntry("free", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "tap", "taz", "tas");
            entry.Allomorphs[0].Environments.Add(new AllomorphEnvironment(SpanFactory, ConstraintType.Require, null, Pattern<Word, ShapeNode>.New().Annotation(vowel).Value));

            entry = AddEntry("disj", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "baz", "bat", "bad", "bas");
            var unroundedVowel = FeatureStruct.New(phonologicalFeatSys).Symbol(HCFeatureSystem.Segment).Symbol("voc+").Symbol("round-").Value;
            entry.Allomorphs[0].Environments.Add(new AllomorphEnvironment(SpanFactory, ConstraintType.Require, null, Pattern<Word, ShapeNode>.New().Annotation(unroundedVowel).Value));
            entry.Allomorphs[1].Environments.Add(new AllomorphEnvironment(SpanFactory, ConstraintType.Require, null, Pattern<Word, ShapeNode>.New().Annotation(vowel).Value));
            entry.Allomorphs[2].Environments.Add(new AllomorphEnvironment(SpanFactory, ConstraintType.Require, null, Pattern<Word, ShapeNode>.New().Annotation(vowel).Value));

            entry = AddEntry("stemname", FeatureStruct.New(syntacticFeatSys).Symbol("V").Feature(Head).EqualTo(head => head.Feature("tense").EqualTo("pres")).Value, Morphophonemic, "san", "sad", "sap");
            entry.Allomorphs[1].StemName = new StemName(
                FeatureStruct.New(syntacticFeatSys)
                    .Symbol("V")
                    .Feature(Head).EqualTo(head => head
                        .Feature("pers").EqualTo("1")).Value,
                FeatureStruct.New(syntacticFeatSys)
                    .Symbol("V")
                    .Feature(Head).EqualTo(head => head
                        .Feature("pers").EqualTo("2")).Value) {Name = "sn1"};
            entry.Allomorphs[2].StemName = new StemName(
                FeatureStruct.New(syntacticFeatSys)
                    .Symbol("V")
                    .Feature(Head).EqualTo(head => head
                        .Feature("pers").EqualTo("1")).Value,
                FeatureStruct.New(syntacticFeatSys)
                    .Symbol("V")
                    .Feature(Head).EqualTo(head => head
                        .Feature("pers").EqualTo("3")).Value) {Name = "sn2"};

            AddEntry("synfs", FeatureStruct.New(syntacticFeatSys).Symbol("V").Feature(Head).EqualTo(head => head.Feature("tense").EqualTo("pres")).Value, Morphophonemic, "bag");

            entry = AddEntry("bound", FeatureStruct.New(syntacticFeatSys).Symbol("V").Value, Morphophonemic, "dag");
            entry.PrimaryAllomorph.IsBound = true;

            Language = new Language
            {
                Name = "Test",
                PhonologicalFeatureSystem = phonologicalFeatSys,
                SyntacticFeatureSystem = syntacticFeatSys,
                Strata = { Morphophonemic, Allophonic, Surface }
            };
        }
예제 #9
0
 public void TearDown()
 {
     TraceManager.Stop();
     TraceManager.ClearTracers();
 }
예제 #10
0
        public bool Build(Project project, bool runOutput, bool releaseMode)
        {
            // save modified files
            mainForm.CallCommand("SaveAllModified", null);

            string       compiler = null;
            InstalledSDK sdk      = null;

            if (project.IsCompilable)
            {
                sdk      = GetProjectSDK(project);
                compiler = GetCompilerPath(project, sdk);
            }
            project.TraceEnabled = !releaseMode;

            if (project.OutputType == OutputType.OtherIDE)
            {
                // compile using associated IDE
                string error;
                string command = project.GetOtherIDE(runOutput, releaseMode, out error);

                if (error != null)
                {
                    ErrorManager.ShowInfo(TextHelper.GetString(error));
                }
                else
                {
                    if (command == "FlashIDE")
                    {
                        RunFlashIDE(project, runOutput, releaseMode);
                    }
                    else
                    {
                        Hashtable data = new Hashtable();
                        data["command"]     = command;
                        data["project"]     = project;
                        data["runOutput"]   = runOutput;
                        data["releaseMode"] = releaseMode;
                        DataEvent de = new DataEvent(EventType.Command, "ProjectManager.RunWithAssociatedIDE", data);
                        EventManager.DispatchEvent(project, de);
                        if (de.Handled)
                        {
                            return(true);
                        }
                    }
                }
                return(false);
            }
            else if (project.OutputType == OutputType.CustomBuild)
            {
                // validate commands not empty
                if (project.PreBuildEvent.Trim().Length == 0 && project.PostBuildEvent.Trim().Length == 0)
                {
                    String info = TextHelper.GetString("Info.NoOutputAndNoBuild");
                    TraceManager.Add(info);
                }
            }
            else if (project.IsCompilable)
            {
                // ask the project to validate itself
                string error;
                project.ValidateBuild(out error);

                if (error != null)
                {
                    ErrorManager.ShowInfo(TextHelper.GetString(error));
                    return(false);
                }

                if (project.OutputPath.Length < 1)
                {
                    String info = TextHelper.GetString("Info.SpecifyValidOutputSWF");
                    ErrorManager.ShowInfo(info);
                    return(false);
                }

                if (compiler == null || (!Directory.Exists(compiler) && !File.Exists(compiler)))
                {
                    string info = TextHelper.GetString("Info.CheckSDKSettings");
                    MessageBox.Show(info, TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.OK);
                    return(false);
                }
            }

            // close running AIR projector
            if (project.MovieOptions.Platform == AS3MovieOptions.AIR_PLATFORM ||
                project.MovieOptions.Platform == AS3MovieOptions.AIR_MOBILE_PLATFORM)
            {
                foreach (Process proc in Process.GetProcessesByName("adl"))
                {
                    try { proc.Kill(); proc.WaitForExit(10 * 1000); }
                    catch { }
                }
            }

            return(FDBuild(project, runOutput, releaseMode, sdk));
        }
        internal void ComputeAttachmentDelta(
            ChangeGroupService changeGroupService,
            DateTime waterMarkChangeStartTime,
            ITranslationService translationService,
            Guid sourceId,
            List <ChangeGroup> groups)
        {
            List <TfsMigrationFileAttachment> files = new List <TfsMigrationFileAttachment>();

            if (WorkItem.Attachments.Count > 0)
            {
                List <Revision> revsToBeSynced = FindUnsyncedRevisions(waterMarkChangeStartTime,
                                                                       translationService,
                                                                       sourceId,
                                                                       null);

                bool hasAttachmentChanges = false;
                foreach (Revision rev in revsToBeSynced)
                {
                    if (rev.Index == 0 &&
                        (int)rev.Fields[CoreField.AttachedFileCount].Value > 0)
                    {
                        hasAttachmentChanges = true;
                        break;
                    }

                    if (rev.Index > 0)
                    {
                        int      currAttchCount = (int)rev.Fields[CoreField.AttachedFileCount].Value;
                        Revision prevRev        = rev.WorkItem.Revisions[rev.Index - 1];
                        int      prevAttchCount = (int)prevRev.Fields[CoreField.AttachedFileCount].Value;
                        if (currAttchCount != prevAttchCount)
                        {
                            hasAttachmentChanges = true;
                            break;
                        }
                    }
                }

                if (!hasAttachmentChanges)
                {
                    return;
                }

                foreach (Attachment attachment in WorkItem.Attachments)
                {
                    if (attachment.AttachedTimeUtc <= waterMarkChangeStartTime ||
                        !attachment.IsSaved)
                    {
                        continue;
                    }
                    files.Add(new TfsMigrationFileAttachment(attachment));
                }
            }

            Guid        changeActionId = WellKnownChangeActionId.AddAttachment;
            ChangeGroup changeGroup    = changeGroupService.CreateChangeGroupForDeltaTable(
                string.Format("{0}:{1}", WorkItem.Id, "Attachments"));

            foreach (TfsMigrationFileAttachment attachmentFile in files)
            {
                XmlDocument migrationActionDetails = CreateAttachmentDescriptionDoc(attachmentFile, WorkItem.Rev.ToString());
                changeGroup.CreateAction(
                    changeActionId,
                    attachmentFile,
                    WorkItem.Id.ToString(),
                    "",
                    "0",
                    "",
                    WellKnownContentType.WorkItem.ReferenceName,
                    migrationActionDetails);
                TraceManager.TraceVerbose(String.Format("Generating AddAttachment change action: Work Item: {0}, Attachment File: {1}",
                                                        WorkItem.Id.ToString(), attachmentFile.Name));
            }

            // VERY IMPORTANT: use the RelatedArtifactsStore to detect detailed attachment changes
            WorkItemAttachmentStore       store = new WorkItemAttachmentStore(sourceId);
            List <FileAttachmentMetadata> additionalAttachmentToDelete;

            store.UpdatePerItemAttachmentChangesByCheckingRelatedItemRecords(
                WorkItem.Id.ToString(), changeGroup, out additionalAttachmentToDelete);

            foreach (FileAttachmentMetadata attch in additionalAttachmentToDelete)
            {
                TfsMigrationFileAttachment attachmentFile = new TfsMigrationFileAttachment(attch);
                XmlDocument migrationActionDetails        = CreateAttachmentDescriptionDoc(attachmentFile, WorkItem.Rev.ToString());
                changeGroup.CreateAction(
                    WellKnownChangeActionId.DelAttachment,
                    attachmentFile,
                    WorkItem.Id.ToString(),
                    "",
                    "0",
                    "",
                    WellKnownContentType.WorkItem.ReferenceName,
                    migrationActionDetails);
                TraceManager.TraceVerbose(String.Format("Generating DeleteAttachment change action: Work Item: {0}, Attachment File: {1}",
                                                        WorkItem.Id.ToString(), attachmentFile.Name));
            }

            groups.Add(changeGroup);
        }
예제 #12
0
        /// <summary>
        /// This function reads and processes every incoming message arriving from the server.
        /// </summary>
        /// <returns>False, if the connection manager thread has to stop, true otherwise.</returns>
        private bool ProcessIncomingMessages()
        {
            List <RCPackage> incomingPackages = new List <RCPackage>();

            if (this.connection.ReceiveIncomingPackages(ref incomingPackages))
            {
                foreach (RCPackage package in incomingPackages)
                {
                    if (package.PackageType == RCPackageType.NETWORK_CUSTOM_PACKAGE &&
                        package.Sender >= 0 && package.Sender < this.memberCount && package.Sender != this.clientID)
                    {
                        /// Custom message from a member --> notify the listener.
                        this.listener.PackageArrived(package, package.Sender);
                    }
                    else if (package.PackageType == RCPackageType.NETWORK_CONTROL_PACKAGE &&
                             package.PackageFormat.ID == Network.FORMAT_LOBBY_LINE_STATE_REPORT)
                    {
                        /// Line state report from the server.
                        short            clientID       = package.ReadShort(0);
                        byte[]           lineStateBytes = package.ReadByteArray(1);
                        LobbyLineState[] lineStates     = new LobbyLineState[lineStateBytes.Length];
                        bool             lineStatesOK   = true;
                        for (int i = 0; i < lineStateBytes.Length; i++)
                        {
                            if (lineStateBytes[i] == (byte)LobbyLineState.Closed ||
                                lineStateBytes[i] == (byte)LobbyLineState.Engaged ||
                                lineStateBytes[i] == (byte)LobbyLineState.Opened)
                            {
                                lineStates[i] = (LobbyLineState)lineStateBytes[i];
                            }
                            else
                            {
                                lineStatesOK = false;
                            }
                        }
                        lineStatesOK = lineStatesOK && (clientID == this.clientID) && (lineStateBytes.Length == this.memberCount);
                        if (!lineStatesOK)
                        {
                            /// Line state report error --> shutdown.
                            this.connection.Shutdown();
                            if (this.Disposed != null)
                            {
                                this.Disposed(this);
                            }
                            this.listener.LobbyLost();
                            return(false);
                        }
                        else
                        {
                            /// Line state report arrived --> notify the listener
                            this.listener.LineStateReport(clientID, lineStates);
                            ///return true;
                        }
                    }
                    else if (package.PackageType == RCPackageType.NETWORK_CONTROL_PACKAGE &&
                             package.PackageFormat.ID == Network.FORMAT_DISCONNECT_INDICATOR)
                    {
                        /// Disconnection indicator from the server.
                        RCPackage disconnectAck = RCPackage.CreateNetworkControlPackage(Network.FORMAT_DISCONNECT_ACK);
                        disconnectAck.WriteString(0, string.Empty);
                        disconnectAck.WriteByteArray(1, new byte[0] {
                        });
                        this.connection.SendPackage(disconnectAck);
                        this.connection.Shutdown();
                        if (this.Disposed != null)
                        {
                            this.Disposed(this);
                        }
                        this.listener.LobbyLost();
                        return(false);
                    }
                    else if (package.PackageType == RCPackageType.NETWORK_CONTROL_PACKAGE &&
                             package.PackageFormat.ID != Network.FORMAT_DEDICATED_MESSAGE &&
                             package.PackageFormat.ID != Network.FORMAT_DISCONNECT_ACK &&
                             package.PackageFormat.ID != Network.FORMAT_DISCONNECT_INDICATOR &&
                             package.PackageFormat.ID != Network.FORMAT_LOBBY_INFO &&
                             package.PackageFormat.ID != Network.FORMAT_LOBBY_INFO_VANISHED &&
                             package.PackageFormat.ID != Network.FORMAT_LOBBY_LINE_STATE_REPORT)
                    {
                        /// Custom internal message from the server --> notify the listener
                        TraceManager.WriteAllTrace(string.Format("Incoming package: {0}", package.ToString()), NetworkingSystemTraceFilters.INFO);
                        this.listener.ControlPackageArrived(package);
                    }
                    else
                    {
                        /// Unexpected package format and type --> immediate shutdown
                        this.connection.Shutdown();
                        if (this.Disposed != null)
                        {
                            this.Disposed(this);
                        }
                        this.listener.LobbyLost();
                        return(false);
                    }
                } /// end-foreach (RCPackage package in incomingPackages)

                /// Incoming packages has been processed.
                return(true);
            }
            else
            {
                /// Receive error --> immediate shutdown
                this.connection.Shutdown();
                if (this.Disposed != null)
                {
                    this.Disposed(this);
                }
                this.listener.LobbyLost();
                return(false);
            }
        }
예제 #13
0
 static void debugger_OnError(string line)
 {
     TraceManager.AddAsync(line, 3);
 }
예제 #14
0
 public ProductsController([CreateNew] IUnitOfWork unitOfWork)
 {
     this.unitOfWork = unitOfWork;
     this.logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
     this.traceManager = new TraceManager(this.logWriter);
 }
예제 #15
0
        private CCConfiguration(MigrationSource migrationSource)
        {
            VobList                    = new List <string>();
            UsePrecreatedView          = false;
            DetectChangesInCC          = true;
            LabelAllVersions           = false;
            QueryRenameHistory         = true;
            ClearfsimportConfiguration = new ClearfsimportConfiguration();
            foreach (CustomSetting setting in migrationSource.CustomSettings.CustomSetting)
            {
                if (string.Equals(setting.SettingKey, CCResources.BranchSettingName, StringComparison.OrdinalIgnoreCase))
                {
                    BranchName = setting.SettingValue;
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.StorageLocationSettingName, StringComparison.OrdinalIgnoreCase))
                {
                    StorageLocation = setting.SettingValue;
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.StorageLocationLocalPathSettingName, StringComparison.OrdinalIgnoreCase))
                {
                    StorageLocationLocalPath = setting.SettingValue;
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.VobSettingName, StringComparison.OrdinalIgnoreCase))
                {
                    VobList.Add(setting.SettingValue);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.PrecreatedViewSettingName, StringComparison.OrdinalIgnoreCase))
                {
                    PrecreatedViewName = setting.SettingValue;
                    UsePrecreatedView  = true;
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.DetectChangesInCC, StringComparison.OrdinalIgnoreCase))
                {
                    DetectChangesInCC = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.DynamicViewRootSettingName, StringComparison.OrdinalIgnoreCase))
                {
                    DynamicViewRoot = ValidateAndNormalizeDynamicViewRoot(setting);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.BatchChangesInGroup, StringComparison.OrdinalIgnoreCase))
                {
                    BatchChangesInGroup = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.DownloadFolderSettingName, StringComparison.OrdinalIgnoreCase))
                {
                    DownloadFolder = setting.SettingValue;
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.ClearfsimportConfigurationUnco, StringComparison.OrdinalIgnoreCase))
                {
                    ClearfsimportConfiguration.Unco = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.ClearfsimportConfigurationIdentical, StringComparison.OrdinalIgnoreCase))
                {
                    ClearfsimportConfiguration.Identical = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.ClearfsimportConfigurationMaster, StringComparison.OrdinalIgnoreCase))
                {
                    ClearfsimportConfiguration.Master = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.ClearfsimportConfigurationParseOutput, StringComparison.OrdinalIgnoreCase))
                {
                    ClearfsimportConfiguration.ParseOutput = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.QueryRenameHistory, StringComparison.OrdinalIgnoreCase))
                {
                    QueryRenameHistory = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.ClearfsimportConfigurationBatchSize, StringComparison.OrdinalIgnoreCase))
                {
                    int batchSize;
                    if (int.TryParse(setting.SettingValue, out batchSize))
                    {
                        ClearfsimportConfiguration.BatchSize = batchSize;
                    }
                    else
                    {
                        TraceManager.TraceWarning("The specified {0} of {1} is not a valid batch size. Use the default batch size of 1000",
                                                  CCResources.ClearfsimportConfigurationBatchSize,
                                                  setting.SettingValue);
                    }
                    continue;
                }
                if (string.Equals(setting.SettingKey, CCResources.LabelAllVersions, StringComparison.OrdinalIgnoreCase))
                {
                    LabelAllVersions = string.Equals(setting.SettingValue, "True", StringComparison.OrdinalIgnoreCase);
                    continue;
                }
            }

            verifyCCCustomSettings();
        }
예제 #16
0
        // Todo raise a conflict instead throw exception
        private void verifyCCCustomSettings()
        {
            if (string.IsNullOrEmpty(DownloadFolder))
            {
                throw new MigrationException(string.Format(CCResources.Culture, CCResources.DownloadLocationNotSpecified));
            }

            if (UsePrecreatedView)
            {
                if (string.IsNullOrEmpty(DynamicViewRoot) && (string.IsNullOrEmpty(StorageLocation)))
                {
                    throw new MigrationException(string.Format(CCResources.Culture, CCResources.ViewRootNeeded));
                }
                else if (!string.IsNullOrEmpty(DynamicViewRoot))
                {
                    if (!string.IsNullOrEmpty(StorageLocation))
                    {
                        throw new MigrationException(string.Format(CCResources.Culture, CCResources.RedundentViewRoot));
                    }
                    else
                    {
                        UseDynamicView = true;
                    }
                }
                else
                {
                    // StorageLocation is non-null and DynamicViewRoot is null
                    if (string.IsNullOrEmpty(StorageLocationLocalPath))
                    {
                        throw new MigrationException(
                                  string.Format(CCResources.Culture, CCResources.CustomSettingNotSpecified, "StorageLocationLocalPath", "SnapshotView"));
                    }
                    Utils.VerifyStorageLocationSetting(StorageLocation);
                    UseDynamicView = false;
                }
            }
            else
            {
                // Runtime created snapshot view.
                if (string.IsNullOrEmpty(StorageLocation))
                {
                    throw new MigrationException(
                              string.Format(CCResources.Culture, CCResources.CustomSettingNotSpecified, "StorageLocation", "SnapshotView"));
                }
                if (string.IsNullOrEmpty(StorageLocationLocalPath))
                {
                    throw new MigrationException(
                              string.Format(CCResources.Culture, CCResources.CustomSettingNotSpecified, "StorageLocationLocalPath", "SnapshotView"));
                }
                if (!string.IsNullOrEmpty(DynamicViewRoot))
                {
                    throw new MigrationException(
                              string.Format(CCResources.Culture, CCResources.RedundentViewRoot));
                }
            }

            // Log a warning if the branch name is not specified when a snapshot view is used,
            // but not for dynamic views as the view defines the branch (or brances) that make up the view.
            if (!UsePrecreatedView)
            {
                if (string.IsNullOrEmpty(BranchName))
                {
                    TraceManager.TraceWarning(
                        "Branch name is not specified in the configuration file. Using the default branch name {0}",
                        CCResources.DefaultBranchName);
                    BranchName = CCResources.DefaultBranchName;
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Parse la configuration DirectShow
        /// </summary>
        public static FiltersConfiguration Parse()
        {
            try
            {
                FiltersConfigurationSection configSection = FiltersConfigurationSection.GetConfiguration();

                FiltersConfiguration conf = new FiltersConfiguration();

                foreach (ExtensionElement extension in configSection.Extensions)
                {
                    var ext = new ExtensionFiltersSource()
                    {
                        Extension     = extension.Extension,
                        MinSpeedRatio = extension.MinSpeedRatio,
                        MaxSpeedRatio = extension.MaxSpeedRatio,
                        Splitter      = new FilterSource
                        {
                            Name          = extension.Splitter.Name,
                            SourceType    = extension.Splitter.SourceType,
                            ExternalCLSID = extension.Splitter.ExternalCLSID,
                        },
                        VideoDecoder = new FilterSource
                        {
                            Name          = extension.VideoDecoder.Name,
                            SourceType    = extension.VideoDecoder.SourceType,
                            ExternalCLSID = extension.VideoDecoder.ExternalCLSID,
                        },
                        AudioDecoder = new FilterSource
                        {
                            Name          = extension.AudioDecoder.Name,
                            SourceType    = extension.AudioDecoder.SourceType,
                            ExternalCLSID = extension.AudioDecoder.ExternalCLSID,
                        }
                    };

                    conf[ext.Extension] = ext;
                }

                // Filtres par défaut, minimum requis
                if (conf[".wmv"] == null)
                {
                    conf[".wmv"] = new ExtensionFiltersSource
                    {
                        Extension = ".wmv",
                        Splitter  = new FilterSource
                        {
                            Name          = "GDCL WMV Splitter",
                            SourceType    = FilterSourceTypeEnum.External,
                            ExternalCLSID = CLSID_WMV_SPLITTER,
                        },
                        VideoDecoder = new FilterSource
                        {
                            Name          = "LAV Video Decoder",
                            SourceType    = FilterSourceTypeEnum.External,
                            ExternalCLSID = CLSID_LAV_VIDEO_DECODER,
                        },
                        AudioDecoder = new FilterSource
                        {
                            Name       = "Auto Audio Decoder",
                            SourceType = FilterSourceTypeEnum.Auto,
                        }
                    };
                }

                // Vérification de l'exactitude des valeurs
                if (conf.Select(e => e.Extension).GroupBy(e => e).Any(g => g.Count() > 2))
                {
                    throw new ConfigurationErrorsException("Les extensions configurées doivent être uniques.");
                }

                foreach (var e in conf)
                {
                    if (e.Splitter.SourceType == FilterSourceTypeEnum.Auto)
                    {
                        throw new ConfigurationErrorsException("Le splitter ne peut pas être Auto");
                    }

                    if ((e.MinSpeedRatio.HasValue && !e.MaxSpeedRatio.HasValue) ||
                        (!e.MinSpeedRatio.HasValue && e.MaxSpeedRatio.HasValue))
                    {
                        throw new ConfigurationErrorsException("Les vitesses de lecture doivent être toutes les deux définies");
                    }

                    if (e.MinSpeedRatio.HasValue && e.MaxSpeedRatio.HasValue && e.MinSpeedRatio.Value > e.MaxSpeedRatio.Value)
                    {
                        throw new ConfigurationErrorsException("Les vitesses de lecture sont incorrectes");
                    }

                    var sources = new FilterSource[]
                    {
                        e.Splitter,
                        e.AudioDecoder,
                        e.VideoDecoder
                    };

                    foreach (var source in sources)
                    {
                        if (source.SourceType == FilterSourceTypeEnum.External && string.IsNullOrEmpty(source.ExternalCLSID))
                        {
                            throw new ConfigurationErrorsException("Une source externe doit être accompagnée d'un CLSID externe");
                        }

                        if (source.SourceType == FilterSourceTypeEnum.Auto && !string.IsNullOrEmpty(source.ExternalCLSID))
                        {
                            throw new ConfigurationErrorsException("Une source auto ne doit pas être accompagnée d'un CLSID externe");
                        }
                    }
                }

                return(conf);
            }
            catch (ConfigurationErrorsException ex)
            {
                TraceManager.TraceError(ex, "Erreur de configuration");
                MessageBox.Show(Resources.LocalizationResources.Error_Configuration_Filters, Resources.LocalizationResources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                return(null);
            }
            catch (Exception e)
            {
                TraceManager.TraceError(e, "Erreur lors de l'initialisation de la configuration des filtres");
                MessageBox.Show(Resources.LocalizationResources.Exception_GenericMessage, Resources.LocalizationResources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                return(null);
            }
        }
예제 #18
0
        /// <summary>
        ///
        /// </summary>
        internal bool Start(bool alwaysStart)
        {
            if (!alwaysStart && !CheckCurrent())
            {
                return(false);
            }
            UpdateMenuState(DebuggerState.Starting);

            // load JVM.. only once
            if (!jvm_up)
            {
                try
                {
                    BridgeSetup bridgeSetup = null;
                    bridgeSetup = new BridgeSetup();

                    string flexSDKPath = null;
                    if (currentProject != null)
                    {
                        flexSDKPath = currentProject.CurrentSDK;
                    }
                    else
                    {
                        flexSDKPath = PluginCore.Helpers.PathHelper.ResolvePath(PluginBase.MainForm.ProcessArgString("$(FlexSDK)"));
                    }

                    if (flexSDKPath != null && Directory.Exists(flexSDKPath))
                    {
                        Dictionary <string, string> jvmConfig = JvmConfigHelper.ReadConfig(flexSDKPath);
                        String javaHome = JvmConfigHelper.GetJavaHome(jvmConfig, flexSDKPath);
                        if (!String.IsNullOrEmpty(javaHome))
                        {
                            bridgeSetup.JavaHome = javaHome;
                        }
                    }

                    bridgeSetup.AddAllJarsClassPath(PluginCore.Helpers.PathHelper.PluginDir);
                    bridgeSetup.AddAllJarsClassPath(Path.Combine(PluginCore.Helpers.PathHelper.ToolDir, @"flexlibs\lib"));
                    Bridge.CreateJVM(bridgeSetup);
                    Bridge.RegisterAssembly(typeof(IProgress).Assembly); // ??
                    Bridge.RegisterAssembly(typeof(Bootstrap).Assembly);
                    jvm_up = true;
                }
                catch (Exception ex)
                {
                    String msg = "Debugger startup error. For troubleshooting see: http://www.flashdevelop.org/wikidocs/index.php?title=F.A.Q\n";
                    TraceManager.Add(msg + "Error details: " + ex.ToString());
                    return(false);
                }
            }

            PluginBase.MainForm.ProgressBar.Visible   = true;
            PluginBase.MainForm.ProgressLabel.Visible = true;
            PluginBase.MainForm.ProgressLabel.Text    = TextHelper.GetString("Info.WaitingForPlayer");
            if (bgWorker == null || !bgWorker.IsBusy)
            {
                // only run a debugger if one is not already runnin - need to redesign core to support multiple debugging instances
                // other option: detach old worker, wait for it to exit and start new one
                bgWorker         = new BackgroundWorker();
                bgWorker.DoWork += bgWorker_DoWork;
                bgWorker.RunWorkerAsync();
            }
            return(true);
        }
예제 #19
0
        public void EditRenameConflictTakeMergeTest()
        {
            // 1. migrate a.txt -> a.txt
            string fileName = "a.txt";
            MigrationItemStrings sourceFile = new MigrationItemStrings(fileName, null, TestEnvironment, true);
            MigrationItemStrings targetFile = new MigrationItemStrings(fileName, "b.txt", TestEnvironment, false);
            int changeset;

            changeset = SourceAdapter.AddFile(sourceFile.LocalPath);
            TraceManager.TraceInformation("Add Changeset: {0}, {1}", changeset, SourceAdapter.AdapterType);

            RunAndValidate();

            // 2. source system: a.txt -> b.txt
            int editChangesetId = SourceAdapter.EditFile(sourceFile.LocalPath);

            TraceManager.TraceInformation("Edit Changeset: {0}, {1}", editChangesetId, SourceAdapter.AdapterType);

            // 3. target system: a.txt -> edit
            changeset = TargetAdapter.RenameItem(targetFile.ServerPath, targetFile.NewServerPath);
            TraceManager.TraceInformation("Rename Changeset: {0}, {1}", changeset, TargetAdapter.AdapterType);

            // 4. Migration will detect a conflict
            Run();

            // 5. resolve conflicts
            // 5.1 check if we have correct conflicts in db
            ConflictResolver  conflictResolver = new ConflictResolver(Configuration);
            List <RTConflict> conflicts        = conflictResolver.GetConflicts();

            Assert.AreEqual(1, conflicts.Count, "There should be only 1 conflict");
            VCNameSpaceContentConflictType namespaceConflict = new VCNameSpaceContentConflictType();

            Assert.AreEqual(namespaceConflict.ReferenceName, conflicts[0].ConflictTypeReference.Value.ReferenceName,
                            "It should be vc namespace content conflict");

            // 5.2 user actions
            //
            // revert edit on a.txt
            PendEditToRevertFile(SourceWorkspace, sourceFile, editChangesetId, editChangesetId - 1);
            int sourceChangeId = SourceWorkspace.CheckIn(SourceWorkspace.GetPendingChanges(), "user: revert edit change on a.txt **NOMIGRATION**");

            TraceManager.TraceInformation("Undo Edit Changeset: {0}, {1}", sourceChangeId, SourceAdapter.AdapterType);

            // revert rename on target
            int targetChangeId = TargetAdapter.RenameItem(targetFile.NewServerPath, targetFile.ServerPath,
                                                          "Revert rename change on target side **NOMIGRATION**");

            TraceManager.TraceInformation("Undo Rename Changeset: {0}, {1}", targetChangeId, TargetAdapter.AdapterType);

            int deltaChangeId = sourceChangeId;
            int miChangeId    = targetChangeId;

            if (TestEnvironment.MigrationTestType == MigrationTestType.TwoWayRight)
            {
                deltaChangeId = targetChangeId;
                miChangeId    = sourceChangeId;
            }

            // resolve conflicts
            Dictionary <string, string> dataFields = new Dictionary <string, string>();

            dataFields.Add(VCContentConflictUserMergeChangeAction.MigrationInstructionChangeId, miChangeId.ToString());
            dataFields.Add(VCContentConflictUserMergeChangeAction.DeltaTableChangeId, deltaChangeId.ToString());

            foreach (RTConflict conflict in conflicts)
            {
                conflictResolver.TryResolveConflict(conflict, new VCContentConflictUserMergeChangeAction(), "$/", dataFields);
            }

            // 6. migrate
            Run();

            // 7. validation
            // no remaining conflicts and content match
            conflicts = conflictResolver.GetConflicts();
            Assert.AreEqual(0, conflicts.Count, "There should be NO conflict");
            // content match
            Assert.IsTrue(VerifyContents());
        }
예제 #20
0
		void RenderItem (TraceManager manager, HtmlTextWriter output, int item)
		{
			manager.TraceData [item - 1].Render (output);
		}
        /// <summary>
        /// Get the information for a new label to be created on the target side of a migration/sync operation
        /// for item with a specified path.   The path format will be the same as that of the filter pair
        /// strings for the source side adapter.  The label returned is intended to be applied recursively
        /// to all items in the corresponding sub-tree on the target side.
        /// </summary>
        /// <param name="serviceContainer">A service container that provides access to services provided by the
        /// TFS Integration Platform Toolkit</param>
        /// <param name="subTreePath">The path of a sub tree being migrated (as specified a filter string)</param>
        /// <returns>An object that implements the ILabel interface</returns>
        private ILabel GetSubTreeLabel(IServiceContainer serviceContainer, string fileSystemPath)
        {
            SubTreeLabel label = null;

            try
            {
                XmlElement element = GetSemaphoreFileElement(c_label);

                if (m_vcTranslationService == null)
                {
                    // This Addin is probably configured with a WIT session; ignore any Label element that exists,
                    // but log a warning if one does.
                    if (element != null)
                    {
                        TraceManager.TraceWarning(SemaphoreFileAnalysisAddinResources.LabelInSemaphoreFileIgnored);
                    }
                }
                else
                {
                    // If the Label element is present, we will either take values from the Name and Comment
                    // attributes or will generate defaults.  If the Label element is not found, we will not
                    // add a label.
                    if (element != null && m_vcTranslationService != null)
                    {
                        string targetSideScope = m_vcTranslationService.GetMappedPath(fileSystemPath, m_sourceId);
                        label = new SubTreeLabel(fileSystemPath, targetSideScope);

                        foreach (XmlAttribute attribute in element.Attributes)
                        {
                            if (string.Equals(attribute.Name, c_name))
                            {
                                label.Name = attribute.Value;
                                if (!m_excludeDateTimeFromLabelName)
                                {
                                    label.Name += "_" + String.Format(CultureInfo.InvariantCulture, SemaphoreFileAnalysisAddinResources.DefaultLabelNameFormat,
                                                                      DateTime.Now);
                                }
                            }
                            else if (string.Equals(attribute.Name, c_comment))
                            {
                                label.Comment = attribute.Value;
                            }
                        }

                        label.LabelItems.Add(new RecursiveLabelItem(fileSystemPath));
                    }
                    else
                    {
                        TraceManager.TraceInformation(String.Format(CultureInfo.InvariantCulture,
                                                                    SemaphoreFileAnalysisAddinResources.LabelNotFoundInSemaphoreFile,
                                                                    Path.GetFullPath(m_semaphoreFilePath)));
                    }
                }
            }
            catch (Exception ex)
            {
                TraceManager.TraceWarning(String.Format(CultureInfo.InvariantCulture,
                                                        SemaphoreFileAnalysisAddinResources.ExceptionProcessingSemaphoreFile,
                                                        ex.ToString()));
            }

            return(label);
        }
예제 #22
0
        private void OnMediaPlayerActionEvent(MediaPlayerActionEvent e)
        {
            if (e.Sender == AssociatedObject.DataContext || e.Sender == AssociatedObject)
            {
#if DEBUG_QUEUEING
                TraceManager.TraceDebug($"Execute : {e.Id} - {e.Action}");
#endif
                Action action = null;

                switch (e.Action)
                {
                case MediaPlayerAction.Play:
                    action = () => MediaPlayer.Play();
                    break;

                case MediaPlayerAction.Pause:
                    action = () => MediaPlayer.Pause();
                    break;

                case MediaPlayerAction.PlayPause:
                    if (MediaPlayer.IsPlaying)
                    {
                        action = () => MediaPlayer.Pause();
                    }
                    else
                    {
                        action = () => MediaPlayer.Play();
                    }
                    break;

                case MediaPlayerAction.Stop:
                    action = () => MediaPlayer.Stop();
                    break;

                case MediaPlayerAction.Mute:
                    if (KMediaPlayer != null)
                    {
                        action = () => KMediaPlayer.Mute();
                    }
                    break;

                case MediaPlayerAction.Unmute:
                    if (KMediaPlayer != null)
                    {
                        action = () => KMediaPlayer.Unmute();
                    }
                    break;

                case MediaPlayerAction.ToggleMute:
                    if (KMediaPlayer != null)
                    {
                        action = () => KMediaPlayer.ToggleMute();
                    }
                    break;

                case MediaPlayerAction.StepBackward:
                    action = () => MediaPlayer.StepBackward();
                    break;

                case MediaPlayerAction.StepForward:
                    action = () => MediaPlayer.StepForward();
                    break;

                case MediaPlayerAction.ShowTimeline:
                    if (KMediaPlayer != null)
                    {
                        action = () => KMediaPlayer.TimelineShow(e.ShowTimelineStart, e.ShowTimelineEnd, true);
                    }
                    break;

                case MediaPlayerAction.ResetTimeline:
                    if (KMediaPlayer != null)
                    {
                        action = () => KMediaPlayer.TimelineReset();
                    }
                    break;

                case MediaPlayerAction.ActivateMediaPlayerService:
                    action = () => IoC.Resolve <IServiceBus>().Register <IMediaPlayerService>(this);
                    break;

                case MediaPlayerAction.UnactivateMediaPlayerService:
                    action = () => IoC.Resolve <IServiceBus>().Unregister <IMediaPlayerService>();
                    break;

                case MediaPlayerAction.ExecuteWhenDispatcherReady:
                    action = e.ActionWhenPlayerDispatcherReady;
                    break;

                case MediaPlayerAction.ExecuteOnPlayerWhenDispatcherReady:
                    action = () => e.ActionOnPlayerWhenPlayerDispatcherReady(MediaPlayer);
                    break;

                case MediaPlayerAction.ToggleScreenMode:
                    action = () =>
                    {
                        if (KMediaPlayer.ScreenModeCommand != null && KMediaPlayer.ScreenModeCommand.CanExecute(null))
                        {
                            KMediaPlayer.ScreenModeCommand.Execute(null);
                        }
                    };
                    break;

                case MediaPlayerAction.ShowAnnotations:
                    action = () =>
                    {
                        AnnotationsAdornment.SetAnnotationsIsVisible(KMediaPlayer.MediaElement.VideoImage, true);
                        AnnotationsAdornment.SetIsInEditMode(KMediaPlayer.MediaElement.VideoImage, true);
                    };
                    break;

                case MediaPlayerAction.HideAnnotations:
                    action = () =>
                    {
                        if (AnnotationsAdornment.GetIsVisible(KMediaPlayer.MediaElement.VideoImage))
                        {
                            AnnotationsAdornment.DestroyAnnotations(KMediaPlayer.MediaElement.VideoImage);
                        }
                    };
                    break;

                default:
                    break;
                }

                if (action != null)
                {
                    if (e.SendWhenPlayerDispatcherReady)
                    {
                        Action <Action> onDispatcherAction = (a) =>
                        {
                            if (MediaPlayer is KMediaPlayer)
                            {
                                if (KMediaPlayer.MediaElement != null)
                                {
                                    KMediaPlayer.MediaElement.BeginInvokeOnMediaPlayerDispatcher((Action) delegate
                                    {
                                        Dispatcher.Invoke(a);
                                    });
                                }
                                else
                                {
                                    a();
                                }
                            }
                            else if (MediaPlayer is KMiniPlayer)
                            {
                                if (KMiniPlayer.MediaElement != null)
                                {
                                    KMiniPlayer.MediaElement.BeginInvokeOnMediaPlayerDispatcher((Action) delegate
                                    {
                                        Dispatcher.Invoke(a);
                                    });
                                }
                                else
                                {
                                    a();
                                }
                            }
                        };

                        if (MediaPlayer is KMediaPlayer)
                        {
                            if (KMediaPlayer.MediaElement == null)
                            {
                                Dispatcher.BeginInvoke(onDispatcherAction, System.Windows.Threading.DispatcherPriority.Loaded, action);
                            }
                            else
                            {
                                onDispatcherAction(action);
                            }
                        }
                        else if (MediaPlayer is KMiniPlayer)
                        {
                            if (KMiniPlayer.MediaElement == null)
                            {
                                Dispatcher.BeginInvoke(onDispatcherAction, System.Windows.Threading.DispatcherPriority.Loaded, action);
                            }
                            else
                            {
                                onDispatcherAction(action);
                            }
                        }
                    }
                    else
                    {
                        action();
                    }
                }
            }
        }
예제 #23
0
        public override System.Collections.ObjectModel.ReadOnlyCollection <LinkChangeGroup> GenerateNextLinkDeltaSlice(
            LinkService linkService,
            int maxDeltaSliceSize)
        {
            try
            {
                var linkChangeGroups = new List <LinkChangeGroup>();

                if (null == ExtractLinkChangeActionsCallback)
                {
                    return(linkChangeGroups.AsReadOnly());
                }

                // load main Highwater Mark
                m_hwmLink.Reload();
                DateTime hwmLinkValue = m_hwmLink.Value;
                // search back 60 seconds to deal with potential WIT race condition
                if (!hwmLinkValue.Equals(default(DateTime)))
                {
                    hwmLinkValue = hwmLinkValue.AddSeconds(-60);
                }
                string hwmLinkValueStr = hwmLinkValue.ToString(CultureInfo.InvariantCulture);

                // load Work Items for extracting links
                string sourceId  = m_migrationSource.UniqueId;
                string storeName = m_migrationSource.WorkItemStore.StoreName;

                // Get items based on primary Highwater Mark
                TraceManager.TraceInformation(TfsWITAdapterResources.GettingModifiedItems, sourceId, storeName);
                IEnumerable <TfsMigrationWorkItem> items = m_migrationSource.WorkItemStore.GetItems(ref hwmLinkValueStr);
                TraceManager.TraceInformation(TfsWITAdapterResources.ReceivedModifiedItems, sourceId, storeName);

                // Record the updated HWM value
                DateTime wiqlExecutionTime = Convert.ToDateTime(hwmLinkValueStr, CultureInfo.InvariantCulture);

                // store to be used to analyze deleted links
                WorkItemLinkStore store = new WorkItemLinkStore(new Guid(sourceId));

                // extract links
                DateTime lastWorkITemUpdateTime = DateTime.MinValue;
                var      inMaxDeltaSliceSize    = maxDeltaSliceSize;
                foreach (TfsMigrationWorkItem tfsMigrationWorkItem in items)
                {
                    if (tfsMigrationWorkItem.WorkItem == null)
                    {
                        continue;
                    }

                    TraceManager.TraceInformation("Generating linking delta for Work Item: {0}", tfsMigrationWorkItem.WorkItem.Id.ToString());
                    var detectedLinkChangeGroups = new List <LinkChangeGroup>();
                    ExtractLinkChangeActionsCallback(tfsMigrationWorkItem, detectedLinkChangeGroups, store);

                    if (detectedLinkChangeGroups.Count == 0)
                    {
                        TraceManager.TraceInformation("Number of links: {0}", 0);
                        continue;
                    }

                    Dictionary <string, LinkChangeGroup> perWorkItemConsolidatedLinkChangeGroup = new Dictionary <string, LinkChangeGroup>();
                    for (int i = 0; i < detectedLinkChangeGroups.Count; ++i)
                    {
                        foreach (LinkChangeAction action in detectedLinkChangeGroups[i].Actions)
                        {
                            if (!perWorkItemConsolidatedLinkChangeGroup.ContainsKey(action.Link.SourceArtifact.Uri))
                            {
                                var linkChangeGroup = new LinkChangeGroup(
                                    action.Link.SourceArtifactId, LinkChangeGroup.LinkChangeGroupStatus.Created, false);
                                perWorkItemConsolidatedLinkChangeGroup.Add(action.Link.SourceArtifact.Uri, linkChangeGroup);
                            }
                            perWorkItemConsolidatedLinkChangeGroup[action.Link.SourceArtifact.Uri].AddChangeAction(action);
                        }
                    }

                    // always make sure that the currently analyzed work item has a link change group to represent it
                    // even though the group can be empty
                    if (!perWorkItemConsolidatedLinkChangeGroup.ContainsKey(tfsMigrationWorkItem.Uri))
                    {
                        perWorkItemConsolidatedLinkChangeGroup.Add(
                            tfsMigrationWorkItem.Uri,
                            new LinkChangeGroup(TfsWorkItemHandler.IdFromUri(tfsMigrationWorkItem.Uri), LinkChangeGroup.LinkChangeGroupStatus.Created, false));
                    }


                    foreach (var workItemLinkGroup in perWorkItemConsolidatedLinkChangeGroup)
                    {
                        string workItemIdStr = TfsWorkItemHandler.IdFromUri(workItemLinkGroup.Key);
                        TraceManager.TraceInformation("Detected {0} links for Work Item '{1}'",
                                                      workItemLinkGroup.Value.Actions.Count, workItemIdStr);

                        if (workItemLinkGroup.Key.Equals(tfsMigrationWorkItem.Uri, StringComparison.OrdinalIgnoreCase))
                        {
                            // VERY IMPORTANT: use the RelatedArtifactsStore to detect link deletion
                            store.UpdatePerItemLinkChangeGroupsByCheckingRelatedItemRecords(
                                workItemLinkGroup.Key, workItemLinkGroup.Value, this);
                        }
                        else
                        {
                            store.UpdatePerItemLinkChangeGroupsByCheckingRelatedItemRecordsWithoutImplicitDelete(
                                workItemLinkGroup.Key, workItemLinkGroup.Value, this);
                        }

                        if (workItemLinkGroup.Value.Actions.Count > 0)
                        {
                            linkChangeGroups.Add(workItemLinkGroup.Value);
                        }
                        maxDeltaSliceSize -= workItemLinkGroup.Value.Actions.Count;

                        if (maxDeltaSliceSize <= 0)
                        {
                            // size limit reached - persist groups to DB
                            linkService.AddChangeGroups(linkChangeGroups);
                            linkChangeGroups.Clear();
                            maxDeltaSliceSize = inMaxDeltaSliceSize;
                        }
                    }

                    DateTime lastRevChangedDate = tfsMigrationWorkItem.WorkItem.ChangedDate;

                    if (lastWorkITemUpdateTime.CompareTo(lastRevChangedDate) <= 0)
                    {
                        lastWorkITemUpdateTime = lastRevChangedDate;
                    }
                }

                // persist remaining groups to DB
                linkService.AddChangeGroups(linkChangeGroups);

                // clean up the returned link change group collection
                // when the caller (toolkit) receives an empty collection, it understands there is no more
                // delta to generate for the moment, and proceeds to next phase
                linkChangeGroups.Clear();

                // update primary Highwater Mark
                //m_hwmLink.Update(newHwmLinkValue);

                string newHwmValueStr = hwmLinkValueStr;
                if (lastWorkITemUpdateTime.Equals(DateTime.MinValue))
                {
                    // no changes in this sync cycle, record the wiql query execution time
                    m_hwmLink.Update(wiqlExecutionTime);
                }
                else
                {
                    // hwm is recorded in UTC, so does the WIQL query asof time
                    lastWorkITemUpdateTime = lastWorkITemUpdateTime.ToUniversalTime();

                    if (lastWorkITemUpdateTime.CompareTo(wiqlExecutionTime) <= 0)
                    {
                        // last work item rev time is earlier than wiql query execution time, use it as hwm
                        m_hwmLink.Update(lastWorkITemUpdateTime);
                        newHwmValueStr = lastWorkITemUpdateTime.ToString();
                    }
                    else
                    {
                        m_hwmLink.Update(wiqlExecutionTime);
                    }
                }
                TraceManager.TraceInformation("Persisted WIT linking HWM: {0}", Toolkit.Constants.HwmDeltaLink);
                TraceManager.TraceInformation(TfsWITAdapterResources.UpdatedHighWatermark, newHwmValueStr);

                return(linkChangeGroups.AsReadOnly());
            }
            catch (Exception exception)
            {
                MigrationConflict genericeConflict = WitGeneralConflictType.CreateConflict(exception);
                var conflictManager = m_conflictManager.GetService(typeof(ConflictManager)) as ConflictManager;
                Debug.Assert(null != conflictManager);
                List <MigrationAction>   resolutionActions;
                ConflictResolutionResult resolveRslt =
                    conflictManager.TryResolveNewConflict(conflictManager.SourceId, genericeConflict, out resolutionActions);
                Debug.Assert(!resolveRslt.Resolved);
                return(new List <LinkChangeGroup>().AsReadOnly());
            }
        }
예제 #24
0
 public void Setup()
 {
     _mockLogger = new Mock <ILogger>();
     TraceManager.Start(_mockLogger.Object);
 }
예제 #25
0
 static public bool expandSnippet(Hashtable data)
 {
     if (data["snippet"] == null)
     {
         ScintillaControl sci = PluginBase.MainForm.CurrentDocument.SciControl;
         if (sci == null)
         {
             return(false);
         }
         // extract zen expression
         int  pos       = sci.CurrentPos - 1;
         int  lastValid = sci.CurrentPos;
         char c         = ' ';
         while (pos >= 0)
         {
             c = (char)sci.CharAt(pos);
             if (c <= 32)
             {
                 lastValid = pos + 1;
                 break;
             }
             if (c == '>')
             {
                 if (lastValid - 1 <= pos)
                 {
                     break;
                 }
                 lastValid = pos + 1;
             }
             else if (!Char.IsLetterOrDigit(c) && "+*$.#:-".IndexOf(c) < 0)
             {
                 break;
             }
             pos--;
             if (pos < 0)
             {
                 lastValid = 0;
             }
         }
         // expand
         if (lastValid < sci.CurrentPos)
         {
             sci.SetSel(lastValid, sci.CurrentPos);
             try
             {
                 string expr = expandExpression(sci.SelText);
                 if (expr == null)
                 {
                     return(false);
                 }
                 if (expr.IndexOf("$(EntryPoint)") < 0)
                 {
                     expr += "$(EntryPoint)";
                 }
                 data["snippet"] = expr;
             }
             catch (ZenExpandException zex)
             {
                 // error in expression, no snippet display
                 TraceManager.AddAsync(zex.Message);
                 return(true);
             }
             // insert modified snippet or show snippet list
             return(false);
         }
     }
     return(false);
 }
예제 #26
0
 public void CannotStartMultipleTimes()
 {
     Assert.True(TraceManager.Started, "Test setup failed?");
     Assert.False(TraceManager.Start(_mockLogger.Object));
 }
        private bool SubmitWorkItemLinkChanges(
            LinkChangeGroup linkChanges,
            ServiceContainer serviceContainer,
            ConfigurationService configService,
            ITranslationService translationService,
            TfsLinkingProviderBase.LinkSubmissionPhase submissionPhase)
        {
            var linkChangeActions = ExtractWorkItemLinkChanges(linkChanges);

            if (linkChangeActions.Count == 0)
            {
                return(true);
            }

            ConflictManager conflictManageer         = serviceContainer.GetService(typeof(ConflictManager)) as ConflictManager;
            var             updatedocsForEditLinks   = new List <XmlDocument>(linkChangeActions.Count);
            var             updateDocsForAddLinks    = new List <XmlDocument>(linkChangeActions.Count);
            var             updateDocsForDeleteLinks = new List <XmlDocument>(linkChangeActions.Count);
            Dictionary <int, LinkChangeAction> docForEditlinksToActionMap   = new Dictionary <int, LinkChangeAction>();
            Dictionary <int, LinkChangeAction> docForAddlinksToActionMap    = new Dictionary <int, LinkChangeAction>();
            Dictionary <int, LinkChangeAction> docForDeletelinksToActionMap = new Dictionary <int, LinkChangeAction>();

            for (int i = 0; i < linkChangeActions.Count; ++i)
            {
                if (linkChangeActions[i].Status != LinkChangeAction.LinkChangeActionStatus.ReadyForMigration ||
                    linkChangeActions[i].IsConflicted)
                {
                    continue;
                }

                if (!ProcessActionInCurrentSubmissionPhase(linkChangeActions[i], submissionPhase))
                {
                    continue;
                }

                var tfsUpdateDocument = InitializeUpdateDocument();

                var handler = linkChangeActions[i].Link.LinkType as ILinkHandler;
                Debug.Assert(null != handler);

                handler.UpdateTfs(tfsUpdateDocument, linkChangeActions[i]);

                if (linkChangeActions[i].ChangeActionId.Equals(WellKnownChangeActionId.Add))
                {
                    docForAddlinksToActionMap.Add(updateDocsForAddLinks.Count, linkChangeActions[i]);
                    updateDocsForAddLinks.Add(tfsUpdateDocument.UpdateDocument);
                }
                else if (linkChangeActions[i].ChangeActionId.Equals(WellKnownChangeActionId.Delete))
                {
                    docForDeletelinksToActionMap.Add(updateDocsForDeleteLinks.Count, linkChangeActions[i]);
                    updateDocsForDeleteLinks.Add(tfsUpdateDocument.UpdateDocument);
                }
                else if (linkChangeActions[i].ChangeActionId.Equals(WellKnownChangeActionId.Edit))
                {
                    docForEditlinksToActionMap.Add(updatedocsForEditLinks.Count, linkChangeActions[i]);
                    updatedocsForEditLinks.Add(tfsUpdateDocument.UpdateDocument);
                }
                else
                {
                    TraceManager.TraceVerbose("Change action '{0}' in Link Change Group '{1}' is not supported.",
                                              linkChangeActions[i].ChangeActionId.ToString(), linkChanges.GroupName);
                    linkChangeActions[i].Status = LinkChangeAction.LinkChangeActionStatus.Completed;
                }
            }

            bool succeeded = true;

            if (updatedocsForEditLinks.Count > 0)
            {
                succeeded &= SubmitBatchedAddOrDeleteLinkChanges(
                    updatedocsForEditLinks, docForEditlinksToActionMap, translationService, configService, conflictManageer);
            }
            if (updateDocsForDeleteLinks.Count > 0)
            {
                succeeded &= SubmitBatchedAddOrDeleteLinkChanges(
                    updateDocsForDeleteLinks, docForDeletelinksToActionMap, translationService, configService, conflictManageer);
            }
            if (updateDocsForAddLinks.Count > 0)
            {
                succeeded &= SubmitBatchedAddOrDeleteLinkChanges(
                    updateDocsForAddLinks, docForAddlinksToActionMap, translationService, configService, conflictManageer);
            }
            return(succeeded);
        }
예제 #28
0
        /// <summary>
        /// Create a changegroup that contains all change actions needed to bring a migration target to the specificed snapshot
        /// </summary>
        /// <param name="changeGroupName">The change group name of the snapshot</param>
        private void generateSnapshotForVCSession()
        {
            foreach (var setting in ConfigurationService.VcCustomSetting.Settings.Setting)
            {
                if (setting.SettingKey == "SnapshotStartPoint")
                {
                    m_sessionLevelSnapshotChangeset = parseSnapShotStartPoint(setting.SettingValue);
                }
                else if (setting.SettingKey == "SnapshotBatchSize")
                {
                    try
                    {
                        m_snapshotCheckinBatchSize = int.Parse(setting.SettingValue);
                    }
                    catch (Exception)
                    {
                        // wrong format, use the default batch size
                    }
                }
            }

            m_hwmDelta.Reload();
            if (m_hwmDelta.Value >= m_sessionLevelSnapshotChangeset)
            {
                // We've already passed snapshot changeset Id, just return.
                m_sessionlevelSnapshotCompleted = true;
                return;
            }

            VersionSpec   snapshotVersionSpec = new ChangesetVersionSpec(m_sessionLevelSnapshotChangeset);
            List <string> pathsToGet          = new List <string>();

            foreach (MappingEntry mappingEntry in ConfigurationService.Filters)
            {
                if (mappingEntry.Cloak)
                {
                    continue;
                }

                // Always query at one level down the mapping
                ItemSet itemSet = m_tfsClient.GetItems(mappingEntry.Path, snapshotVersionSpec, RecursionType.OneLevel);
                Item[]  items   = itemSet.Items;
                foreach (Item childItem in items)
                {
                    // Avoid the item itself.
                    if (!VersionControlPath.Equals(childItem.ServerItem, mappingEntry.Path))
                    {
                        pathsToGet.Add(childItem.ServerItem);
                    }
                }
            }

            int         countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize;
            int         batchExecutionOrder             = m_sessionLevelSnapshotChangeset;
            ChangeGroup batchGroup = createChangeGroupForSnapshot(m_sessionLevelSnapshotChangeset, batchExecutionOrder);

            foreach (string path in pathsToGet)
            {
                TraceManager.TraceInformation("Getting snapshot at changeset: {0}, path: {1}", m_sessionLevelSnapshotChangeset, path);
                ItemSet itemSet = m_tfsClient.GetItems(path, snapshotVersionSpec, RecursionType.Full);
                Item[]  items   = itemSet.Items;
                itemSet = null;
                TraceManager.TraceInformation("Snapshot contains {0} items", items.Length);
                for (int i = 0; i < items.Length; i++)
                {
                    // We want to include the situation where a snapshot on a path is the same as the snapshot of the VC session.
                    // In this situation, we want to include the item in the session snapshot changeset.
                    // So we use changesetId + 1 as the reference changeset id.
                    if (IsPathMapped(items[i].ServerItem, m_sessionLevelSnapshotChangeset + 1) == MappingResult.Mapped)
                    {
                        countDownToCreateNewChangeGroup--;
                        if (countDownToCreateNewChangeGroup == 0)
                        {
                            TraceManager.TraceInformation("Saving {0} change actions", m_snapshotCheckinBatchSize);
                            batchGroup.Save();

                            batchGroup.Actions.Clear();
                            batchGroup = null;

                            batchExecutionOrder--;
                            batchGroup = createChangeGroupForSnapshot(m_sessionLevelSnapshotChangeset, batchExecutionOrder);
                            countDownToCreateNewChangeGroup = m_snapshotCheckinBatchSize;
                            TraceManager.TraceInformation("Saved {0} change actions", m_snapshotCheckinBatchSize);
                        }
                        batchGroup.CreateAction(
                            WellKnownChangeActionId.Add,
                            new TfsMigrationItem(items[i]),
                            null,
                            items[i].ServerItem,
                            null,
                            null,
                            TfsAnalysisAlgorithms.convertContentType(items[i].ItemType),
                            null);
                    }
                    items[i] = null; // Dispose this object to reduce memory consumption.
                }
            }

            if (batchGroup.Actions.Count > 0)
            {
                int numRemainingItems = batchGroup.Actions.Count;
                TraceManager.TraceInformation("Saving {0} change actions", numRemainingItems);
                batchGroup.Save();
                TraceManager.TraceInformation("Saved {0} change actions", numRemainingItems);
            }

            m_hwmDelta.Update(m_sessionLevelSnapshotChangeset);
            m_changeGroupService.PromoteDeltaToPending();
            m_sessionlevelSnapshotCompleted = true;
        }
        private bool SubmitBatchedAddOrDeleteLinkChanges(
            List <XmlDocument> updateDocuments,
            Dictionary <int, LinkChangeAction> updateDocIndexToLinkChangeActionMap,
            ITranslationService translationService,
            ConfigurationService configService,
            ConflictManager conflictManager)
        {
            bool succeeded = true;

            UpdateResult[] results = TfsBatchUpdateHelper.Submit(Core, WorkItemServer, updateDocuments.ToArray());
            if (results.Length != updateDocuments.Count)
            {
                throw new SynchronizationEngineException("Wrong number of link update results.");
            }

            // Collect list of successful LinkChangeActions (for LinkTypes with GetsActionsFromLinkChangeHistory true) to pass to SetServerLinkChangeIds()
            List <LinkChangeAction> actionsNeedingServerLinkIdSet = new List <LinkChangeAction>();

            for (int i = 0; i < results.Length; ++i)
            {
                UpdateResult rslt = results[i];

                if (rslt.Exception != null)
                {
                    if (rslt.Exception.Message.Contains("The specified link already exists"))
                    {
                        // it is ok to eat this exception

                        // mark the change action completed so it is not retried later
                        LinkChangeAction action = updateDocIndexToLinkChangeActionMap[i];
                        action.Status = LinkChangeAction.LinkChangeActionStatus.Skipped;

                        TraceManager.TraceInformation("Tried to add a link that already exists so skipping it: " + GetLinkChangeActionDescription(action));

                        System.Web.Services.Protocols.SoapException soapException = rslt.Exception as System.Web.Services.Protocols.SoapException;
                        if (soapException != null)
                        {
                            TraceManager.TraceVerbose("SoapException.Detail.InnerXml for ignored exception: " + soapException.Detail.InnerXml);
                        }
                    }
                    else if (updateDocIndexToLinkChangeActionMap[i].ChangeActionId == WellKnownChangeActionId.Delete && rslt.Exception.Message.Contains("This specified link does not exist"))
                    {
                        // it is ok to eat this exception and skip the action

                        // mark the change action completed so it is not retried later
                        LinkChangeAction action = updateDocIndexToLinkChangeActionMap[i];
                        action.Status = LinkChangeAction.LinkChangeActionStatus.Skipped;

                        TraceManager.TraceInformation("Tried to delete a link that does not exist so skipping it: " + GetLinkChangeActionDescription(action));

                        System.Web.Services.Protocols.SoapException soapException = rslt.Exception as System.Web.Services.Protocols.SoapException;
                        if (soapException != null)
                        {
                            TraceManager.TraceVerbose("SoapException.Detail.InnerXml for ignored exception: " + soapException.Detail.InnerXml);
                        }
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             rslt.Exception.Message.StartsWith(
                                 TFSMulitpleParentLinkConflictType.SingleParentViolationMessage,
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        MigrationConflict conflict = TFSMulitpleParentLinkConflictType.CreateConflict(
                            updateDocIndexToLinkChangeActionMap[i], rslt.Exception);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                            succeeded = false;
                        }
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             rslt.Exception.Message.StartsWith(
                                 TFSCyclicLinkConflictType.CircularityLinkHierarchyViolationMessage,
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        ILinkProvider linkProvider = ServiceContainer.GetService(typeof(ILinkProvider)) as ILinkProvider;
                        Debug.Assert(null != linkProvider, "linkProvider is NULL");

                        LinkChangeAction          conflictedAction = updateDocIndexToLinkChangeActionMap[i];
                        NonCyclicReferenceClosure linkRefClosure   =
                            linkProvider.CreateNonCyclicLinkReferenceClosure(conflictedAction.Link.LinkType, conflictedAction.Link.SourceArtifact);

                        MigrationConflict conflict = TFSCyclicLinkConflictType.CreateConflict(conflictedAction, rslt.Exception, linkRefClosure);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                            succeeded = false;
                        }
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             rslt.Exception.Message.StartsWith(
                                 TFSModifyLockedWorkItemLinkConflictType.ModifyLockedWorkItemLinkViolationMessage,
                                 StringComparison.OrdinalIgnoreCase))
                    {
                        MigrationConflict conflict = TFSModifyLockedWorkItemLinkConflictType.CreateConflict(
                            updateDocIndexToLinkChangeActionMap[i], rslt.Exception);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                        }
                        // returning "not succeeded" so that the caller keeps this change group in "ReadyForMigration" status
                        succeeded = false;
                    }
                    else if (rslt.Exception is System.Web.Services.Protocols.SoapException &&
                             null != rslt.Exception.Message &&
                             (rslt.Exception.Message.StartsWith(TFSLinkAccessViolationConflictType.LinkAccessViolationMessage1, StringComparison.OrdinalIgnoreCase) ||
                              rslt.Exception.Message.StartsWith(TFSLinkAccessViolationConflictType.LinkAccessViolationMessage2, StringComparison.OrdinalIgnoreCase)))
                    {
                        MigrationConflict conflict = TFSLinkAccessViolationConflictType.CreateConflict(
                            updateDocIndexToLinkChangeActionMap[i], rslt.Exception);

                        List <MigrationAction> actions;
                        var resolutionRslt = conflictManager.TryResolveNewConflict(conflictManager.SourceId, conflict, out actions);
                        if (!resolutionRslt.Resolved)
                        {
                            updateDocIndexToLinkChangeActionMap[i].IsConflicted = true;
                        }
                        // returning "not succeeded" so that the caller keeps this change group in "ReadyForMigration" status
                        succeeded = false;
                    }
                    else
                    {
                        LinkChangeAction action = updateDocIndexToLinkChangeActionMap[i];
                        // TODO
                        // Try resolve conflict and push to backlog if resolution fails
                        action.IsConflicted = true;

                        TraceManager.TraceError(String.Format(CultureInfo.InvariantCulture,
                                                              "Exception processing {0}: {1}", GetLinkChangeActionDescription(action), rslt.Exception.ToString()));
                        succeeded = false;
                    }
                }
                else // rslt.Exception == null
                {
                    LinkChangeAction successfulAction = updateDocIndexToLinkChangeActionMap[i];
                    MarkLinkChangeActionCompleted(successfulAction);

                    TraceManager.TraceVerbose("Successful " + GetLinkChangeActionDescription(successfulAction));

                    List <LinkChangeAction> updatedActions = new List <LinkChangeAction>();
                    updatedActions.Add(successfulAction);

                    if (successfulAction.Link.LinkType.GetsActionsFromLinkChangeHistory)
                    {
                        actionsNeedingServerLinkIdSet.Add(successfulAction);
                    }

                    UpdateLinkConversionHistory(configService, translationService, rslt, updatedActions);
                }
            }

            SetServerLinkChangeIds(actionsNeedingServerLinkIdSet);

            return(succeeded);
        }
예제 #30
0
        private int[] getMappedTfsChange()
        {
            m_hwmDelta.Reload();


            Debug.Assert(m_hwmDelta.Value >= 0, "High water mark of delta table must be non-negtive");

            int latestChangeset = m_tfsClient.GetLatestChangesetId();

            // No new changesets on server, return.
            if (m_hwmDelta.Value >= latestChangeset)
            {
                return(new int[0]);
            }

            int startingChangeset = m_hwmDelta.Value + 1;

            string skipComment     = ConfigurationService.GetValue <string>(Constants.SkipComment, "**NOMIGRATION**");
            string commentModifier = ConfigurationService.GetValue <string>(Constants.CommentModifier, TfsVCAdapterResource.DefaultCommentModifier);

            SortedDictionary <int, bool> mappedChangesets = new SortedDictionary <int, bool>();

            foreach (MappingEntry m in ConfigurationService.Filters)
            {
                if (m.Cloak)
                {
                    continue;
                }
                try
                {
                    foreach (Changeset changeset in m_tfsClient.QueryHistory(m.Path,
                                                                             VersionSpec.Latest,
                                                                             0,
                                                                             RecursionType.Full,
                                                                             null,
                                                                             new ChangesetVersionSpec(startingChangeset),
                                                                             new ChangesetVersionSpec(latestChangeset),
                                                                             int.MaxValue, // All changes
                                                                             false,
                                                                             true))
                    {
                        if (mappedChangesets.ContainsKey(changeset.ChangesetId))
                        {
                            continue;
                        }

                        if (TfsUtil.IsOurTfsChange(changeset, TranslationService, m_conflictManagementService.SourceId))
                        {
                            TraceManager.TraceInformation("Skipping mirrored change {0}", changeset.ChangesetId);
                            continue;
                        }

                        if (!string.IsNullOrEmpty(skipComment))
                        {
                            if (changeset.Comment != null && changeset.Comment.Contains(skipComment))
                            {
                                TraceManager.TraceInformation("Changeset {0} contains the skip comment {1}",
                                                              changeset.ChangesetId,
                                                              skipComment);
                                continue;
                            }
                        }

                        if (!mappedChangesets.ContainsKey(changeset.ChangesetId))
                        {
                            mappedChangesets.Add(changeset.ChangesetId, true);
                        }
                    }
                }
                catch (ItemNotFoundException)
                {
                    // the path does not contain any changesets
                }
            }
            if (mappedChangesets.Count > 0)
            {
                int[] mappedChangesetsArray = new int[mappedChangesets.Count];
                mappedChangesets.Keys.CopyTo(mappedChangesetsArray, 0);
                return(mappedChangesetsArray);
            }
            else
            {
                // No new changesets are found, update the HWM as current latest
                m_hwmDelta.Update(latestChangeset);
                return(new int[0]);
            }
        }
        private void SetServerLinkChangeIds(List <LinkChangeAction> linkChangeActions)
        {
            if (linkChangeActions.Count == 0)
            {
                return;
            }
            m_hwmSubmittedLinkChangeId.Reload();
            long hwmSubmittedValue = m_hwmSubmittedLinkChangeId.Value;

            Dictionary <int, List <LinkChangeAction> > linkChangeActionsByLowerId = new Dictionary <int, List <LinkChangeAction> >();

            foreach (LinkChangeAction action in linkChangeActions)
            {
                int workItemIdKey = GetLowerWorkItemId(action);
                if (!linkChangeActionsByLowerId.ContainsKey(workItemIdKey))
                {
                    linkChangeActionsByLowerId.Add(workItemIdKey, new List <LinkChangeAction>());
                }
                linkChangeActionsByLowerId[workItemIdKey].Add(action);
            }

            /*
             * TraceManager.TraceVerbose(String.Format(
             *  "SetServerLinkChangeIds calling WorkItemServer.GetWorkItemLinkChanges to find Ids for {0} successful link actions starting with RowNumber {1}",
             *  linkChangeActions.Count, hwmSubmittedValue));
             */
            Stopwatch stopwatch = Stopwatch.StartNew();

            int serverLinkChangeIdsSet = 0;

            foreach (WorkItemLinkChange linkChange in WorkItemServer.GetWorkItemLinkChanges(Guid.NewGuid().ToString(), hwmSubmittedValue))
            {
                int linkChangeKey = GetLowerWorkItemId(linkChange);
                List <LinkChangeAction> actions;
                if (linkChangeActionsByLowerId.TryGetValue(linkChangeKey, out actions))
                {
                    foreach (LinkChangeAction action in actions)
                    {
                        if (LinkChangeMatchesLinkAction(linkChange, action))
                        {
                            action.ServerLinkChangeId = linkChange.RowVersion.ToString();
                            serverLinkChangeIdsSet++;
                            hwmSubmittedValue = linkChange.RowVersion;
                            // Don't break here because there could be more than one LinkChangeAction in the list that matches the WorkItemLinkChange
                            // break;
                        }
                    }
                }
            }

            stopwatch.Stop();
            TraceManager.TraceVerbose("Time to call GetWorkItemLinkChanges() and process return values: {0} seconds", stopwatch.Elapsed.TotalSeconds);

            if (serverLinkChangeIdsSet < linkChangeActions.Count)
            {
                // Look for any LinkChangeActions that did not get the ServerLinkChangeId set
                foreach (LinkChangeAction linkChangeAction in linkChangeActions)
                {
                    if (linkChangeAction.ServerLinkChangeId == null)
                    {
                        string msg = String.Format(
                            "Unable to set ServerLinkChangeId on at least one LinkChangeAction: {0} '{1}'->'{2}' ({3})",
                            linkChangeAction.ChangeActionId == WellKnownChangeActionId.Add ? "Add" : "Delete",
                            linkChangeAction.Link.SourceArtifact.Uri, linkChangeAction.Link.TargetArtifact.Uri, linkChangeAction.Link.LinkType.ReferenceName);
                        TraceManager.TraceWarning(msg);
                        break;
                    }
                }
            }

            /*
             * else
             * {
             *  TraceManager.TraceVerbose(String.Format("SetServerLinkChangeIds set values for {0} link actions ending with RowNumber {1}",
             *      serverLinkChangeIdsSet, hwmSubmittedValue));
             * }
             */

            m_hwmSubmittedLinkChangeId.Update(hwmSubmittedValue);

            TraceManager.TraceInformation("Persisted WIT linking sequence HWM: {0} (MigrationSourceId: {1})",
                                          TfsConstants.HwmSubmittedLinkChangeId, m_hwmSubmittedLinkChangeId.SourceUniqueId.ToString());
            TraceManager.TraceInformation(TfsWITAdapterResources.UpdatedHighWatermark, hwmSubmittedValue);
        }
예제 #32
0
        /// <summary>
        /// Determines if the provided path is a valid TFS server path
        /// </summary>
        /// <param name="path">The path to test</param>
        /// <param name="throwOnError">If true a MigrationException is thrown if the path is not valid.  if false, false will be returned if the path is not valid.</param>
        /// <returns>True if the path is valid or false if it is not and if throwOnError is false.</returns>
        public static bool IsValidTfsServerPath(string path, bool throwOnError)
        {
            bool   isValid  = false;
            string errorMsg = null;

            if (!string.IsNullOrEmpty(path))
            {
                if (path.Length <= 260)
                {
                    // server paths always start with the root node
                    if (path.StartsWith("$/"))
                    {
                        // server paths use '/' not '\'
                        if (path.IndexOf('\\') == -1)
                        {
                            // path segment starts with '$'
                            if (!path.Contains("/$"))
                            {
                                isValid = true;
                            }
                            else
                            {
                                errorMsg = string.Format(
                                    TfsVCAdapterResource.Culture,
                                    TfsVCAdapterResource.InvalidServerPath_DollarSegment,
                                    path);
                            }
                        }
                        else
                        {
                            errorMsg = string.Format(
                                TfsVCAdapterResource.Culture,
                                TfsVCAdapterResource.InvalidServerPath_WrongSlashes,
                                path);
                        }
                    }
                    else
                    {
                        errorMsg = string.Format(
                            TfsVCAdapterResource.Culture,
                            TfsVCAdapterResource.InvalidServerPath_MustStartWithDollarSlash,
                            path);
                    }
                }
                else
                {
                    errorMsg = string.Format(
                        TfsVCAdapterResource.Culture,
                        TfsVCAdapterResource.InvalidServerPath_260Limit,
                        path);
                }
            }
            else
            {
                errorMsg = TfsVCAdapterResource.InvalidServerPath_NullOrEmpty;
            }

            if (!isValid)
            {
                Debug.Assert(!string.IsNullOrEmpty(errorMsg));

                TraceManager.TraceWarning(errorMsg);
                if (throwOnError)
                {
                    throw new MigrationException(errorMsg);
                }
            }

            return(isValid);
        }
        protected bool SubmitNonWorkItemLinkChanges(
            LinkChangeGroup linkChanges,
            ServiceContainer serviceContainer,
            ConfigurationService configService,
            ITranslationService translationService,
            TfsLinkingProviderBase.LinkSubmissionPhase submissionPhase)
        {
            // group non-WorkItemLink changes by work item Id
            Dictionary <int, List <LinkChangeAction> > perWorkItemLinkChanges = RegroupLinkChangeActions(linkChanges);
            var orderedWorkitemId = new Dictionary <int, int>();
            int index             = 0;

            foreach (int workItemId in perWorkItemLinkChanges.Keys)
            {
                orderedWorkitemId.Add(index++, workItemId);
            }

            // batch-submit links of each work item
            var updateDocs = new List <XmlDocument>(perWorkItemLinkChanges.Count);

            foreach (var perWorkItemLinkChange in perWorkItemLinkChanges)
            {
                if (perWorkItemLinkChange.Value.Count == 0)
                {
                    continue;
                }

                WorkItem workItem = WorkItemStore.GetWorkItem(perWorkItemLinkChange.Key);

                var tfsUpdateDocument = InitializeUpdateDocument();
                tfsUpdateDocument.CreateWorkItemUpdateDoc(workItem);
                bool hasNonWorkItemLinkChanges = false;
                foreach (LinkChangeAction linkChangeAction in perWorkItemLinkChange.Value)
                {
                    if (linkChangeAction.Status != LinkChangeAction.LinkChangeActionStatus.ReadyForMigration ||
                        linkChangeAction.IsConflicted ||
                        linkChangeAction.Link.LinkType is WorkItemLinkTypeBase)
                    {
                        continue;
                    }

                    if (!ProcessActionInCurrentSubmissionPhase(linkChangeAction, submissionPhase))
                    {
                        continue;
                    }

                    hasNonWorkItemLinkChanges = true;
                    var handler = linkChangeAction.Link.LinkType as ILinkHandler;
                    Debug.Assert(null != handler);
                    handler.UpdateTfs(tfsUpdateDocument, linkChangeAction);
                }

                if (hasNonWorkItemLinkChanges)
                {
                    updateDocs.Add(tfsUpdateDocument.UpdateDocument);
                }
            }

            if (updateDocs.Count == 0)
            {
                return(true);
            }

            UpdateResult[] results = TfsBatchUpdateHelper.Submit(Core, WorkItemServer, updateDocs.ToArray());

            if (results.Length != updateDocs.Count)
            {
                throw new SynchronizationEngineException("Wrong number of link update results.");
            }

            bool succeeded = true;

            for (int i = 0; i < results.Length; ++i)
            {
                UpdateResult rslt = results[i];

                if (rslt.Exception != null &&
                    !rslt.Exception.Message.Contains("The specified link already exists"))
                {
                    TraceManager.TraceError(rslt.Exception.ToString());
                    succeeded = false;
                    // TODO
                    // Try resolve conflict and push to backlog if resolution fails
                    foreach (LinkChangeAction action in perWorkItemLinkChanges[orderedWorkitemId[i]])
                    {
                        action.IsConflicted = true;
                    }
                }
                else
                {
                    foreach (LinkChangeAction action in perWorkItemLinkChanges[orderedWorkitemId[i]])
                    {
                        if (ProcessActionInCurrentSubmissionPhase(action, submissionPhase))
                        {
                            MarkLinkChangeActionCompleted(action);
                        }
                    }

                    if (rslt.Exception == null)
                    {
                        UpdateLinkConversionHistory(configService, translationService, rslt, perWorkItemLinkChanges[orderedWorkitemId[i]]);
                    }
                    else if (rslt.Exception.Message.Contains("The specified link already exists"))
                    {
                        WorkItemLinkStore relatedArtifactsStore = new WorkItemLinkStore(configService.SourceId);
                        relatedArtifactsStore.UpdateSyncedLinks(perWorkItemLinkChanges[orderedWorkitemId[i]]);
                    }
                }
            }
            return(succeeded);
        }
예제 #34
0
 /// <summary>
 /// Register adapter's supported content types.
 /// </summary>
 /// <param name="contentTypeRegistrationService"></param>
 public override void RegisterSupportedContentTypes(ContentTypeRegistrationService contentTypeRegistrationService)
 {
     TraceManager.TraceInformation("WSSVC:AP:RegisterSupportedContentTypes");
 }
        protected override TfsUpdateDocument SubmitAttachmentChanges(IMigrationAction action, ConflictManager conflictMgrService)
        {
            /*
             * retrieve change details
             */
            XmlDocument desc     = action.MigrationActionDescription;
            XmlElement  rootNode = desc.DocumentElement;

            Debug.Assert(null != rootNode);
            XmlNode attachmentNode   = rootNode.FirstChild;
            string  originalName     = attachmentNode.Attributes["Name"].Value;
            string  utcCreationDate  = attachmentNode.Attributes["UtcCreationDate"].Value;
            string  utcLastWriteDate = attachmentNode.Attributes["UtcLastWriteDate"].Value;
            string  length           = attachmentNode.Attributes["Length"].Value;
            string  comment          = attachmentNode.FirstChild.InnerText;
            int     targetWorkItemId = FindTargetWorkItemId(action, conflictMgrService);
            string  targetRevision   = rootNode.Attributes["TargetRevision"].Value;

            /*
             * create operation document
             */
            TfsUpdateDocument tfsUpdateDocument = InitializeUpdateDocument();

            tfsUpdateDocument.CreateWorkItemUpdateDoc(targetWorkItemId.ToString(), targetRevision);

            /*
             * insert Connector specific comment
             */
            WorkItem item = WorkItemStore.GetWorkItem(targetWorkItemId);

            Debug.Assert(null != item, "target work item does not exist");
            tfsUpdateDocument.InsertConversionHistoryCommentToHistory(item.Type.Name, GenerateMigrationHistoryComment(action));

            int[] fileId = FindAttachmentFileId(targetWorkItemId, originalName,
                                                utcCreationDate, utcLastWriteDate, length, comment);

            /*
             * delete attachment
             */
            if (action.Action == WellKnownChangeActionId.DelAttachment)
            {
                if (fileId.Length == 0)
                {
                    action.State = ActionState.Skipped;
                    return(null);
                }
                else
                {
                    tfsUpdateDocument.RemoveAttachment(fileId[0]);
                    return(tfsUpdateDocument);
                }
            }

            /*
             * add attachment
             */
            try
            {
                string sourceStoreCountString = attachmentNode.Attributes["CountInSourceSideStore"].Value;
                int    sourceStoreCount;
                if (int.TryParse(sourceStoreCountString, out sourceStoreCount))
                {
                    if (sourceStoreCount <= fileId.Length)
                    {
                        action.State = ActionState.Skipped;
                        return(null);
                    }
                }
            }
            catch (Exception e)
            {
                TraceManager.TraceVerbose(e.ToString());
                // for backward compatibility, just proceed
            }

            if (AttachmentIsOversized(length))
            {
                MigrationConflict conflict = new FileAttachmentOversizedConflictType().CreateConflict(
                    originalName, length, MaxAttachmentSize, targetWorkItemId.ToString(), Core.ServerName, Core.Config.Project, action);

                List <MigrationAction>   actions;
                ConflictResolutionResult resolveRslt = conflictMgrService.TryResolveNewConflict(conflictMgrService.SourceId, conflict, out actions);

                if (!resolveRslt.Resolved)
                {
                    return(null);
                }

                if (resolveRslt.ResolutionType == ConflictResolutionType.SuppressedConflictedChangeAction)
                {
                    action.State = ActionState.Skipped;
                    return(null);
                }

                if (resolveRslt.ResolutionType == ConflictResolutionType.Other)
                {
                    // conflict resolved, just proceed
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            Guid fileGuid = Guid.NewGuid();

            tfsUpdateDocument.AddAttachment(originalName, XmlConvert.ToString(fileGuid),
                                            utcCreationDate, utcLastWriteDate, length, comment);

            // get areaNodeUri - required by Dev10 OM
            Project project        = item.Project;
            string  projectNodeUri = (project.Uri).ToString();
            string  areaNodeUri    = string.Empty;

            if (project.Id == item.AreaId)
            {
                areaNodeUri = Core.AreaNodeUri;
            }
            else
            {
                // Loop through the area root nodes looking for the one we're on
                foreach (Node node in project.AreaRootNodes)
                {
                    // It could be one of the root nodes
                    if (node.Id == item.AreaId)
                    {
                        areaNodeUri = node.Uri.ToString();
                        break;
                    }

                    // Now check if it is a child of the current area root node
                    try
                    {
                        Node node2 = node.FindNodeInSubTree(item.AreaId);
                        areaNodeUri = node2.Uri.ToString();
                        break;
                    }
                    catch (DeniedOrNotExistException)
                    {
                        // Ignore if not found, go onto the next area root node
                        continue;
                    }
                }
            }

            //Now upload the file since that has to be done before the Xml batch is executed.
            Debug.Assert(!string.IsNullOrEmpty(LocalWorkDir));
            string filePath = Path.Combine(LocalWorkDir, fileGuid.ToString());

            action.SourceItem.Download(filePath);
            using (var strm = File.OpenRead(filePath))
            {
                var f = new FileAttachment();
                f.AreaNodeUri  = areaNodeUri;
                f.ProjectUri   = projectNodeUri;
                f.FileNameGUID = fileGuid;
                f.LocalFile    = strm; // attachment.GetFileContents();

                WorkItemServer.UploadFile(f);
            }

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            return(tfsUpdateDocument);
        }
예제 #36
0
        static void Main(string[] args)
        {
            IRepositoryFactory repositoryFactory = RepositoryFactory.Instance;
            ISymmetricAlgorithmProvider symmetricAlgorithmProvider = SymmetricAlgorithmProvider.Instance;

            using (var traceManager = new TraceManager("trace.txt"))
            {
                using (var dbContext = new KerberosStorageContext())
                {
                    using (var unitOfWork = new UnitOfWork(dbContext, repositoryFactory))
                    {
                        var users =
                            unitOfWork.Repository<User, int>()
                                      .Query()
                                      .Filter(p => p.Email.Equals("*****@*****.**", StringComparison.OrdinalIgnoreCase))
                                      .Get();

                        var user = users.FirstOrDefault();

                        if (user != null)
                        {
                            IAuthenticationService authenticationService = new AuthenticationService(
                                unitOfWork,
                                symmetricAlgorithmProvider,
                                traceManager);

                            var authenticationRequest = new AuthenticationRequest
                            {
                                ServerId = "authentication server",
                                TimeStamp = DateTime.Now,
                                UserId = user.Email
                            };
                            traceManager.Trace("Authentication Request Sent", authenticationRequest);
                            IAuthenticationReply authenticationReply = authenticationService.Authenticate(authenticationRequest);
                            traceManager.Trace("TGS encrypted received", Tuple.Create(authenticationReply.TgsBytes, authenticationReply.TgtBytes));

                            ITgsToken tgsToken = authenticationService.DecryptReply(user.Email, authenticationReply);
                            traceManager.Trace("TGS decrypted: ", tgsToken);

                            IAuthorizationService authorizationService = new AuthorizationService(
                                unitOfWork,
                                symmetricAlgorithmProvider,
                                traceManager);
                            byte[] authenticator = authorizationService.CreateAuthenticator(user.Email, tgsToken.SessionKey);
                            traceManager.Trace("Auth authenticator encrypted", authenticator);

                            var authorizationRequest = new AuthorizationRequest
                            {
                                AutheticatorBytes = authenticator,
                                TgtBytes = authenticationReply.TgtBytes
                            };

                            IAuthorizationReply authorizationReply = authorizationService.Authorize(authorizationRequest);
                            traceManager.Trace("Authorization reply received", Tuple.Create(authorizationReply.ServiceTicket, authorizationReply.ServiceToken));

                            IServiceToken serviceToken = authorizationService.DecryptReply(user.Email, authorizationReply, tgsToken.SessionKey);
                            traceManager.Trace("Service token decrypted", serviceToken);

                            IDataService dataService = new DataService(unitOfWork, symmetricAlgorithmProvider, traceManager);
                            authenticator = dataService.CreateAuthenticator(user.Email, serviceToken.SessionKey);

                            var dataServiceRequest = new DataServiceRequest
                            {
                                Authenticator = authenticator,
                                ServiceTicket = authorizationReply.ServiceTicket
                            };

                            traceManager.Trace("Data service request sent", dataServiceRequest);

                            IDataServiceReply dataServiceReply = dataService.GetAccess(dataServiceRequest);
                            ITimeStampContainer timeStampContainer = dataService.DecryptReply(user.Email, dataServiceReply, serviceToken.SessionKey);

                            if (Math.Abs((DateTime.UtcNow - new DateTime(timeStampContainer.TimeStamp, DateTimeKind.Utc)).Ticks) < new TimeSpan(1, 0, 0).Ticks)
                            {
                                traceManager.Trace("The operation has been completed successfully.");
                            }
                        }
                    }
                }

            }
        }
예제 #37
0
 /// <summary>
 ///
 /// </summary>
 private void flashInterface_TraceEvent(Object sender, String trace)
 {
     TraceManager.AddAsync(trace, 1);
 }
예제 #38
0
        void AddDiagnosticsResults(List <LintingResult> list, HaxeCompleteStatus status, List <HaxeDiagnosticsResult> results, HaxeComplete hc)
        {
            if (status == HaxeCompleteStatus.DIAGNOSTICS && results != null)
            {
                foreach (var res in results)
                {
                    var range = res.Range ?? res.Args.Range;

                    var result = new LintingResult
                    {
                        File      = range.Path,
                        FirstChar = range.CharacterStart,
                        Length    = range.CharacterEnd - range.CharacterStart,
                        Line      = range.LineStart + 1,
                    };

                    switch (res.Severity)
                    {
                    case HaxeDiagnosticsSeverity.INFO:
                        result.Severity = LintingSeverity.Info;
                        break;

                    case HaxeDiagnosticsSeverity.ERROR:
                        result.Severity = LintingSeverity.Error;
                        break;

                    case HaxeDiagnosticsSeverity.WARNING:
                        result.Severity = LintingSeverity.Warning;
                        break;

                    default:
                        continue;
                    }

                    switch (res.Kind)
                    {
                    case HaxeDiagnosticsKind.UnusedImport:
                        result.Description = TextHelper.GetString("Info.UnusedImport");
                        break;

                    case HaxeDiagnosticsKind.UnresolvedIdentifier:
                        result.Description = TextHelper.GetString("Info.UnresolvedIdentifier");
                        break;

                    case HaxeDiagnosticsKind.CompilerError:
                    case HaxeDiagnosticsKind.RemovableCode:
                        result.Description = res.Args.Description;
                        break;

                    default:     //in case new kinds are added in new compiler versions
                        continue;
                    }

                    list.Add(result);
                }
            }
            else if (status == HaxeCompleteStatus.ERROR)
            {
                PluginBase.RunAsync(() =>
                {
                    TraceManager.Add(hc.Errors, (int)TraceType.Error);
                });
            }
        }
예제 #39
0
		void RenderMenu (TraceManager manager, HtmlTextWriter output, string dir)
		{
			
			output.RenderBeginTag (HtmlTextWriterTag.Html);
			
			output.RenderBeginTag (HtmlTextWriterTag.Head);
			TraceData.RenderStyleSheet (output);
			output.RenderEndTag ();

			RenderHeader (output, dir);
			
			output.RenderBeginTag (HtmlTextWriterTag.Body);
			output.AddAttribute ("class", "tracecontent");
			output.RenderBeginTag (HtmlTextWriterTag.Span);

			Table table = TraceData.CreateTable ();
			
			table.Rows.Add (TraceData.AltRow ("Requests to the Application"));
			table.Rows.Add (TraceData.SubHeadRow ("No", "Time of Request",
							"File", "Status Code", "Verb", "&nbsp;"));

			if (manager.TraceData != null) {
				for (int i=0; i<manager.ItemCount; i++) {
					int item = i + 1;
					TraceData d = manager.TraceData [i];
					TraceData.RenderAltRow (table, i, item.ToString (), d.RequestTime.ToString (),
							d.RequestPath, d.StatusCode.ToString (), d.RequestType,
							"<a href=\"Trace.axd?id=" + item + "\" class=\"tinylink\">" +
							"<b><nobr>View Details</a>");
				}
				table.RenderControl (output);
			}
			
			output.RenderEndTag ();
			output.RenderEndTag ();
			
			output.RenderEndTag ();
		}