public static void GetDateTime(string date, out DateTime pubDate) { if (string.IsNullOrWhiteSpace(date)) { pubDate = DateTime.Today; return; } if (DateTime.TryParse(date, out pubDate)) { return; } date = date.ToLower(); const string pattern = @"(?<day>[1-9]|[12][0-9]|3[01]) (?<month>jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec) (?<year>(?:19|20)[0-9]{2})"; MatchCollection matches = Regex.Matches(date, pattern, RegexOptions.IgnoreCase); Match match = matches[0]; if (string.IsNullOrEmpty(match.Value)) { pubDate = DateTime.Today; return; } int month = GetMonth(Regex.Replace(match.Value, pattern, $"${nameof(month)}")); int day = Convert.ToInt32(Regex.Replace(match.Value, pattern, $"${nameof(day)}")); int year = Convert.ToInt32(Regex.Replace(match.Value, pattern, $"${nameof(year)}")); pubDate = !NullableHelper.AnyIsNull(day, month, year) ? new DateTime(year, month, day) : DateTime.Today; }
private CatalogOfferViewModel(OfferComposedId initOfferId = null) : base(initOfferId) { InitFields(); NeedToCalculateDiff = true; DisplayName = "Сводный прайс-лист"; Filters = new[] { "Все", "Основные", "Неосновные" }; CurrentFilter.Value = Filters[0]; CurrentRegion.Value = Consts.AllRegionLabel; GroupByProduct.Value = Settings.Value.GroupByProduct; GroupByProduct.Subscribe(_ => Offers.Value = Sort(Offers.Value)); RetailMarkup = new NotifyValue <decimal>(true, () => MarkupConfig.Calculate(Settings.Value.Markups, CurrentOffer.Value, User, Address), Settings); RetailCost = CurrentOffer.CombineLatest(RetailMarkup, Rounding, (o, m, r) => Round(NullableHelper.Round(o?.ResultCost * (1 + m / 100), 2), r)) .ToValue(); CurrentOffer.Subscribe(_ => RetailMarkup.Recalculate()); Persist(HideJunk, "HideJunk"); Persist(GroupByProduct, "GroupByProduct"); SessionValue(CurrentRegion, "CurrentRegion"); SessionValue(CurrentFilter, "CurrentFilter"); PrintMenuItems = new ObservableCollection <MenuItem>(); IsView = true; }
private void DumpProperties(StringBuilder sb, object obj, NestedModel nested, IList properties) { foreach (PropertyModel m in properties) { if (nested != null) { sb.AppendFormat("{0}.", nested.Property.Name); } if ((m.PropertyAtt.ColumnType ?? "").EndsWith("Blob")) { sb.AppendFormat("{0} = (blob); ", m.Property.Name); } else { object value = m.Property.GetValue(obj, null); if (NullableHelper.IsNull(value)) { sb.AppendFormat("{0} = (null); ", m.Property.Name); } else { sb.AppendFormat("{0} = '{1}'; ", m.Property.Name, value); } } } }
/// <summary> /// Replaces the or add subdomain. /// </summary> /// <param name="host">The host.</param> /// <param name="subdomainTo">The subdomain to.</param> /// <param name="path">The path.</param> /// <returns></returns> public static string ReplaceOrAddSubdomainPath(string host, string subdomainTo, string path) { if (NullableHelper.AnyIsNull(host, subdomainTo, path)) { return(path); } // path: //www.campingbooking.com // host: campingbooking.com // subdomainto: cdn. // -> //cdn.campingbooking.com Regex regexHostNoDomain = new Regex(string.Concat("//www.", host)); path = regexHostNoDomain.Replace(path, string.Concat("//", subdomainTo, host)); // path: //www.campingbooking.com // host: www.campingbooking.com // subdomainto: cdn. // -> //cdn.campingbooking.com var hostWithNewSubdomain = host.Replace("www.", subdomainTo); path = path.Replace("//" + host, "//" + hostWithNewSubdomain); // path: //campingbooking.com // host: campingbooking.com // subdomainto: cdn. // -> //cdn.campingbooking.com Regex regexHostNoWWW = new Regex(string.Concat("//", host)); path = regexHostNoWWW.Replace(path, string.Concat("//", subdomainTo, host)); return(path); }
/// <summary> /// Replaces the or add subdomain. /// img src=www.campingbooking -> img src=cdn.campingbooking.com /// </summary> /// <param name="host">The host.</param> /// <param name="subdomainTo">The subdomain to.</param> /// <param name="html">The HTML.</param> /// <returns></returns> public static string ReplaceOrAddSubdomain(string host, string subdomainTo, string html) { if (NullableHelper.AnyIsNull(host, subdomainTo, html)) { return(html); } // all imgs using (var regexImgReplacer = new RegexSubdomainReplacer("imgsrc", host, subdomainTo)) { html = RegexImgElements.Replace(html, regexImgReplacer.Replace); } // all script using (var regexScriptReplacer = new RegexSubdomainReplacer("scriptsrc", host, subdomainTo)) { html = RegexScriptElements.Replace(html, regexScriptReplacer.Replace); } // all link using (var regexLinkReplacer = new RegexSubdomainReplacer("linkhref", host, subdomainTo)) { html = RegexLinkElements.Replace(html, regexLinkReplacer.Replace); } // any plain stuff if (html.StartsWith("//") || html.StartsWith("http")) { html = ReplaceOrAddSubdomainPath(host, subdomainTo, html); } return(html); }
public int Add(StartProcessInput <AddRecordInput> input) { NullableHelper.SetNull(input.Data); var variables = new Dictionary <string, object>(); var userId = _authInfoProvider.GetCurrent().User.Id; variables.Add("starter", userId.ToString()); int processInstanceId = _runtimeProvider.StartProcessInstanceByName( input.ProcessDefinitionName, $"{input.ProcessDefinitionName}-{input.Data.RecordName}", variables); var tasks = _taskProvider.GetByProcessInstance(processInstanceId); if (tasks.Count == 0) { throw new AppCoreException("任务未创建成功!"); } var record = input.Data.MapTo <Record>(); record.ProcessInstanceId = processInstanceId; record.DataState = DataState.Creating; record.Mid = null; _recordRepository.Add(record); var task = tasks[0]; if (!input.PreventCommit) { _taskProvider.Complete(task.Id); } return(record.Id); }
public int Add(StartProcessInput <AddProjectInput> input) { NullableHelper.SetNull(input.Data); var variables = new Dictionary <string, object>(); var userId = _authInfoProvider.GetCurrent().User.Id; variables.Add("starter", userId.ToString()); int processInstanceId = _runtimeProvider.StartProcessInstanceByName( input.ProcessDefinitionName, $"{input.ProcessDefinitionName}-{input.Data.Name}", variables); var tasks = _taskProvider.GetByProcessInstance(processInstanceId); if (tasks.Count == 0) { throw new AppCoreException("任务未创建成功!"); } var project = input.Data.MapTo <Project>(); var count = ProjectContext.Instance.GetProjectBaseInfoNoCount(() => _projectRepository.Count(u => u.CreateTime.Value.Year == DateTime.Now.Year && (u.DataState == DataState.Stable || u.DataState == DataState.Creating))); project.ProcessInstanceId = processInstanceId; project.DataState = DataState.Creating; project.No = $"{DateTime.Now.Year}{count.ToString("0000")}"; project.Mid = null; _projectRepository.Add(project); var task = tasks[0]; if (!input.PreventCommit) { _taskProvider.Complete(task.Id); } return(project.Id); }
private async Task <CompletionResult> _SetCompleted(string error = null, string result = null, bool?isCancelled = null) { var idParam = new SqlParameter("@MetaDataID", System.Data.SqlDbType.Int); idParam.Value = _metaDataID; var resultParam = new SqlParameter("@Result", System.Data.SqlDbType.NVarChar, 255); resultParam.Value = NullableHelper.DBNullConvertFrom(result); var cancelledParam = new SqlParameter("@isCanceled", System.Data.SqlDbType.Bit); cancelledParam.Value = NullableHelper.DBNullConvertFrom(isCancelled); var errorParam = new SqlParameter("@ErrorMessage", System.Data.SqlDbType.NVarChar, 4000); errorParam.Value = NullableHelper.DBNullConvertFrom(error); if (error != null) { return(CompletionResult.Error); } if (isCancelled == true) { return(CompletionResult.Cancelled); } await this.SSSBDb.Database.ExecuteSqlCommandAsync("EXEC [PPS].[sp_SetCompleted] @MetaDataID, @Result, @isCanceled, @ErrorMessage", new object[] { idParam, resultParam, cancelledParam, errorParam }); MetaData metaData = await GetMetaData(CancellationToken.None); return(IsAllTasksCompleted(metaData)); }
public string FormatValue(object obj) { if (NullableHelper.IsNull(obj)) { obj = null; } if (mapValues != null) { var val = (string)mapValues[Convert.ToString(obj)]; if (val != null) { obj = val; } } if (obj == null && NullValue != null) { obj = NullValue; } using (new CultureSwitch(CultureInfo.CurrentUICulture)) { if (FormatString != null) { return(String.Format(PluggableFormatProvider.Instance, FormatString, obj)); } return(Convert.ToString(obj)); } }
public decimal SetTotalSum(DataRow dataRow, DataRow resultRow) { var share = 0m; var total = Convert.ToDecimal(dataRow["TotalSum"]); if (total <= 0) { resultRow["Share"] = DBNull.Value; } else { var supplierSum = Convert.ToDecimal(dataRow["SupplierSum"]); share = Math.Round(supplierSum / total * 100, 2); resultRow["Share"] = share.ToString(); resultRow["SupplierSum"] = supplierSum.ToString("C"); var prevTotalSum = dataRow["PrevTotalSum"] is DBNull ? null : (decimal?)Convert.ToDecimal(dataRow["PrevTotalSum"]); var prevSum = dataRow["PrevSupplierSum"] is DBNull ? null : (decimal?)Convert.ToDecimal(dataRow["PrevSupplierSum"]); if (prevTotalSum > 0) { var prevShare = NullableHelper.Round(prevSum / prevTotalSum * 100, 2); resultRow["ShareDiff"] = (share - prevShare).ToString(); } } return(share); }
public void Dispose() { if (!_disposed) { _disposed = true; NullableHelper.SetNull(ref _cts)?.Dispose(); } }
private bool IsSimpleType(Type columnDataType) { #if !GENERICS return(columnDataType.IsValueType || typeof(INullableType).IsAssignableFrom(columnDataType)); #else return(columnDataType.IsValueType || NullableHelper.IsNullableType(columnDataType)); #endif }
public void IsNotNullableTest() { var fields = typeof(NotNullableTestClass).GetAllFields(); foreach (var field in fields) { Assert.That(!NullableHelper.IsMarkedAsNullable(field), Is.True, $"{field}"); } }
public void TestFloatToNullableDouble() { object input = 5.4F; double?output = NullableHelper.ConvertToNullable <double>(input); double?correct = (double)5.4F; Assert.That(output, Is.EqualTo(correct)); }
public void TestNullableLongToNullableLong() { object input = (long?)5; long? output = NullableHelper.ConvertToNullable <long>(input); long? correct = 5; Assert.That(output, Is.EqualTo(correct)); }
public static string GetVolledigeNaam(string voorletters, string tussenvoegsels, string achternaam, string vervolgnaam) { if (NullableHelper.AllAreNull(voorletters, tussenvoegsels, achternaam, vervolgnaam)) { return(null); } return(StringHelper.Concat(InitialsNormalization.Instance.Normalize(voorletters), tussenvoegsels.ToLowerNullable(), GetVolledigeAchternaam(achternaam, vervolgnaam))); }
public void TestDoubleToNullableDecimal() { object input = 5.4; decimal?output = NullableHelper.ConvertToNullable <decimal>(input); decimal?correct = 5.4M; Assert.That(output, Is.EqualTo(correct)); }
public static string GetVolledigeNaamInformeel(string roepnaam, string tussenvoegsels, string achternaam, string vervolgnaam) { if (NullableHelper.AllAreNull(roepnaam, tussenvoegsels, achternaam, vervolgnaam)) { return(null); } return(StringHelper.Concat(roepnaam, tussenvoegsels.ToLowerNullable(), GetVolledigeAchternaam(achternaam, vervolgnaam))); }
public static string GetAchternaamVoorletters(string voorletters, string tussenvoegsels, string achternaam, string vervolgnaam = null) { if (NullableHelper.AllAreNull(voorletters, tussenvoegsels, achternaam, vervolgnaam)) { return(null); } return(StringHelper.Concat(tussenvoegsels.FirstLetterToUpper(), GetVolledigeAchternaam(achternaam, vervolgnaam)) + ", " + InitialsNormalization.Instance.Normalize(voorletters)); }
public void TestIntToNullableLong() { //making input an "object" to simulate the actual conditions //for this method's niche use case. object input = 5; long? output = NullableHelper.ConvertToNullable <long>(input); long? correct = 5; Assert.That(output, Is.EqualTo(correct)); }
public static string GetVolledigeRoepnaamTitels(string aanhef, string tussenvoegsels, string achternaam, string vervolgnaam, string titel, string titelSpec, string roepnaam) { if (NullableHelper.AllAreNull(roepnaam, tussenvoegsels, achternaam, vervolgnaam)) { return(null); } string name = StringHelper.Concat(aanhef, titel, roepnaam.ToTitleCase(), tussenvoegsels.ToLower(), GetVolledigeAchternaam(achternaam, vervolgnaam), titelSpec); return(name.Sanitize()); }
public object Coalesce(params object[] objs) { foreach (object obj in objs) { if (!NullableHelper.IsNull(obj)) { return(obj); } } return(null); }
static DictionaryEqualityComparer() { var expressionCompiler = ExpressionCompiler.Default; // ReSharper disable MultipleSpaces KeyEqualsFunc = expressionCompiler.Compile((Expression <Func <TKey, TKey, bool> >)EqualsExpressions.CreateEqualsExpression(typeof(TKey) /*,typeof(TKey).IsArray*/)); KeyGetHashCodeFunc = expressionCompiler.Compile((Expression <Func <TKey, int> >)HashCodeExpressions.CreateGetHashCodeExpression(typeof(TKey) /*,typeof(TKey).IsArray*/)); ValueEqualsFunc = expressionCompiler.Compile((Expression <Func <TValue, TValue, bool> >)EqualsExpressions.CreateEqualsExpression(typeof(TValue) /*,typeof(TKey).IsArray*/)); ValueGetHashCodeFunc = expressionCompiler.Compile((Expression <Func <TValue, int> >)HashCodeExpressions.CreateGetHashCodeExpression(typeof(TValue) /*,typeof(TKey).IsArray*/)); IsValueNullFunc = expressionCompiler.Compile(NullableHelper.GetIsNullExpression <TValue>()); // ReSharper restore MultipleSpaces }
public int Update(StartProcessInput <UpdateProjectInput> input) { //if (!_projectHelper.HasPermission("项目负责人", input.Data.Id)) //{ // throw new AppCoreException("项目没有权限"); //} if (_authInfoProvider.GetCurrent().User.Id != _projectRepository.Get().Where(u => u.Id == input.Data.Id).Select(u => u.CreatorId).FirstOrDefault()) { throw new AppCoreException("项目没有权限"); } NullableHelper.SetNull(input.Data); var variables = new Dictionary <string, object>(); var userId = _authInfoProvider.GetCurrent().User.Id; variables.Add("starter", userId.ToString()); int processInstanceId = _runtimeProvider.StartProcessInstanceByName( input.ProcessDefinitionName, $"{input.ProcessDefinitionName}-{input.Data.Name}", variables); var tasks = _taskProvider.GetByProcessInstance(processInstanceId); if (tasks.Count == 0) { throw new AppCoreException("任务未创建成功!"); } var project = input.Data.MapTo <Project>(); var projectNo = _projectRepository.Get().Where(u => u.Id == project.Id).Select(u => u.No).FirstOrDefault(); project.ProcessInstanceId = processInstanceId; project.No = projectNo; project.Attachments.ForEach(u => u.Id = 0); project.Members.ForEach(u => u.Id = 0); project.Units.ForEach(u => { u.Id = 0; u.Members.ForEach(v => v.Id = 0); }); if (project.Location != null) { project.Location.Id = 0; project.Location.ProjectId = 0; } project.DataState = DataState.Updating; project.Mid = project.Id; project.Id = 0; _projectRepository.Add(project); var task = tasks[0]; _taskProvider.Complete(task.Id); return(project.Id); }
public virtual void EndEdit() { if (Waybill != null && Waybill.IsCreatedByUser) { Amount = Quantity * SupplierCost; NdsAmount = NullableHelper.Round(Nds / 100m * Amount, 2); Calculate(Waybill.Settings); foreach (var property in typeof(WaybillLine).GetProperties()) { OnPropertyChanged(property.Name); } Waybill.Recalculate(); } }
private decimal?CalculateRetailCost(decimal?markup) { var type = GetMarkupType(); var baseCost = SupplierCostWithoutNds; if (type == MarkupType.VitallyImportant) { baseCost = ProducerCost; } var value = SupplierCost + baseCost * markup / 100 * TaxFactor; return(Round(NullableHelper.Round(value, 2), Settings.Rounding)); }
public SqlTransaction OpenTransaction() { var tsql = new SqlTransaction(this); try { tsql.OpenTransaction(); return(NullableHelper.SetNull(ref tsql)); } finally { tsql?.Dispose(); } }
static async ValueTask <MultiSqlReader> WaitAsync(ValueTask task, MultiSqlReader sqlReader) { var copy = sqlReader; try { await task.ConfigureAwait(false); return(NullableHelper.SetNull(ref copy)); } finally { copy?.Dispose(); } }
static async ValueTask <SqlTransaction> WaitAsync(ValueTask task, SqlTransaction transaction) { var copy = transaction; try { await task.ConfigureAwait(false); return(NullableHelper.SetNull(ref copy)); } finally { copy?.Dispose(); } }
/// <summary> /// https://msdn.microsoft.com/en-us/library/ms229716(v=vs.110).aspx /// </summary> /// <returns></returns> public static string GetFileNamePathByPattern(string ftpPath, string filePattern, string ftpUser, string ftpPassword) { if (NullableHelper.AnyIsNull(ftpPath, filePattern, ftpUser, ftpPassword)) { return(null); } FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath)); ftp.Timeout = 60000; ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; ftp.UseBinary = true; ftp.Proxy = null; if (string.IsNullOrEmpty(ftpUser) || string.IsNullOrEmpty(ftpPassword)) { throw new InvalidCredentialException(); } ftp.Credentials = new NetworkCredential(ftpUser, ftpPassword); FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); List <string> files = new List <string>(); while (reader.Peek() >= 0) { string line = reader.ReadLine(); //string[] fileItems = line.CollapseWhiteSpaces().Split(' '); files.Add(line); } string ftpFile = null; foreach (var item in files.OrderByDescending(o => o)) { if (new Regex(filePattern).IsMatch(item)) { ftpFile = item; break; } } return($"{ftpPath}/{ftpFile}"); }