Пример #1
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;
        }
        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));
        }
Пример #3
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();
        }
        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);
            }
        }
Пример #5
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="******" password="******"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;
            }
        }
Пример #6
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;
        }
        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("$"));
            }
        }
Пример #8
0
    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();
    }
Пример #9
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 ();
			}
		}
	}
Пример #10
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();
 }
Пример #11
0
        //[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);
        }
Пример #12
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;
        }
        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));
        }
Пример #14
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);
        }
        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));
        }
Пример #16
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;
     }
 }
Пример #17
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);
        }
Пример #18
0
        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;
        }
Пример #19
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();
        }
Пример #20
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);
            }
        }
Пример #21
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();
            }
        }
Пример #22
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;
        }
Пример #23
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;
         }
     }
 }
Пример #24
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();
        }
Пример #25
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;
 }
Пример #26
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);
    }
Пример #27
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;
        }
Пример #28
0
 /// <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"));
 }
Пример #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;
 }
Пример #30
0
        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;
                }

            }
        }
Пример #31
0
        /// <summary>
        /// Identifies the language of a piece of text
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public async Task <DetectedLanguageResult> DetectLanguageAsync(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException("Input text is empty.");
            }

            // Request uri
            Uri requestUri = new Uri($"{this.BaseServiceUrl}/detect?{this.API_VERSION}");
            var content    = new object[] { new { Text = text } };

            List <DetectedLanguageResult> response = await HttpClientUtility.PostAsJsonAsync <List <DetectedLanguageResult> >(requestUri, this.RequestHeaders, content);

            return(response?.FirstOrDefault());
        }
Пример #32
0
        public async Task <TodoItem> GetItemAsync(string id)
        {
            var item = _items?.FirstOrDefault(x => x.Id == id);

            if (item != null)
            {
                return(item);
            }

            item = await GetResult <TodoItem>(await CreateHttpClient().GetAsync($"{id}"));

            _items.Add(item);

            return(item);
        }
Пример #33
0
        /// <summary>
        /// Sends a message to all except those specified in the exclude list
        /// which contains the hubguid of the player
        /// </summary>
        /// <param name="message">message to send to all</param>
        /// <param name="excludeThesePlayers">list of HubGuid's to exclude</param>
        /// <param name="players">players to send message to</param>
        public static void SendToAllExcept(string message, List <string> excludeThesePlayers, List <PlayerSetup.Player> players)
        {
            if (message == null)
            {
                return;
            }

            foreach (var player in players)
            {
                if (player != null && player.HubGuid != excludeThesePlayers?.FirstOrDefault(x => x.Equals(player.HubGuid)))
                {
                    HubContext.getHubContext.Clients.Client(player.HubGuid).addNewMessageToPage(message);
                }
            }
        }
Пример #34
0
        private int GetVersionFromString(List <string> vers, string v)
        {
            var ret = 0;
            var str = string.Empty;

            str = vers?.FirstOrDefault(s => s.Contains(v));

            if (str == null)
            {
                return(ret);
            }

            int.TryParse(Regex.Split(str, @"\s+")[2], out ret);
            return(ret);
        }
Пример #35
0
        public async Task <Account> GetAccountAsync(long steamId)
        {
            string pathAccountsFileJson = _pathFolderCache + "\\" + ACCOUNTS_FILENAME;

            if (!File.Exists(pathAccountsFileJson))
            {
                return(null);
            }
            string         json     = File.ReadAllText(pathAccountsFileJson);
            List <Account> accounts = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <List <Account> >(json));

            Account account = accounts?.FirstOrDefault(a => a.SteamId == steamId.ToString());

            return(account);
        }
Пример #36
0
        /// <exclude />
        public ActionToken Resolve(IData data, ActionIdentifier actionIdentifier)
        {
            var interfaces = GetOrderedInterfaces(data.DataSourceId.InterfaceType);

            foreach (var type in interfaces)
            {
                var conditionalAction = _conditionalActions?.FirstOrDefault(f => f.Check(type, data, actionIdentifier));
                if (conditionalAction != null)
                {
                    return conditionalAction.GetActionToken(data);
                }
            }

            return ResolveDefault(data, actionIdentifier);
        }
Пример #37
0
        /// <summary>
        /// Gets the single option multiple quantity.
        /// </summary>
        /// <param name="setValues">if set to <c>true</c> [set values].</param>
        /// <param name="controlLabel">The control label.</param>
        /// <param name="feeValues">The fee values.</param>
        /// <param name="usageCountRemaining">The usage count remaining.</param>
        /// <returns></returns>
        private Control GetFeeSingleOptionMultipleQuantityControl(bool setValues, string controlLabel, List <FeeInfo> feeValues, int?usageCountRemaining)
        {
            var fee       = this;
            var numUpDown = new NumberUpDown
            {
                ID       = "fee_" + fee.Id.ToString(),
                Minimum  = fee.IsRequired == true ? 1 : 0,
                Required = fee.IsRequired,
                Label    = controlLabel
            };

            var currentValue = feeValues?.FirstOrDefault()?.Quantity ?? 0;

            if (usageCountRemaining.HasValue)
            {
                if (usageCountRemaining <= 0)
                {
                    numUpDown.Label  += " (none remaining)";
                    numUpDown.Maximum = currentValue;

                    // if there aren't any remaining, and the currentValue isn't counted in the used counts, disable the option
                    if (currentValue == 0)
                    {
                        // Unless this should be hidden, then set to null so it isn't added.
                        if (HideWhenNoneRemaining == true)
                        {
                            numUpDown = null;
                        }
                        else
                        {
                            numUpDown.Enabled = false;
                        }
                    }
                }
                else
                {
                    numUpDown.Label  += $" ({usageCountRemaining} remaining)";
                    numUpDown.Maximum = usageCountRemaining.Value;
                }
            }

            if (numUpDown != null && setValues && feeValues != null && feeValues.Any())
            {
                numUpDown.Value = feeValues.First().Quantity;
            }

            return(numUpDown);
        }
        public HttpResponseMessage ItensPedidoDespachado(HttpRequestMessage request, List <ItemPedidoViewModel> itenspedidoVm)
        {
            return(CreateHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;
                Usuario usuario = _usuarioRep.GetSingle(int.Parse(HttpContext.Current.User.Identity.GetUserId()));
                var fornecedor = _fornecedorRep.FirstOrDefault(x => x.PessoaId == usuario.PessoaId);
                var idPedido = itenspedidoVm?.FirstOrDefault().PedidoId;
                var pedido = _pedidoRep.FirstOrDefault(x => x.Id == idPedido);

                //Pegamos os ítens de pedidos que foram aprovados.
                var itensPedido = pedido.ItemPedidos
                                  .Where(x => x.AprovacaoFornecedor && x.Ativo && x.FornecedorId == fornecedor.Id).ToList();


                foreach (var item in itensPedido)
                {
                    item.UsuarioAlteracao = usuario;
                    item.DataEntregaFornecedor = DateTime.Now;
                    item.FlgDespacho = true;
                    _itemPedidoRep.Edit(item);
                }

                _ultilService.EnviaEmailPedido(pedido.Id, 6, usuario);

                //pega o telefone do usuário q criou o pedido
                var usuariosMembro = pedido.UsuarioCriacao;

                Sms sms = new Sms()
                {
                    UsuarioCriacao = usuario,
                    DtCriacao = DateTime.Now,
                    Numero = usuariosMembro.Telefones.Select(t => t.DddCel).FirstOrDefault() + usuariosMembro.Telefones.Select(t => t.Celular).FirstOrDefault(),
                    Mensagem = "Economiza Já-Fornecedor Despachou para Entrega itens do seu pedido " + pedido.Id,
                    Status = StatusSms.NaoEnviado,
                    OrigemSms = TipoOrigemSms.FornecedorDespachoItensPedido,
                    Ativo = true
                };

                _smsRep.Add(sms);

                _unitOfWork.Commit();

                response = request.CreateResponse(HttpStatusCode.OK, new { success = true, pedidoId = pedido.Id });

                return response;
            }));
        }
Пример #39
0
        private void UpdateTeamInfo(List <long> userIds, TeamConfig userConfig)
        {
            var sqlList = new List <string>();

            IEnumerable <BatchParameter> batchParameters = new List <BatchParameter>();

            foreach (var userId in userIds)
            {
                var userMap = GetSingle(userId);
                if (userMap != null)
                {
                    // 设置当前会员的直推数量和子会员数据为空
                    var sql =
                        $"update User_UserMap set LevelNumber=0 ,TeamNumber=0 where UserId={userId}";
                    sqlList.Add(sql);
                    var parentMap = new List <ParentMap>();
                    try {
                        parentMap = userMap.ParentMap.DeserializeJson <List <ParentMap> >();
                    } catch (Exception ex) {
                        // 组织架构图数据出错处理
                        Console.WriteLine(ex.Message);
                        userMap.ParentMap = new List <ParentMap>().ToJson(); // 默认值
                        UpdateMap(userMap.UserId, userMap.ParentMap);
                        parentMap = userMap.ParentMap.DeserializeJson <List <ParentMap> >();
                    }

                    // 更新直推会员数量
                    var parentUser = parentMap?.FirstOrDefault(r => r.ParentLevel == 1); // 直推用户Id
                    if (parentUser != null)
                    {
                        sql = $"update User_UserMap set LevelNumber=LevelNumber+1  where UserId={parentUser.UserId}";
                        sqlList.Add(sql);
                    }

                    // 更新团队有效人数的会员数
                    var teamUserIds = parentMap.Where(r => r.ParentLevel <= userConfig.TeamLevel).Select(r => r.UserId)
                                      .ToList();
                    if (teamUserIds.Count > 0)
                    {
                        sql =
                            $"update User_UserMap set  TeamNumber=TeamNumber+1 ,ChildNode=ChildNode+',{userId}' where UserId in ({teamUserIds.ToSqlString()})";
                        sqlList.Add(sql);
                    }
                }
            }

            var count = RepositoryContext.ExecuteSqlList(sqlList);
        }
Пример #40
0
        public static Image DrawBoxes(AnnotationImage image, List <ObjectClass> objectClasses)
        {
            var colorCodes = GetColorCodes();

            var items = image.BoundingBoxes;

            var originalBitmap = new Bitmap(image.FilePath);
            var bitmap         = new Bitmap(originalBitmap, ImageSize);

            originalBitmap.Dispose();

            using (var canvas = Graphics.FromImage(bitmap))
            {
                foreach (var item in items)
                {
                    var width  = item.Width * bitmap.Width;
                    var height = item.Height * bitmap.Height;
                    var x      = (item.CenterX * bitmap.Width) - (width / 2);
                    var y      = (item.CenterY * bitmap.Height) - (height / 2);

                    var color = ColorTranslator.FromHtml(colorCodes[item.ObjectIndex]);
                    using (var pen = new Pen(color, 3))
                    {
                        canvas.DrawRectangle(pen, x, y, width, height);

                        var objectClass = objectClasses?.FirstOrDefault(o => o.Id == item.ObjectIndex);
                        if (objectClass != null)
                        {
                            using (var brush = new SolidBrush(color))
                                using (var bgBrush = new SolidBrush(Color.FromArgb(128, 255, 255, 255)))
                                    using (var font = new Font("Arial", 20))
                                    {
                                        var text  = $"{objectClass.Id} {objectClass.Name}";
                                        var point = new PointF(x + 4, y + 4);
                                        var size  = canvas.MeasureString(text, font);

                                        canvas.FillRectangle(bgBrush, point.X, point.Y, size.Width, size.Height);
                                        canvas.DrawString(text, font, brush, point);
                                    }
                        }
                    }
                }

                canvas.Flush();
            }

            return(bitmap);
        }
Пример #41
0
        /// <summary>
        /// Builds the single option single quantity checkbox
        /// </summary>
        /// <param name="setValues">if set to <c>true</c> [set values].</param>
        /// <param name="controlLabel">The control label.</param>
        /// <param name="feeValues">The fee values.</param>
        /// <param name="usageCountRemaining">The usage count remaining.</param>
        /// <returns></returns>
        private Control GetFeeSingleOptionSingleQuantityControl(bool setValues, string controlLabel, List <FeeInfo> feeValues, int?usageCountRemaining)
        {
            var fee = this;
            var cb  = new RockCheckBox();

            cb.ID = "fee_" + fee.Id.ToString();
            cb.SelectedIconCssClass   = "fa fa-check-square-o fa-lg";
            cb.UnSelectedIconCssClass = "fa fa-square-o fa-lg";
            cb.Required = fee.IsRequired;
            cb.Label    = controlLabel;

            var currentValue = feeValues?.FirstOrDefault()?.Quantity ?? 0;

            if (fee.IsRequired)
            {
                cb.Checked = true;
                cb.Enabled = false;
            }
            else
            {
                if (usageCountRemaining <= 0)
                {
                    cb.Label += " (none remaining)";

                    // if there aren't any remaining, and the currentValue isn't counted in the used counts, disable the option
                    if (currentValue == 0)
                    {
                        // Unless this should be hidden, then set to null so it isn't added.
                        if (HideWhenNoneRemaining == true)
                        {
                            cb = null;
                        }
                        else
                        {
                            cb.Enabled           = false;
                            cb.FormGroupCssClass = "none-remaining text-muted disabled";
                        }
                    }
                }

                if (cb != null && setValues)
                {
                    cb.Checked = currentValue > 0;
                }
            }

            return(cb);
        }
Пример #42
0
        private bool handleMouseDragStart(InputState state)
        {
            Trace.Assert(DraggedDrawable == null, $"The {nameof(DraggedDrawable)} was not set to null by {nameof(handleMouseDragEnd)}.");
            Trace.Assert(!dragStarted, $"A {nameof(DraggedDrawable)} was already searched for. Call {nameof(handleMouseDragEnd)} first.");

            dragStarted = true;

            DraggedDrawable = mouseDownInputQueue?.FirstOrDefault(target => target.IsAlive && target.IsPresent && target.TriggerOnDragStart(state));
            if (DraggedDrawable != null)
            {
                DraggedDrawable.IsDragged = true;
                Logger.Log($"MouseDragStart handled by {DraggedDrawable}.", LoggingTarget.Runtime, LogLevel.Debug);
            }

            return(DraggedDrawable != null);
        }
Пример #43
0
    /// <summary>
    /// Get Holding at date for specific holding
    /// </summary>
    /// <param name="holdingName">Name or Ticker from Holding object</param>
    /// <param name="dateTime">Day to download data</param>
    /// <returns></returns>
    public Holding GetHoldingAt(string holdingName, DateTime dateTime)
    {
        DateTime parsedDateTime = GetDateBasedOnHoldingDefaultFormat(dateTime);

        if (parsedDateTime != DateTime.MinValue)
        {
            DownloadHoldingsIfMissing(ref parsedDateTime);

            List <Holding> holdingsAtCurrentDate = _downloadedHoldings[parsedDateTime];
            return(holdingsAtCurrentDate?.FirstOrDefault(h => h.Name.Equals(holdingName) || h.Ticker.Equals(holdingName)));
        }
        else
        {
            return(null);
        }
    }
Пример #44
0
        public static string GetPrimaryKeyName(Table thisTable, List <Table> allTables)
        {
            var ret = (!string.IsNullOrEmpty(thisTable.PrimaryKeyName))
                ? thisTable.PrimaryKeyName
                : $"{thisTable.Name}ID";

            if (string.IsNullOrEmpty(thisTable.Base))
            {
                return(ret);
            }

            var baseTable = allTables?.FirstOrDefault(t => t.Name == thisTable.Base);

            ret = GetPrimaryKeyName(baseTable, null);
            return(ret);
        }
Пример #45
0
    public Item MatchSettingsWithGameObject(GameObject go)
    {
        return(items?.FirstOrDefault(s => {
            bool nameMatch = string.IsNullOrEmpty(s.containsName) || (go.name?.Contains(s.containsName) ?? false);
            bool sceneMatch = string.IsNullOrEmpty(s.scene) || go.scene.name == s.scene;

            bool isLookingForBase = !string.IsNullOrEmpty(s.component) && s.component.Length > 1 && s.component[0] == '$';
            string className = isLookingForBase ? s.component.Substring(1) : s.component;

            bool componentMatch = string.IsNullOrEmpty(className) ||
                                  go.GetComponents <Component>().Select(c => isLookingForBase ? c?.GetType().BaseType.Name : c?.GetType().Name).Contains(className);
            bool allEmpty = string.IsNullOrEmpty(s.containsName) && string.IsNullOrEmpty(s.scene) && string.IsNullOrEmpty(s.component);

            return nameMatch && sceneMatch && componentMatch && !allEmpty;
        }));
    }
Пример #46
0
        public Model(ProjectData project, SetupData setup)
        {
            this.project = project;
            this.setup   = setup;

            boards = new List <Board>();

            loadSettings();
            libManager = new LibManager(this.project, this.setup);
            if (!openProjectPath())
            {
                parseBoardsTxt();
                selectedBoard = boards?.FirstOrDefault();
                generateFiles();
            }
        }
Пример #47
0
        /// <summary>
        /// DBリストア欄のファイル選択ボタン
        /// </summary>
        private void btnSelectDBRestoreFile_Click(object sender, EventArgs e)
        {
            ClearStatusMessage();

            var path      = txtDBRestoreFilePath.Text;
            var fileNames = new List <string>();

            if (!LimitAccessFolder ?
                !ShowOpenFileDialog(path, out fileNames, filter: "すべてのファイル(*.*)|*.*|BAKファイル(*.bak)|*.bak", initialFileName: $"{DateTime.Now:yyyyMMdd_HHmmss}.BAK") :
                !ShowRootFolderBrowserDialog(ApplicationControl.RootPath, out fileNames, FolderBrowserType.SelectFile))
            {
                return;
            }

            txtDBRestoreFilePath.Text = fileNames?.FirstOrDefault() ?? string.Empty;
        }
Пример #48
0
 public static bool Allowed(
     this List <ColumnAccessControl> columnAccessControls,
     Context context,
     SiteSettings ss,
     Column column,
     Types?type,
     List <string> mine)
 {
     return(columnAccessControls?
            .FirstOrDefault(o => o.ColumnName == column.Name)?
            .Allowed(
                context: context,
                ss: ss,
                type: type,
                mine: mine) != false);
 }
Пример #49
0
        public override string ToString()
        {
            if (_children != null && _children.Count > 0)
            {
                var values = _children.Values.Select(v => v.ToString()).Aggregate((a, b) => string.Concat(a, ", ", b));
                return(Name == null?string.Concat("{ ", values, "}") : string.Concat(Name, ": { ", values, " }"));
            }

            if (_values != null && _values.Count > 1)
            {
                return(string.Concat(Name, ": ",
                                     _values.Select(v => v?.ToString()).Aggregate((a, b) => string.Concat(a, ",", b))));
            }

            return(string.Concat(Name, ": ", _values?.FirstOrDefault()));
        }
Пример #50
0
        private IEvent GetReceivedEvent(string eventName)
        {
            List <IEvent> publishedEvents = null;

            var eventPublisher = _container.GetInstance <IEventPublisher>();

            if (eventPublisher is TestSpyEventPublisher spyEventPublisher)
            {
                publishedEvents = spyEventPublisher.ReceivedEvents;
            }

            var target = publishedEvents?.FirstOrDefault(
                e => string.CompareOrdinal(e.GetType().Name, eventName) == 0);

            return(target);
        }
Пример #51
0
        public ArtistViewModel ConvertAlbumsToArtistSingle(List <AlbumViewModel> albums)
        {
            var firstAlbum = albums?.FirstOrDefault();

            var albName = firstAlbum.AlbumTitle;

            AlbumArtCollection.SharedArtistArt.TryGetValue(firstAlbum.AlbumArtist, out var artistArt);

            return(new ArtistViewModel(_messenger)
            {
                Albums = albums?.ToObservableCollection(),
                Artist = firstAlbum?.AlbumArtist,
                AlbumCount = albums?.Count ?? 0,
                ArtistCover = artistArt
            });
        }
Пример #52
0
        /// <summary>
        /// Provides alternative translations for a word and a small number of idiomatic phrases.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="languageFrom"></param>
        /// <param name="languageTo"></param>
        /// <returns></returns>
        public async Task <LookupLanguage> GetDictionaryLookup(string text, string languageFrom, string languageTo)
        {
            if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(languageFrom) || string.IsNullOrEmpty(languageTo))
            {
                throw new ArgumentNullException("Input parameter is empty.");
            }

            // Request uri
            string languageCodeParams = $"&from={languageFrom}&to={languageTo}";
            Uri    requestUri         = new Uri($"{this.BaseServiceUrl}/dictionary/lookup?{this.API_VERSION}{languageCodeParams}");
            var    content            = new object[] { new { Text = text } };

            List <LookupLanguage> response = await HttpClientUtility.PostAsJsonAsync <List <LookupLanguage> >(requestUri, this.RequestHeaders, content);

            return(response?.FirstOrDefault());
        }
Пример #53
0
        private BaseRuleCollection GetRuleCollectionByName <BaseRuleCollection>(string ruleCollectionName, List <BaseRuleCollection> ruleCollections) where BaseRuleCollection : PSAzureFirewallBaseRuleCollection
        {
            if (string.IsNullOrEmpty(ruleCollectionName))
            {
                throw new ArgumentException($"Rule Collection name cannot be an empty string.");
            }

            var ruleCollection = ruleCollections?.FirstOrDefault(rc => ruleCollectionName.Equals(rc.Name));

            if (ruleCollection == null)
            {
                throw new ArgumentException($"Rule Collection with name {ruleCollectionName} does not exist.");
            }

            return(ruleCollection);
        }
        void setMarks(StatsStudentModel student)
        {
            if (student?.MarkList == null)
            {
                return;
            }

            var marksResults = student.MarkList?.Select(m => {
                var lab      = _currentLabsMarksList?.FirstOrDefault(l => l.LabId == m.LabId);
                var labTitle = lab == null ? null : $"{lab.ShortName}. {lab.Theme}";
                var result   = string.IsNullOrEmpty(m.Mark) ? _emptyRatingString : m.Mark;
                return(new StatsResultsPageModel(labTitle, m.Date, setCommentByRole(m.Comment), result));
            });

            Marks = new List <StatsResultsPageModel>(marksResults);
        }
Пример #55
0
        public LanguageMappingModel GetLanguageMappingModel(LanguagePair languageDirection, List <MappedLanguage> mappedLanguages)
        {
            var mapping = new InternalLanguageMapping
            {
                SourceLanguageCode = mappedLanguages?.FirstOrDefault(s => s.TradosCode.Equals(languageDirection.SourceCulture?.Name))
            };

            if (mapping.SourceLanguageCode == null)
            {
                return(null);
            }

            mapping.SourceLanguageMappings        = LanguageMappingsService.GetMTCloudLanguages(mapping.SourceLanguageCode, languageDirection.SourceCulture);
            mapping.SelectedSourceLanguageMapping = mapping.SourceLanguageMappings.FirstOrDefault(a => a.IsLocale) ?? mapping.SourceLanguageMappings[0];

            mapping.TargetLanguageCode = mappedLanguages.FirstOrDefault(s => s.TradosCode.Equals(languageDirection.TargetCulture?.Name));
            if (mapping.TargetLanguageCode == null)
            {
                return(null);
            }

            mapping.Name = $"{languageDirection.SourceCulture?.DisplayName} - {languageDirection.TargetCulture?.DisplayName}";
            mapping.SavedLanguageMappingModel = Options.LanguageMappings.FirstOrDefault(a => a.Name.Equals(mapping.Name, StringComparison.InvariantCultureIgnoreCase));

            mapping.TargetLanguageMappings        = LanguageMappingsService.GetMTCloudLanguages(mapping.TargetLanguageCode, languageDirection.TargetCulture);
            mapping.SelectedTargetLanguageMapping = mapping.TargetLanguageMappings.FirstOrDefault(a => a.IsLocale) ?? mapping.TargetLanguageMappings[0];

            // assign the selected target langauge
            mapping.SelectedTargetLanguageMapping = mapping.TargetLanguageMappings.FirstOrDefault(a => a.CodeName.Equals(mapping.SavedLanguageMappingModel?.SelectedTarget?.CodeName))
                                                    ?? mapping.SelectedTargetLanguageMapping;

            mapping.EngineModels = LanguageMappingsService.GetTranslationModels(mapping.SelectedSourceLanguageMapping, mapping.SelectedTargetLanguageMapping,
                                                                                mapping.SourceLanguageCode.TradosCode, mapping.TargetLanguageCode.TradosCode);

            if (mapping.SavedLanguageMappingModel?.SelectedModel.DisplayName != PluginResources.Message_No_model_available)
            {
                ValidateEngineExistence(mapping);
            }

            if (mapping.EngineModels.Any())
            {
                var languageMappingModel = GetLanguageMappingModel(mapping);
                return(languageMappingModel);
            }

            return(null);
        }
Пример #56
0
        /// <summary>
        /// Initializes the AppHost.
        /// Calls the <see cref="Configure"/> method.
        /// Should be called before start.
        /// </summary>
        public virtual ServiceStackHost Init()
        {
            if (Instance != null)
            {
                throw new InvalidDataException($"ServiceStackHost.Instance has already been set ({Instance.GetType().Name})");
            }

            Service.GlobalResolver = Instance = this;

            Config = HostConfig.ResetInstance();
            OnConfigLoad();

            Config.DebugMode = GetType().GetAssembly().IsDebugBuild();
            if (Config.DebugMode)
            {
                Plugins.Add(new RequestInfoFeature());
            }

            OnBeforeInit();
            ServiceController.Init();
            Configure(Container);

            ConfigurePlugins();

            List <IVirtualPathProvider> pathProviders = null;

            if (VirtualFileSources == null)
            {
                pathProviders = GetVirtualFileSources().Where(x => x != null).ToList();

                VirtualFileSources = pathProviders.Count > 1
                    ? new MultiVirtualPathProvider(this, pathProviders.ToArray())
                    : pathProviders.First();
            }

            if (VirtualFiles == null)
            {
                VirtualFiles = pathProviders?.FirstOrDefault(x => x is FileSystemVirtualPathProvider) as IVirtualFiles
                               ?? GetVirtualFileSources().FirstOrDefault(x => x is FileSystemVirtualPathProvider) as IVirtualFiles;
            }

            OnAfterInit();

            LogInitComplete();

            return(this);
        }
Пример #57
0
        /// <summary>
        /// 拼团成功,返利提现到零钱
        /// </summary>
        /// <returns></returns>
        public string ReturnMoney(PinGroup groupInfo)
        {
            string               msg = string.Empty;
            PinGoodsOrderBLL     pinGoodsOrderBLL = new PinGoodsOrderBLL();
            TransactionModel     tran             = new TransactionModel();
            string               sqlwhere         = $"state={(int)PinEnums.PinOrderState.交易成功} and paystate={(int)PinEnums.PayState.已付款} and groupid ={groupInfo.id} and isReturnMoney=0";
            List <PinGoodsOrder> orderList        = pinGoodsOrderBLL.GetList(sqlwhere);

            if (orderList == null || orderList.Count <= 0)
            {
                msg = $"拼团成功,找不到交易成功且已付款的订单 groupids:{groupInfo.id}";
                log4net.LogHelper.WriteError(GetType(), new Exception(msg));
                groupInfo.state = (int)PinEnums.GroupState.返利失败;
                tran.Add(BuildUpdateSql(groupInfo, "state"));
            }
            else
            {
                string aids = string.Join(",", orderList.Select(s => s.aid).Distinct());
                List <XcxAppAccountRelation> xcxAppAccountRelationList = XcxAppAccountRelationBLL.SingleModel.GetValuableListByIds(aids);

                foreach (var order in orderList)
                {
                    XcxAppAccountRelation xcxAppAccountRelation = xcxAppAccountRelationList?.FirstOrDefault(f => f.Id == order.aid);
                    if (xcxAppAccountRelation == null)
                    {
                        msg += $"拼享惠返利,找不到平台小程序信息 aid:{order.id}||";
                        log4net.LogHelper.WriteError(GetType(), new Exception($"拼享惠返利,找不到平台小程序信息 aid:{order.id}"));
                        continue;
                    }
                    string str = DrawCashApplyBLL.SingleModel.PxhUserApplyDrawCash(order, order.userId, xcxAppAccountRelation.AppId);
                    if (!string.IsNullOrEmpty(str))
                    {
                        msg += $"拼享惠提现错误,orderId:{order.id},{str}";
                        log4net.LogHelper.WriteError(GetType(), new Exception($"拼享惠提现错误,orderId:{order.id},{str}"));
                    }
                }
                groupInfo.state = (int)PinEnums.GroupState.已返利;
                Update(groupInfo, "state");
                // tran.Add(BuildUpdateSql(groupInfo, "state"));
            }
            //if (!ExecuteTransactionDataCorect(tran.sqlArray, tran.ParameterArray))
            //{
            //    msg = $"拼团成功返利处理失败 groupids:{groupInfo.id},sql:{JsonConvert.SerializeObject(tran.sqlArray)}";
            //    log4net.LogHelper.WriteError(GetType(), new Exception($"拼团成功返利处理失败 groupids:{groupInfo.id},sql:{JsonConvert.SerializeObject(tran.sqlArray)}"));
            //}
            return(msg);
        }
Пример #58
0
        public object GetListByCondition(string appId, int pageIndex, int pageSize, int state, int type, string value, string startDate, string endDate)
        {
            List <GroupUser> groupUserList = new List <GroupUser>();

            if (string.IsNullOrEmpty(appId))
            {
                return(groupUserList);
            }
            List <MySqlParameter> paramters = new List <MySqlParameter>();
            string sql      = $" select a.* from groupUser a left join GroupSponsor b on a.GroupSponsorId=b.id  where ";
            string sqlwhere = GetSqlwhere(paramters, appId, state, type, value, startDate, endDate);

            sql += $" {sqlwhere} order by id desc limit {(pageIndex - 1) * pageSize},{pageSize}";
            using (var dr = SqlMySql.ExecuteDataReader(connName, CommandType.Text, sql, paramters.ToArray()))
            {
                groupUserList = GetList(dr);
            }
            if (groupUserList != null && groupUserList.Count > 0)
            {
                string sponsorIds = string.Join(",", groupUserList.Select(s => s.GroupSponsorId).Distinct());
                List <GroupSponsor> groupSponsorList = GroupSponsorBLL.SingleModel.GetListByIds(sponsorIds);

                string        groupIds   = string.Join(",", groupUserList.Select(s => s.GroupId).Distinct());
                List <Groups> groupsList = GroupsBLL.SingleModel.GetListByIds(groupIds);

                foreach (GroupUser groupUser in groupUserList)
                {
                    GroupSponsor groupSponsor = groupSponsorList?.FirstOrDefault(f => f.Id == groupUser.GroupSponsorId);
                    if (groupSponsor != null)
                    {
                        groupUser.PState  = groupSponsor.State;
                        groupUser.EndDate = groupSponsor.EndDate;
                    }
                    Groups group = groupsList?.FirstOrDefault(f => f.Id == groupUser.GroupId);
                    groupUser.GroupName = group.GroupName;
                    if (groupUser.GroupSponsorId == 0)//一键成团
                    {
                        groupUser.PState = 3;
                    }
                    else if (groupUser.PState == 1 && groupUser.EndDate < DateTime.Now)//拼团过期
                    {
                        groupUser.PState = -1;
                    }
                }
            }
            return(groupUserList);
        }
Пример #59
0
 private void UpdateBookingDaysInMonthOfDay(List <BookingDayViewModel> daysInMonth)
 {
     foreach (var dayInMonth in daysInMonth)
     {
         var booking = _bookings?.FirstOrDefault(x => x.BookingStartDate == dayInMonth.Day);
         if (booking != null)
         {
             dayInMonth.IsBooked  = true;
             dayInMonth.BookingId = booking.ID;
         }
         else
         {
             dayInMonth.IsBooked  = false;
             dayInMonth.BookingId = 0;
         }
     }
 }
Пример #60
0
        /// <summary>
        /// Créer la carte avec les lignes extraites du fichier d'entrée
        /// </summary>
        /// <param name="dataLines">Lignes extraites du fichier d'entrée</param>
        /// <returns></returns>
        public static Map CreateMapWithInitialData(List <string> dataLines)
        {
            Map    map             = new Map();
            string mapSizeDataLine = dataLines?.FirstOrDefault(l => l.StartsWith("C"));

            map.InitializeCells(mapSizeDataLine);
            List <string> mountainDataLines = dataLines?.FindAll(l => l.StartsWith("M"));

            map?.InitializeMountains(mountainDataLines);
            List <string> treasureDataLines = dataLines?.FindAll(l => l.StartsWith("T"));

            map?.InitializeTreasures(treasureDataLines);
            List <string> adventurerDataLines = dataLines?.FindAll(l => l.StartsWith("A"));

            map?.InitializeAdventurers(adventurerDataLines);
            return(map);
        }