コード例 #1
0
        public static List<ClassifiedsListing> GetListings(Item item, ListingProperties props, 
			OrderType orderType)
        {
            VersatileIO.Info("Searching bp.tf classifieds for {0}...", props.ToString(item));
            List<ClassifiedsListing> all = ClassifiedsScraper.GetClassifieds(item, props);

            List<ClassifiedsListing> res = new List<ClassifiedsListing>();
            foreach (ClassifiedsListing c in all)
            {
                if (c.ItemInstance.Item.IsSkin())
                {
                    continue;
                }

                if (c.OrderType == orderType)
                {
                    res.Add(c);
                }
            }

            if (res.IsNullOrEmpty())
            {
                VersatileIO.Warning("No classifieds found for {0}.", props.ToString(item));
                return res.EmptyIfNull().ToList();
            }

            VersatileIO.Info("{0} listings found.", res.Count);
            return res;
        }
コード例 #2
0
ファイル: ReportProvider.cs プロジェクト: ZhangHanLong/gitwms
        /// <summary>
        /// 创建报表文件格式
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public int Create(ReportsEntity entity,List<ReportParamsEntity> list)
        {
            if (!entity.ReportNum.IsEmpty())
            {
                return Update(entity,list);
            }
            int line = 0;
            using (TransactionScope ts = new TransactionScope())
            {
                entity.ReportNum = entity.ReportNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReportsEntity)) : entity.ReportNum;
                entity.IncludeAll();
                line += this.Reports.Add(entity);

                if (!list.IsNullOrEmpty())
                {
                    foreach (ReportParamsEntity item in list)
                    {
                        item.ParamNum = item.ParamNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReportParamsEntity)) : item.ParamNum;
                        item.ReportNum = entity.ReportNum;
                        item.IncludeAll();
                    }
                    this.ReportParams.Add(list);
                }
                ts.Complete();
            }

            return line;
        }
コード例 #3
0
ファイル: PowerProvider.cs プロジェクト: ZhangHanLong/gitwms
        /// <summary>
        /// 给某个角色分配权限
        /// </summary>
        /// <param name="roleNum"></param>
        /// <param name="resItems"></param>
        /// <returns></returns>
        public int AllotPower(string roleNum, List<string> resItems)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                int line = 0;
                if (!resItems.IsNullOrEmpty())
                {
                    SysRelationEntity entity = new SysRelationEntity();
                    entity.Where(a => a.RoleNum == roleNum);
                    line = this.SysRelation.Delete(entity);

                    SysResourceProvider provider = new SysResourceProvider();

                    List<SysRelationEntity> list = new List<SysRelationEntity>();
                    foreach (string resNum in resItems)
                    {
                        SysResourceEntity resource = provider.GetResource(resNum);
                        short ResType = resource != null ? resource.ResType : (short)EResourceType.Page;
                        entity = new SysRelationEntity() { RoleNum = roleNum, ResNum = resNum, ResType = ResType };
                        entity.IncludeAll();
                        list.Add(entity);
                    }
                    line += this.SysRelation.Add(list);
                }
                ts.Complete();
                if (line > 0)
                {
                    CacheHelper.Remove(string.Format(CacheKey.JOOSHOW_ROLEPOWER_CACHE, roleNum));
                    CacheHelper.Remove(CacheKey.JOOSHOW_ALLOTPOWER_CACHE);
                }
                return line;
            }
        }
コード例 #4
0
        private async Task GroupSearchResults(List<SearchHint> items)
        {
            if (items.IsNullOrEmpty())
            {
                return;
            }

            await TaskEx.Run(() =>
            {
                var emptyGroups = new List<Group<SearchHint>>();

                var types = items.Select(x => x.Type).Distinct().ToList();

                types.ForEach(type => emptyGroups.Add(new Group<SearchHint>(type, new List<SearchHint>())));

                var groupedItems = (from t in items
                    group t by t.Type
                    into grp
                    orderby grp.Key
                    select new Group<SearchHint>(grp.Key, grp)).ToList();

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    SearchResults = (from g in groupedItems.Union(emptyGroups)
#if WP8
                        where g.Count > 0
#else
                                     where g.HasItems

#endif
                        orderby g.Title
                        select g).ToList();
                });
            });
        }
コード例 #5
0
            public void ReturnsFalseWhenValueHasElements()
            {
                var enumerableString = new List<string> { "a", "b" };
                var enumerableInt = new List<int> { 1, 2 };

                enumerableString.IsNullOrEmpty().Should().BeFalse();
                enumerableInt.IsNullOrEmpty().Should().BeFalse();
            }
コード例 #6
0
            public void ReturnsTrueWhenValueIsHasZeroElements()
            {
                var emptyString = new List<string>();
                var emptyInt = new List<int>();

                emptyString.IsNullOrEmpty().Should().BeTrue();
                emptyInt.IsNullOrEmpty().Should().BeTrue();
            }
コード例 #7
0
            public void WhenHasElements_ShouldReturnFalse()
            {
                var enumerable = new List<object>();
                enumerable.Add(new { });
                var actual = enumerable.IsNullOrEmpty();

                Assert.False(actual);
            }
コード例 #8
0
ファイル: TagCache.cs プロジェクト: GSerjo/ImagePocket
 public void Remove(List<TagEntity> tags)
 {
     if (tags.IsNullOrEmpty())
     {
         return;
     }
     tags.Iter(x => _tags.Remove(x.EntityId));
     _tagRepository.Remove(tags);
 }
コード例 #9
0
ファイル: DynamicExtender.cs プロジェクト: Kuick/Kuicker
        public static void CurrentBindDynamicRow(
			this DbDataReader reader, 
			List<DynamicColumn> columns,
			ref DynamicRow row)
        {
            if(null == reader) { return; }
            if(columns.IsNullOrEmpty()) { return; }

            var dbValues = new object[columns.Count];
            reader.GetValues(dbValues);

            var flatValues = new List<Any>();
            var values = new List<Any>();
            var hashCodes = new List<Any>();
            var dbNulls = new List<string>();
            var columnIndex = -1;

            foreach(var column in columns) {
                columnIndex++;
                var value = dbValues[columnIndex];
                if(DBNull.Value == value) {
                    dbNulls.Add(column.BaseColumnName);
                    value = null;
                }
                flatValues.SafeAdd(column.ColumnName, value);
                flatValues.SafeAdd(column.BaseColumnName, value);
                values.Add(column.BaseColumnName, value);

                if(null != value) {
                    int hashCode = value.GetHashCode();
                    hashCodes.Add(
                        column.BaseColumnName, hashCode
                    );
                }
            }

            row.__ReturnAny = true;
            row.__DatabaseFirst = true;
            row.__DynamicColumns = columns;
            row.__FlatValues = flatValues;
            row.__DynamicValues = values;
            row.__DynamicOriginalValues = values;
            row.__OriginalHashCodes = hashCodes;
            row.__DynamicDbNulls = dbNulls;
            row.__OriginalHashCode = row.GetHashCode();

            if(dbNulls.Any()) {
                foreach(var dbNull in dbNulls) {
                    hashCodes.Add(
                        dbNull,
                        row.__OriginalHashCode
                    );
                }
            }
            row.__OriginalHashCodes = hashCodes;
        }
コード例 #10
0
 /// <summary>
 /// Method searches for a random location on the map. Give true for a list of availible points and false for all points.
 /// </summary>
 /// <param name="searchForFreePoints"></param>
 /// <returns></returns>
 public Vector2 GetRandomLocation(bool searchForFreePoints, List<SpawnPoint> points, bool setTaken)
 {
     if (points.IsNullOrEmpty())
     {
         return Vector2.zero;
     }
     SpawnPoint temp = points[(Random.Range(0, points.Count - 1))];
     temp.taken = setTaken;
     return temp.location;
 }
コード例 #11
0
        public void IsNullOrEmpty_OneItemEnumerable_ReturnsFalse()
        {
            // arrange
            IEnumerable<object> oneItemEnumerable = new List<object> {new object()};

            // act

            // assert
            Assert.False(oneItemEnumerable.IsNullOrEmpty());
        }
コード例 #12
0
        public void IsNullOrEmpty_EmptyEnumerable_ReturnsTrue()
        {
            // arrange
            IEnumerable<object> emptyEnumerable = new List<object>();

            // act

            // assert
            Assert.True(emptyEnumerable.IsNullOrEmpty());
        }
コード例 #13
0
        public ActionResult CreatePackage(string newPkgName, string newFunctions, string newMaterials, string newCompanies)
        {
            try
            {
                Package newPkg = new Package {PackageName = newPkgName};
                StringToCollections(newPkg, newMaterials, newFunctions, newCompanies);

                //check for repeated functions in packages
                List<string> repeatedPackageNames = new List<string>();
                List<string> repeatedFunctionNames = new List<string>();
                IEnumerable<Employee_Function> tmpFunctionsInt;
                foreach (Package aPackage in DB.Packages)
                {
                    tmpFunctionsInt = aPackage.Functions.Intersect(newPkg.Functions);
                    if (tmpFunctionsInt.Any())
                    {
                        repeatedPackageNames.Add(aPackage.PackageName);
                        foreach (Employee_Function aFunction in tmpFunctionsInt)
                        {
                            if (!repeatedFunctionNames.Contains(aFunction.Label))
                            {
                                repeatedFunctionNames.Add(aFunction.Label);
                            }
                        }
                    }
                }

                if (!repeatedPackageNames.IsNullOrEmpty())
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Conflict, "Packages " + String.Join(", ", repeatedPackageNames)
                        + " already have the following functions: " + String.Join(", ", repeatedFunctionNames));
                }

                newPkg.CreatedDate = DateTime.Now;
                DB.Packages.Add(newPkg);
                DB.SaveChanges();

                Dictionary<string, string> rowInfo = new Dictionary<string, string>();
                rowInfo.Add("id", newPkg.PackageId.ToString());
                rowInfo.Add("pkgName", newPkg.PackageName);
                rowInfo.Add("materials", String.Join(" | ", newPkg.GenericMaterials.ToDictionary(mat => mat.GenericMaterialId, mat => mat.Label).Values));
                rowInfo.Add("functions", String.Join(" | ", newPkg.Functions.ToDictionary(fun => fun.FunctionId, fun => fun.Label).Values));
                rowInfo.Add("companies", newPkg.Companies.Any() ? String.Join(" | ", newPkg.Companies.ToDictionary(com => com.ID, com => com.CompanyCodeName).Values) : "All Companies");
                rowInfo.Add("deleteLink", Url.Action("Delete", "Package"));
                rowInfo.Add("editLink", Url.Action("GetPackageDetails", "Package"));

                return Json(rowInfo);
            }
            catch (Exception ex)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
コード例 #14
0
	public void GainItem(List<string> args)
	{
		if(args.IsNullOrEmpty())
			throw new ArgumentNullException("GainItem requires a list containing the item to gain, and the quantity.");

		string itemName = args[0];
		int quantity = Convert.ToInt32(args[1]);

		InventoryItem item = _itemDatabase.FindItemWithName(itemName);
		if(item != default(InventoryItem))
			_inventory.GainItem(item, quantity);

		DebugMessage("Could not find item " + itemName + " in the inventory database.", LogLevel.LogicError);
	}
コード例 #15
0
ファイル: BaseHelper.cs プロジェクト: ZhangHanLong/gitwms
 /// <summary>
 /// 获得数据类型
 /// </summary>
 /// <param name="dbType"></param>
 /// <returns></returns>
 public static string GetDataType(string dbType)
 {
     List<string> list = new List<string>()
     {
         "varchar","nvarchar","text","datetime","int"
     };
     StringBuilder sb = new StringBuilder();
     string menuTemplate = "<option value='{0}' {1}>{2}</option>";
     sb.AppendFormat(menuTemplate, "", "", "请选择");
     if (!list.IsNullOrEmpty())
     {
         foreach (string item in list)
         {
             sb.AppendFormat(menuTemplate, item, item == dbType ? "selected='selected'" : string.Empty, item);
         }
     }
     return sb.ToString();
 }
コード例 #16
0
        public static string GenerateFilterLocationRequest(List<ILocation> locations)
        {
            if (locations.IsNullOrEmpty())
            {
                return String.Empty;
            }

            StringBuilder queryBuilder = new StringBuilder();
            // queryBuilder.Append("locations=");
            for (int i = 0; i < locations.Count - 1; ++i)
            {
                queryBuilder.Append(GenerateLocationParameters(locations[i], false));
            }

            queryBuilder.Append(GenerateLocationParameters(locations[locations.Count - 1], true));

            return String.Format("locations={0}", StringFormater.UrlEncode(queryBuilder.ToString()));
        }
コード例 #17
0
        public static string GenerateFilterTrackRequest(List<string> tracks)
        {
            if (tracks.IsNullOrEmpty())
            {
                return String.Empty;
            }

            StringBuilder queryBuilder = new StringBuilder();
            queryBuilder.Append("track=");
            for (int i = 0; i < tracks.Count - 1; ++i)
            {
                queryBuilder.Append(Uri.EscapeDataString(String.Format("{0},", tracks.ElementAt(i))));
            }

            queryBuilder.Append(Uri.EscapeDataString(tracks.ElementAt(tracks.Count - 1)));

            return queryBuilder.ToString();
        }
コード例 #18
0
        public static string GenerateFilterFollowRequest(List<long?> followUserIds)
        {
            if (followUserIds.IsNullOrEmpty())
            {
                return String.Empty;
            }

            StringBuilder queryBuilder = new StringBuilder();
            queryBuilder.Append("follow=");
            for (int i = 0; i < followUserIds.Count - 1; ++i)
            {
                queryBuilder.Append(Uri.EscapeDataString(String.Format("{0},", followUserIds.ElementAt(i))));
            }

            queryBuilder.Append(followUserIds.ElementAt(followUserIds.Count - 1));

            return queryBuilder.ToString();
        }
コード例 #19
0
        /// <summary>
        /// 添加客户信息
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public int AddCustomer(CustomerEntity entity, List<CusAddressEntity> list)
        {
            entity.IncludeAll();
            int line = this.Customer.Add(entity);
            if (!list.IsNullOrEmpty())
            {
                list.ForEach(a =>
                {
                    a.CusNum = entity.CusNum;
                    a.IncludeAll();
                });
                line += this.CusAddress.Add(list);

            }
            if (line > 0)
            {
                CacheHelper.Remove(CacheKey.JOOSHOW_CUSADDRESS_CACHE);
            }
            return line;
        }
コード例 #20
0
ファイル: ImageRepository.cs プロジェクト: GSerjo/ImagePocket
        public void SaveOrUpdate(List<ImageEntity> images)
        {
            if (images.IsNullOrEmpty())
            {
                return;
            }
            foreach (ImageEntity image in images)
            {
                if (image.Tags.IsEmpty() && image.New)
                {
                    continue;
                }
                TagCache.Instance.SaveOrUpdate(image.Tags);
            }

            List<ImageEntity> forRemove = images.Where(x => x.Tags.IsEmpty() && x.New == false).ToList();
            List<ImageEntity> forAddOrUpdate = images.Where(x => x.Tags.IsNotEmpty()).ToList();

            Database.Remove(forRemove);
            Database.AddOrUpdate(forAddOrUpdate);
        }
コード例 #21
0
ファイル: BarChartProxy.cs プロジェクト: kuritka/MarketLoader
        /// <summary>
        /// Gets the chart path with ma selective period or frame
        /// </summary>     
        private string GetChartPath(string contractCode, Period periodSize, FrameSize frameSize, List<int> movingAverages)
        {
            var period = string.Empty;
            var indicatorString = string.Empty;
            switch (periodSize)
            {
                case Period.Daily: period = "DO"; break;
                case Period.Weekly: period = "WN"; break;
                case Period.Monthly: period = "MN"; break;
            }
            if (!string.IsNullOrEmpty(period)) period = "&p=" + period;
            var indexes = new[] {string.Empty, "L", "O", "M", "H", "X" };
            var selectedValue = (int) frameSize;
            var frame = "&d=" +indexes[selectedValue];

            if (!movingAverages.IsNullOrEmpty())
            {
                indicatorString += "&indicators=";
                indicatorString = movingAverages.Where(indicatorSma => indicatorSma > 1).Aggregate(indicatorString, (current, indicatorSma) => current + string.Format("SMA({0},11650);", indicatorSma));
            }
            if (string.IsNullOrEmpty(contractCode)) return string.Empty;
            var address = string.Format("http://www.barchart.com/chart.php?sym={0}&style=technical{1}{3}&sd=&ed=&size=M&log=0&t=BAR&v=2&g=1&evnt=1&late=1&sh=100{2}&txtDate=#jump", contractCode.ToUpper(), period, indicatorString,frame);
            return address;
        }
コード例 #22
0
 private bool IsEmpty(List <UrlShortenerModel> list) =>
 list.IsNullOrEmpty();
コード例 #23
0
 public virtual ISugarQueryable <T> UnionAll <T>(List <ISugarQueryable <T> > queryables) where T : class, new()
 {
     Check.Exception(queryables.IsNullOrEmpty(), "UnionAll.queryables is null ");
     return(UnionAll(queryables.ToArray()));
 }
コード例 #24
0
ファイル: ICfgExplorer.cs プロジェクト: quizcanners/Koobyky
 public int CountForInspector() => _tags.IsNullOrEmpty() ? data.Length : _tags.CountForInspector();
コード例 #25
0
 public static List <T> Clone <T>(this List <T> list) where T : ICloneable
 {
     return(list.IsNullOrEmpty() ? null : list.Where(c => c != null).Select(c => (T)c.Clone()).ToList());
 }
コード例 #26
0
        public void SendMail(List <string> iToAddressList, List <string> iCopyAddressList, string iSubject, string iMessage, List <string> iAttachmentList)
        {
            if (iToAddressList.IsNullOrEmpty())
            {
                throw new Exception("La liste des destinataires est requise");
            }

            if (iSubject.IsNullOrEmpty())
            {
                throw new Exception("Le sujet du mail est requis");
            }

            using (var client = new SmtpClient())
            {
                client.Port = SMTPPort;
                client.Host = SMTPHost;

                client.UseDefaultCredentials = false;
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                client.EnableSsl             = false;
                client.Timeout = 20000;

                using (var mail = new System.Net.Mail.MailMessage())
                {
                    mail.From = new MailAddress(SMTPFrom);
                    foreach (var toItem in iToAddressList.Enum())
                    {
                        if (!IsValidEmail(toItem))
                        {
                            throw new Exception("L'adresse '{0}' n'est pas valide".FormatString(toItem));
                        }
                        mail.To.Add(new MailAddress(toItem));
                    }

                    foreach (var ccItem in iCopyAddressList.Enum())
                    {
                        if (!IsValidEmail(ccItem))
                        {
                            throw new Exception("L'adresse '{0}' n'est pas valide".FormatString(ccItem));
                        }
                        mail.CC.Add(new MailAddress(ccItem));
                    }

                    mail.Body    = iMessage;
                    mail.Subject = iSubject;

                    mail.BodyEncoding = UTF8Encoding.UTF8;
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                    foreach (var attachmentItem in iAttachmentList.Enum())
                    {
                        var attachment = new Attachment(attachmentItem, MediaTypeNames.Application.Octet);
                        ContentDisposition disposition = attachment.ContentDisposition;
                        disposition.CreationDate     = File.GetCreationTime(attachmentItem);
                        disposition.ModificationDate = File.GetLastWriteTime(attachmentItem);
                        disposition.ReadDate         = File.GetLastAccessTime(attachmentItem);
                        disposition.FileName         = Path.GetFileName(attachmentItem);
                        disposition.Size             = new FileInfo(attachmentItem).Length;
                        disposition.DispositionType  = DispositionTypeNames.Attachment;
                        mail.Attachments.Add(attachment);
                    }

                    client.Send(mail);
                }
            }
        }
コード例 #27
0
        public ActionResult Create([ModelBinder(typeof(JsonBinder <List <ReturnDetailEntity> >))] List <ReturnDetailEntity> list)
        {
            string   OrderNum      = WebUtil.GetFormValue <string>("OrderNum", string.Empty);
            int      ReturnType    = WebUtil.GetFormValue <int>("ReturnType", (int)EReturnType.Sell);
            int      ProductType   = WebUtil.GetFormValue <int>("ProductType", (int)EProductType.Goods);
            string   ContractOrder = WebUtil.GetFormValue <string>("ContractOrder", string.Empty);
            string   CusNum        = WebUtil.GetFormValue <string>("CusNum", string.Empty);
            string   CusName       = WebUtil.GetFormValue <string>("CusName", string.Empty);
            string   Contact       = WebUtil.GetFormValue <string>("Contact", string.Empty);
            string   Phone         = WebUtil.GetFormValue <string>("Phone", string.Empty);
            string   Address       = WebUtil.GetFormValue <string>("Address", string.Empty);
            DateTime CreateTime    = WebUtil.GetFormValue <DateTime>("CreateTime", DateTime.Now);
            string   Remark        = WebUtil.GetFormValue <string>("Remark", string.Empty);

            ReturnOrderEntity entity = new ReturnOrderEntity();

            entity.OrderNum = OrderNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReturnOrderEntity)) : OrderNum;
            List <OutStoDetailEntity> listOrder = Session[CacheKey.TEMPDATE_CACHE_RETURNPRODUCTDETAIL] as List <OutStoDetailEntity>;
            string StorageNum = ResourceManager.GetSettingEntity("STORE_DEFAULT_PRODUCT").Value;

            if (!list.IsNullOrEmpty() && !listOrder.IsNullOrEmpty())
            {
                list.ForEach(a =>
                {
                    OutStoDetailEntity detail = listOrder.SingleOrDefault(b => b.ProductNum == a.ProductNum && b.BarCode == a.BarCode && b.LocalNum == a.LocalNum && b.StorageNum == StorageNum && b.BatchNum == a.BatchNum);
                    if (detail != null)
                    {
                        a.ProductName   = detail.ProductName;
                        a.BatchNum      = detail.BatchNum;
                        a.OutPrice      = detail.OutPrice;
                        a.Num           = detail.Num;
                        a.Amount        = detail.Amount;
                        a.BackAmount    = a.OutPrice * a.BackNum;
                        a.CreateTime    = DateTime.Now;
                        a.StorageNum    = StorageNum;
                        a.ContractOrder = ContractOrder;
                    }
                    a.SnNum = SequenceProvider.GetSequence(typeof(ReturnDetailEntity));
                });
                entity.ReturnType    = ReturnType;
                entity.ProductType   = ProductType;
                entity.CusNum        = CusNum;
                entity.CusName       = CusName;
                entity.Phone         = Phone;
                entity.Contact       = Contact;
                entity.Address       = Address;
                entity.Num           = list.Sum(a => a.BackNum);
                entity.Amount        = list.Sum(a => a.BackAmount);
                entity.Status        = (int)EAudite.Wait;
                entity.IsDelete      = (int)EIsDelete.NotDelete;
                entity.CreateTime    = CreateTime;
                entity.CreateUser    = this.LoginUser.UserCode;
                entity.OperateType   = (int)EOpType.PC;
                entity.EquipmentNum  = string.Empty;
                entity.EquipmentCode = string.Empty;
                entity.Remark        = Remark;
                entity.ContractOrder = ContractOrder;
                entity.StorageNum    = this.DefaultStore;

                Bill <ReturnOrderEntity, ReturnDetailEntity> bill = new ReturnOrder();
                //如果单号不存在则为创建
                if (OrderNum.IsEmpty())
                {
                    string returnValue = bill.Create(entity, list);
                    if (returnValue == EnumHelper.GetEnumDesc <EReturnStatus>(EReturnStatus.Success))
                    {
                        this.ReturnJson.AddProperty("d", "1000");
                    }
                    else
                    {
                        this.ReturnJson.AddProperty("d", "1001");
                    }
                }
                else
                {
                    string returnValue = bill.EditOrder(entity, list);
                    this.ReturnJson.AddProperty("d", returnValue);
                }
            }
            else
            {
                this.ReturnJson.AddProperty("d", "1005");
            }
            return(Content(this.ReturnJson.ToString()));
        }
コード例 #28
0
ファイル: ImportProcess.cs プロジェクト: haoas/CRMTPE
 private static void UpdatePhone(int contactId, List<string> mobiles)
 {
     if (mobiles.IsNullOrEmpty()) return;
     var listPhones = PhoneRepository.GetByContact(contactId) ?? new List<PhoneInfo>();
     foreach (var mobile in mobiles
         .Where(c => !c.IsStringNullOrEmpty())
         .Where(c => !listPhones.Exists(p => p.PhoneNumber.Equals(c))))
     {
         if (!listPhones.Exists(c => c.PhoneType.ToInt32() == (int)PhoneType.HomePhone))
         {
             var phone = new PhoneInfo
                             {
                                 IsPrimary = 0,
                                 PhoneNumber = mobile,
                                 ContactId = contactId,
                                 PhoneType = ((int)PhoneType.HomePhone).ToString(),
                             };
             PhoneRepository.Create(phone);
             listPhones.Add(phone);
         }
         if (!listPhones.Exists(c => c.PhoneType.ToInt32() == (int)PhoneType.MobilePhone))
         {
             var phone = new PhoneInfo
             {
                 IsPrimary = 0,
                 PhoneNumber = mobile,
                 ContactId = contactId,
                 PhoneType = ((int)PhoneType.MobilePhone).ToString(),
             };
             PhoneRepository.Create(phone);
             listPhones.Add(phone);
         }
         if (!listPhones.Exists(c => c.PhoneType.ToInt32() == (int)PhoneType.Tel))
         {
             var phone = new PhoneInfo
             {
                 IsPrimary = 0,
                 PhoneNumber = mobile,
                 ContactId = contactId,
                 PhoneType = ((int)PhoneType.Tel).ToString(),
             };
             PhoneRepository.Create(phone);
             listPhones.Add(phone);
         }
     }
 }
コード例 #29
0
        // ورودی این متد بایستی نقاط تمیز شده باشد
        public static LogisticGeometrySimplificationTrainingData <T> GenerateTrainingData(
            List <T> originalPoints,
            List <T> simplifiedPoints,
            bool isRingMode,
            //int zoomLevel,
            List <LogisticGeometrySimplificationFeatures> features,
            Func <T, T> toScreenMap = null)
        {
            if (originalPoints.IsNullOrEmpty() || simplifiedPoints.IsNullOrEmpty())
            {
                return(new LogisticGeometrySimplificationTrainingData <T>());
            }

            List <LogisticGeometrySimplificationParameters <T> > parameters = new List <LogisticGeometrySimplificationParameters <T> >();

            // ایجاد رکوردهای مثبت برای فایل ساده شده
            //for (int i = 0; i < simplifiedPoints.Count - 2; i++)
            //{
            //    parameters.Add(new LogisticGeometrySimplificationParameters(simplifiedPoints[i], simplifiedPoints[i + 1], simplifiedPoints[i + 2], /*zoomLevel,*/ toScreenMap)
            //    {
            //        IsRetained = true
            //    });
            //}

            // تعیین ارتباط بین اندکس نقطه در لیست
            // اصلی و اندکس نقطه در لیست ساده شده
            Dictionary <int, int> indexMap = new Dictionary <int, int>();

            for (int simplifiedIndex = 0; simplifiedIndex < simplifiedPoints.Count; simplifiedIndex++)
            {
                var currentPoint = simplifiedPoints[simplifiedIndex];

                for (int originalIndex = simplifiedIndex; originalIndex < originalPoints.Count; originalIndex++)
                {
                    if (currentPoint.DistanceTo(originalPoints[originalIndex]) < 0.0000001)
                    {
                        indexMap.Add(simplifiedIndex, originalIndex);

                        break;
                    }
                }
            }

            if (indexMap.Count != simplifiedPoints.Count)
            {
                throw new NotImplementedException("خطا در شناسایی معادل نقطه عارضه ساده شده در عارضه اصلی");
            }

            var startIndex  = indexMap.First().Value;
            var middleIndex = originalPoints.Count <= startIndex + 1 ? 0 : startIndex + 1;
            var lastIndex   = originalPoints.Count <= middleIndex + 1 ? 0 : middleIndex + 1;

            do
            {
                if (!isRingMode && lastIndex <= startIndex)
                {
                    break;
                }

                // نقطه حفظ شده
                if (indexMap.ContainsValue(middleIndex))
                {
                    parameters.Add(new LogisticGeometrySimplificationParameters <T>(
                                       originalPoints[startIndex],
                                       originalPoints[middleIndex],
                                       originalPoints[lastIndex],
                                       /*zoomLevel,*/
                                       features,
                                       toScreenMap)
                    {
                        IsRetained = true,
                    });

                    startIndex = middleIndex;
                }
                // نقطه حذف نشده
                else
                {
                    parameters.Add(new LogisticGeometrySimplificationParameters <T>(
                                       originalPoints[startIndex],
                                       originalPoints[middleIndex],
                                       originalPoints[lastIndex],
                                       /*zoomLevel,*/
                                       features,
                                       toScreenMap)
                    {
                        IsRetained = false,
                    });
                }

                middleIndex = lastIndex;
                lastIndex   = originalPoints.Count <= middleIndex + 1 ? 0 : middleIndex + 1;
            } while (middleIndex != indexMap.First().Value);

            return(new LogisticGeometrySimplificationTrainingData <T>()
            {
                Records = parameters
            });
        }
コード例 #30
0
		/// <summary>
		/// Removes the specified nodes from the tree view.
		/// </summary>
		/// <remarks>
		/// The user is asked to confirm the removal.
		/// </remarks>
		/// <param name="p_lstNodes">The nodes to remove.</param>
		public void RemoveNodes(IList<TreeNode> p_lstNodes)
		{
			//make a copy in case removing nodes changes the given p_lstNodes
			List<TreeNode> lstNodesToRemove = new List<TreeNode>(p_lstNodes);
			if (lstNodesToRemove.IsNullOrEmpty())
				return;
			string strMessage = null;
			if (lstNodesToRemove.Count == 1)
				strMessage = String.Format("Are you sure you want to removed '{0}?'", lstNodesToRemove[0].Text);
			else
				strMessage = String.Format("Are you sure you want to removed the {0} selected nodes?", lstNodesToRemove.Count);
			if (MessageBox.Show(this.FindForm(), strMessage, "Confirm Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
			{
				FileSystemTreeNode tndNode = null;
				for (Int32 i = lstNodesToRemove.Count - 1; i >= 0; i--)
				{
					tndNode = (FileSystemTreeNode)lstNodesToRemove[i];
					tndNode.Remove();
					OnNodeRemoved(new NodesChangedEventArgs(tndNode));
				}
			}
		}
コード例 #31
0
 public void IsNullOrEmptyTest()
 {
     List<int> Temp = new List<int>();
     Assert.True(Temp.IsNullOrEmpty());
     Temp = null;
     Assert.True(Temp.IsNullOrEmpty());
     Temp = new int[] { 1, 2, 3 }.ToList();
     Assert.False(Temp.IsNullOrEmpty());
 }
コード例 #32
0
        private static bool IsNullCodeList(List<aim4_dotnet.iso_21090.CD> codeList)
        {
            if (codeList.IsNullOrEmpty())
                return false;

            return AimTemplateTreeUtilities.IsNullCodeSequence(ToStandardCodeSequence(codeList.First()));
        }
コード例 #33
0
        public void null_or_empty_on_null()
        {
            List <int> test = null;

            Assert.True(test.IsNullOrEmpty());
        }
コード例 #34
0
 public static T TryTake <T>(this List <T> list, int index)
 {
     if (list.IsNullOrEmpty() || list.Count <= index)
     {
         return(default);
コード例 #35
0
        public bool GetResponse(Uri requestUri, Stream stream)
        {
            var query = new RequestQuery(requestUri);

            if (query.IsValid)
            {
                try
                {
                    DeviceDefinition           device     = null;
                    List <ComponentDefinition> components = null;
                    List <DataItemDefinition>  dataItems  = null;

                    var stpw = new System.Diagnostics.Stopwatch();
                    stpw.Start();

                    // Get Current Agent
                    var connection = Database.ReadConnection(query.DeviceId);
                    if (connection != null)
                    {
                        var agent = Database.ReadAgent(query.DeviceId);
                        if (agent != null)
                        {
                            // Get Device
                            device = Database.ReadDevice(query.DeviceId, agent.InstanceId);

                            if (!query.DeviceOnly)
                            {
                                // Get Components
                                components = Database.ReadComponents(query.DeviceId, agent.InstanceId);

                                // Get Data Items
                                dataItems = Database.ReadDataItems(query.DeviceId, agent.InstanceId);
                            }
                        }

                        stpw.Stop();
                        Console.WriteLine(stpw.ElapsedMilliseconds + "ms");

                        if (device != null)
                        {
                            // Use a converter to actually convert Defintions to DataItem objects.
                            // This is because we don't want to output the Defintion properties to JSON (as they are redundant)
                            var converter = new Converter <DataItemDefinition, DataItem>(ConvertDataItem);

                            // Create new Item
                            var deviceItem = new DeviceItem(device, connection, agent);

                            if (!components.IsNullOrEmpty() && !dataItems.IsNullOrEmpty())
                            {
                                deviceItem.Add(dataItems.FindAll(o => o.ParentId == deviceItem.Id).ConvertAll(converter));

                                var componentItems = new List <ComponentItem>();

                                foreach (var component in components)
                                {
                                    var item = new ComponentItem(component);
                                    item.Add(dataItems.FindAll(o => o.ParentId == component.Id).ConvertAll(converter));

                                    // Add any child components
                                    foreach (var child in componentItems.FindAll(o => o.ParentId == component.Id))
                                    {
                                        componentItems.Remove(child);
                                        item.Add(child);
                                    }

                                    // Add to parent component
                                    var parent = componentItems.Find(o => o.Id == component.ParentId);
                                    if (parent != null)
                                    {
                                        parent.Add(item);
                                    }
                                    else
                                    {
                                        componentItems.Add(item);
                                    }
                                }

                                deviceItem.Add(componentItems);
                            }

                            // Write DeviceItem JSON to stream
                            string json  = Json.Convert.ToJson(deviceItem, true);
                            var    bytes = Encoding.UTF8.GetBytes(json);
                            stream.Write(bytes, 0, bytes.Length);
                        }
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    log.Trace(ex);
                }
            }

            return(false);
        }
コード例 #36
0
        public void GenerateHafAssessment(long eventId)
        {
            try
            {
                var eventLogger = _logManager.GetLogger("HealthAssessmentFormGenerator_" + eventId);
                eventLogger.Info("Generating HAF for Event Id: " + eventId);
                _pdfGenerator.PaperSize = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.PaperSize);

                try
                {
                    var eventCustomers = _eventCustomerRepository.GetbyEventId(eventId);

                    if (eventCustomers != null && eventCustomers.Any())
                    {
                        eventCustomers = eventCustomers.Where(ec => ec.AppointmentId.HasValue).ToArray();

                        if (eventCustomers != null && eventCustomers.Any())
                        {
                            eventLogger.Info("found EventCustomers Count: " + eventCustomers.Count());

                            var mediaLocation = _mediaRepository.GetMedicalHistoryMediaLocation(eventId);

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(mediaLocation.PhysicalPath);

                            DirectoryOperationsHelper.DeleteFiles(mediaLocation.PhysicalPath);
                            var eventData = _eventRepository.GetById(eventId);
                            var account   = _corporateAccountRepository.GetbyEventId(eventId);

                            var corporateSurveyPdf = "";
                            if (account != null && account.CaptureSurvey)
                            {
                                if (account.SurveyPdfFileId > 0)
                                {
                                    var surveyPdf = _fileRepository.GetById(account.SurveyPdfFileId);
                                    if (surveyPdf != null)
                                    {
                                        corporateSurveyPdf = _mediaRepository.GetCorporateSurveyPdfFolderLocation().PhysicalPath + surveyPdf.Path;
                                    }
                                }
                            }

                            var corporateCheckListPdf = "";
                            if (account != null && account.PrintCheckList && account.CheckListFileId > 0 && eventData.EventDate >= _settings.ChecklistChangeDate)
                            {
                                var checkListFilePdf = _fileRepository.GetById(account.CheckListFileId);
                                if (checkListFilePdf != null)
                                {
                                    corporateCheckListPdf = _mediaRepository.GetCorporateCheckListPdfFolderLocation().PhysicalPath + checkListFilePdf.Path;
                                }
                            }

                            var filesFocAttestation    = new[] { "" };
                            var mediaLocFocAttestation = _mediaRepository.GetUnlockEventsParseLocation(eventId);

                            if (account != null && account.Id == _settings.HcpNvAccountId)
                            {
                                if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath))
                                {
                                    filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.*");
                                    filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray();
                                }
                            }
                            else
                            {
                                if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath))
                                {
                                    filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.pdf");
                                    filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray();
                                }
                            }

                            var tempMediaLocation = _mediaRepository.GetTempMediaFileLocation();
                            var customers         = _customerRepository.GetCustomers(eventCustomers.Select(ec => ec.CustomerId).ToArray());

                            int index = 0;
                            foreach (var eventCustomer in eventCustomers)
                            {
                                eventLogger.Info(string.Format("Generating HAF for Event Id: {0} and Customer Id : {1} ", eventId, eventCustomer.CustomerId));
                                string url                = _settings.HealthAssessmentFormUrl + string.Format("?eventId={0}&customerId={1}&LoadLayout=false&showKynEditModel=true&bulkPrint=true&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid());
                                var    customer           = customers.First(c => c.CustomerId == eventCustomer.CustomerId);
                                var    focAttestationFile = string.Empty;

                                if (account != null)
                                {
                                    var questFile = Path.Combine(_mediaRepository.GetQuestUploadMediaFileLocation().PhysicalPath, account.Tag + "_Quest.pdf");

                                    if (account.Id == _settings.WellmedAccountId || account.Id == _settings.WellmedTxAccountId)
                                    {
                                        var memberId = string.IsNullOrEmpty(customer.InsuranceId) ? "" : customer.InsuranceId.ToLower().Trim();
                                        focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == memberId);
                                        eventLogger.Info(string.Format("focAttestationFile : {0}", focAttestationFile));

                                        var _files = new List <string>();

                                        if (!string.IsNullOrEmpty(focAttestationFile) && DirectoryOperationsHelper.IsFileExist(focAttestationFile))
                                        {
                                            eventLogger.Info(string.Format("focAttestationFile : First if {0}", focAttestationFile));
                                            _files.Add(focAttestationFile);
                                        }

                                        if (DirectoryOperationsHelper.IsFileExist(questFile))
                                        {
                                            eventLogger.Info(string.Format("focAttestationFile : 2nd if {0}", questFile));
                                            _files.Add(questFile);
                                        }

                                        if (!_files.IsNullOrEmpty())
                                        {
                                            if (_files.Count() > 1)
                                            {
                                                eventLogger.Info(string.Format("focAttestationFile : File Count {0}", _files.Count()));
                                                focAttestationFile = GetFocAttestationFileMerge(_files, focAttestationFile, eventLogger);
                                            }
                                            else
                                            {
                                                eventLogger.Info(string.Format("focAttestationFile : File[0] {0}", _files[0]));
                                                focAttestationFile = _files[0];
                                                eventLogger.Info(string.Format("focAttestationFile : Last {0}", focAttestationFile));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        focAttestationFile = GetFocAttestationFileForMht(filesFocAttestation, customer.CustomerId.ToString(), eventLogger);
                                    }
                                    //else if (account.Id == _settings.MolinaAccountId)
                                    //{
                                    //    var hicn = string.IsNullOrEmpty(customer.Hicn) ? "" : customer.Hicn.ToLower().Trim();
                                    //    focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == hicn);
                                    //}
                                    //else if (account.Id == _settings.HcpNvAccountId)
                                    //{

                                    //}
                                    //else if (_settings.MonarchAccountIds.Contains(account.Id))
                                    //{
                                    //    var gmpi = string.IsNullOrEmpty(customer.AdditionalField4) ? "" : customer.AdditionalField4.ToLower().Trim();

                                    //    if (!string.IsNullOrEmpty(gmpi))
                                    //    {
                                    //        focAttestationFile = GetFocAttestationFile(filesFocAttestation, "_" + gmpi.ToLower(), focAttestationFile, eventLogger);
                                    //    }
                                    //}
                                    //else if (account.Id == _settings.AppleCareAccountId)
                                    //{
                                    //    focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger);
                                    //}
                                    //else if (account.Id == _settings.NammAccountId)
                                    //{
                                    //    focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger);
                                    //}
                                }

                                var focAttestationFilePath = string.Empty;
                                eventLogger.Info("focAttestationFile: " + focAttestationFile);

                                if (!string.IsNullOrEmpty(focAttestationFile))
                                {
                                    focAttestationFilePath = focAttestationFile;
                                }

                                var annualComprehensiveExamPdf  = string.Empty;
                                var memberInformationProfilePdf = string.Empty;

                                if (!string.IsNullOrEmpty(customer.Hicn))
                                {
                                    var fileNamePattern = customer.Hicn + (customer.Name != null ? "_" + customer.Name.LastName + "_" + customer.Name.FirstName : "");
                                    if (account != null && account.PrintAceForm)
                                    {
                                        try
                                        {
                                            var mediaLocationForAce = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "ACE");
                                            var aceFiles            = DirectoryOperationsHelper.GetFiles(mediaLocationForAce.PhysicalPath, fileNamePattern + "*_ACE.pdf");
                                            if (aceFiles.Any())
                                            {
                                                annualComprehensiveExamPdf = _pdfGenerator.ExtractPdfPagesFromEnd(aceFiles.First(), tempMediaLocation.PhysicalPath + "Ripped_" + customer.Hicn + "_ACE.pdf", NumberOfPagesToExtractFromAcePdf);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            eventLogger.Error(string.Format("Unable to attach ACE form to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message));
                                        }
                                    }

                                    if (account != null && account.PrintMipForm)
                                    {
                                        try
                                        {
                                            var mediaLocationForMip = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "MIP");
                                            var mipFiles            = DirectoryOperationsHelper.GetFiles(mediaLocationForMip.PhysicalPath, fileNamePattern + "*_MIP.pdf");
                                            if (mipFiles.Any())
                                            {
                                                memberInformationProfilePdf = mipFiles.First();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            eventLogger.Error(string.Format("Unable to attach MIP to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message));
                                        }
                                    }
                                }
                                var consentHeaderWithChecklistpdf = string.Empty;

                                if (!string.IsNullOrWhiteSpace(corporateCheckListPdf) && DirectoryOperationsHelper.IsFileExist(corporateCheckListPdf))
                                {
                                    var    tempPath         = _mediaRepository.GetTempMediaFileLocation();
                                    var    consentHeader    = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf");
                                    string consentHeaderUrl = _settings.ConsentHeaderFormUrl + string.Format("?eventId={0}&customerId={1}&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid());
                                    _pdfGenerator.GeneratePdf(consentHeaderUrl, consentHeader);

                                    consentHeaderWithChecklistpdf = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf");
                                    var consentHeaderWithChecklistpdfArray = new string[] { consentHeader, corporateCheckListPdf };
                                    _pdfGenerator.Merge(consentHeaderWithChecklistpdf, consentHeaderWithChecklistpdfArray);
                                }


                                _pdfGenerator.GeneratePdfForHaf(url, mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf", corporateSurveyPdf, "", focAttestationFilePath, consentHeaderWithChecklistpdf,
                                                                annualComprehensiveExamPdf, memberInformationProfilePdf);
                            }

                            eventLogger.Info("Merging HAF for Event Id: " + eventId);
                            _pdfGenerator.GetPdffilesfromLocationandMergeintoOne(mediaLocation.PhysicalPath, mediaLocation.PhysicalPath + "Event_" + eventId + ".pdf");
                            _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);

                            index = 0;

                            foreach (var eventCustomer in eventCustomers)
                            {
                                DirectoryOperationsHelper.Delete(mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf");
                            }
                        }
                        else
                        {
                            eventLogger.Info("No customer found with appointment attached with this event. Merging HAF for Event Id: " + eventId);
                            _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);
                        }
                    }
                    else
                    {
                        eventLogger.Info("No customer found attached with this event. Merging HAF for Event Id: " + eventId);
                        _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);
                    }
                }
                catch (Exception ex)
                {
                    _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending);
                    eventLogger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
                }
            }
            catch (Exception ex)
            {
                _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending);
                _logger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
            }
        }
コード例 #37
0
    void Start()
    {
        string playerProfilesCsv = SceneData.SelectedPlayerProfiles.Select(it => it.Name).ToCsv();

        Debug.Log($"{playerProfilesCsv} start (or continue) singing of {SongMeta.Title} at {SceneData.PositionInSongInMillis} ms.");

        // Handle players
        List <PlayerProfile> playerProfilesWithoutMic = new List <PlayerProfile>();

        foreach (PlayerProfile playerProfile in SceneData.SelectedPlayerProfiles)
        {
            SceneData.PlayerProfileToMicProfileMap.TryGetValue(playerProfile, out MicProfile micProfile);
            if (micProfile == null)
            {
                playerProfilesWithoutMic.Add(playerProfile);
            }
            CreatePlayerController(playerProfile, micProfile);
        }

        // Handle dummy singers
        if (Application.isEditor)
        {
            DummySingers = FindObjectsOfType <AbstractDummySinger>().ToList();
            foreach (AbstractDummySinger dummySinger in DummySingers)
            {
                if (dummySinger.playerIndexToSimulate < PlayerControllers.Count)
                {
                    dummySinger.SetPlayerController(PlayerControllers[dummySinger.playerIndexToSimulate]);
                }
                else
                {
                    Debug.LogWarning("DummySinger cannot simulate player with index " + dummySinger.playerIndexToSimulate);
                    dummySinger.gameObject.SetActive(false);
                }
            }
        }

        // Create warning about missing microphones
        string playerNameCsv = string.Join(",", playerProfilesWithoutMic.Select(it => it.Name).ToList());

        if (!playerProfilesWithoutMic.IsNullOrEmpty())
        {
            UiManager.Instance.CreateWarningDialog("Missing microphones", $"No microphone for player(s) {playerNameCsv}");
        }

        // Associate LyricsDisplayer with one of the (duett) players
        if (!PlayerControllers.IsNullOrEmpty())
        {
            LyricsDisplayer lyricsDisplayer = FindObjectOfType <LyricsDisplayer>();
            PlayerControllers[0].LyricsDisplayer = lyricsDisplayer;
        }

        //Save information about the song being started into stats
        Statistics stats = StatsManager.Instance.Statistics;

        stats.RecordSongStarted(SongMeta);

        songVideoPlayer.Init(SongMeta, songAudioPlayer);

        StartCoroutine(StartMusicAndVideo());
    }
コード例 #38
0
ファイル: ContextMethods.cs プロジェクト: hlxcoo2007/NetCore
        public KeyValuePair <string, SugarParameter[]> ConditionalModelToSql(List <IConditionalModel> models, int beginIndex = 0)
        {
            if (models.IsNullOrEmpty())
            {
                return(new KeyValuePair <string, SugarParameter[]>());
            }
            StringBuilder         builder    = new StringBuilder();
            List <SugarParameter> parameters = new List <SugarParameter>();
            var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig);

            foreach (var model in models)
            {
                if (model is ConditionalModel)
                {
                    var item  = model as ConditionalModel;
                    var index = models.IndexOf(item) + beginIndex;
                    var type  = index == 0 ? "" : "AND";
                    if (beginIndex > 0)
                    {
                        type = null;
                    }
                    string temp          = " {0} {1} {2} {3}  ";
                    string parameterName = string.Format("{0}Conditional{1}{2}", sqlBuilder.SqlParameterKeyWord, item.FieldName, index);
                    if (parameterName.Contains("."))
                    {
                        parameterName = parameterName.Replace(".", "_");
                    }
                    switch (item.ConditionalType)
                    {
                    case ConditionalType.Equal:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "=", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.Like:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName);
                        parameters.Add(new SugarParameter(parameterName, "%" + item.FieldValue + "%"));
                        break;

                    case ConditionalType.GreaterThan:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.GreaterThanOrEqual:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">=", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.LessThan:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.LessThanOrEqual:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<=", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.In:
                        if (item.FieldValue == null)
                        {
                            item.FieldValue = string.Empty;
                        }
                        var inValue1 = ("(" + item.FieldValue.Split(',').ToJoinSqlInVals() + ")");
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "IN", inValue1);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.NotIn:
                        if (item.FieldValue == null)
                        {
                            item.FieldValue = string.Empty;
                        }
                        var inValue2 = ("(" + item.FieldValue.Split(',').ToJoinSqlInVals() + ")");
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "NOT IN", inValue2);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.LikeLeft:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue + "%"));
                        break;

                    case ConditionalType.NoLike:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), " NOT LIKE", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue + "%"));
                        break;

                    case ConditionalType.LikeRight:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName);
                        parameters.Add(new SugarParameter(parameterName, "%" + item.FieldValue));
                        break;

                    case ConditionalType.NoEqual:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<>", parameterName);
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.IsNullOrEmpty:
                        builder.AppendFormat("{0} ({1}) OR ({2}) ", type, item.FieldName.ToSqlFilter() + " IS NULL ", item.FieldName.ToSqlFilter() + " = '' ");
                        parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        break;

                    case ConditionalType.IsNot:
                        if (item.FieldValue == null)
                        {
                            builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), " IS NOT ", "NULL");
                        }
                        else
                        {
                            builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<>", parameterName);
                            parameters.Add(new SugarParameter(parameterName, item.FieldValue));
                        }
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    var item = model as ConditionalCollections;
                    if (item != null)
                    {
                        foreach (var con in item.ConditionalList)
                        {
                            var index   = item.ConditionalList.IndexOf(con);
                            var isFirst = index == 0;
                            var isLast  = index == (item.ConditionalList.Count - 1);
                            if (isFirst)
                            {
                                builder.AppendFormat(" {0} ( ", con.Key.ToString().ToUpper());
                            }
                            List <IConditionalModel> conModels = new List <IConditionalModel>();
                            conModels.Add(con.Value);
                            var childSqlInfo = ConditionalModelToSql(conModels, 1000 * (1 + index));
                            if (!isFirst)
                            {
                                builder.AppendFormat(" {0} ", con.Key.ToString().ToUpper());
                            }
                            builder.Append(childSqlInfo.Key);
                            parameters.AddRange(childSqlInfo.Value);
                            if (isLast)
                            {
                                builder.Append(" ) ");
                            }
                            else
                            {
                            }
                        }
                    }
                }
            }
            return(new KeyValuePair <string, SugarParameter[]>(builder.ToString(), parameters.ToArray()));
        }
コード例 #39
0
        private string GetFocAttestationFileForMht(IEnumerable <string> filesFocAttestation, string selector, ILogger eventLogger)
        {
            var attestationfiles = filesFocAttestation.Where(fsd => fsd.ToLower().Contains(selector) && fsd.ToLower().EndsWith(".mht"));

            var tempLocation  = _mediaRepository.GetTempMediaFileLocation();
            var pinkFlagFiles = string.Empty;

            if (!attestationfiles.IsNullOrEmpty())
            {
                if (attestationfiles.Count() == 1)
                {
                    var filePath = Path.Combine(tempLocation.PhysicalPath, Guid.NewGuid() + ".pdf");

                    ConvertMhtToPdf(attestationfiles.First(), filePath, eventLogger);
                    if (DirectoryOperationsHelper.IsFileExist(filePath))
                    {
                        pinkFlagFiles = filePath;
                    }
                }
                else if (attestationfiles.Count() > 1)
                {
                    try
                    {
                        var    tempAttestationList = new List <string>();
                        string tempFileName        = string.Empty;

                        foreach (var attestationfile in attestationfiles)
                        {
                            tempFileName = tempLocation.PhysicalPath + Guid.NewGuid() + ".pdf";
                            ConvertMhtToPdf(attestationfile, tempFileName, eventLogger);

                            if (DirectoryOperationsHelper.IsFileExist(tempFileName))
                            {
                                tempAttestationList.Add(tempFileName);
                            }
                        }

                        tempFileName = tempLocation.PhysicalPath + Guid.NewGuid() + ".pdf";

                        _pdfGenerator.Merge(tempFileName, tempAttestationList);

                        pinkFlagFiles = tempFileName;
                    }
                    catch (Exception ex)
                    {
                        eventLogger.Error("some Error occurred while merging Attestation form");
                        eventLogger.Error("Message: " + ex.Message);
                        eventLogger.Error("Stack Trace: " + ex.StackTrace);
                    }
                }
            }

            attestationfiles = filesFocAttestation.Where(fsd => fsd.ToLower().Contains(selector) && fsd.ToLower().EndsWith(".pdf"));
            var pirFiles = string.Empty;

            if (!attestationfiles.IsNullOrEmpty())
            {
                pirFiles = GetFocAttestationFile(attestationfiles, selector, pirFiles, eventLogger);
            }

            if (string.IsNullOrEmpty(pinkFlagFiles) && string.IsNullOrEmpty(pirFiles))
            {
                return(string.Empty);
            }

            if (!string.IsNullOrEmpty(pinkFlagFiles) && string.IsNullOrEmpty(pirFiles))
            {
                return(DirectoryOperationsHelper.IsFileExist(pinkFlagFiles) ? pinkFlagFiles : string.Empty);
            }

            if (string.IsNullOrEmpty(pinkFlagFiles) && !string.IsNullOrEmpty(pirFiles))
            {
                return(DirectoryOperationsHelper.IsFileExist(pirFiles) ? pirFiles : string.Empty);
            }

            var tempfile     = tempLocation.PhysicalPath + Guid.NewGuid() + ".pdf";
            var combinefiles = new List <string>();

            if (DirectoryOperationsHelper.IsFileExist(pinkFlagFiles))
            {
                combinefiles.Add(pinkFlagFiles);
            }

            if (DirectoryOperationsHelper.IsFileExist(pirFiles))
            {
                combinefiles.Add(pirFiles);
            }

            if (combinefiles.IsNullOrEmpty())
            {
                return(string.Empty);
            }

            _pdfGenerator.Merge(tempfile, combinefiles);

            return(tempfile);
        }
コード例 #40
0
    /// <summary>
    /// Saves uploaded IFormFile files to physical file path. If file list is null or empty returns empty <see cref="List{String}"/>
    /// Target Path will be : "<paramref name ="basePath"></paramref>/<b><paramref name="folderNameCreator"/>()</b>/<paramref name="entity"></paramref>.<paramref name="propertyName"/>"
    /// </summary>
    ///
    /// <para><b>Remarks:</b></para>
    ///
    /// <remarks>
    ///
    /// <para> Don't forget validate files with <see cref="ValidateFile(IFormFile, long, List{string}, FileType)"/>, before use this method.</para>
    ///
    /// </remarks>
    ///
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="files"> Uploaded file in entity. </param>
    /// <param name="entity"></param>
    /// <param name="basePath"></param>
    /// <param name="folderNameCreator"></param>
    /// <param name="propertyName"></param>
    /// <returns> Completed Task </returns>
    public static async Task <List <string> > SaveFilesToPathAsync <TEntity>(this List <IFormFile> files,
                                                                             TEntity entity,
                                                                             string basePath,
                                                                             FilesFolderNameCreator folderNameCreator,
                                                                             string propertyName)
    {
        if (files.IsNullOrEmpty())
        {
            return(new List <string>());
        }

        //Gets file extension.
        var fileExtension = Path.GetExtension(files.First().FileName);

        //Gets the class name. E.g. If class is ProductDTO then sets the value of this variable as "Product".
        var folderNameOfClass = folderNameCreator.Invoke(entity.GetType());

        //We combined the name of this class (folderNameOfClass) with the path of the basePath folder. So we created the path of the folder belonging to this class.
        var folderPathOfClass = Path.Combine(basePath, folderNameOfClass);

        //Since each data belonging to this class (folderNameOfClass) will have a separate folder, we received the Id of the data sent.
        var folderNameOfItem = CommonHelper.PropertyExists <TEntity>(propertyName)
                                ? entity.GetType().GetProperty(propertyName).GetValue(entity, null).ToString()
                                : throw new MilvaDeveloperException("PropertyNotExists");

        //We created the path to the folder of this Id (folderNameOfItem).
        var folderPathOfItem = Path.Combine(folderPathOfClass, folderNameOfItem);

        try
        {
            //If there is no such folder in this path (folderPathOfClass), we created it.
            if (!Directory.Exists(folderPathOfClass))
            {
                Directory.CreateDirectory(folderPathOfClass);
            }

            //If there is no such folder in this path (folderPathOfItem), we created it.
            if (!Directory.Exists(folderPathOfItem))
            {
                Directory.CreateDirectory(folderPathOfItem);
            }

            DirectoryInfo directory = new(folderPathOfItem);

            var directoryFiles = directory.GetFiles();

            int markerNo = directoryFiles.IsNullOrEmpty()
                            ? 1
                            : (directoryFiles.Max(fileInDir => Convert.ToInt32(Path.GetFileNameWithoutExtension(fileInDir.FullName).Split('_')[1])) + 1);

            var folderPaths = new List <string>();

            foreach (var item in files)
            {
                var fileNameWithExtension = $"{folderNameOfItem}_{markerNo}{fileExtension}";
                var filePathOfItem        = Path.Combine(folderPathOfItem, fileNameWithExtension);
                using (var fileStream = new FileStream(filePathOfItem, FileMode.Create))
                {
                    await item.CopyToAsync(fileStream).ConfigureAwait(false);
                }
                folderPaths.Add(filePathOfItem);
                markerNo++;
            }

            return(folderPaths);
        }
        catch (Exception)
        {
            Directory.Delete(folderPathOfClass);
            Directory.Delete(folderPathOfItem);
            throw;
        }
    }
コード例 #41
0
        /// <summary>
        /// 销售退货单明细分页列表
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="pageInfo"></param>
        /// <returns></returns>
        public override List <SaleReturnDetailEntity> GetDetailList(SaleReturnDetailEntity entity, ref Framework.DataTypes.PageInfo pageInfo)
        {
            SaleReturnDetailEntity detail = new SaleReturnDetailEntity();

            detail.And(a => a.CompanyID == this.CompanyID)
            ;
            if (!entity.OrderSnNum.IsEmpty())
            {
                detail.And(a => a.OrderSnNum == entity.OrderSnNum);
            }
            if (!entity.BarCode.IsEmpty())
            {
                detail.And("BarCode", ECondition.Like, "%" + entity.BarCode + "%");
            }
            if (!entity.ProductName.IsEmpty())
            {
                detail.And("ProductName", ECondition.Like, "%" + entity.ProductName + "%");
            }

            SaleReturnEntity returnOrder = new SaleReturnEntity();

            detail.Left <SaleReturnEntity>(returnOrder, new Params <string, string>()
            {
                Item1 = "OrderSnNum", Item2 = "SnNum"
            });
            returnOrder.Include(a => new { CusNum = a.CusNum, CusName = a.CusName, Phone = a.Phone, Contact = a.Contact, SaleSnNum = a.SaleSnNum, SaleOrderNum = a.SaleOrderNum, Status = a.Status });
            returnOrder.And(a => a.IsDelete == (int)EIsDelete.NotDelete);

            if (!entity.CusNum.IsEmpty())
            {
                returnOrder.AndBegin <SaleReturnEntity>()
                .And <SaleReturnEntity>("CusNum", ECondition.Like, "%" + entity.CusNum + "%")
                .Or <SaleReturnEntity>("CusName", ECondition.Like, "%" + entity.CusNum + "%")
                .End <SaleReturnEntity>()
                ;
            }
            if (!entity.CusName.IsEmpty())
            {
                returnOrder.AndBegin <SaleReturnEntity>()
                .And <SaleReturnEntity>("CusNum", ECondition.Like, "%" + entity.CusName + "%")
                .Or <SaleReturnEntity>("CusName", ECondition.Like, "%" + entity.CusName + "%")
                .End <SaleReturnEntity>()
                ;
            }
            if (!entity.Phone.IsEmpty())
            {
                returnOrder.And("Phone", ECondition.Like, "%" + entity.Phone + "%");
            }
            if (!entity.SaleSnNum.IsEmpty())
            {
                returnOrder.And(item => item.SaleSnNum == entity.SaleSnNum);
            }
            if (!entity.SaleOrderNum.IsEmpty())
            {
                returnOrder.And("SaleOrderNum", ECondition.Like, "%" + entity.SaleOrderNum + "%");
            }
            if (!entity.OrderNum.IsEmpty())
            {
                returnOrder.And("OrderNum", ECondition.Like, "%" + entity.OrderNum + "%");
            }
            if (!entity.BeginTime.IsEmpty())
            {
                DateTime time = ConvertHelper.ToType <DateTime>(entity.BeginTime, DateTime.Now.Date.AddDays(-1));
                returnOrder.And(a => a.CreateTime >= time);
            }
            if (!entity.EndTime.IsEmpty())
            {
                DateTime time = ConvertHelper.ToType <DateTime>(entity.EndTime, DateTime.Now.Date.AddDays(1));
                returnOrder.And(a => a.CreateTime < time);
            }
            if (entity.Status > 0)
            {
                returnOrder.And(item => item.Status == entity.Status);
            }

            detail.IncludeAll();
            detail.Exclude(item => new { item.Status });
            detail.OrderBy(a => a.ID, EOrderBy.DESC);
            int rowCount = 0;
            List <SaleReturnDetailEntity> listResult = this.SaleReturnDetail.GetList(detail, pageInfo.PageSize, pageInfo.PageIndex, out rowCount);

            pageInfo.RowCount = rowCount;
            if (!listResult.IsNullOrEmpty())
            {
                ProductProvider productProvider = new ProductProvider(this.CompanyID);
                foreach (SaleReturnDetailEntity item in listResult)
                {
                    ProductEntity product = productProvider.GetProduct(item.ProductNum);
                    item.UnitName = product != null ? product.UnitName : string.Empty;
                    item.Size     = product != null ? product.Size : string.Empty;
                }
            }
            return(listResult);
        }
コード例 #42
0
 private void GetSongMetasFromManager()
 {
     songMetas = new List <SongMeta>(SongMetaManager.Instance.GetSongMetas());
     songMetas.Sort((songMeta1, songMeta2) => string.Compare(songMeta1.Artist, songMeta2.Artist, true, CultureInfo.InvariantCulture));
     noSongsFoundMessage.SetActive(songMetas.IsNullOrEmpty());
 }
コード例 #43
0
ファイル: InsertableProvider.cs プロジェクト: yexw03/SqlSugar
        private List <DiffLogTableInfo> GetDiffTable(string sql, long?identity)
        {
            List <SugarParameter>   parameters = new List <SugarParameter>();
            List <DiffLogTableInfo> result     = new List <DiffLogTableInfo>();
            var whereSql = string.Empty;
            List <IConditionalModel> cons = new List <IConditionalModel>();

            if (identity != null && identity > 0 && GetIdentityKeys().HasValue())
            {
                var fieldName = GetIdentityKeys().Last();
                cons.Add(new ConditionalModel()
                {
                    ConditionalType = ConditionalType.Equal, FieldName = fieldName, FieldValue = identity.ToString()
                });
            }
            else
            {
                foreach (var item in this.EntityInfo.Columns.Where(it => it.IsIgnore == false && GetPrimaryKeys().Any(pk => pk.Equals(it.DbColumnName, StringComparison.CurrentCultureIgnoreCase))))
                {
                    var fielddName = item.DbColumnName;
                    var fieldValue = this.EntityInfo.Columns.FirstOrDefault(it => it.PropertyName == item.PropertyName).PropertyInfo.GetValue(this.InsertObjs.Last(), null).ObjToString();
                    cons.Add(new ConditionalModel()
                    {
                        ConditionalType = ConditionalType.Equal, FieldName = fielddName, FieldValue = fieldValue
                    });
                }
            }
            Check.Exception(cons.IsNullOrEmpty(), "Insertable.EnableDiffLogEvent need primary key");
            var sqlable = this.SqlBuilder.ConditionalModelToSql(cons);

            whereSql = sqlable.Key;
            parameters.AddRange(sqlable.Value);
            var dt = this.Context.Queryable <T>().Where(whereSql).AddParameters(parameters).ToDataTable();

            if (dt.Rows != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    DiffLogTableInfo item = new DiffLogTableInfo();
                    item.TableDescription = this.EntityInfo.TableDescription;
                    item.TableName        = this.EntityInfo.DbTableName;
                    item.Columns          = new List <DiffLogColumnInfo>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        DiffLogColumnInfo addItem = new DiffLogColumnInfo();
                        addItem.Value             = row[col.ColumnName];
                        addItem.ColumnName        = col.ColumnName;
                        addItem.ColumnDescription = this.EntityInfo.Columns.First(it => it.DbColumnName.Equals(col.ColumnName, StringComparison.CurrentCultureIgnoreCase)).ColumnDescription;
                        item.Columns.Add(addItem);
                    }
                    result.Add(item);
                }
                return(result);
            }
            else
            {
                DiffLogTableInfo diffTable = new DiffLogTableInfo();
                diffTable.TableName        = this.EntityInfo.DbTableName;
                diffTable.TableDescription = this.EntityInfo.TableDescription;
                diffTable.Columns          = this.EntityInfo.Columns.Where(it => it.IsIgnore == false).Select(it => new DiffLogColumnInfo()
                {
                    ColumnDescription = it.ColumnDescription,
                    ColumnName        = it.DbColumnName,
                    Value             = it.PropertyInfo.GetValue(this.InsertObjs.Last(), null)
                }).ToList();
                return(new List <DiffLogTableInfo>()
                {
                    diffTable
                });
            }
        }
コード例 #44
0
        public virtual CategoryEntity FromModel(Category category, PrimaryKeyResolvingMap pkMap)
        {
            if (category == null)
            {
                throw new ArgumentNullException(nameof(category));
            }

            pkMap.AddPair(category, this);

            Id           = category.Id;
            CreatedBy    = category.CreatedBy;
            CreatedDate  = category.CreatedDate;
            ModifiedBy   = category.ModifiedBy;
            ModifiedDate = category.ModifiedDate;

            Code      = category.Code;
            Name      = category.Name;
            Priority  = category.Priority;
            TaxType   = category.TaxType;
            CatalogId = category.CatalogId;

            ParentCategoryId = category.ParentId;
            EndDate          = DateTime.UtcNow.AddYears(100);
            StartDate        = DateTime.UtcNow;
            IsActive         = category.IsActive ?? true;

            if (!category.Properties.IsNullOrEmpty())
            {
                var propValues = new List <PropertyValue>();
                foreach (var property in category.Properties.Where(x => x.Type == PropertyType.Category))
                {
                    if (property.Values != null)
                    {
                        //Do not use values from inherited properties and skip empty values
                        foreach (var propValue in property.Values.Where(x => !x.IsInherited && !x.IsEmpty))
                        {
                            //Need populate required fields
                            propValue.PropertyName = property.Name;
                            propValue.ValueType    = property.ValueType;
                            propValues.Add(propValue);
                        }
                    }
                }
                if (!propValues.IsNullOrEmpty())
                {
                    CategoryPropertyValues = new ObservableCollection <PropertyValueEntity>(AbstractTypeFactory <PropertyValueEntity> .TryCreateInstance().FromModels(propValues, pkMap));
                }
            }


            if (category.Links != null)
            {
                OutgoingLinks = new ObservableCollection <CategoryRelationEntity>(category.Links.Select(x => AbstractTypeFactory <CategoryRelationEntity> .TryCreateInstance().FromModel(x)));
            }

            if (category.Images != null)
            {
                Images = new ObservableCollection <ImageEntity>(category.Images.Select(x => AbstractTypeFactory <ImageEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }

            if (category.SeoInfos != null)
            {
                SeoInfos = new ObservableCollection <SeoInfoEntity>(category.SeoInfos.Select(x => AbstractTypeFactory <SeoInfoEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }

            return(this);
        }
コード例 #45
0
 public static List <NovelRecentReadView> ToNovelRecentReadViewList(this List <NovelReadRecordInfo> list)
 {
     return(!list.IsNullOrEmpty <NovelReadRecordInfo>() ? Mapper.Map <List <NovelReadRecordInfo>, List <NovelRecentReadView> >(list) : null);
 }
コード例 #46
0
ファイル: Program.cs プロジェクト: npkalala/AuExtension
        private static void Sample_SystemExt()
        {
            #region
            // 1. IsNullOrEmpty<T>
            List <string> lsCity = new List <string>()
            {
                "Kaohsiung", "Taipei", "Tainan"
            };
            Debug.WriteLine(lsCity.IsNullOrEmpty());

            string context = "";
            Debug.WriteLine(context.IsNullOrEmpty());

            float?confidence = null;
            Debug.WriteLine(confidence.IsNullOrEmpty());

            double?rate = null;
            Debug.WriteLine(rate.IsNullOrEmpty());

            int?score = 99;
            Debug.WriteLine(score.IsNullOrEmpty());

            /* Output
             * False
             * True
             * True
             * True
             * False
             */

            //2. NullAs<T>
            string result = null;
            result = result.NullAs("Hello World");
            Debug.WriteLine(result);

            result = "The confidence is " + confidence.NullAs("0");
            Debug.WriteLine(result);

            result = "The rate is " + rate.NullAs("0");
            Debug.WriteLine(result);

            result = "The score is " + score.NullAs("0");
            Debug.WriteLine(result);

            /* Output
             * Hello World
             * The confidence is 0
             * The rate is 0
             * The score is 99
             */

            // 3. Regex ReplaceAll
            String s = "John Smith $100,000.00 M";
            s = s.ReplaceAll(@"\s+\$|\s+(?=\w+$)", ",");
            Debug.WriteLine(s);

            /* Output
             * John Smith,100,000.00,M
             */

            // 4. Regex IsMatch
            string number = "1298-673-4192";
            string status = number.IsMatch(@"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) ? "is" : "is not";
            Debug.WriteLine($"{number} {status} a valid part number.");

            /* Output
             * 1298-673-4192 is a valid part number.
             */

            // 5. DateTime To Format String
            DateTime?date = DateTime.Now;
            Debug.WriteLine(date.ToDateString());

            Debug.WriteLine(date.ToDateString("D"));

            Debug.WriteLine(date.ToDateString("D1"));

            Debug.WriteLine(date.ToDateString("D2"));

            Debug.WriteLine(date.ToDateString("D3"));

            Debug.WriteLine(date.ToUniversalDateString());

            Debug.WriteLine(date.ToUniversalDateString("D"));

            Debug.WriteLine(date.ToUniversalDateString("D1"));

            Debug.WriteLine(date.ToUniversalDateString("D2"));

            Debug.WriteLine(date.ToUniversalDateString("D3"));

            /* output
             * 2019-04-02
             * 2019-04-02 13:17:36
             * 2019-04-02 13:17:36.997
             * 2019/04/02 13:17:36
             * 2019/04/02 13:17:36.997
             * 2019-04-02T
             * 2019-04-02T05:17:36
             * 2019-04-02T05:17:36.997Z
             * 2019/04/02T05:17:36
             * 2019/04/02T05:17:36.997Z
             */

            //6. ContainList
            Debug.WriteLine("This is Kaohsiung".ContainList(lsCity));

            string[] arCity = lsCity.ToArray();
            Debug.WriteLine("This is Tokyo".ContainList(arCity));

            /* Output
             * True
             * False
             */
            #endregion

            //Linq

            List <City> dtCity = new List <City>()
            {
                new City()
                {
                    city_id          = 1,
                    city_name        = "KH",
                    city_create_time = "2011/01/01"
                },
                new City()
                {
                    city_id          = 1,
                    city_name        = "KH",
                    city_create_time = "2011/01/02"
                },
                new City()
                {
                    city_id          = 2,
                    city_name        = "KH",
                    city_create_time = "2011/11/01"
                }
            };

            var cityName = dtCity.DistinctBy(t => new { t.city_name, t.city_id }).ToList();
        }
コード例 #47
0
        public void PollForMemberUploadbyAces()
        {
            try
            {
                if (_stopMemberUploadbyAces)
                {
                    _logger.Info("Customer Eligibility Upload Polling Agent stopped @:" + DateTime.Now);
                    return;
                }

                _logger.Info("Entering Member Upload by Aces Polling Agent @" + DateTime.Now);

                if (!DirectoryOperationsHelper.IsDirectoryExist(_memberUploadbyAcesSourceFolderPath))
                {
                    _logger.Info("Source folder not availble.");
                    return;
                }
                var files = DirectoryOperationsHelper.GetFiles(_memberUploadbyAcesSourceFolderPath, "*.txt");

                if (files.IsNullOrEmpty())
                {
                    _logger.Info("Files not availble in Source Folder.");
                    return;
                }

                var intakeFiles = files.Where(x => x.ToLower().Contains("outtake") && !x.ToLower().Contains("eligibility")).ToList();

                if (intakeFiles.IsNullOrEmpty())
                {
                    _logger.Info("Files not availble in Source Folder after outtake filter.");
                    return;
                }

                var mediaLocation = _mediaRepository.GetMemberUploadbyAcesFolderLocation();

                MoveFileMediaLocation(intakeFiles, mediaLocation);

                var todaysFiles = DirectoryOperationsHelper.GetFiles(Path.Combine(mediaLocation.PhysicalPath, DateTime.Today.ToString("yyyyMMdd")));

                if (todaysFiles.IsNullOrEmpty())
                {
                    _logger.Info("Files not availble in Source Folder.");
                    return;
                }

                var corporateAccount = _corporateAccountRepository.GetAllCorporateAccountAcestoHipInTake();
                if (corporateAccount.IsNullOrEmpty())
                {
                    _logger.Info("Account not found for Aces to Hip upload.");
                    return;
                }

                var languages = _languageRepository.GetAll();
                var labs      = _labRepository.GetAll();

                var sendMail = false;
                foreach (var account in corporateAccount)
                {
                    _logger.Info("Parsing start for Account Tag :" + account.Tag);

                    var acesToHipIntakeShortName = account.AcesToHipIntakeShortName;

                    if (string.IsNullOrWhiteSpace(acesToHipIntakeShortName))
                    {
                        _logger.Info("AcesToHipIntake ShortName is blank for Account Tag :" + account.Tag);
                        continue;
                    }

                    acesToHipIntakeShortName = acesToHipIntakeShortName.ToLower() + "_";
                    var filesAcesToHipIntakeShortName = todaysFiles.Where(x => x.ToLower().Contains(acesToHipIntakeShortName) && x.ToLower().Contains("outtake") && !x.ToLower().Contains("eligibility"));

                    if (filesAcesToHipIntakeShortName.IsNullOrEmpty())
                    {
                        _logger.Info("Files not available for Short name : " + acesToHipIntakeShortName + " and Account Tag :" + account.Tag);
                        continue;
                    }

                    var customerList = new List <long>();

                    foreach (var file in filesAcesToHipIntakeShortName)
                    {
                        var filewithoutExtension = Path.GetFileNameWithoutExtension(file);
                        var acesClientShortName  = filewithoutExtension.Split('_')[0];
                        if (acesClientShortName.ToLower() != account.AcesToHipIntakeShortName.ToLower())
                        {
                            _logger.Info("File Short name : " + acesClientShortName + " and Account Short name :" + account.AcesToHipIntakeShortName.ToLower() + " not matched.");
                            continue;
                        }

                        if (ParseMemberUploadbyAces(file, account, customerList, languages, labs))
                        {
                            if (!sendMail)
                            {
                                sendMail = true;
                            }
                        }
                    }

                    if (customerList.IsNullOrEmpty())
                    {
                        _logger.Info("PatientReportWithnoCustomTag Report not generated because new Customer not found for short name : " + acesToHipIntakeShortName + " and Account Tag :" + account.Tag);
                        continue;
                    }

                    PatientReportWithnoCustomTag(customerList.ToArray(), account.Tag);
                }
                if (sendMail)
                {
                    var listWithoutCustomTagsModel = _emailNotificationModelsFactory.GetListWithoutCustomTagsViewModel(_memberUploadbyAcesSourceFolderPath, Path.Combine(_memberUploadbyAcesSourceFolderPath, "Failed")
                                                                                                                       , Path.Combine(_memberUploadbyAcesSourceFolderPath, "AdjustOrder"));
                    _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.ListWithoutCustomTags, EmailTemplateAlias.ListWithoutCustomTags, listWithoutCustomTagsModel, 0, 1, "MemberUploadbyAcesPollingAgent");
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Exception occurred during execution of servcie. \nException Message: {0}\n\tStackTrace:{1}", ex.Message, ex.StackTrace));
                return;
            }
        }
コード例 #48
0
        private bool ParseMemberUploadbyAces(string file, CorporateAccount corporateAccount, List <long> customerList, IEnumerable <Language> languages, IEnumerable <Lab> labs)
        {
            try
            {
                _logger.Info("Start converting data from CSV to data table :" + DateTime.Now);

                var mediaLocation = _mediaRepository.GetMemberUploadbyAcesFolderLocation();
                var fileToParse   = GetFileName(file, mediaLocation);
                var memberData    = GetRows(fileToParse);

                var corportateUpload = _memberUploadByAcesHelper.Upload(fileToParse, corporateAccount);

                if (memberData == null)
                {
                    return(false);
                }

                var rowCountInFile = memberData.Rows.Count;

                _logger.Info("Data coverted from CSV to Data Table :" + DateTime.Now + " & Row count is : " + rowCountInFile);

                if (IsAnyColumnMissing(memberData))
                {
                    return(false);
                }

                //var failedCustomers = new List<MemberUploadbyAcesFailedCustomerModel>();
                var adjustOrderCustomer = new List <EventCusomerAdjustOrderViewModel>();

                var rows = memberData.AsEnumerable();

                var orgRoleUser = new OrganizationRoleUser()
                {
                    Id = OrgRoleUserId, RoleId = OrgRoleId
                };
                var corporateModel = new CorporateUploadEditModel {
                    Tag = corporateAccount.Tag, CorporateAccountId = corporateAccount.Id, UploadCorporateId = corportateUpload.Id
                };

                var accountAdditionalFields = _accountAdditionalFieldRepository.GetAccountAdditionalFieldsEditModelByAccountId(corporateAccount.Id);
                var index = 1;
                var customerIdWithSameAcesId = new List <CustomerWithDuplicateAcesModel>();

                foreach (DataRow row in rows)
                {
                    _logger.Info(index + " out of " + rowCountInFile + " processing");

                    var customerEditModel = CreateEditModel(row);

                    if (customerEditModel == null)
                    {
                        continue;
                    }
                    var sb = new StringBuilder();

                    try
                    {
                        _logger.Info("Record:  First Name :" + customerEditModel.FirstName + ", Last Name :" + customerEditModel.LastName + " and ACES Id :" + customerEditModel.AcesId);
                        var customerWithDuplicateAcesModel = new CustomerWithDuplicateAcesModel();
                        _corporateUploadService.CorporateUploadDataRow(customerEditModel, languages, labs, null, corporateModel, accountAdditionalFields,
                                                                       adjustOrderCustomer, orgRoleUser, OrgRoleId, customerList, (long)MemberUploadSource.Aces, sb, corportateUpload.Id, out customerWithDuplicateAcesModel);

                        if (customerWithDuplicateAcesModel != null && customerWithDuplicateAcesModel.CustomerId > 0)
                        {
                            customerIdWithSameAcesId.Add(customerWithDuplicateAcesModel);
                        }
                    }
                    catch (Exception ex)
                    {
                        customerEditModel.ErrorMessage = sb.ToString();
                        if (!string.IsNullOrEmpty(ex.Message))
                        {
                            customerEditModel.ErrorMessage += " Error Message: " + ex.Message;
                        }
                        _logger.Error("While Saving customer");
                        _logger.Error(customerEditModel.ErrorMessage);
                        //var model = _memberUploadbyAcesFailedCustomerFactory.Create(customerEditModel);
                        //failedCustomers.Add(model);
                    }
                    _logger.Info(index + " out of " + rowCountInFile + " completed");

                    var memberUploadParseDetail = _memberUploadParseDetailFactory.GetDomain(customerEditModel, corportateUpload.Id);
                    _memberUploadParseDetailRepository.Save(memberUploadParseDetail);

                    index++;
                }

                if (!customerIdWithSameAcesId.IsNullOrEmpty())
                {
                    _customerWithDuplicateAcesIdFileGenerator.GenerateCsvFile(corportateUpload.Id, customerIdWithSameAcesId);
                }

                var failedRecords   = _memberUploadParseDetailRepository.GetByCorporateUploadId(corportateUpload.Id, false);
                var failedCustomers = _memberUploadParseDetailFactory.GetMemberUploadbyAcesFailedCustomerListModel(failedRecords, corportateUpload.SourceId);

                CreateFailedUploadFile(file, mediaLocation, failedCustomers, corportateUpload);

                CreateAdjustOrderUploadFile(file, mediaLocation, adjustOrderCustomer, corportateUpload);

                corportateUpload.ParseStatus = (int)MemberUploadParseStatus.Start;
                corportateUpload             = _memberUploadByAcesHelper.UpdateCorporateUpload(corportateUpload, failedCustomers.Count(), rowCountInFile);

                if (corportateUpload.SuccessfullUploadCount > 0)
                {
                    _logger.Info("Set IsTermByAbsence is True");
                    corportateUpload.IsTermByAbsence = true;
                    _corporateUploadRepository.Save(corportateUpload);

                    _logger.Info("Publishing: Corporate Upload Id: " + corportateUpload.Id);
                    _memberTermByAbsencePublisher.PublishCorporateUpload(corportateUpload.Id);
                    _logger.Info("Publish Successfully: Corporate Upload Id: " + corportateUpload.Id);
                }

                return(failedCustomers.Any() || accountAdditionalFields.Any() || customerList.Any());
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Error occurred while processing the {0}.\nMessage: {1}\n\tStackTrace: {2}", file, ex.Message, ex.StackTrace));
                return(false);
            }
        }
コード例 #49
0
        private void WireCommands()
        {
            ArtistPageLoaded = new RelayCommand(async() =>
            {
                if (_navigationService.IsNetworkAvailable && !_gotAlbums)
                {
                    SetProgressBar(AppResources.SysTrayGettingAlbums);

                    await GetArtistInfo();

                    SetProgressBar();
                }
            });

            AlbumPageLoaded = new RelayCommand(async() =>
            {
                if (_artistTracks.IsNullOrEmpty())
                {
                    SetProgressBar("Getting tracks...");

                    try
                    {
                        if (SelectedArtist != null)
                        {
                            await GetArtistInfo();

                            AlbumTracks = _artistTracks.Where(x => x.ParentId == SelectedAlbum.Id)
                                          .OrderBy(x => x.ParentIndexNumber)
                                          .ThenBy(x => x.IndexNumber).ToList();
                        }
                        else
                        {
                            await GetAlbumTracks();
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.ErrorException("AlbumPageLoaded", ex);
                    }

                    SetProgressBar();
                }
            });

            AlbumTapped = new RelayCommand <BaseItemDto>(album =>
            {
                SelectedAlbum = album;
                AlbumTracks   = _artistTracks.Where(x => x.ParentId == SelectedAlbum.Id)
                                .OrderBy(x => x.IndexNumber)
                                .ToList();
            });

            AlbumPlayTapped = new RelayCommand <BaseItemDto>(album =>
            {
                var albumTracks = _artistTracks.Where(x => x.ParentId == album.Id)
                                  .OrderBy(x => x.IndexNumber)
                                  .ToList();

                var newList = albumTracks.ToPlayListItems(_apiClient);

                Messenger.Default.Send(new NotificationMessage <List <PlaylistItem> >(newList, Constants.Messages.SetPlaylistAsMsg));
            });

            SelectionChangedCommand = new RelayCommand <SelectionChangedEventArgs>(args =>
            {
                if (args.AddedItems != null)
                {
                    foreach (var track in args.AddedItems.Cast <BaseItemDto>())
                    {
                        SelectedTracks.Add(track);
                    }
                }

                if (args.RemovedItems != null)
                {
                    foreach (var track in args.RemovedItems.Cast <BaseItemDto>())
                    {
                        SelectedTracks.Remove(track);
                    }
                }

                SelectedTracks = SelectedTracks.OrderBy(x => x.IndexNumber).ToList();
            });

            AddToNowPlayingCommand = new RelayCommand(() =>
            {
                if (!SelectedTracks.Any())
                {
                    return;
                }

                var newList = SelectedTracks.ToPlayListItems(_apiClient);

                Messenger.Default.Send(new NotificationMessage <List <PlaylistItem> >(newList, Constants.Messages.AddToPlaylistMsg));

                SelectedTracks = new List <BaseItemDto>();

                App.ShowMessage(string.Format("{0} tracks added successfully", newList.Count));

                IsInSelectionMode = false;
            });

            PlayItemsCommand = new RelayCommand(() =>
            {
                var newList = SelectedTracks.ToPlayListItems(_apiClient);

                Messenger.Default.Send(new NotificationMessage <List <PlaylistItem> >(newList, Constants.Messages.SetPlaylistAsMsg));
            });

            PlaySongCommand = new RelayCommand <BaseItemDto>(song =>
            {
                if (song == null)
                {
                    return;
                }

                var playlist = new List <PlaylistItem>
                {
                    song.ToPlaylistItem(_apiClient)
                };

                Messenger.Default.Send(new NotificationMessage <List <PlaylistItem> >(playlist, Constants.Messages.SetPlaylistAsMsg));
            });

            AddRemoveFavouriteCommand = new RelayCommand <BaseItemDto>(async item =>
            {
                try
                {
                    SetProgressBar(AppResources.SysTrayAddingToFavourites);

                    CanUpdateFavourites = false;

                    item.UserData = await _apiClient.UpdateFavoriteStatusAsync(item.Id, AuthenticationService.Current.LoggedInUser.Id, !item.UserData.IsFavorite);
                }
                catch (HttpException ex)
                {
                    Log.ErrorException("AddRemoveFavouriteCommand (Music)", ex);
                    App.ShowMessage("Error making your changes");
                }

                SetProgressBar();

                CanUpdateFavourites = true;
            });

            PlayAllItemsCommand = new RelayCommand(() =>
            {
                if (_artistTracks.IsNullOrEmpty())
                {
                    return;
                }

                var playlist = _artistTracks.ToPlayListItems(_apiClient);

                Messenger.Default.Send(new NotificationMessage <List <PlaylistItem> >(playlist, Constants.Messages.SetPlaylistAsMsg));
            });
        }
コード例 #50
0
 public static List <NovelClassView> ToNovelClassViewList(this List <NovelClass> list)
 {
     return(!list.IsNullOrEmpty <NovelClass>() ? Mapper.Map <List <NovelClass>, List <NovelClassView> >(list) : null);
 }
コード例 #51
0
        public static TemplateTree.StandardValidTerm ToStandardValidTerm(List<aim4_dotnet.iso_21090.CD> codes)
        {
            if (codes.IsNullOrEmpty())
                return null;

            var firstCode = codes.First();
            return new TemplateTree.StandardValidTerm(
                ToStandardCodeSequence(firstCode),
                new List<TemplateTree.StandardValidTerm>
                    {
                        ToStandardValidTerm(codes.Where(code => !Equals(code, firstCode)).ToList())
                    });
        }
コード例 #52
0
        private void addProducts()
        {
            //get the data
            List <ProductInitializerHelper> dataList = GetDataListForProduct;

            if (!dataList.IsNullOrEmpty())
            {
                foreach (ProductInitializerHelper prodInitHelper in dataList)
                {
                    //check to see if the product exists... if it does continue.
                    Product p = FindByName(prodInitHelper.Name);

                    if (!p.IsNull())
                    {
                        continue;
                    }

                    p              = new Product();
                    p.Name         = prodInitHelper.Name;
                    p.IsUnApproved = false;
                    //p.UomVolume = UomVolumeBiz.FindByName(prodInitHelper.UomVolumeName);
                    //p.UomVolume.IsNullThrowException();

                    //p.UomDimensions = UomLengthBiz.FindByName(prodInitHelper.UomLengthName);
                    //p.UomDimensions.IsNullThrowException();

                    //p.UomWeightActual = UomWeightBiz.FindByName(prodInitHelper.UomShipWeightName);


                    //p.UomWeightListed = UomWeightBiz.FindByName(prodInitHelper.UomWeightListedName);
                    //p.UomWeightListed.IsNullThrowException();

                    //p.UomPurchase = UomQuantityBiz.FindByName(prodInitHelper.UomPurchaseName);
                    //p.UomPurchase.IsNullThrowException();

                    //p.UomSale = UomQuantityBiz.FindByName(prodInitHelper.UomSaleName);
                    //p.UomSale.IsNullThrowException();

                    //p.Dimensions.Height = prodInitHelper.Height;
                    //p.Dimensions.Width = prodInitHelper.Width;
                    //p.Dimensions.Length = prodInitHelper.Length;
                    //p.UomDimensionsId = p.UomDimensions.Id;
                    //p.UomVolumeId = p.UomVolume.Id;
                    //p.UomDimensionsId = p.UomDimensions.Id;
                    //p.WeightActual = prodInitHelper.ShipWeight;
                    //p.UomWeightActualId = p.UomWeightActual.Id;

                    //p.UomWeightListedId = p.UomWeightListed.Id;
                    //p.UomPurchaseId = p.UomPurchase.Id;
                    //p.UomSaleId = p.UomSale.Id;

                    //p.WeightListed = prodInitHelper.WeightListed;
                    //p.Volume = prodInitHelper.ShipVolume;

                    if (ErrorsGlobal.HasErrors)
                    {
                        throw new Exception(ErrorsGlobal.ToString());
                    }



                    #region Menu Path

                    if (prodInitHelper.Menupaths.IsNull())
                    {
                    }
                    else
                    {
                        foreach (MenuPathHelper mph in prodInitHelper.Menupaths)
                        {
                            MenuPathMain mpm = MenuPathMainBiz.FindAll().FirstOrDefault(x =>
                                                                                        x.MenuPath1.Name.ToLower() == mph.MenuPath1Name.ToLower() &&
                                                                                        x.MenuPath2.Name.ToLower() == mph.MenuPath2Name.ToLower() &&
                                                                                        x.MenuPath3.Name.ToLower() == mph.MenuPath3Name.ToLower());

                            if (mpm.IsNull())
                            {
                                continue;
                            }

                            if (p.MenuPathMains.IsNull())
                            {
                                p.MenuPathMains = new List <MenuPathMain>();
                            }

                            p.MenuPathMains.Add(mpm);

                            if (mpm.Products.IsNull())
                            {
                                mpm.Products = new List <Product>();
                            }

                            mpm.Products.Add(p);
                        }
                    }
                    #endregion



                    #region ProductIdentifier
                    if (prodInitHelper.ProductIdentifiers.IsNull())
                    {
                    }
                    else
                    {
                        foreach (string piStr in prodInitHelper.ProductIdentifiers)
                        {
                            ProductIdentifier pi = ProductIdentifierBiz.Find(piStr);

                            if (!pi.IsNull())
                            {
                                throw new Exception(string.Format("Duplicate product Identifier: '{0}'", piStr));
                            }

                            pi = ProductIdentifierBiz.Factory() as ProductIdentifier;

                            pi.Name      = piStr;
                            pi.Product   = p;
                            pi.ProductId = p.Id;

                            if (p.ProductIdentifiers.IsNull())
                            {
                                p.ProductIdentifiers = new List <ProductIdentifier>();
                            }

                            p.ProductIdentifiers.Add(pi);
                        }
                    }
                    #endregion
                    CreateSave_ForInitializeOnly(p);
                }
            }

            AddInitData_ProductChild();
        }
コード例 #53
0
        private void UploadAppBits(string name, DirectoryInfo path)
        {
            /*
             * Before creating the app, ensure we can build resource list
             */
            string uploadFile = Path.GetTempFileName();
            DirectoryInfo explodeDir = Utility.GetTempDirectory();

            ProcessPath(path, explodeDir);

            try
            {
                var resources = new List<Resource>();
                ulong totalSize = AddDirectoryToResources(resources, explodeDir, explodeDir.FullName);

                if (false == resources.IsNullOrEmpty())
                {
                    Resource[] appcloudResources = null;
                    if (totalSize > (64*1024))
                    {
                        appcloudResources = CheckResources(resources.ToArray());
                    }
                    if (appcloudResources.IsNullOrEmpty())
                    {
                        appcloudResources = resources.ToArrayOrNull();
                    }
                    else
                    {
                        foreach (Resource r in appcloudResources)
                        {
                            string localPath = Path.Combine(explodeDir.FullName, r.FN);
                            var localFileInfo = new FileInfo(localPath);
                            localFileInfo.Delete();
                            resources.Remove(r);
                        }
                    }
                    if (resources.IsNullOrEmpty())
                    {
                        /*
                            If no resource needs to be sent, add an empty file to ensure we have
                            a multi-part request that is expected by nginx fronting the CC.
                         */
                        File.WriteAllText(Path.Combine(explodeDir.FullName, ".__empty__"), String.Empty);
                    }

                    var zipper = new FastZip();
                    zipper.CreateZip(uploadFile, explodeDir.FullName, true, String.Empty);
                    VcapJsonRequest request = base.BuildVcapJsonRequest(Method.PUT, Constants.AppsResource, name,
                                                                        "application");
                    request.AddFile("application", uploadFile);
                    request.AddParameter("resources", JsonConvert.SerializeObject(appcloudResources.ToArrayOrNull()));
                    IRestResponse response = request.Execute();
                }
            }
            finally
            {
                Directory.Delete(explodeDir.FullName, true);
                File.Delete(uploadFile);
            }
        }
コード例 #54
0
        public static void CurrentBindDynamicRow(
            this DbDataReader reader,
            List <DynamicColumn> columns,
            ref DynamicRow row)
        {
            if (null == reader)
            {
                return;
            }
            if (columns.IsNullOrEmpty())
            {
                return;
            }

            var dbValues = new object[columns.Count];

            reader.GetValues(dbValues);

            var flatValues  = new List <Any>();
            var values      = new List <Any>();
            var hashCodes   = new List <Any>();
            var dbNulls     = new List <string>();
            var columnIndex = -1;

            foreach (var column in columns)
            {
                columnIndex++;
                var value = dbValues[columnIndex];
                if (DBNull.Value == value)
                {
                    dbNulls.Add(column.BaseColumnName);
                    value = null;
                }
                flatValues.SafeAdd(column.ColumnName, value);
                flatValues.SafeAdd(column.BaseColumnName, value);
                values.Add(column.BaseColumnName, value);


                if (null != value)
                {
                    int hashCode = value.GetHashCode();
                    hashCodes.Add(
                        column.BaseColumnName, hashCode
                        );
                }
            }

            row.__ReturnAny             = true;
            row.__DatabaseFirst         = true;
            row.__DynamicColumns        = columns;
            row.__FlatValues            = flatValues;
            row.__DynamicValues         = values;
            row.__DynamicOriginalValues = values;
            row.__OriginalHashCodes     = hashCodes;
            row.__DynamicDbNulls        = dbNulls;
            row.__OriginalHashCode      = row.GetHashCode();

            if (dbNulls.Any())
            {
                foreach (var dbNull in dbNulls)
                {
                    hashCodes.Add(
                        dbNull,
                        row.__OriginalHashCode
                        );
                }
            }
            row.__OriginalHashCodes = hashCodes;
        }
コード例 #55
0
 public void SwitchSpouses(List<Guid> marriageIds)
 {
     if (!marriageIds.IsNullOrEmpty())
         _marriagesDll.SwapSpouses(marriageIds);
 }
        public void then_empty_list_is_null_or_empty()
        {
            var list = new List <int>();

            Assert.IsTrue(list.IsNullOrEmpty());
        }
コード例 #57
0
ファイル: ReportProvider.cs プロジェクト: ZhangHanLong/gitwms
        /// <summary>
        /// 修改报表格式
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public int Update(ReportsEntity entity, List<ReportParamsEntity> list)
        {
            int line = 0;
            using (TransactionScope ts = new TransactionScope())
            {
                ReportParamsEntity param = new ReportParamsEntity();
                param.Where(a => a.ReportNum == entity.ReportNum);
                line += this.ReportParams.Delete(param);

                entity.Include(a => new { a.ReportName, a.ReportType, a.Remark, a.DataSource, a.DsType, a.FileName });
                entity.Where(a => a.ReportNum == entity.ReportNum);
                line += this.Reports.Update(entity);

                if (!list.IsNullOrEmpty())
                {
                    foreach (ReportParamsEntity item in list)
                    {
                        item.ParamNum = item.ParamNum.IsEmpty() ? SequenceProvider.GetSequence(typeof(ReportParamsEntity)) : item.ParamNum;
                        item.ReportNum = entity.ReportNum;
                        item.IncludeAll();
                    }
                    this.ReportParams.Add(list);
                }
                ts.Complete();
            }

            return line;
        }
        public void then_null_list_is_null_or_empty()
        {
            List <int> list = null;

            Assert.IsTrue(list.IsNullOrEmpty());
        }
コード例 #59
0
ファイル: ReportProvider.cs プロジェクト: ZhangHanLong/gitwms
 /// <summary>
 /// 批量删除
 /// </summary>
 /// <param name="list"></param>
 /// <returns></returns>
 public int Delete(List<string> list)
 {
     if (!list.IsNullOrEmpty())
     {
         ReportsEntity entity = new ReportsEntity();
         entity.IsDelete = (int)EIsDelete.Deleted;
         entity.IncludeIsDelete(true);
         entity.Where("ReportNum", ECondition.In, list.ToArray());
         int line = this.Reports.Update(entity);
         return line;
     }
     return 0;
 }
コード例 #60
0
ファイル: URLParser.cs プロジェクト: zhouweiaccp/sones
        /// <summary>
        /// This will check
        /// </summary>
        /// <param name="urlNodes"></param>
        /// <param name="urlParts">the splittet</param>
        /// <param name="parameters">The parameters, parsed from the url</param>
        /// <param name="url">The uriginal url - this is needed to get the real parameter before splitting. Due to the split we lost the seperator char</param>
        /// <param name="posInUrl">The current pos in the url - this is needed to get the real parameter before splitting. Due to the split we lost the seperator char</param>
        /// <returns></returns>
        private Tuple <UrlNode, List <Object> > GetCallback(Dictionary <String, UrlNode> urlNodes, IEnumerable <String> urlParts, List <Object> parameters, String url, Int32 posInUrl)
        {
            var val = urlParts.FirstOrDefault();

            if (val == null)
            {
                throw new ArgumentNullException("urlParts.First");
            }
            val = val.ToLower();

            UrlNode curUrlNode = null;

            if (urlNodes.ContainsKey(val))
            {
                #region The current url node has this part of the URL

                curUrlNode = urlNodes[val];
                posInUrl  += (val.Length == 0) ? 1 : val.Length + 1; // for just a / (which is now a empty string because of the split)

                #endregion
            }
            else if (urlNodes.ContainsKey("{}"))
            {
                #region If there is a wildcard in this node, use this

                curUrlNode = urlNodes["{}"];
                if (curUrlNode.ChildNodes.IsNullOrEmpty())
                {
                    // this is the last parameter - so add the rest of the url as well
                    parameters.Add(url.Substring(posInUrl));
                    posInUrl = url.Length;
                    return(new Tuple <UrlNode, List <object> >(curUrlNode, parameters));
                }
                else
                {
                    // just add this part and proceed
                    if (url.Length > posInUrl)
                    {
                        //parameters.Add(url.Substring(posInUrl, (val.Length == 0) ? 1 : val.Length));
                        parameters.Add(url.Substring(posInUrl, val.Length));
                        posInUrl += val.Length + 1; // add 1 for the missing seperator char
                    }
                    else
                    {
                        parameters.Add("");
                    }
                }

                #endregion
            }
            else
            {
                #region The node does not have this part and a wildcard neither

                return(null);

                #endregion
            }


            if (urlParts.CountIsGreater(1) && !curUrlNode.ChildNodes.IsNullOrEmpty())
            {
                #region There are more url parts AND childs in the current node

                // we have some more childs defined
                Tuple <UrlNode, List <object> > retval = null;
                var newParams = new List <Object>();
                do
                {
                    #region As long as we can go deeper lets do it

                    retval = GetCallback(curUrlNode.ChildNodes, urlParts.Skip(1), newParams, url, posInUrl);
                    if (retval == null)
                    {
                        #region There is no hit for the current nodes childs and the next url parts

                        if (curUrlNode.ChildNodes.ContainsKey("{}"))
                        {
                            #region But the childs contains a wildcard we could use

                            curUrlNode = curUrlNode.ChildNodes["{}"];
                            if (curUrlNode.ChildNodes.IsNullOrEmpty())
                            {
                                #region The wildcard child has no more childs to verify, so lets take it

                                parameters.Add(url.Substring(posInUrl));
                                retval = new Tuple <UrlNode, List <object> >(curUrlNode, newParams);//parameters);

                                #endregion
                            }
                            else
                            {
                                #region The wildcard child have mor childs which needs to be verified

                                urlParts = urlParts.Skip(1);
                                if (GetCallback(curUrlNode.ChildNodes, urlParts.Skip(1), newParams, url, posInUrl) == null)
                                {
                                    #region The next parts do not leed into a successfull mapping, lets use this wildcard

                                    parameters.Add(url.Substring(posInUrl));
                                    retval     = new Tuple <UrlNode, List <object> >(curUrlNode, parameters);
                                    parameters = null;

                                    #endregion
                                }
                                else
                                {
                                    #region Take this wildcard as parameter and proceed

                                    val = urlParts.First();
                                    newParams.Add(url.Substring(posInUrl, (val.Length == 0) ? 1 : val.Length));
                                    posInUrl += (val.Length == 0) ? 1 : val.Length + 1;

                                    #endregion
                                }

                                #endregion
                            }

                            #endregion
                        }
                        else
                        {
                            #region This part is still not valid, return null to proceed with the predecessor level

                            return(null);

                            #endregion
                        }

                        #endregion
                    }

                    #endregion
                } while (retval == null);

                #region Are there any parameters to add to the result?

                if (!parameters.IsNullOrEmpty())
                {
                    #region We need to swap the parameters due to recursive call

                    parameters.AddRange(retval.Item2);
                    retval = new Tuple <UrlNode, List <object> >(retval.Item1, parameters);

                    #endregion
                }

                #endregion

                return(retval);

                #endregion
            }


            else if (curUrlNode.Callback == null && !curUrlNode.ChildNodes.IsNullOrEmpty() && curUrlNode.ChildNodes.ContainsKey("{}"))
            {
                #region The current callback is null AND this is the last part of the url

                parameters.Add(url.Substring(posInUrl));
                curUrlNode = curUrlNode.ChildNodes["{}"];

                #endregion
            }

            else if (urlParts.CountIsGreater(1) && curUrlNode.ChildNodes.IsNullOrEmpty())
            {
                #region No childs but still some url parts

                return(null);

                #endregion
            }

            else if (curUrlNode.Callback == null && !curUrlNode.ChildNodes.IsNullOrEmpty() && !curUrlNode.ChildNodes.ContainsKey("{}"))
            {
                #region There are childs but they have no placeholders ({}), so we have no valid definition

                return(null);

                #endregion
            }

            return(new Tuple <UrlNode, List <object> >(curUrlNode, parameters));
        }