public void SetCameraModels(List<string> cameras, string selectedCamera, string videoStandard)
        {
            cbxCameras.Items.Clear();

            string videoStandardNameChunk = string.Concat("(", videoStandard, ")");

            if (!string.IsNullOrEmpty(videoStandard))
                cbxCameras.Items.AddRange(cameras.Where(x => x.Contains(videoStandardNameChunk)).Cast<object>().ToArray());

            if (cbxCameras.Items.Count == 0)
                cbxCameras.Items.AddRange(cameras.Cast<object>().ToArray());

            // First look for exact match
            string cameraToSelect = cameras.FirstOrDefault(x => x.Replace(" ", "").Equals(selectedCamera.Replace(" ", ""), StringComparison.InvariantCultureIgnoreCase) && x.Contains(videoStandardNameChunk));

            if (cameraToSelect == null)
                // Then do a 'starts with' search
                cameraToSelect = cameras.FirstOrDefault(x => x.Replace(" ", "").Contains(selectedCamera.Replace(" ", "")) && x.Contains(videoStandardNameChunk));

            if (cameraToSelect != null)
            {
                cbxCameras.SelectedIndex = cbxCameras.Items.IndexOf(cameraToSelect);
                rbCorrect.Checked = true;
            }
            else
                rbDontCorrect.Checked = true;
        }
Example #2
0
        public TrueTypeFont Read(Stream stream)
        {
            var little = BitConverter.IsLittleEndian;
            using (BinaryReader reader = new ByteOrderSwappingBinaryReader(stream))
            {
                var version = reader.ReadUInt32();
                var tableCount = reader.ReadUInt16();
                var searchRange = reader.ReadUInt16();
                var entrySelector = reader.ReadUInt16();
                var rangeShift = reader.ReadUInt16();

                var tables = new List<Table>(tableCount);

                for (int i = 0; i < tableCount; i++)
                {
                    var tag = reader.ReadUInt32();
                    var checkSum = reader.ReadUInt32();
                    var offset = reader.ReadUInt32();
                    var length = reader.ReadUInt32();

                    var bytes = BitConverter.GetBytes(tag);
                    Array.Reverse(bytes);
                    var name = Encoding.ASCII.GetString(bytes);

                    tables.Add(new Table(tag, name, checkSum, offset, length));
                }

                var header = ExtractAsHeader(reader, tables.FirstOrDefault(e => e.Name.ToLower() == "head"));
                var maxp = ExtractAsMaxp(reader, tables.FirstOrDefault(e => e.Name.ToLower() == "maxp"));
                var loca = ExtractAsLoca(reader, maxp.NumGlyphs, header.IndexToLocFormat, tables.FirstOrDefault(e => e.Name.ToLower() == "loca"));
                var glyf = ExtractAsGlyf(reader, maxp.NumGlyphs, loca, tables.FirstOrDefault(e => e.Name.ToLower() == "glyf"));

                return new TrueTypeFont(header, maxp, loca, glyf);
            }
        }
Example #3
0
        public static List<DigimonVM> GetVMs(this IEnumerable<Digimon> digimons)
        {
            var result = new List<DigimonVM>();
            var count = digimons.Count();
            var index = 0;

            foreach (var digimon in digimons)
            {
                result.Add(digimon.GetVM());
            }

            foreach (var digimonVm in result)
            {
                digimonVm.DigivolveFrom =
                    new ObservableCollection<DigivolveDigimonVM>(digimonVm.Source.DigivolesFrom.OrderBy(x => x.DP)
                        .Select(
                            x => new DigivolveDigimonVM
                            {
                                Digimon = result.FirstOrDefault(y => y.Source.NameEng == x.DigimonFromId),
                                DP = x.DP
                            }));
                digimonVm.DigivolveTo =
                    new ObservableCollection<DigivolveDigimonVM>(digimonVm.Source.DigivolesTo.OrderBy(x => x.DP).Select(
                        x => new DigivolveDigimonVM
                        {
                            Digimon = result.FirstOrDefault(y => y.Source.NameEng == x.DigimonToId),
                            DP = x.DP
                        }));
                index++;
                PercentDigimonChanged?.Invoke((decimal)index / count);
            }

            return result.OrderBy(x => x.Name).ToList();
        }
        public static void RegisterDefaultConventions(Action<Type, Type> registerMethod, Assembly[] interfaceAssemblies,
            Assembly[] implementationAssemblies, Type[] excludeTypes, string excludeRegEx)
        {
            var interfaces = new List<Type>();

            foreach (var assembly in interfaceAssemblies)
            {
                interfaces.AddRange(GetInterfaces(assembly));
            }

            foreach (var interfaceType in interfaces)
            {
                if (IsExcludedType(interfaceType, excludeTypes, excludeRegEx)) { continue; }

                var implementations = new List<Type>();

                foreach (var assembly in implementationAssemblies)
                {
                    implementations.AddRange(
                        GetImplementationsOfInterface(assembly, interfaceType)
                            .Where(implementation => !IsExcludedType(implementation, excludeTypes, excludeRegEx))
                            .ToArray());
                }

                var implementationType = implementations.FirstOrDefault(implementation => IsDefaultType(interfaceType, implementation)) ??
                                         implementations.FirstOrDefault(implementation => IsAdapterType(interfaceType, implementation));

                if (implementationType == null) { continue; }

                Debug.WriteLine("Auto registration of {1} : {0}", interfaceType.Name, implementationType.Name);

                registerMethod(interfaceType, implementationType);
            }
        }
Example #5
0
        public static void ApplyPatch(string patchFolderLocation, string applyLocation, bool ignoreMD5 = false)
        {
            _hash.Clear();
            if (!ignoreMD5)
            {
                _hash =
                    ChangeFileHashDetails.DeserializeListFromFile(patchFolderLocation + "\\_changedFileList.hashstore");
                var files = Directory.GetFiles(patchFolderLocation, "*.changed", SearchOption.AllDirectories);
                files = files.Where(s => !s.Contains(".hashstore")).ToArray();
                if (_hash.Count != files.Length)
                {
                    //throw new InvalidOperationException("Incorrect number of patch files to hashes");
                }
                var foundFilesInHash = 0;
                foreach (var file in files)
                {
                    var relativePath = file.Replace(patchFolderLocation, "");
                    var validHashForFile = _hash.FirstOrDefault(s => relativePath == s._relativePatchFileLocation);
                    if (validHashForFile == null)
                    {
                        throw new InvalidOperationException("Couldn't Find Valid Hash" + relativePath);
                    }
                    foundFilesInHash++;
                }
                if (foundFilesInHash != _hash.Count)
                {
                    throw new InvalidOperationException("Didn't find every file in the hash file");
                }
                //check patch files
                foreach (var file in files)
                {
                    Trace(file, "");
                    var hash = FileComputeHasher.ComputeHashFromFile(file);
                    var relativePath = file.Replace(patchFolderLocation, "");
                    if (
                        _hash.FirstOrDefault(s => s._patchHash == hash && s._relativePatchFileLocation == relativePath) ==
                        null)
                    {
                        throw new InvalidOperationException("Hash doesn't match for existing patch file" + relativePath);
                    }
                }

                // check apply files
                foreach (var file in Directory.GetFiles(applyLocation, "*.*", SearchOption.AllDirectories))
                {
                    var hash = FileComputeHasher.ComputeHashFromFile(file);

                    var relativePath = file.Replace(applyLocation, "");
                    if (_hash.FirstOrDefault(s => s._relativeOldFileLocation == relativePath) == null) continue;

                    if (
                        _hash.FirstOrDefault(s => s._oldFileHash == hash && s._relativeOldFileLocation == relativePath) ==
                        null)
                    {
                        throw new InvalidOperationException(string.Format("Hash doesn't match for existing apply file {0} old Hash = {1} new hash = {2}", file, hash, _hash.First(s=> s._relativeOldFileLocation == relativePath)._oldFileHash));
                    }
                }
            }
            ApplyPatchImpl(patchFolderLocation, applyLocation);
        }
        static void Main(string[] args)
        {
            var nums = new List<int>() {1, 2, 3, 4, 5, 6, 7};

            Console.WriteLine(nums.FirstOrDefault(e => e % 2 == 0));
            Console.WriteLine(nums.FirstOrDefault(x => x < 0));
        }
        private void PrepareProducts(List<Product> products)
        {
            products.RemoveAll(x => x.Name.Contains("*"));

            var coupon = products.FirstOrDefault(x => x.Name.Contains("$"));
            if (coupon != null)
            {
                for (var i = 0; i < coupon.Quantity; i++)
                {
                    var bread = products.First(x => x.Name.Contains("хляб") && !x.Name.Contains("$") && x.Quantity > 0 && x.SellingPrice > coupon.SellingPrice * -1);
                    bread.Quantity--;

                    var breadWithCouponName = bread.Name + " с купон";

                    var breadWithCoupon = products.FirstOrDefault(x => x.Name == breadWithCouponName);

                    if (breadWithCoupon != null)
                    {
                        breadWithCoupon.Quantity++;
                    }
                    else
                    {
                        breadWithCoupon = new Product { Name = breadWithCouponName, SellingPrice = bread.SellingPrice - coupon.SellingPrice * -1, Quantity = 1 };
                        products.Add(breadWithCoupon);
                    }
                }

                products.RemoveAll(x => x.Quantity == 0);
                products.RemoveAll(x => x.Name.Contains("$"));
            }
        }
Example #8
0
        public static List<Node> GetNodes()
        {
            int count = int.Parse(Console.ReadLine());
            var nodesSoFar = new HashSet<int>();
            var nodes = new List<Node>();
            while (count > 1)
            {
                string[] input = Console.ReadLine().Split(' ');
                int parentValue = int.Parse(input[0]);
                int childValue = int.Parse(input[1]);
                var parent = nodes.FirstOrDefault(n => n.Value == parentValue);
                var child = nodes.FirstOrDefault(n => n.Value == childValue);
                if (child == null)
                {
                    child = new Node(childValue);
                    nodes.Add(child);
                }

                if (parent == null)
                {
                    parent = new Node(parentValue);
                    nodes.Add(parent);
                }

                parent.AddChild(child);
                count--;
            }
            return nodes;
        }
Example #9
0
        public Verse(string verseText, bool showChords, int verseNumber)
        {
            DisplayLines = new List<Line>();
            AllLines = new List<Line>();

            VerseNumber = verseNumber;

            var lines = verseText.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var lineText in lines)
            {
                AllLines.Add(new Line(lineText));
            }

            if(showChords)
            {
                ShowChords();
            }
            else
            {
                HideChords();
            }

            FirstLineChords = AllLines.FirstOrDefault(x => x.Type == LineType.Chord);
            FirstLine = AllLines.FirstOrDefault(x => x.Type == LineType.Text);
        }
Example #10
0
        //public ItemsResponse<Incident> GetComplaint(IncidentAddRequest model)
        //{
        //    ItemsResponse<Incident> resp = new ItemsResponse<Incident>();

        //    List<SqlParameter> collection = new List<SqlParameter>();
        //    collection.Add(CreateParameter("@categoryId", model.CategoryId, SqlDbType.Int, ParameterDirection.Input));
        //    collection.Add(CreateParameter("@lat", model.Lat, SqlDbType.BigInt, ParameterDirection.Input));
        //    collection.Add(CreateParameter("@lng", model.Lng, SqlDbType.BigInt, ParameterDirection.Input));

        //    Func<IDataRecord, Incident> complaintReader = delegate (IDataRecord record)
        //    {
        //        Incident req = new Incident();
        //        req.Id = record.GetInt32(0);
        //        req.Lat = record.GetDouble(1);
        //        req.Lng = record.GetDouble(2);
        //        req.Status = (ComplaintStatusType)record.GetInt32(3);
        //        req.CategoryId = record.GetInt32(4);
        //        req.TweetId = record.GetInt32(5);

        //        return req;
        //    };

        //    try
        //    {
        //        resp.Items = ExecuteReader<Incident>("DBNAME", "SP_NAME", complaintReader, collection);
        //        resp.IsSuccessFull = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception(ex.Message);
        //    }

        //    return resp;
        //}

        public IncidentResponse CreateComplaint(IncidentAddRequest model)
        {
            //var id = 0;

            List<SqlParameter> collection = new List<SqlParameter>();
            collection.Add(CreateParameter("@categoryId", model.categoryId, SqlDbType.Int, ParameterDirection.Input));
            collection.Add(CreateParameter("@lat", model.Lat, SqlDbType.Float, ParameterDirection.Input));
            collection.Add(CreateParameter("@lng", model.Lng, SqlDbType.Float, ParameterDirection.Input));
            collection.Add(CreateParameter("@userId", model.UserId, SqlDbType.Int, ParameterDirection.Input));
            collection.Add(CreateParameter("@TweetId", null, SqlDbType.BigInt, ParameterDirection.Output));
            collection.Add(CreateParameter("@IncidentId", null, SqlDbType.Int, ParameterDirection.Output));


            ExecuteNonQuery("wehackdb", "dbo.Incident_Insert", collection);

            //id = (int)collection.FirstOrDefault(x => x.ParameterName == "@userId").SqlValue;

            IncidentResponse resp = new IncidentResponse();
            if (collection.FirstOrDefault(x => x.ParameterName == "@TweetId").Value == DBNull.Value)
            {
                resp.TweetId = null;
            }
            else
            {
                resp.TweetId = (long?)collection.FirstOrDefault(x => x.ParameterName == "@TweetId").SqlValue;
            }
            resp.IncidentId = (int)collection.FirstOrDefault(x => x.ParameterName == "@IncidentId").Value;

            return resp;
        }
Example #11
0
 private StreamInfo GetOptimalStream(List<StreamInfo> streams)
 {
     // Grab the first one that can be direct streamed
     // If that doesn't produce anything, just take the first
     return streams.FirstOrDefault(i => i.IsDirectStream) ??
         streams.FirstOrDefault();
 }
Example #12
0
	void Update()
	{
		var dist = (transform.position - Camera.main.transform.position).z;
		float leftBorder = Camera.main.ViewportToWorldPoint (new Vector3 (0, 0, dist)).x;
		float rightBorder = Camera.main.ViewportToWorldPoint (new Vector3 (1, 0, dist)).x;

		backgroundPart = backgroundPart.OrderBy (t => t.transform.position.x).ToList ();
		SpriteRenderer firstChild = backgroundPart.FirstOrDefault ();

		if (firstChild != null) {
			while (firstChild.transform.position.x + firstChild.bounds.extents.x < leftBorder) {
				float newX = rightBorder + 2f * firstChild.bounds.extents.x;
				if (firstChild.sortingLayerName == "Ground") {
					newX = firstChild.transform.position.x + 4f * firstChild.bounds.extents.x;
				}
				firstChild.transform.position = new Vector3 (
					newX,
					firstChild.transform.position.y,
					firstChild.transform.position.z
				);

				// The first part become the last one
				backgroundPart.Remove (firstChild);
				backgroundPart.Add (firstChild);
				firstChild = backgroundPart.FirstOrDefault ();
			}
		}
	}
Example #13
0
 public TblUpdate GetClientLastUpdate()
 {
     DateTime min = DateTime.Parse("2000/01/01");
     TblUpdate novalue = new TblUpdate()
     {
         LastActivityLogUpdate = min,
         LastClientUpdate = min,
         LastConsutantUpdate = min,
         LastInfoUpdate = min,
         LastUserPermissionUpdate = min,
         LocalActivityLogUpdate = min,
         LocalClientUpdate = min,
         LocalConsutantUpdate = min,
         LocalInfoUpdate = min,
         LocalUserUpdate = min
     };
     List<TblUpdate> u = new List<TblUpdate>();
     var conn = new System.Data.SqlServerCe.SqlCeConnection(connectionString);
     using (Sonartez_server db = new Sonartez_server(conn))
     {
         var q =
         from a in db.TblUpdate
         select a;
         u = q.ToList();
     }
     if (u.FirstOrDefault() != null)
     {
         if (u.FirstOrDefault().LastClientUpdate != null)
             return u.FirstOrDefault();
         else
             return novalue;
     }
     else
         return novalue;
 }
Example #14
0
        public bool LoginAccount(List<DataElement> de, out int userId)
        {
            try
            {
                var username = de.FirstOrDefault(p => p.Name.ToLower() == "username").Value ?? "";
                var password = de.FirstOrDefault(p => p.Name.ToLower() == "password").Value ?? "";
                Logger.Info("LoginServers-LoginAccount:username="+username+" password="+password);
                var user = userRepository.getUserByUsername(username);

                if (!ValidateUser(user, out userId))
                {
                    Logger.Info("LoginServers-LoginAccount:can not find user" );

                    return false;
                }
                var result=membershipRepository.ValidatePassword(userId, password);

                if (result)
                {
                    trackingRepository.AddTracking(userId, 1, "登陆成功");
                }

                return result;
            }
            catch (Exception e)
            {
                Logger.Error("LoginServers-LoginAccount:Error:"+e);
                userId = 0;
                return false;
            }
        }
        public static void Main()
        {
            List<int> collection = new List<int> { 1, 2, 3, 4, 6, 11, 6 };

            Console.WriteLine(collection.FirstOrDefault(x => x > 6));
            Console.WriteLine(collection.FirstOrDefault(x => x < 0));
        }
        static void Main(string[] args)
        {
            List<int> collection = new List<int> { 1, 2, 3, 4, 6, 11, 6 };

            Console.WriteLine(collection.FirstOrDefault(x => x > 7));
            Console.WriteLine(collection.FirstOrDefault(x => x < 0));
        }
Example #17
0
        internal static void Initialize(CompositionContainer composition)
        {
            List<Language> languages = new List<Language>();
            if (composition != null)
                languages.AddRange(composition.GetExportedValues<Language>());
            else {
                languages.Add(new CSharpLanguage());
                languages.Add(new VB.VBLanguage());
            }

            // Fix order: C#, VB, IL
            var langs2 = new List<Language>();
            var lang = languages.FirstOrDefault(a => a is CSharpLanguage);
            if (lang != null) {
                languages.Remove(lang);
                langs2.Add(lang);
            }
            lang = languages.FirstOrDefault(a => a is VB.VBLanguage);
            if (lang != null) {
                languages.Remove(lang);
                langs2.Add(lang);
            }
            langs2.Add(new ILLanguage(true));
            for (int i = 0; i < langs2.Count; i++)
                languages.Insert(i, langs2[i]);

            #if DEBUG
            languages.AddRange(ILAstLanguage.GetDebugLanguages());
            languages.AddRange(CSharpLanguage.GetDebugLanguages());
            #endif
            allLanguages = languages.AsReadOnly();
        }
Example #18
0
 /// <summary>
 /// 根据刚刚查询所返回的回执集合
 /// 获取本次查询状态——是否已经查询完毕(若是第一个线程,则说明当前查询后,本次线程中所有用户已经查询完毕;
 /// 若是第二个线程,则还需要做相关操作
 /// </summary>
 /// <param name="list">刚刚查询所返回的回执集合</param>
 /// <returns></returns>
 public QueryState_Enum GetQueryState(List<SMSModel_QueryReceive> list)
 {
     if (list.Count == 1)
     {
         //判断该集合中的唯一的对象的desc是否为成功
         if(list.Count()==1&& list.FirstOrDefault().desc=="成功"&&list.FirstOrDefault().phoneNumber==null)
         {
             //1:未有未被查询到的用户
             return QueryState_Enum.finish;
         }
         else
         {
             //99:原因未知
             return QueryState_Enum.unknown;
         }
     }
     else if(list.Count==0)
     {
         return QueryState_Enum.error;
     }
     else
     {
         //大于1时
         return QueryState_Enum.remnant;
     }
 }
Example #19
0
        public PackageResult(IPackage package, string installLocation, string source = null)
            : this(package.Id.to_lower(), package.Version.to_string(), installLocation)
        {
            Package = package;
            Source = source;
            var sources = new List<Uri>();
            if (!string.IsNullOrEmpty(source))
            {
                sources.AddRange(source.Split(new[] {";", ","}, StringSplitOptions.RemoveEmptyEntries).Select(s => new Uri(s)));
            }

            var rp = Package as DataServicePackage;
            if (rp != null)
            {
                SourceUri = rp.DownloadUrl.ToString();
                Source = sources.FirstOrDefault(uri => uri.IsBaseOf(rp.DownloadUrl)).to_string();
                if (string.IsNullOrEmpty(Source))
                {
                    Source = sources.FirstOrDefault(uri => uri.DnsSafeHost == rp.DownloadUrl.DnsSafeHost).to_string();
                }
            }
            else
            {
                Source = sources.FirstOrDefault(uri => uri.IsFile || uri.IsUnc).to_string();
            }
        }
        //[Import("MainWindow")]
        //public new Window MainWindow
        //{
        //    get { return base.MainWindow; }
        //    set { base.MainWindow = value; }
        //}

        /// <summary>
        /// Sets the UI language
        /// </summary>
        /// <param name="culture">Language code (ex. "en-EN")</param>
        public static void SelectCulture(string culture)
        {
            // List all our resources      
            List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                dictionaryList.Add(dictionary);
            }
            // We want our specific culture      
            string requestedCulture = string.Format("Locale.{0}.xaml", culture);
            ResourceDictionary resourceDictionary = 
                dictionaryList.FirstOrDefault(d => d.Source.OriginalString == "/BetterExplorer;component/Translation/" + requestedCulture);
            if (resourceDictionary == null)
            {
                // If not found, we select our default language        
                //        
                requestedCulture = "DefaultLocale.xaml";
                resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString == "/BetterExplorer;component/Translation/" + requestedCulture);
            }

            // If we have the requested resource, remove it from the list and place at the end.\      
            // Then this language will be our string table to use.      
            if (resourceDictionary != null)
            {
                Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
                Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
            }
            // Inform the threads of the new culture      
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
        }
Example #21
0
 public int UploadImageInDataBase(HttpPostedFileBase file, string _empNo)
 {
     using (var context = new TAS2013Entities())
     {
         List<EmpPhoto> _empPhotoList = new List<EmpPhoto>();
         EmpPhoto _EmpPhoto = new EmpPhoto();
         Emp _Emp = new Emp();
         int empPhotoID = 0;
         _Emp = context.Emps.First(aa => aa.EmpNo == _empNo);
         _empPhotoList = context.EmpPhotoes.Where(aa => aa.EmpID == _Emp.EmpID).ToList();
         _EmpPhoto.EmpPic = ConvertToBytes(file);
         if (_empPhotoList.Count > 0)
         {
             //Update Existing Image
             _EmpPhoto.EmpID = _empPhotoList.FirstOrDefault().EmpID;
             _EmpPhoto.PhotoID = _empPhotoList.FirstOrDefault().PhotoID;
         }
         else
         {
             //Add New Image
             _EmpPhoto.EmpID = _Emp.EmpID;
             context.EmpPhotoes.Add(_EmpPhoto);
         }
         try
         {
             empPhotoID = _EmpPhoto.PhotoID;
             context.SaveChanges();
             return empPhotoID;
         }
         catch (Exception ex)
         {
             return empPhotoID;
         }
     }
 }
Example #22
0
        private static JObject CombineRows(string rootId, List<Row> rows)
        {
            var rootObjectRow = rows.FirstOrDefault(r => r.Id == rootId);

            if (rootObjectRow == null)
            {
                return null; // the child triggered transform before the parent
            }

            JObject rootObject = rootObjectRow.Data;

            // reassemble the document, adding children to parents
            foreach (var r in rows)
            {
                if (!string.IsNullOrEmpty(r.ParentId))
                {
                    var parentObject = rows.FirstOrDefault(x => x.Id == r.ParentId);
                    if (parentObject != null)
                    {
                        if (parentObject.Data[r.Type] == null)
                        {
                            parentObject.Data[r.Type] = new JArray();
                        }

                        ((JArray) parentObject.Data[r.Type]).Add(r.Data);
                    }
                }

            }

            return rootObject;
        }
Example #23
0
        public static List<TreeNode<int>> CreateTree(int[,] nodesValues)
        {
            var tree = new List<TreeNode<int>>();

            for (int i = 0; i < nodesValues.GetLength(0); i++)
            {
                int parentValue = nodesValues[i, 0];
                int childValue = nodesValues[i, 1];

                var parentNode = tree.FirstOrDefault(x => x.Value == parentValue);
                var childNode = tree.FirstOrDefault(x => x.Value == childValue);

                if (parentNode == null)
                {
                    parentNode = new TreeNode<int>(parentValue);
                    tree.Add(parentNode);
                }

                if (childNode == null)
                {
                    childNode = new TreeNode<int>(childValue);
                    tree.Add(childNode);
                }

                parentNode.AddChild(childNode);
            }

            return tree;
        }
Example #24
0
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://sam2012"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Test1(web);
                   // GetAllItemsIncludeFolders(web);
                    Test2(web);
                }

                Console.ReadKey();
            }

            List<string> l = new List<string>(){"1","2","3","4"};
            for (int i = 0; i < 3; i++)
            {
                string s = l.FirstOrDefault(k => k == 1.ToString());
                l.Remove(s);
                string s1 = l.FirstOrDefault(k => k == 2.ToString());
                l.Remove(s1);
            }

            foreach (string v in l)
            {
                Console.WriteLine(v);
            }

            Console.ReadKey();
        }
Example #25
0
    /// <summary>
    /// Sets the UI language
    /// </summary>
    /// <param name="culture">Language code (ex. "en-EN")</param>
    public void SelectCulture(String culture) {
      if (culture == ":null:") {
        culture = CultureInfo.InstalledUICulture.Name;
      }

      // List all our resources      
      var dictionaryList = new List<ResourceDictionary>(Current.Resources.MergedDictionaries);

      // We want our specific culture      
      String requestedCulture = $"Locale.{culture}.xaml";
      ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString == "/BetterExplorer;component/Translation/" + requestedCulture);
      if (resourceDictionary == null) {
        // If not found, we select our default language         
        requestedCulture = "DefaultLocale.xaml";
        resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString == "/BetterExplorer;component/Translation/" + requestedCulture);
      }

      // If we have the requested resource, remove it from the list and place at the end.\      
      // Then this language will be our string table to use.      
      if (resourceDictionary != null) {
        Current.Resources.MergedDictionaries.Remove(resourceDictionary);
        Current.Resources.MergedDictionaries.Add(resourceDictionary);
      }

      // Inform the threads of the new culture    
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
      Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
    }
Example #26
0
        public static List<Vector2> CalculatePath(Vector2 start, Vector2 end,
			List<PolyNode> n)
        {
            var startPoly = n.FirstOrDefault (pn => CollisionChecker.PointToPoly (start, pn.Poly));
            var endPoly = n.FirstOrDefault (pn => CollisionChecker.PointToPoly (end, pn.Poly));

            PolyNode currentPoly = startPoly;
            List<Vector2> route = new List<Vector2>(new [] {
                start});

            int MAX_STEPS = 10;
            int steps = 0;
            while (true)
            {
                currentPoly = StepPath (route, currentPoly, endPoly, ref end);
                if (currentPoly == null)
                    break;

                steps++;
                if (steps >= MAX_STEPS)
                    break;
            }

            route.Add (end);
            return route;
        }
    public HtmlString AddPrice(List<Price> oldPrices, Price newPrice)
    {
      List<Price> result = new List<Price>();
      DateTime endingDatePrevious = newPrice.StartingDate.AddDays(-1);

      if (oldPrices != null)
      {
        if (oldPrices.All(price => !price.EndingDate.HasValue || newPrice.StartingDate > price.EndingDate.Value))
        {
          Price currentPrice = oldPrices.FirstOrDefault(price => !price.EndingDate.HasValue);
          if (currentPrice != null)
          {
            currentPrice.EndingDate = endingDatePrevious;
          }
        }
        else
        {
          Price currentPrice = oldPrices.FirstOrDefault(price => price.EndingDate > newPrice.StartingDate);
          DateTime? oldEndingDate = currentPrice.EndingDate;
          currentPrice.EndingDate = endingDatePrevious;
          if (newPrice.EndingDate.HasValue && oldEndingDate > newPrice.EndingDate.Value)
          {
            result.Add(new Price() { Article = currentPrice.Article, BasePrice = currentPrice.BasePrice, StartingDate = newPrice.EndingDate.Value.AddDays(1), EndingDate = oldEndingDate });
          }
        }

        result.AddRange(oldPrices);
      }

      result.Add(newPrice);

      return result.ToHtmlJson();
    }
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="l">A list of MetricReports that wil be parsed to this members properties</param>
 public MetricsReport(List<MetricReport> l)
 {
     MaintainabilityIndex = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "MaintainabilityIndex"));
     CyclomaticComplexity = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "CyclomaticComplexity"));
     ClassCoupling = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "ClassCoupling"));
     DepthOfInheritance = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "DepthOfInheritance"));
     LinesOfCode = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "LinesOfCode"));
 }
Example #29
0
 public static List<Country> GetPairCountries(int firstCountryId, int secondCountryId,List<Country> allCountry )
 {
     var countries = new List<Country>();
     countries.Add(allCountry.FirstOrDefault(c => c.Id == firstCountryId));
     countries.Add(allCountry.FirstOrDefault(c => c.Id == secondCountryId));
     countries = countries.OrderBy(c => c.Code).ToList();
     return countries;
 }
        public bool AddList(List<Att_AnnualLeaveDetailEntity> models)
        {
            bool isSuccess = false;
            var leaveType = string.Empty;
            var status = string.Empty;
            var year = 2013;
            if (models != null && models.FirstOrDefault() != null && models.FirstOrDefault().Year != null) 
            {
                year = Convert.ToInt32(models.FirstOrDefault().Year);
                leaveType = models.FirstOrDefault().Type;
            }

            using (var context = new VnrHrmDataContext())
            {
                var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));
                var repo = new CustomBaseRepository<Att_AnnualLeaveDetail>(unitOfWork);
                try
                {
                    var annualLeaveDetails = GetAllUseEntity<Att_AnnualLeaveDetail>(ref status).Where(p => p.Type == leaveType && p.Year == year).ToList().AsQueryable();
                    foreach (var attAnnualLeaveDetail in models)
                    {
                        var addSuccess = false;
                        var existAnnualDetail = annualLeaveDetails.Where(p => p.ProfileID == attAnnualLeaveDetail.ProfileID ).FirstOrDefault();
                        if (existAnnualDetail != null)
                        {
                            existAnnualDetail.Month1 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month2 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month3 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month4 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month5 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month6 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month7 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month8 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month9 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month10 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month11 = attAnnualLeaveDetail.Month1;
                            existAnnualDetail.Month12 = attAnnualLeaveDetail.Month1;

                            repo.Edit(existAnnualDetail);
                        }
                        else
                        {
                            Att_AnnualLeaveDetail temp = new Att_AnnualLeaveDetail();
                            temp = attAnnualLeaveDetail.CopyData<Att_AnnualLeaveDetail>();
                            repo.Add(temp);
                        }
                    }
                    repo.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }

            }
        }