private static Dictionary<DateTime, String> LoadEvents(String filePath)
        {
            List<String> activities = new List<String>();
            List<DateTime> timestamps = new List<DateTime>();

            Dictionary<DateTime, String> events = new Dictionary<DateTime, String>();

            int k = 0;
            foreach (String line in File.ReadAllLines(filePath))
            {
                string[] tokens = line.Split(new char[] { ';' });
                Console.WriteLine("Line " + k);
                timestamps.Add(DateTime.Parse(tokens[0]));
                activities.Add(tokens[1]);
                events.Add(DateTime.Parse(tokens[0]), tokens[1]);
                Console.WriteLine("Timestamp per line " + DateTime.Parse(tokens[0]) + " Activity = " + tokens[1]);
                k++;

            }
            var tsArray = timestamps.ToArray();
            var actArray = activities.ToArray();
            Console.WriteLine("tsArray length " + tsArray.Length + ", actArray length " + actArray.Length);
            for (int j = 0; j < tsArray.Length; j++)
            {
                Console.WriteLine("tsArray[" + j + "] = " + tsArray[j].ToString() + " -- actArray[" + j + "] = " + actArray[j].ToString());
            }

            SimulateReadingFile(events);

            return events;
        }
Example #2
1
        private static Thickness ConvertFromString(string s)
        {
            var parts = s.Split(',')
                .Take(4)
                .Select(part => part.Trim());

            if (parts.Count() == 1)
            {
                var uniformLength = double.Parse(parts.First());
                return new Thickness(uniformLength);
            }

            double left = 0, top = 0, right = 0, bottom = 0;

            IList<Action<double>> setValue = new List<Action<double>>
            {
                val => left = val,
                val => top = val,
                val => right = val,
                val => bottom = val,
            };

            var i = 0;
            foreach (var part in parts)
            {
                var v = double.Parse(part);
                setValue[i](v);
                i++;
            }

            return new Thickness(left, top, right, bottom);
        }
Example #3
1
        // Constructor(s)
        public Weapon()
            : base()
        {
            this.Damage = Globals.Randomizer.Next(10, 20);
            this.ShieldPiercing = (float)Math.Round(Globals.Randomizer.NextDouble(), 2);
            this.Chance = Globals.Randomizer.Next(20, 30);
            this.Depth = 0.5f;

            this.Texture = TextureManager.weapons[Globals.Randomizer.Next(0, TextureManager.weapons.Count)];

            ShootMethods = new List<Shoot>();
            ShootMethods.Add(FireStandard);
            ShootMethods.Add(FireAiming);
            ShootMethods.Add(FireCrit);
            ShootMethods.Add(FireDelayEnemyShot);
            ShootMethods.Add(FireDamageOverTime);
            ShootMethods.Add(FireChanceToMiss);

            Action = Globals.Randomizer.Next(0, ShootMethods.Count);

            // Initialize weapon
            ShootMethods[Action](Position, Direction, 0, null, true);

            Targets = new List<string>();

            // Description
            LoadDescription();
        }
Example #4
1
        static void Main()
        {
            List<MethodInvoker> list = new List<MethodInvoker>();

            for (int index = 0; index < 5; index++)
            {
                int counter = index * 10;
                list.Add(delegate
                {
                    Console.WriteLine(counter);
                    counter++;
                });
            }

            foreach (MethodInvoker t in list)
            {
                t();
            }

            list[0]();
            list[0]();
            list[0]();

            list[1]();
        }
 public void Create(object self, List<Func<object, IFilter>> creators)
 {
     _filters = new IFilter[creators.Count];
     for (var i = 0; i < creators.Count; i++)
     {
         _filters[i] = creators[i](self);
     }
 }
Example #6
1
 private static void Main(string[] args)
 {
     var contents = new List<Func<int>>();
     for (var i = 4; i < 7; i++)
     {
         int j = i;
         contents.Add(() => j);
     }
     for (var k = 0; k < contents.Count; k++)
         Console.WriteLine(contents[k]());
 }
    static void Main()
    {
        var methods = new List<Action>();
        foreach (var word in new string[] { "hello", "world" })
        {
            methods.Add(() => Console.Write(word + " "));
        }

        methods[0]();
        methods[1]();
    }
Example #8
1
	static IEnumerable<int> Test_2 ()
	{
		List<Func<int>> lambdas = new List<Func<int>> ();
		for (int i = 0; i < 4; ++i) {
			int h = i;
			lambdas.Add (() => h);
		}

		for (int i = 0; i < 4; ++i) {
			yield return lambdas[i] ();
		}
	}
Example #9
1
 private static void Main(string[] args)
 {
     var contents = new List<Func<int>>();
     var s = new StringBuilder();
     for (var i = 4; i < 7; i++)
     {
         var j = i;
         contents.Add(() => j);
     }
     for (var k = 0; k < contents.Count; k++)
         s.Append(contents[k]());
     Console.WriteLine(s);
 }
Example #10
1
        static void LawOfClosures()
        {
            var DelayedActions = new List<Func<int>>();
            var s = "";

            for (var i = 4; i < 7; i++)
            {
                DelayedActions.Add(() => i);
            }
            for (var k = 0; k < DelayedActions.Count; k++)
                s += DelayedActions[k]();

            Console.WriteLine(s);
        }
Example #11
1
 static void Main()
 {
     var items = new string[] {"Moe", "Larry", "Curly"};
     var actions = new List<Action>{};
     int i;
     for(i=0;i<items.Length;i++) //foreach (string item in items)
     {
         actions.Add(()=>{ Console.WriteLine(items[i]);});
     }
     for (i=0;i<items.Length;i++)
     {
         actions[i]();
     }
 }
	public static void Main() 
	{
		var actions = new List<Action>();

		var sb = new StringBuilder();
		for (int i = 0; i < 5; i++) {
			int i2 = i;
			actions.Add(() => sb.AppendLine(i2.ToString()));
		}

		for (int i = 0; i < actions.Count; i++)
			actions[i]();

		Console.WriteLine(sb.ToString());
	}
        public bool Execute(List<Vehicle> vehicles)
        {
            try
            {
                foreach (var vehicle in vehicles)
                {
                    var vehicleEntity = _db.Vehicle.Find(vehicle.Id);

                    if (vehicleEntity != null)
                    {
                        vehicleEntity.Id = vehicle.Id;
                        vehicleEntity.BookingId = vehicle.BookingId;
                        vehicleEntity.VehicleType = vehicle.VehicleType;
                        vehicleEntity.TrailerType = vehicle.TrailerType;
                        _db.MarkVehicleAsModified(vehicleEntity);
                        _db.SaveChanges();
                    }
                }
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
		public static List<ProjectItem> GetPendingChanges()
		{
			var projectItems = new List<ProjectItem>();
			var dte = (DTE)Package.GetGlobalService(typeof(SDTE));
			var projectCollections = new List<RegisteredProjectCollection>(RegisteredTfsConnections.GetProjectCollections());
			foreach (var registeredProjectCollection in projectCollections)
			{
				var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProjectCollection);
				var versionControl = projectCollection.GetService<VersionControlServer>();
				var workspace = versionControl.GetWorkspace(dte.Solution.FileName);

				foreach (var pendingChange in workspace.GetPendingChangesEnumerable())
				{
					if (pendingChange.FileName != null && (pendingChange.FileName.EndsWith(".cs") || pendingChange.FileName.EndsWith(".config")))
					{
						var projectItem = dte.Solution.FindProjectItem(pendingChange.FileName);
						if (projectItem != null)
						{
							projectItems.Add(projectItem);
						}
					}
				}
			}
			return projectItems;
		}
Example #15
1
 /// <summary>
 /// get nesting of circles within given dimensions
 /// </summary>
 /// <param name="circles">input planar surfaces to be cut</param>
 /// <param name="spacing">spacing between input result</param>
 /// <param name="width">width of sheet</param>
 /// <param name="length">length of sheet</param>
 internal Nesting(List<PolyCurve> polycurves, double spacing, double width, double length)
 {
     Width = width;
     Length = length;
     Spacing = spacing;
     ListPolyCurve = TileVertical(MapToXYPlane(polycurves), spacing);
 }
Example #16
1
        static void Main(string[] args)
        {
            List<ulong> testIntegers = new List<ulong>() { 117, 0, 1, 4, 69, 642, 932, 6903, 69382, 504967, 4028492, 902409102, 1403102045, ulong.MaxValue };

            ConsoleTests(testIntegers);
            UnicodeTests(testIntegers);
        }
        protected void Initialize()
        {
            Instance.PropertyChanged += Instance_PropertyChanged;

            PropertyInfo[] propertyInfos = Instance.GetType().GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                // Inspect each INotifyPropertyChanged
                if (propertyInfo.PropertyType.GetInterfaces().Contains(typeof(INotifyPropertyChanged)))
                {
                    INotifyPropertyChanged propertyValue = propertyInfo.GetValue(Instance) as INotifyPropertyChanged;

                    if (propertyValue != null)
                    {
                        propertyValues.Add(propertyInfo.Name, propertyValue);
                        propertyValue.PropertyChanged += PropertyValue_PropertyChanged;
                    }
                }

                // Inspect each DependsOn attribute
                DependsOnAttribute dependsOnAttribute = propertyInfo.GetCustomAttribute<DependsOnAttribute>();
                if (dependsOnAttribute != null)
                {
                    foreach (string property in dependsOnAttribute.Properties)
                    {
                        List<PropertyInfo> dependencies;

                        if (!propertyDependencies.TryGetValue(property, out dependencies))
                            propertyDependencies.Add(property, dependencies = new List<PropertyInfo>());
                        if (!dependencies.Contains(propertyInfo))
                            dependencies.Add(propertyInfo);
                    }
                }
            }
        }
        static void Main2(string[] args)
        {
            var numReal = new List<double>(80);
            Random gerador = new Random();
            double maior = 0;
            double menor = 0;
            double soma = 0;
            double media = 0;
            for (int i = 0; i < 80; i++)
            {
                numReal.Add(gerador.NextDouble());
                if (i == 0)
                {
                    maior = numReal[i];
                    menor = numReal[i];
                }
                soma += numReal[i];

            }
            media = soma / 80;
            for (int i = 0; i < 80; i++)
            {
                maior = (numReal[i] > maior) ? numReal[i] : maior;
                menor = (numReal[i] < menor) ? numReal[i] : menor;
            }
            Console.WriteLine("Maior: {0:F2}", maior);
            Console.WriteLine("Menor: {0:F2}", menor);
            Console.WriteLine("Soma: {0:F2}", soma);
            Console.WriteLine("Media: {0:F2}", media);
            Console.ReadKey();
        }
Example #19
1
        public static string[] Split(string str, char[] separators, int maxComponents, StringSplitOptions options)
        {
            ContractUtils.RequiresNotNull(str, "str");
            #if SILVERLIGHT || WP75
            if (separators == null) return SplitOnWhiteSpace(str, maxComponents, options);

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = str.IndexOfAny(separators, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + 1;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
            #else
            return str.Split(separators, maxComponents, options);
            #endif
        }
		public virtual IList<ItemToolboxNode> Load (LoaderContext ctx, string filename)
		{
			SystemPackage sp = Runtime.SystemAssemblyService.DefaultAssemblyContext.GetPackageFromPath (filename);
			ReferenceType rt;
			string rname;
			
			if (sp != null) {
				rt = ReferenceType.Package;
				rname = Runtime.SystemAssemblyService.DefaultAssemblyContext.GetAssemblyFullName (filename, null);
			} else {
				rt = ReferenceType.Assembly;
				rname = filename;
			}
			
			List<ItemToolboxNode> list = new List<ItemToolboxNode> ();
			var types = Runtime.RunInMainThread (delegate {
				// Stetic is not thread safe, it has to be used from the gui thread
				return GuiBuilderService.SteticApp.GetComponentTypes (filename);
			}).Result;
			foreach (ComponentType ct in types) {
				if (ct.Category == "window")
					continue;
				ComponentToolboxNode cn = new ComponentToolboxNode (ct);
				cn.ReferenceType = rt;
				cn.Reference = rname;
				list.Add (cn);
			}
			return list;
		}
Example #21
0
        /// <summary>
        /// Returns a list of visual branches which are around the given commit.
        /// </summary>
        /// <param name="commit"></param>
        /// <param name="repo"></param>
        /// <returns></returns>
        public static List<Branch> GetBranchesAroundCommit(Commit commit, ObservableCollection<Branch> branches)
        {
            List<Branch> list = new List<Branch>();

            // Loop through all branches and determine if they are around the specified commit.
            foreach (Branch branch in branches)
            {
                // Tip has to be found and in case multiple branches share the tree, get rid of the others -- messes up visual position counting.
                if (branch.Tip == null || list.Any(b => branch.Tip.Branches.Contains(b)) || list.Any(b => b.Tip.Branches.Contains(branch)))
                    continue;

                // The branch's tip must be newer/same than the commit.
                if (branch.Tip.Date >= commit.Date) // TODO: && first commit-ever must be older? We might not need to do that... ... ?
                {
                    list.Add(branch);
                }
                else
                {
                    // If there's a branch with a tip commit older than commit.Date, then it's around this commit if they don't share a single branch.
                    bool foundThisBranch = branch.Tip.Branches.Any(b => commit.Branches.Contains(b));

                    if (foundThisBranch == false)
                        list.Add(branch);
                }
            }

            return list;
        }
Example #22
0
        void Init(String domainName, String connStringName, Boolean pSecure, bool chekControllers)
        {
            //_LdapWrapper = new LdapWrapper();

            //LoadControllersFromDatabase( pConnString);


            _DomainUrlInfo = DomainsUrl_Get_FromSp(connStringName, domainName);// _DomainUrlInfoList.First<DomainUrlInfo>(p => p.DomainName == domainName);
            if (_DomainUrlInfo == null)
            {
                throw new Fwk.Exceptions.TechnicalException("No se encontró la información del dominio especificado");
            }

            if (chekControllers)
            {
                _DomainControllers = GetDomainControllersByDomainId(System.Configuration.ConfigurationManager.ConnectionStrings[connStringName].ConnectionString, _DomainUrlInfo.Id);
                if (_DomainControllers == null || _DomainControllers.Count == 0)
                    throw new Fwk.Exceptions.TechnicalException("No se encuentra configurado ningún controlador de dominio para el sitio especificado.");


                // Prueba de conectarse a algún controlador de dominio disponible, siempre arranando del primero. debería 
                // TODO: reemplazarse por un sistema de prioridad automática para que no intente conectarse primero a los funcionales conocidos
                //LdapException wLastExcept = GetDomainController(pSecure, _DomainControllers);
                if (_DomainController == null)
                {
                    throw new Fwk.Exceptions.TechnicalException("No se encontró ningún controlador de dominio disponible para el sitio especificado.");//, wLastExcept);
                }
            }
        }
Example #23
0
 private void InitializeMonitor()
 {
     _monitorList = new List<AbstractMonitor>();
     _monitorList.AddRange(from tp in typeof(AbstractMonitor).Assembly.GetTypes()
                           where typeof(AbstractMonitor).IsAssignableFrom(tp) && !tp.IsAbstract
                           select Activator.CreateInstance(tp) as AbstractMonitor);
 }
 public MainPage()
 {
     this.InitializeComponent();
     placeList = new List<Place>();
     getCurrentPosition();
     TravelMap.GotFocus += TravelMap_Tapped;
 }
Example #25
0
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<HisClient.Model.his_pm_import> DataTableToList(DataTable dt)
        {
            List<HisClient.Model.his_pm_import> modelList = new List<HisClient.Model.his_pm_import>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                HisClient.Model.his_pm_import model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new HisClient.Model.his_pm_import();
                                                                    model.ID= dt.Rows[n]["ID"].ToString();
                                                                                                                                model.SEND_DEPT_CODE= dt.Rows[n]["SEND_DEPT_CODE"].ToString();
                                                                                                                                model.RECEIVE_DEPT_CODE= dt.Rows[n]["RECEIVE_DEPT_CODE"].ToString();
                                                                                                                                model.PAKAGE_OUT_CODE= dt.Rows[n]["PAKAGE_OUT_CODE"].ToString();
                                                                                                                                model.CREATE_BY= dt.Rows[n]["CREATE_BY"].ToString();
                                                                                                                if(dt.Rows[n]["CREATE_DATE"].ToString()!="")
                {
                    model.CREATE_DATE=DateTime.Parse(dt.Rows[n]["CREATE_DATE"].ToString());
                }
                                                                                                                                                model.IMPORT_CODE= dt.Rows[n]["IMPORT_CODE"].ToString();

                    modelList.Add(model);
                }
            }
            return modelList;
        }
Example #26
0
        public static string[] GetInfo(string filename)
        {
            List<string> fileinfo = new List<string>();

            TagLib.File tagFile = TagLib.File.Create(filename);
            string artiest = tagFile.Tag.FirstPerformer;
            string titel = tagFile.Tag.Title;

            if (artiest == null || artiest == "")
            {
                // Controleer of de artiest staat aangegeven bij de titel
                if (titel == null || titel == "")
                {
                    titel = System.IO.Path.GetFileNameWithoutExtension(filename);
                }

                if (titel != null && titel != "")
                {
                    // Controleer of de titel gesplits kan worden
                    string[] title = titel.Split(new char[] {'-'});
                    if (title.Length > 1)
                    {
                        artiest = title[0].Trim();
                        titel = title[1].Trim();
                    }
                }
            }

            fileinfo.Add(artiest);
            fileinfo.Add(titel);
            fileinfo.Add(tagFile.Properties.Duration.TotalSeconds.ToString());

            return fileinfo.ToArray();
        }
Example #27
0
        List<ValueNode> gr_array_list()
        {
            List<ValueNode> list = new List<ValueNode>();
            while (Lookahead(TokenType.OpenParanthese) ||
                Lookahead(TokenType.OpenSquareBracket) ||
                //Lookahead(TokenType.ExpressionParanthese) ||
                Lookahead(TokenType.Integer) ||
                Lookahead(TokenType.Float) ||
                Lookahead(TokenType.String) ||
                Lookahead(TokenType.True) ||
                Lookahead(TokenType.False))
            {
                list.Add(gr_value());

                if (Lookahead(TokenType.Comma))
                {
                    Match(TokenType.Comma);
                }
                else
                {
                    break;
                }
            }
            return list;
        }
Example #28
0
        //新建工具树
        public DemoTools()
        {
            items = new List<ToolTreeItem>();

            ToolTreeItem item = new ToolTreeItem("Demo|Basic", "DemoTest", callDemoWindow);
            items.Add(item);
        }
Example #29
0
 public Dir(string key, string name)
 {
     this.key = key;
     this.name = name;
     sub_dirs = new List<Dir>();
     values = new List<Val>();
 }
        public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage)
        {
            var result = new List<int>();

            using (var messageQueue = new MessageQueue(String.Format(_pathPattern, queue)))
            {
                var current = 0;
                var end = @from + perPage;
                var enumerator = messageQueue.GetMessageEnumerator2();

                var formatter = new BinaryMessageFormatter();

                while (enumerator.MoveNext())
                {
                    if (current >= @from && current < end)
                    {
                        var message = enumerator.Current;

                        message.Formatter = formatter;
                        result.Add(int.Parse((string)message.Body));
                    }

                    if (current >= end) break;

                    current++;
                }
            }

            return result;
        }
Example #31
0
 public void Configure(List <Route> routeTable)
 {
     new ApplicationDbContext().Database.Migrate();
 }
Example #32
0
        public MessageResponse Cadastrar(Pessoa pessoa)
        {
            MessageResponse response = new MessageResponse();
            List<string> erros = new List<string>();

            #region Nome
            if (string.IsNullOrWhiteSpace(pessoa.Nome))
            {
                erros.Add("Nome deve ser informado.");
            }
            else
            {
                pessoa.Nome = Regex.Replace(pessoa.Nome, " {2,}", " ");
                pessoa.Nome = pessoa.Nome.Trim();
                if (pessoa.Nome.Length < 3 || pessoa.Nome.Length > 60)
                {
                    erros.Add("Nome deve conter entre 3 e 60 caracteres.");
                }
                else
                {
                    for (int i = 0; i < pessoa.Nome.Length; i++)
                    {
                        if (!char.IsLetter(pessoa.Nome[i]) && pessoa.Nome[i] != ' ')
                        {
                            erros.Add("Nome inválido");
                            break;
                        }
                    }
                }
            }
            #endregion

            #region Sobrenome
            if (string.IsNullOrWhiteSpace(pessoa.Sobrenome))
            {
                erros.Add("Sobrenome deve ser informado.");
            }
            else
            {
                pessoa.Sobrenome = Regex.Replace(pessoa.Sobrenome, " {2,}", " ");
                pessoa.Sobrenome = pessoa.Sobrenome.Trim();
                if (pessoa.Sobrenome.Length < 3 || pessoa.Sobrenome.Length > 60)
                {
                    erros.Add("Sobrenome deve conter entre 3 e 60 caracteres.");
                }
                else
                {
                    for (int i = 0; i < pessoa.Sobrenome.Length; i++)
                    {
                        if (!char.IsLetter(pessoa.Sobrenome[i]) && pessoa.Sobrenome[i] != ' ')
                        {
                            erros.Add("Sobrenome inválido");
                            break;
                        }
                    }
                }
            }
            #endregion

            StringBuilder errosPessoa = new StringBuilder();

            if (erros.Count != 0)
            {
                for (int i = 0; i < erros.Count; i++)
                {
                    errosPessoa.AppendLine(erros[i].ToString());
                }
                response.Success = false;
                response.Message = errosPessoa.ToString();
                return response;
            }
            response = dal.Cadastrar(pessoa);
            response.Message = "Cadastrado com sucesso!";
            return response;
        }
Example #33
0
        /// <summary>
        /// Gets the providers.
        /// </summary>
        /// <returns>IEnumerable{`0}.</returns>
        protected IEnumerable <IMetadataProvider> GetProviders(BaseItem item, LibraryOptions libraryOptions, MetadataRefreshOptions options, bool isFirstRefresh, bool requiresRefresh)
        {
            // Get providers to refresh
            var providers = ((ProviderManager)ProviderManager).GetMetadataProviders <TItemType>(item, libraryOptions).ToList();

            var metadataRefreshMode = options.MetadataRefreshMode;

            // Run all if either of these flags are true
            var runAllProviders = options.ReplaceAllMetadata ||
                                  metadataRefreshMode == MetadataRefreshMode.FullRefresh ||
                                  (isFirstRefresh && metadataRefreshMode >= MetadataRefreshMode.Default) ||
                                  (requiresRefresh && metadataRefreshMode >= MetadataRefreshMode.Default);

            if (!runAllProviders)
            {
                var providersWithChanges = providers
                                           .Where(i =>
                {
                    if (i is IHasItemChangeMonitor hasFileChangeMonitor)
                    {
                        return(HasChanged(item, hasFileChangeMonitor, options.DirectoryService));
                    }

                    return(false);
                })
                                           .ToList();

                if (providersWithChanges.Count == 0)
                {
                    providers = new List <IMetadataProvider <TItemType> >();
                }
                else
                {
                    var anyRemoteProvidersChanged = providersWithChanges.OfType <IRemoteMetadataProvider>()
                                                    .Any();

                    var anyLocalProvidersChanged = providersWithChanges.OfType <ILocalMetadataProvider>()
                                                   .Any();

                    var anyLocalPreRefreshProvidersChanged = providersWithChanges.OfType <IPreRefreshProvider>()
                                                             .Any();

                    providers = providers.Where(i =>
                    {
                        // If any provider reports a change, always run local ones as well
                        if (i is ILocalMetadataProvider)
                        {
                            return(anyRemoteProvidersChanged || anyLocalProvidersChanged || anyLocalPreRefreshProvidersChanged);
                        }

                        // If any remote providers changed, run them all so that priorities can be honored
                        if (i is IRemoteMetadataProvider)
                        {
                            if (options.MetadataRefreshMode == MetadataRefreshMode.ValidationOnly)
                            {
                                return(false);
                            }

                            return(anyRemoteProvidersChanged);
                        }

                        // Run custom refresh providers if they report a change or any remote providers change
                        return(anyRemoteProvidersChanged || providersWithChanges.Contains(i));
                    }).ToList();
                }
            }

            return(providers);
        }
 public GuildInformationsPaddocksMessage( sbyte NbPaddockMax, List<PaddockContentInformations> PaddocksInformations ){
     this.NbPaddockMax = NbPaddockMax;
     this.PaddocksInformations = PaddocksInformations;
 }
Example #35
0
 public ObjectList()
 {
     objects = new List<ObjectRec>();
     name = "Objects";
 }
        public void GetObjectIndexesWithPksOrderingTest()
        {
            foreach (IDataService dataService in DataServices)
            {
                //TODO: Fix OracleDataService error.
                if (dataService is OracleDataService)
                {
                    continue;
                }
                // Arrange.
                SQLDataService      ds      = dataService as SQLDataService;
                SQLWhereLanguageDef langDef = SQLWhereLanguageDef.LanguageDef;

                List <DataObject> dataObjects = new List <DataObject>();
                bool isMssql = dataService.GetType() == typeof(MSSQLDataService) || dataService.GetType().IsSubclassOf(typeof(MSSQLDataService));

                // MSSQL в отличие от других хранилищ имеет свой формат сортировки гуидов. Для его поддержки приходится пользоваться специальным типом SqlGuid.
                List <SqlGuid> keysMssqlList    = new List <SqlGuid>();
                List <Guid>    keysPostgresList = new List <Guid>();

                // Создадим 1000 медведей.
                int objectsCount = 1000;
                for (int i = 0; i < objectsCount; i++)
                {
                    // Для простоты анализа проблем с данными, если они возникнут, выдадим ненастоящие последовательные гуиды.
                    byte[] bytes = new byte[16];
                    BitConverter.GetBytes(i).CopyTo(bytes, 0);
                    var pk = new Guid(bytes);
                    if (isMssql)
                    {
                        keysMssqlList.Add(pk);
                    }
                    else
                    {
                        keysPostgresList.Add(pk);
                    }

                    var createdBear = new Медведь
                    {
                        __PrimaryKey = pk,
                        ЦветГлаз     = "Косолапый Мишка " + i,
                        Вес          = i
                    };
                    dataObjects.Add(createdBear);
                }

                DataObject[] dataObjectsForUpdate = dataObjects.ToArray();
                ds.UpdateObjects(ref dataObjectsForUpdate);

                LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Медведь), Медведь.Views.МедведьL);

                Function findFunction = langDef.GetFunction(langDef.funcL, new VariableDef(langDef.StringType, Information.ExtractPropertyPath <Медведь>(m => m.Вес)), objectsCount);
                if (isMssql)
                {
                    keysMssqlList.Sort();
                }
                else
                {
                    keysPostgresList.Sort();
                }

                // Act.
                IDictionary <int, string> result = ds.GetObjectIndexesWithPks(lcs, findFunction, null);

                // Assert.
                var values = result.Values.GetEnumerator();
                var keys   = result.Keys.GetEnumerator();

                for (int i = 0; i < objectsCount; i++)
                {
                    Assert.Equal(objectsCount, result.Count);

                    values.MoveNext();
                    keys.MoveNext();
                    string key = isMssql ? ((Guid)keysMssqlList[i]).ToString("B") : keysPostgresList[i].ToString("B");
                    Assert.Equal(key, values.Current);
                    Assert.Equal(i + 1, keys.Current);
                }
            }
        }
Example #37
0
        void Initialize()
        {
            ComputeStateStorageDirectory(this.AppName, this.AppVersion);

            this.ExtensionManager = new ExtensionManager(this.StateStorageDirectory);
            this.ExtensionManager.LoadState(this.ExtensionAssemblies);

            this.RootServiceProvider = new RootServiceProvider(this.ExtensionManager);
            this.RootServiceProvider.AddService(typeof(IUserNotificationService), new SimpleNotificationService(this.AppTitle));
            this.RootServiceProvider.AddService(typeof(ToolsUIApplication), this);
            this.RootServiceProvider.AddService(this.GetType(), this);
            this.RootServiceProvider.AddService(typeof(Dispatcher), Dispatcher.CurrentDispatcher);

            this.sessionStateService = new SessionStateService();
            this.RootServiceProvider.AddService(typeof(ISessionStateService), this.sessionStateService);

            this.windowStateFileName  = Path.Combine(this.StateStorageDirectory, "WindowState.xml");
            this.sessionStateFileName = Path.Combine(this.StateStorageDirectory, "SessionState.xml");
            if (File.Exists(this.sessionStateFileName))
            {
                try
                {
                    XElement sessionState = XElement.Load(this.sessionStateFileName);
                    this.sessionStateService.SetFullSessionState(sessionState);
                }
                catch (Exception)
                {
                }
            }

            this.sessionStateService.StateSaveRequested += OnSessionStateSaveRequested;
            InitializeTheme();

            this.viewCreators = this.ExtensionManager.BuildViewCreatorDictionary();

            this.RecentDocumentService = this.RootServiceProvider.GetService(typeof(RecentDocumentService)) as RecentDocumentService;
            if (this.RecentDocumentService != null)
            {
                ((INotifyCollectionChanged)this.RecentDocumentService.DocumentIdentities).CollectionChanged += OnRecentDocumentIdentitiesCollectionChanged;
                OnRecentDocumentIdentitiesCollectionChanged(null, null);
            }

            this.FoldersSource.GroupDescriptions.Add(new PropertyGroupDescription {
                PropertyName = "Category"
            });

            if (this.RecentDocumentService != null)
            {
                NotifyCollectionChangedEventHandler handler = (s, e) =>
                {
                    this.FoldersSource.Source = new CategorizedFolder[]
                    {
                        new CategorizedFolder
                        {
                            Category      = "Current Folder",
                            DirectoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory()),
                            ShortcutKey   = "C"
                        }
                    }.Concat(this.RecentDocumentService.RecentFolders.Select((d, i) => new CategorizedFolder
                    {
                        Category      = "Recent Folders",
                        DirectoryInfo = d,
                        ShortcutKey   = string.Format("D{0}", i + 1)
                    }));
                };

                ((INotifyCollectionChanged)this.RecentDocumentService.RecentFolders).CollectionChanged += handler;
                handler(null, null);
            }

            this.documentCategories = new List <DocumentCategory>();
            foreach (var factoryName in this.ExtensionManager.DocumentFactoryNames)
            {
                var factory = this.ExtensionManager.LookupDocumentFactory(factoryName);

                if (factory != null)
                {
                    var category = new DocumentCategory {
                        DisplayName = factory.DocumentKind, DocumentFactoryName = factoryName
                    };
                    BindingOperations.SetBinding(category, DocumentCategory.ColorProperty, Theme.CreateBinding(factory.ColorThemePropertyName));
                    this.documentCategories.Add(category);
                }
            }

            this.documentCategories.Add(new DocumentCategory {
                Color = Colors.Transparent, DisplayName = "Any", DocumentFactoryName = null
            });

            OnInitialized();
        }
Example #38
0
        void TryLoadWindowState()
        {
            if (!File.Exists(this.windowStateFileName))
            {
                // Load nothing.
                return;
            }

            XElement   windowStateRoot = XElement.Load(this.windowStateFileName);
            XAttribute versionAttr     = windowStateRoot.Attribute("Version");
            XElement   mainWindowState = windowStateRoot.Element("MainWindow");
            XElement   layoutState     = windowStateRoot.Element("LayoutDefinitions");
            int        version;

            if (versionAttr == null || !int.TryParse(versionAttr.Value, out version) || version != WindowStateVersion)
            {
                throw new VersionMismatchException();
            }

            var bumpedDocumentFactories = new HashSet <string>();
            var defaultLayoutVersions   = windowStateRoot.Element("DefaultLayoutVersions");

            if (defaultLayoutVersions != null)
            {
                foreach (var layoutVersion in defaultLayoutVersions.Elements("DefaultLayoutVersion"))
                {
                    var factory = this.ExtensionManager.LookupDocumentFactory(layoutVersion.Attribute("DocumentFactoryName").Value);

                    if (int.Parse(layoutVersion.Attribute("Version").Value) < factory.DefaultLayoutVersion)
                    {
                        bumpedDocumentFactories.Add(factory.Name);
                    }
                }
            }

            // Don't call clear here, instead remove one at a time.  Reason:  Calling Clear()
            // sends a "Reset" event, and the layout handling code in ToolsUIWindow gets mad at that.
            // Usually doesn't matter (at startup), but this also gets called as part of "Revert
            // to Default Window State".
            while (this.LayoutDefinitions.Count > 0)
            {
                this.LayoutDefinitions.RemoveAt(0);
            }

            var usedIds          = new HashSet <Guid>();
            var loadedLayoutDefs = new Dictionary <string, List <LayoutDefinition> >();

            foreach (var layoutDefElement in layoutState.Elements("LayoutDefinition"))
            {
                var layoutDef = LayoutDefinition.LoadFromState(layoutDefElement, this.viewCreators);

                if (layoutDef.Id.Equals(Guid.Empty))
                {
                    // Could be from a state format before layouts had ID's.  Match the name and document affinity to the
                    // default set, and if found, assume its ID.  Failing that, give it a fresh one.
                    var defaultLayoutDef = this.defaultLayoutDefinitions.FirstOrDefault(ld => ld.Header == layoutDef.Header && ld.DocumentFactoryName == layoutDef.DocumentFactoryName);

                    if (defaultLayoutDef != null && !usedIds.Contains(defaultLayoutDef.Id))
                    {
                        layoutDef.Id = defaultLayoutDef.Id;
                    }
                    else
                    {
                        layoutDef.Id = Guid.NewGuid();
                    }
                }

                // We only do this to guard against users having same-named layouts (affinitized with the same document factory).  We
                // trust that Guid.NewGuid actually creates unique values...
                usedIds.Add(layoutDef.Id);

                if (layoutDef.DocumentFactoryName == null)
                {
                    // This is a "global" (any-document) layout, so we can add it now.
                    this.LayoutDefinitions.Add(layoutDef);
                }
                else
                {
                    List <LayoutDefinition> list;

                    // Stage this for validation against layout version
                    if (!loadedLayoutDefs.TryGetValue(layoutDef.DocumentFactoryName, out list))
                    {
                        list = new List <LayoutDefinition>();
                        loadedLayoutDefs.Add(layoutDef.DocumentFactoryName, list);
                    }

                    list.Add(layoutDef);
                }
            }

            foreach (var kvp in loadedLayoutDefs)
            {
                if (bumpedDocumentFactories.Contains(kvp.Key))
                {
                    var oldSet = kvp.Value.ToDictionary(ld => ld.Id);

                    // These need to be updated/upgraded. We do that giving preference to the defaults by loading them first,
                    // but keep their names in case the user has changed them.  Then add the remaining loaded layouts.
                    foreach (var layout in this.defaultLayoutDefinitions.Where(ld => ld.DocumentFactoryName == kvp.Key))
                    {
                        LayoutDefinition existingLayout;

                        if (oldSet.TryGetValue(layout.Id, out existingLayout))
                        {
                            layout.Header = existingLayout.Header;
                            oldSet.Remove(layout.Id);
                        }

                        // Mark this layout as having been reverted to default.  This prevents the per-instance state data
                        // from being loaded, which would likely fail due to structure mismatch with the definition.
                        layout.RevertedToDefault = true;
                        this.LayoutDefinitions.Add(layout);
                    }

                    // Get the rest -- don't just iterate over the dictionary, use the list instead to
                    // preserve order (as much as possible).  Note that these are not reverted to default, as
                    // they do not have one.
                    foreach (var remainingLayout in kvp.Value.Where(ld => oldSet.ContainsKey(ld.Id)))
                    {
                        this.LayoutDefinitions.Add(remainingLayout);
                    }
                }
                else
                {
                    // These are good to go
                    foreach (var layout in kvp.Value)
                    {
                        this.LayoutDefinitions.Add(layout);
                    }
                }
            }

            if (mainWindowState != null)
            {
                this.mainWindow.LoadWindowState(mainWindowState);
            }

            var windowElements = windowStateRoot.Elements("Window");

            if (windowElements.Any())
            {
                if (this.mainWindow.IsLoaded)
                {
                    RecreateAuxiliaryWindows(windowElements);
                }
                else
                {
                    RoutedEventHandler handler = null;

                    handler = (s, e) =>
                    {
                        RecreateAuxiliaryWindows(windowElements);
                        this.mainWindow.Loaded -= handler;
                        this.mainWindow.Activate();
                    };
                    this.mainWindow.Loaded += handler;
                }
            }
        }
        public void DeleteAggregatorWithHierarhiAndAssociationTest()
        {
            foreach (IDataService dataService in DataServices)
            {
                // Arrange.
                SQLDataService ds = dataService as SQLDataService;

                //TODO: Fix OracleDataService error.
                if (dataService is OracleDataService)
                {
                    continue;
                }

                var masterForest = new Лес {
                    Название = "лес1"
                };
                var aggregatorBear = new Медведь {
                    ПорядковыйНомер = 1, ЛесОбитания = masterForest
                };

                ds.UpdateObject(aggregatorBear);

                var aggregatorBearMother = new Медведь {
                    ПорядковыйНомер = 2
                };
                var aggregatorBearFather = new Медведь {
                    ПорядковыйНомер = 2
                };
                aggregatorBear.Мама = aggregatorBearMother;
                aggregatorBear.Папа = aggregatorBearFather;

                ds.UpdateObject(aggregatorBear);

                // Act & Assert.
                LoadingCustomizationStruct lcsBear   = LoadingCustomizationStruct.GetSimpleStruct(typeof(Медведь), Медведь.Views.МедведьE);
                LoadingCustomizationStruct lcsForest = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лес), Лес.Views.ЛесE);

                DataObject[] dataObjectsBear   = ds.LoadObjects(lcsBear);
                DataObject[] dataObjectsForest = ds.LoadObjects(lcsForest);

                // Act
                int countBearBefore   = ds.GetObjectsCount(lcsBear);
                int countForestBefore = ds.GetObjectsCount(lcsForest);

                List <DataObject> objectsForUpdateList = new List <DataObject>();

                foreach (Медведь медведь in dataObjectsBear)
                {
                    медведь.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(медведь);
                }

                foreach (Лес лес in dataObjectsForest)
                {
                    лес.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(лес);
                }

                DataObject[] objectsForUpdate = objectsForUpdateList.ToArray();

                ds.UpdateObjects(ref objectsForUpdate);

                int countBearAfter   = ds.GetObjectsCount(lcsBear);
                int countForestAfter = ds.GetObjectsCount(lcsForest);

                // Assert
                Assert.Equal(3, countBearBefore);
                Assert.Equal(1, countForestBefore);

                Assert.Equal(0, countBearAfter);
                Assert.Equal(0, countForestAfter);
            }
        }
Example #40
0
        /// <summary>
        /// 更新属性状态
        /// </summary>
        /// <param name="status">状态</param>
        /// <param name="listSysNo">属性编号集</param>
        /// <returns>更新行数</returns>
        /// <remarks>2013-06-28 唐永勤 创建</remarks>
        public override int UpdateStatus(Hyt.Model.WorkflowStatus.ProductStatus.商品属性状态 status, List<int> listSysNo)
        {

            string Sql = string.Format("update PdAttribute set Status = {0} where SysNo in ({1})", (int)status, listSysNo.Join(","));
            int rowsAffected = Context.Sql(Sql).Execute();
            return rowsAffected;
        }
        public void DetailsDeleteTest()
        {
            foreach (IDataService dataService in DataServices)
            {
                // Arrange
                SQLDataService ds = (SQLDataService)dataService;

                const string First  = "Первый";
                const string Second = "Второй";
                const string Third  = "Третий";
                const string Fourth = "Четвертый";

                ТипЛапы передняяЛапа = new ТипЛапы {
                    Актуально = true, Название = "Передняя"
                };
                ТипЛапы задняяЛапа = new ТипЛапы {
                    Актуально = true, Название = "Задняя"
                };


                Кошка aggregator = new Кошка
                {
                    ДатаРождения = (NullableDateTime)DateTime.Now,
                    Тип          = ТипКошки.Дикая,
                    Порода       = new Порода {
                        Название = "Чеширская"
                    },
                    Кличка = "Мурка"
                };
                aggregator.Лапа.AddRange(
                    new Лапа {
                    Цвет = First, ТипЛапы = передняяЛапа
                },
                    new Лапа {
                    Цвет = Second, ТипЛапы = передняяЛапа
                },
                    new Лапа {
                    Цвет = Third, ТипЛапы = задняяЛапа
                },
                    new Лапа {
                    Цвет = Fourth, ТипЛапы = задняяЛапа
                });

                ds.UpdateObject(aggregator);

                LoadingCustomizationStruct lcsCat      = LoadingCustomizationStruct.GetSimpleStruct(typeof(Кошка), Кошка.Views.КошкаE);
                LoadingCustomizationStruct lcsPaws     = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лапа), Лапа.Views.ЛапаFull);
                LoadingCustomizationStruct lcsPawsType = LoadingCustomizationStruct.GetSimpleStruct(typeof(ТипЛапы), ТипЛапы.Views.ТипЛапыE);

                DataObject[] dataObjectsCats      = ds.LoadObjects(lcsCat);
                DataObject[] dataObjectsPawsTypes = ds.LoadObjects(lcsPawsType);

                // Act
                int countCatBefore      = ds.GetObjectsCount(lcsCat);
                int countPawsBefore     = ds.GetObjectsCount(lcsPaws);
                int countPawsTypeBefore = ds.GetObjectsCount(lcsPawsType);

                List <DataObject> objectsForUpdateList = new List <DataObject>();

                foreach (Кошка кошка in dataObjectsCats)
                {
                    кошка.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(кошка);
                }

                foreach (ТипЛапы типЛапы in dataObjectsPawsTypes)
                {
                    типЛапы.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(типЛапы);
                }

                DataObject[] objectsForUpdate = objectsForUpdateList.ToArray();

                ds.UpdateObjects(ref objectsForUpdate);

                int countCatAfter      = ds.GetObjectsCount(lcsCat);
                int countPawsAfter     = ds.GetObjectsCount(lcsPaws);
                int countPawsTypeAfter = ds.GetObjectsCount(lcsPawsType);

                // Assert
                Assert.Equal(1, countCatBefore);
                Assert.Equal(4, countPawsBefore);
                Assert.Equal(2, countPawsTypeBefore);

                Assert.Equal(0, countCatAfter);
                Assert.Equal(0, countPawsAfter);
                Assert.Equal(0, countPawsTypeAfter);
            }
        }
Example #42
0
        static void Main(string[] args)
        {
            bool cont = true;

            while (cont)
            {
                var list = new List <uint>();

                for (int i = 1; i <= 3;)
                {
                    Console.WriteLine($"Please input the {i} triangle side length in numbers only.");

                    uint res;

                    if (uint.TryParse(Console.ReadLine(), out res))
                    {
                        list.Add(res);
                        Console.WriteLine("Successfully added.");
                        i++;
                    }
                    else
                    {
                        Console.WriteLine("Please only input numbers above 0, without spaces or any other symbols");
                    }
                }

                list = (from a in list
                        orderby a descending
                        select a).ToList();

                if ((list[1] ^ 2 * list[2] ^ 2) == (list[0] ^ 2) || list[0] == list[1] && list[1] == list[2])
                {
                    if (list[0] == list[1])
                    {
                        if (list[0] == list[2])
                        {
                            Console.WriteLine("Equilateral triangle detected");
                        }
                        else
                        {
                            Console.WriteLine("Isosceles triangle detected");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Scalene triangle detected");
                    }
                }
                else
                {
                    Console.WriteLine($"Input of {list[0]}, {list[1]} and {list[2]} isn't a true triangle");
                }

                Console.WriteLine("Want to input another triangle? Y/N");

                bool finishing = true;
                while (finishing)
                {
                    switch (Console.ReadLine()?.ToLower())
                    {
                    case "y":
                        cont      = true;
                        finishing = false;
                        break;

                    case "n":
                        cont      = false;
                        finishing = false;
                        break;

                    default:
                        Console.WriteLine("Sorry, I didn't understand the input. Please write Y if you want to input another triangle. N if you want to stop");
                        break;
                    }
                }
            }
        }
 public void Initialize()
 {
     questObservers = new List<QuestObserver>();
 }
Example #44
0
        protected virtual async Task <RefreshResult> RefreshWithProviders(
            MetadataResult <TItemType> metadata,
            TIdType id,
            MetadataRefreshOptions options,
            List <IMetadataProvider> providers,
            ItemImageProvider imageService,
            CancellationToken cancellationToken)
        {
            var refreshResult = new RefreshResult
            {
                UpdateType = ItemUpdateType.None
            };

            var item = metadata.Item;

            var customProviders = providers.OfType <ICustomMetadataProvider <TItemType> >().ToList();
            var logName         = !item.IsFileProtocol ? item.Name ?? item.Path : item.Path ?? item.Name;

            foreach (var provider in customProviders.Where(i => i is IPreRefreshProvider))
            {
                await RunCustomProvider(provider, item, logName, options, refreshResult, cancellationToken).ConfigureAwait(false);
            }

            var temp = new MetadataResult <TItemType>
            {
                Item = CreateNew()
            };

            temp.Item.Path = item.Path;

            var userDataList = new List <UserItemData>();

            // If replacing all metadata, run internet providers first
            if (options.ReplaceAllMetadata)
            {
                var remoteResult = await ExecuteRemoteProviders(temp, logName, id, providers.OfType <IRemoteMetadataProvider <TItemType, TIdType> >(), cancellationToken)
                                   .ConfigureAwait(false);

                refreshResult.UpdateType  |= remoteResult.UpdateType;
                refreshResult.ErrorMessage = remoteResult.ErrorMessage;
                refreshResult.Failures    += remoteResult.Failures;
            }

            var hasLocalMetadata = false;

            foreach (var provider in providers.OfType <ILocalMetadataProvider <TItemType> >().ToList())
            {
                var providerName = provider.GetType().Name;
                Logger.LogDebug("Running {0} for {1}", providerName, logName);

                var itemInfo = new ItemInfo(item);

                try
                {
                    var localItem = await provider.GetMetadata(itemInfo, options.DirectoryService, cancellationToken).ConfigureAwait(false);

                    if (localItem.HasMetadata)
                    {
                        foreach (var remoteImage in localItem.RemoteImages)
                        {
                            await ProviderManager.SaveImage(item, remoteImage.url, remoteImage.type, null, cancellationToken).ConfigureAwait(false);

                            refreshResult.UpdateType |= ItemUpdateType.ImageUpdate;
                        }

                        if (imageService.MergeImages(item, localItem.Images))
                        {
                            refreshResult.UpdateType |= ItemUpdateType.ImageUpdate;
                        }

                        if (localItem.UserDataList != null)
                        {
                            userDataList.AddRange(localItem.UserDataList);
                        }

                        MergeData(localItem, temp, Array.Empty <MetadataField>(), !options.ReplaceAllMetadata, true);
                        refreshResult.UpdateType |= ItemUpdateType.MetadataImport;

                        // Only one local provider allowed per item
                        if (item.IsLocked || localItem.Item.IsLocked || IsFullLocalMetadata(localItem.Item))
                        {
                            hasLocalMetadata = true;
                        }

                        break;
                    }

                    Logger.LogDebug("{0} returned no metadata for {1}", providerName, logName);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Error in {provider}", provider.Name);

                    // If a local provider fails, consider that a failure
                    refreshResult.ErrorMessage = ex.Message;
                }
            }

            // Local metadata is king - if any is found don't run remote providers
            if (!options.ReplaceAllMetadata && (!hasLocalMetadata || options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || !item.StopRefreshIfLocalMetadataFound))
            {
                var remoteResult = await ExecuteRemoteProviders(temp, logName, id, providers.OfType <IRemoteMetadataProvider <TItemType, TIdType> >(), cancellationToken)
                                   .ConfigureAwait(false);

                refreshResult.UpdateType  |= remoteResult.UpdateType;
                refreshResult.ErrorMessage = remoteResult.ErrorMessage;
                refreshResult.Failures    += remoteResult.Failures;
            }

            if (providers.Any(i => !(i is ICustomMetadataProvider)))
            {
                if (refreshResult.UpdateType > ItemUpdateType.None)
                {
                    if (hasLocalMetadata)
                    {
                        MergeData(temp, metadata, item.LockedFields, true, true);
                    }
                    else
                    {
                        // TODO: If the new metadata from above has some blank data, this can cause old data to get filled into those empty fields
                        MergeData(metadata, temp, Array.Empty <MetadataField>(), false, false);
                        MergeData(temp, metadata, item.LockedFields, true, false);
                    }
                }
            }

            // var isUnidentified = failedProviderCount > 0 && successfulProviderCount == 0;

            foreach (var provider in customProviders.Where(i => !(i is IPreRefreshProvider)))
            {
                await RunCustomProvider(provider, item, logName, options, refreshResult, cancellationToken).ConfigureAwait(false);
            }

            // ImportUserData(item, userDataList, cancellationToken);

            return(refreshResult);
        }
Example #45
0
 public When_an_event_is_defined_as_ignored_for_state()
 {
     _machine = new TestStateMachine();
     _repository = new InMemorySagaRepository<Instance>();
     _faultMessageContexts = new List<ConsumeContext<Fault>>();
 }
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome population and their associated/parent genome factory.
        /// </summary>
        public NeatEvolutionAlgorithm<NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory<NeatGenome> genomeFactory, List<NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy<NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy<NeatGenome>(distanceMetric, _parallelOptions);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm<NeatGenome> ea = new NeatEvolutionAlgorithm<NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create IBlackBox evaluator.
            SinglePoleBalancingSwingUpEvaluator evaluator = new SinglePoleBalancingSwingUpEvaluator();

            // Create genome decoder.
            IGenomeDecoder<NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();

            // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
            IGenomeListEvaluator<NeatGenome> innerEvaluator = new ParallelGenomeListEvaluator<NeatGenome, IBlackBox>(genomeDecoder, evaluator, _parallelOptions);
            //IGenomeListEvaluator<NeatGenome> innerEvaluator = new SerialGenomeListEvaluator<NeatGenome, IBlackBox>(genomeDecoder, evaluator);


            // Wrap the list evaluator in a 'selective' evaulator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
            // that were in the population in previous generations (elite genomes). This is determiend by examining each genome's evaluation info object.
            IGenomeListEvaluator<NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator<NeatGenome>(
                                                                                    innerEvaluator,
                                                                                    SelectiveGenomeListEvaluator<NeatGenome>.CreatePredicate_OnceOnly());
            // Initialize the evolution algorithm.
            ea.Initialize(selectiveEvaluator, genomeFactory, genomeList);

            // Finished. Return the evolution algorithm
            return ea;
        }
Example #47
0
        private void button1_Click(object sender, EventArgs e)
        {
            string StrSupplier = cb_Supplier.Text;
            string StrPart_NO = cb_PartNO.Text;
            string StrPart_Name = tb_Part_Name.Text;
            string StrSpec = tb_Spec.Text;
            string strBand = tb_Band.Text;
            string StrMaterial = tb_Material.Text;
            string StrProd_Data = datePickFrom.Value.ToString("yyyy'-'MM'-'dd");
            Console.WriteLine(StrProd_Data);
            string StrBuy_NO = tb_buy_no.Text.Trim();
            string StrBuy_Item = tb_buy_item.Text.Trim();
            string StrLot_NO = tb_lot_no.Text.Trim();
            string StrEP_NO = tb_ep_no.Text.Trim();
            string StrVerifier = tb_Verifier.Text.Trim();
            string StrWO_NO = tb_wo.Text.Trim();
            string StrSum = tb_sum.Text;
            string StrBak = tb_bak.Text.Trim();
            string StrUnit = tb_Unit.Text.Trim();

            if (cmbPrinterList.Text == "") { { MessageBox.Show("未選擇打印機!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); cmbPrinterList.Focus(); return; } }
            if (StrSupplier == "") { MessageBox.Show("供應商未選擇", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); cb_Supplier.Focus(); return; }
            if (StrPart_NO == "") { MessageBox.Show("料號不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); cb_PartNO.Focus(); return; }
            if (StrBuy_NO == "") { MessageBox.Show("采購單號不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); tb_buy_no.Focus(); return; }
            if (StrBuy_Item == "") { MessageBox.Show("采購項次不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); tb_buy_item.Focus(); return; }
            if (StrLot_NO == "") { MessageBox.Show("製造批號不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); tb_lot_no.Focus(); return; }
            if (StrEP_NO == "") { MessageBox.Show("電鍍批號不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); tb_ep_no.Focus(); return; }
            if (StrWO_NO == "") { MessageBox.Show("工單不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); tb_wo.Focus(); return; }
            if (StrSum == "" || tb_sum.Value == 0) { MessageBox.Show("數量不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); tb_sum.Focus(); return; }
            if (StrVerifier == "") { MessageBox.Show("檢驗員不能爲空", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); tb_Verifier.Focus(); return; }




            // btApp = getBarTender();
            //檢查是否有安裝BarTend
            //if (btApp == null)
            //{
            //    MessageBox.Show("列印前請先安裝BarTender!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //列印前請先安裝BarTender!
            //    return;
            //}          
            //檢查btw文件是否存在
            string startupPath = System.Windows.Forms.Application.StartupPath;
            string labFileName = startupPath + "\\deyi.Lab";
            string OracleName = startupPath + "\\Oracle.ManagedDataAccess.dll";
            string CodeSoftName = startupPath + "\\Interop.LabelManager2.dll";

            try
            {
                if (!File.Exists(OracleName))
                {
                    MessageBox.Show("沒有找到dll文件:" + startupPath + "\\Oracle.ManagedDataAccess.dll ,請聯系系統管理員", "溫馨提示");
                    return;
                }
                if (!File.Exists(CodeSoftName))
                {
                    MessageBox.Show("沒有找到dll:" + startupPath + "\\Interop.LabelManager2.dll,請聯系系統管理員", "溫馨提示");
                    return;
                }
                if (!File.Exists(labFileName))
                {
                    MessageBox.Show("沒有找到標簽模板文件:" + startupPath + "\\deyi.Lab,請聯系系統管理員", "溫馨提示");
                    return;
                }

                if (!Regex.IsMatch(StrEP_NO, strRegex))
                {
                    MessageBox.Show("電鍍批號格式不正確!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                int itempEP = Convert.ToInt32(StrEP_NO.Substring(11));
                if (itempEP == 0) { return; };
                if ((Convert.ToInt32(tb_printNum.Value) + itempEP) >= 1000)
                {
                    MessageBox.Show("電鍍批號流水碼加打印數量不可超過999", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                string strConnResult = dao.ConnTo();//連接mysql數據庫。
                if (strConnResult == "success")
                {
                    string strGet_ep_sum = dao.get_ep_sum(StrEP_NO);
                    if (strGet_ep_sum == "NO")
                    {
                        MessageBox.Show("電鍍批號已存在,請重新輸入。", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (strGet_ep_sum.Contains("NG"))
                    {
                        MessageBox.Show(strGet_ep_sum, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    
                    List<SnDataVO> list = new List<SnDataVO>();
                    for (int i = 0; i < Convert.ToInt32(tb_printNum.Value); i++)
                    {
                        if (i != 0) 
                        {
                            if((itempEP + i) < 1000)
                            {
                                StrEP_NO = StrEP_NO.Substring(0, 11) + (itempEP + i).ToString("000");
                            }
                            else
                            {
                                //MessageBox.Show("电镀批号流水码已达999,已用尽!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                break;
                            }
                            
                        }                      
                        strGet_ep_sum = dao.get_ep_sum(StrEP_NO);
                        if (strGet_ep_sum == "NO")
                        {
                            continue;
                        }
                        else if (strGet_ep_sum.Contains("NG"))
                        {
                            MessageBox.Show(strGet_ep_sum, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        string strSERIAL_NO = "";
                        string strGet_serial_noResult = dao.get_serial_no(StrProd_Data);
                        string strStrProd_Data2 = datePickFrom.Value.ToString("yyMMdd");
                        if (strGet_serial_noResult == "")
                        {
                            strSERIAL_NO = "A-" + strSUPPLIES_ID + "-" + strStrProd_Data2 + "-" + "00001";//如果SN_DATA中是空的。
                        }
                        else if (strGet_serial_noResult.Substring(0, 2) == "NG")
                        {
                            MessageBox.Show(strGet_serial_noResult, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            //如果SN_DATA中不是空的。
                            int iLenght = strGet_serial_noResult.Length;
                            strSERIAL_NO = "A-" + strSUPPLIES_ID + "-" + strStrProd_Data2 + "-" + (Convert.ToInt32(strGet_serial_noResult.Substring(iLenght-5)) + 1).ToString("00000");
                        }

                        string strResurt = dao.Insert_sn_data(strSERIAL_NO, StrEP_NO, strSUPPLIES_ID, StrLot_NO, StrProd_Data, StrWO_NO, StrSum, StrUnit, StrSupplier, StrPart_NO, StrPart_Name, strBand, StrSpec, StrMaterial, StrBuy_NO, StrBuy_Item, StrVerifier, StrBak);
                        if (strResurt == "Duplicate")
                        {
                            continue;
                        }
                        else if (strResurt.Contains("NG"))
                        {
                            MessageBox.Show(strResurt, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        SnDataVO sndatavo = new SnDataVO();
                        sndatavo.SERIAL_NO = strSERIAL_NO;
                        sndatavo.EP_NO = StrEP_NO;
                        sndatavo.SUPPLYER_ID = strSUPPLIES_ID;
                        sndatavo.LOT_NO = StrLot_NO;
                        sndatavo.PROD_DATE = StrProd_Data;
                        sndatavo.WO_NO = StrWO_NO;
                        sndatavo.QTY = StrSum;
                        sndatavo.UNIT = StrUnit;
                        sndatavo.SUPPLYER = StrSupplier;
                        sndatavo.PART_NO = StrPart_NO;
                        sndatavo.PART_NAME = StrPart_Name;
                        sndatavo.BAND = strBand;
                        sndatavo.SPEC = StrSpec;
                        sndatavo.MATERIAL = StrMaterial;
                        sndatavo.BUY_NO = StrBuy_NO;
                        sndatavo.BUY_ENTRY = StrBuy_Item;
                        sndatavo.VERIFIER = StrVerifier;
                        sndatavo.REMARK = StrBak;
                        list.Add(sndatavo);
                    }

                   // btFormat = btApp.Formats.Open(startupPath + @"\deyi", false, OldActPrn);
                    DateTime dateTime = DateTime.Parse(StrProd_Data);
                    string strYY = dateTime.Year.ToString();
                    int intMonth = dateTime.Month;
                    double doubleM = (double)intMonth / 3.0;
                    string strQuarter = Math.Ceiling(doubleM).ToString();

                    button1.Enabled = false;
                    foreach (SnDataVO vo in list)
                    {
                        labApp = new LabelManager2.ApplicationClass();
                        labApp.Documents.Open(startupPath+@"\deyi.Lab", false);// 调用设计好的label文件
                        doc = labApp.ActiveDocument;
                        doc.Printer.SwitchTo(OldActPrn);

                        doc.Variables.FormVariables.Item("StrSerial_NO").Value = vo.SERIAL_NO; //序号
                        doc.Variables.FormVariables.Item("StrEP_NO").Value = vo.EP_NO; //供应商
                        doc.Variables.FormVariables.Item("StrSupplier").Value = vo.SUPPLYER; //供应商
                        doc.Variables.FormVariables.Item("StrPart_NO").Value = vo.PART_NO;//料号
                        doc.Variables.FormVariables.Item("StrPart_Name").Value = vo.PART_NAME;//品名
                        doc.Variables.FormVariables.Item("StrSpec").Value = vo.SPEC;//規格
                        doc.Variables.FormVariables.Item("strBand").Value = vo.BAND;//带别
                        doc.Variables.FormVariables.Item("StrMaterial").Value = vo.MATERIAL;//材质
                        doc.Variables.FormVariables.Item("StrProd_Data").Value = vo.PROD_DATE;//制造日期
                        doc.Variables.FormVariables.Item("StrProd_Data2").Value = datePickFrom.Value.ToString("yyMMdd");//二维码上的制造日期
                        doc.Variables.FormVariables.Item("StrBuy_NO").Value = vo.BUY_NO;//采购单号
                        doc.Variables.FormVariables.Item("StrBuy_Item").Value = vo.BUY_ENTRY;//采购项次
                        doc.Variables.FormVariables.Item("StrLot_NO").Value = vo.LOT_NO;//制造批号
                        doc.Variables.FormVariables.Item("StrEP_NO").Value = vo.EP_NO;//电镀批号
                        doc.Variables.FormVariables.Item("StrVerifier").Value = vo.VERIFIER;//检验员
                        doc.Variables.FormVariables.Item("StrWO_NO").Value = vo.WO_NO;//工单
                        doc.Variables.FormVariables.Item("StrSum").Value = vo.QTY;//数量
                        doc.Variables.FormVariables.Item("StrUnit").Value = vo.UNIT;//单位
                        doc.Variables.FormVariables.Item("StrBak").Value = StrBak;//备注
                        doc.Variables.FormVariables.Item("StrYY").Value = strYY;//年strQuarter
                        doc.Variables.FormVariables.Item("strQuarter").Value = strQuarter;

                        doc.PrintDocument(1);                             //打印
                        if (labApp != null)
                        {
                            labApp.Documents.CloseAll(true);
                            labApp.Quit();//退出
                            labApp = null;
                            doc = null;
                        }
                        //btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;  //设置同序列打印的份数
                        //btFormat.PrintSetup.NumberSerializedLabels = 1;  //设置需要打印的序列数
                        //btFormat.SetNamedSubStringValue("StrSerial_NO", vo.SERIAL_NO); //序号
                        //btFormat.SetNamedSubStringValue("StrEP_NO", vo.EP_NO); //供应商
                        //btFormat.SetNamedSubStringValue("StrSupplier", vo.SUPPLYER); //供应商
                        //btFormat.SetNamedSubStringValue("StrPart_NO", vo.PART_NO);//料号
                        //btFormat.SetNamedSubStringValue("StrPart_Name", vo.PART_NAME);//品名
                        //btFormat.SetNamedSubStringValue("StrSpec", vo.SPEC);//規格
                        //btFormat.SetNamedSubStringValue("strBand", vo.BAND);//带别
                        //btFormat.SetNamedSubStringValue("StrMaterial", vo.MATERIAL);//材质
                        //btFormat.SetNamedSubStringValue("StrProd_Data", vo.PROD_DATE);//制造日期
                        //btFormat.SetNamedSubStringValue("StrBuy_NO", vo.BUY_NO);//采购单号
                        //btFormat.SetNamedSubStringValue("StrBuy_Item", vo.BUY_ENTRY);//采购项次
                        //btFormat.SetNamedSubStringValue("StrLot_NO", vo.LOT_NO);//制造批号
                        //btFormat.SetNamedSubStringValue("StrEP_NO", vo.EP_NO);//电镀批号
                        //btFormat.SetNamedSubStringValue("StrVerifier", vo.VERIFIER);//检验员
                        //btFormat.SetNamedSubStringValue("StrWO_NO", vo.WO_NO);//工单
                        //btFormat.SetNamedSubStringValue("StrSum", vo.QTY);//数量
                        //btFormat.SetNamedSubStringValue("StrUnit", vo.UNIT);//单位
                        //btFormat.SetNamedSubStringValue("StrBak", StrBak);//备注
                        //btFormat.SetNamedSubStringValue("StrYY", strYY);//年strQuarter
                        //btFormat.SetNamedSubStringValue("strQuarter", strQuarter);
                        //btFormat.PrintOut(false, false); //第二个false设置打印时是否跳出打印属性
                    }
                    //btFormat.Close(BarTender.BtSaveOptions.btDoNotSaveChanges); //退出时是否保存标签
                }
                else
                {
                    MessageBox.Show("数据库连接错误!" + strConnResult, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                getLastEPNO();
                button1.Enabled = true;
                //inival();
            }
            catch (Exception ex)
            {
                MessageBox.Show("出錯啦,原因如下:\n\r" + ex.Message, "出錯啦");
                button1.Enabled = true;
            }
            finally
            {
                if (labApp != null)
                {
                    labApp.Documents.CloseAll(true);
                    labApp.Quit();//退出
                    labApp = null;
                    doc = null;
                }
                button1.Enabled = true;
                dao.Close();
                GC.Collect(0);

            }
        }
Example #48
0
 public void LoadEmptyRoom(int idRoomType)
 {
     List<Room> rooms = RoomDAO.Instance.LoadEmptyRoom(idRoomType);
     cbRoom.DataSource = rooms;
     cbRoom.DisplayMember = "Name";
 }
Example #49
0
		public TrajectoryConstraints()
		{
			constraints = new List<Constraints>();
		}
Example #50
0
 public void LoadListRoomType()
 {
     List<RoomType> rooms = RoomTypeDAO.Instance.LoadListRoomType();
     cbRoomType.DataSource = rooms;
     cbRoomType.DisplayMember = "Name";
 }
Example #51
0
 public void Initialize()
 {
     ProjectileList = new List <IProjectile>();
 }
 public static void DrawBresenhamLine(this WriteableBitmap wbm, int x0, int y0, int x1, int y1, List <Color> colors)
 {
     if (x0 >= wbm.PixelWidth || x1 >= wbm.PixelWidth || y0 >= wbm.PixelHeight || y1 >= wbm.PixelHeight || x1 < 0 || x0 < 0 || y0 < 0 || y1 < 0)
     {
         return;
     }
     wbm.SetPixels(Bresenham.CalculateBresenhamLine(x0, y0, x1, y1), colors);
 }
 /**
  * Constructors.
  **/
 public ISimpleMesh() {
     //Create Lists
     lVertex = new List<Vertex>();
     lNormal = new List<Normal>();
     lPrimitive = new List<Primitive>();
 }
 public static List<sp_searchcustomerdetailsResult> Search(string search)
 {
     db = new db_MiletecDataContext();
     List<sp_searchcustomerdetailsResult> searchcus = db.sp_searchcustomerdetails(search).ToList<sp_searchcustomerdetailsResult>();
     return searchcus;
 }
 /// <summary>
 /// 將輸入清單的每個元素作XOR運算
 /// </summary>
 /// <param name="input">輸入清單</param>
 /// <returns>CRC驗證碼</returns>
 public static byte MakeCrc(List<byte> input)
 {
     byte result = 0x00;
     foreach (byte data in input) result ^= data;
     return result;
 }
Example #56
0
        private void TV_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //AttType a = TV.SelectedNode.Tag as AttType;
            //MessageBox.Show(a.Tag + "" + a.Type);

            List<string> OptionList1 = new List<string>();
            List<string> OptionList2 = new List<string>();
            List<string> OptionList3 = new List<string>();
            List<string> OptionList4 = new List<string>();
            try
            {
                TreeNodeCollection nodes = TV.SelectedNode.Parent.Nodes;
                foreach (ICloneable node in nodes)
                {
                    TreeNode t = (TreeNode) node.Clone();
                    OptionList1.Add(t.Text);
                    OptionList2.Add(t.Text);
                    OptionList3.Add(t.Text);
                    OptionList4.Add(t.Text);
                }
                cbOption1.DataSource = OptionList1;
                cbOption2.DataSource = OptionList2;
                cbOption3.DataSource = OptionList3;
                cbOption4.DataSource = OptionList4;
            }
            catch (Exception)
            {
            }
           
            try
            {
                at = TV.SelectedNode.Tag as AttType;
                if (at.Type == "Dialog")
                {
                    txtName.Text = at.SpeakerName.Trim();
                    txtProfileID.Text = at.SpeakerProfile.Trim();
                    if (at.Pos.Trim() == "Left")
                    {
                        cbPos.SelectedIndex = 0;
                    }
                    else
                    {
                        cbPos.SelectedIndex = 1;
                    }
                    txtContent.Text = at.Content.Trim();
                    if (at.IsOption)
                    {
                        cheakBoxIsOption.Checked = true;
                        Option1.Text = at.OptionName1 == null ? "" : at.OptionName1.Trim();
                        Option2.Text = at.OptionName2 == null ? "" : at.OptionName2.Trim();
                        Option3.Text = at.OptionName3 == null ? "" : at.OptionName3.Trim();
                        Option4.Text = at.OptionName4 == null ? "" : at.OptionName4.Trim();
                        cbOption1.SelectedIndex =at.OptionAction1==null?0: int.Parse(at.OptionAction1);
                        cbOption2.SelectedIndex = at.OptionAction2 == null ? 0 : int.Parse(at.OptionAction2);
                        cbOption3.SelectedIndex = at.OptionAction3 == null ? 0 : int.Parse(at.OptionAction3);
                        cbOption4.SelectedIndex = at.OptionAction4 == null ? 0 : int.Parse(at.OptionAction4);
                        if (!string.IsNullOrEmpty(at.OptionName1))
                        {
                            chbOption1.Checked = true;
                        }
                        else
                        {
                            chbOption1.Checked = false;

                        }
                        if (!string.IsNullOrEmpty(at.OptionName2))
                        {
                            chbOption2.Checked = true;
                        }
                        else
                        {
                            chbOption2.Checked = false;

                        }
                        if (!string.IsNullOrEmpty(at.OptionName3))
                        {
                            chbOption3.Checked = true;
                        }
                        else
                        {
                            chbOption3.Checked = false;

                        }
                        if (!string.IsNullOrEmpty(at.OptionName4))
                        {
                            chbOption4.Checked = true;
                        }
                        else
                        {
                            chbOption4.Checked = false;

                        }
                        if (string.IsNullOrEmpty(Option1.Text))
                        {
                            Option1.Enabled = false;
                            cbOption1.Enabled = false;
                        }
                        else
                        {
                            Option1.Enabled = true;
                            cbOption1.Enabled = true;
                        }
                        if (string.IsNullOrEmpty(Option2.Text))
                        {
                            Option2.Enabled = false;
                            cbOption2.Enabled = false;
                        }
                        else
                        {
                            Option2.Enabled = true;
                            cbOption2.Enabled = true;
                        }
                        if (string.IsNullOrEmpty(Option3.Text))
                        {
                            Option3.Enabled = false;
                            cbOption3.Enabled = false;
                        }
                        else
                        {
                            Option3.Enabled = true;
                            cbOption3.Enabled = true;
                        }
                        if (string.IsNullOrEmpty(Option4.Text))
                        {
                            Option4.Enabled = false;
                            cbOption4.Enabled = false;
                        }
                        else
                        {
                            Option4.Enabled = true;
                            cbOption4.Enabled = true;
                        }
                    }
                    else
                    {
                        cheakBoxIsOption.Checked = false;
                        Option1.Text = null;
                        Option2.Text = null;
                        Option3.Text = null;
                        Option4.Text = null;
                        cbOption1.SelectedIndex = 0;
                        cbOption2.SelectedIndex = 0;
                        cbOption3.SelectedIndex = 0;
                        cbOption4.SelectedIndex = 0;
                    }
                }





            }
            catch (Exception)
            {
                return;

            }
            if (at.Type == "Point")
            {
                btnPreview.Enabled = true;

            }
            else
            {
                btnPreview.Enabled = false;

            }

                //AttType xxx = TV.SelectedNode.Tag as AttType;
                //MessageBox.Show(xxx.Tag + ";" + xxx.Type);
          
        }
 /// <summary>
 /// 以指定範圍的List<byte>製作CRC驗證碼</byte>
 /// </summary>
 /// <param name="input">輸入List</param>
 /// <param name="pStart">起使位置</param>
 /// <param name="length">納入運算的長度</param>
 /// <returns>CRC驗證碼</returns>
 public static byte MakeCrc(List<byte> input, int pStart, int length)
 { return MakeCrc(input.GetRange(pStart, length)); }
 public BLEDongle(List<byte> source)
 {
     FormatData(source);
 }
        public void DeleteUpdateAssociationTest()
        {
            foreach (IDataService dataService in DataServices)
            {
                // Arrange.
                SQLDataService ds = dataService as SQLDataService;

                //TODO: Fix OracleDataService error.
                if (dataService is OracleDataService)
                {
                    continue;
                }
                var masterBreedType = new ТипПороды {
                    Название = "тип породы1", ДатаРегистрации = DateTime.Now
                };
                var innerMasterBreed = new Порода {
                    Название = "порода1", ТипПороды = masterBreedType
                };
                var innerMasterCat = new Кошка
                {
                    Кличка       = "кошка",
                    ДатаРождения = (NullableDateTime)DateTime.Now,
                    Тип          = ТипКошки.Дикая,
                    Порода       = innerMasterBreed
                };
                var innerKitten = new Котенок {
                    КличкаКотенка = "котеночек", Кошка = innerMasterCat
                };

                // Act
                ds.UpdateObject(innerKitten);

                LoadingCustomizationStruct lcsKitten    = LoadingCustomizationStruct.GetSimpleStruct(typeof(Котенок), Котенок.Views.КотенокE);
                LoadingCustomizationStruct lcsCat       = LoadingCustomizationStruct.GetSimpleStruct(typeof(Кошка), Кошка.Views.КошкаE);
                LoadingCustomizationStruct lcsBreed     = LoadingCustomizationStruct.GetSimpleStruct(typeof(Порода), Порода.Views.ПородаE);
                LoadingCustomizationStruct lcsBreedType = LoadingCustomizationStruct.GetSimpleStruct(typeof(ТипПороды), ТипПороды.Views.ТипПородыE);

                DataObject[] dataObjectsKitten     = ds.LoadObjects(lcsKitten);
                DataObject[] dataObjectsCats       = ds.LoadObjects(lcsCat);
                DataObject[] dataObjectsBreed      = ds.LoadObjects(lcsBreed);
                DataObject[] dataObjectsBreedTypes = ds.LoadObjects(lcsBreedType);

                int countKittenBefore    = ds.GetObjectsCount(lcsKitten);
                int countCatBefore       = ds.GetObjectsCount(lcsCat);
                int countBreedBefore     = ds.GetObjectsCount(lcsBreed);
                int countBreedTypeBefore = ds.GetObjectsCount(lcsBreed);

                List <DataObject> objectsForUpdateList = new List <DataObject>();

                foreach (Котенок котенок in dataObjectsKitten)
                {
                    котенок.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(котенок);
                }

                foreach (Кошка кошка in dataObjectsCats)
                {
                    кошка.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(кошка);
                }

                foreach (Порода порода in dataObjectsBreed)
                {
                    порода.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(порода);
                }

                foreach (ТипПороды типПороды in dataObjectsBreedTypes)
                {
                    типПороды.SetStatus(ObjectStatus.Deleted);
                    objectsForUpdateList.Add(типПороды);
                }

                DataObject[] objectsForUpdate = objectsForUpdateList.ToArray();

                ds.UpdateObjects(ref objectsForUpdate);

                int countKittenAfter    = ds.GetObjectsCount(lcsKitten);
                int countCatAfter       = ds.GetObjectsCount(lcsCat);
                int countBreedAfter     = ds.GetObjectsCount(lcsBreed);
                int countBreedTypeAfter = ds.GetObjectsCount(lcsBreedType);

                // Assert
                Assert.Equal(1, countKittenBefore);
                Assert.Equal(1, countCatBefore);
                Assert.Equal(1, countBreedBefore);
                Assert.Equal(1, countBreedTypeBefore);

                Assert.Equal(0, countKittenAfter);
                Assert.Equal(0, countCatAfter);
                Assert.Equal(0, countBreedAfter);
                Assert.Equal(0, countBreedTypeAfter);
            }
        }
Example #60
0
 public Vertex(T value)
 {
     Edges = new List <Vertex <T> >();
     Value = value;
 }