/// <summary> /// Inserts single record into target table asynchronously and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="obj">Object with data to insert.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Inserted record.</returns> public static Task <TTarget> InsertWithOutputAsync <TTarget>( this ITable <TTarget> target, [InstantHandle] TTarget obj, CancellationToken token = default) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } IQueryable <TTarget> query = target; var items = query.Provider.CreateQuery <TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, obj), new[] { query.Expression, Expression.Constant(obj) })); return(items.AsAsyncEnumerable().FirstOrDefaultAsync(token)); }
/// <summary> /// Get the Route data for postcode /// </summary> /// <param name="postcode"></param> /// <param name="fields"></param> /// <returns></returns> public async Task <List <DeliveryRouteDTO> > GetRouteData(string postcode, string fields) { using (loggingHelper.RMTraceManager.StartTrace("Integration.GetRouteData")) { string methodName = MethodHelper.GetActualAsyncMethodName(); loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionStarted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.PostalAddressAPIPriority, LoggerTraceConstants.PostalAddressIntegrationServiceMethodEntryEventId, LoggerTraceConstants.Title); ReferenceDataCategoryDTO referenceCategories = new ReferenceDataCategoryDTO(); HttpResponseMessage result = await httpHandler.GetAsync(routeDataWebAPIName + "deliveryroute/postcode/" + postcode + "/" + fields); if (!result.IsSuccessStatusCode) { var responseContent = result.ReasonPhrase; throw new ServiceException(responseContent); } List <DeliveryRouteDTO> apiResult = JsonConvert.DeserializeObject <List <DeliveryRouteDTO> >(result.Content.ReadAsStringAsync().Result); loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionCompleted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.PostalAddressAPIPriority, LoggerTraceConstants.PostalAddressIntegrationServiceMethodExitEventId, LoggerTraceConstants.Title); return(apiResult); } }
/// <summary> /// Deletes records from source query into target table asynchronously and returns deleted records. /// </summary> /// <typeparam name="TSource">Source query record type.</typeparam> /// <typeparam name="TOutput">Output table record type.</typeparam> /// <param name="source">Source query, that returns data for delete operation.</param> /// <param name="outputExpression">Output record constructor expression. /// Expression supports only record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Array of records.</returns> public static Task <TOutput[]> DeleteWithOutputAsync <TSource, TOutput>( this IQueryable <TSource> source, Expression <Func <TSource, TOutput> > outputExpression, CancellationToken token = default) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (outputExpression == null) { throw new ArgumentNullException(nameof(outputExpression)); } var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; return(currentSource.Provider.CreateQuery <TOutput>( Expression.Call( null, MethodHelper.GetMethodInfo(DeleteWithOutput, source, outputExpression), currentSource.Expression, Expression.Quote(outputExpression))) .ToArrayAsync(token)); }
private static Func <T, T, bool> CreateEqualsFunc(IEnumerable <LambdaExpression> membersToCompare, bool assertOnFail = false) { var x = Expression.Parameter(typeof(T), "x"); var y = Expression.Parameter(typeof(T), "y"); var expressions = membersToCompare.Select(me => { var arg0 = RemoveCastToObject(me.GetBody(x)); var arg1 = RemoveCastToObject(me.GetBody(y)); var eq = GetEqualityComparer(arg1.Type); var pi = eq.GetPropertyEx("Default"); var mi = eq.GetMethodsEx().Single(m => m.IsPublic && m.Name == "Equals" && m.GetParameters().Length == 2); Debug.Assert(pi != null, "pi != null"); Expression expr = Expression.Call(Expression.Property(null, pi), mi, arg0, arg1); if (assertOnFail) { expr = Expression.Call( MethodHelper.GetMethodInfo(Assert, true, (object)null, (object)null), expr, Expression.Convert(arg0, typeof(object)), Expression.Convert(arg1, typeof(object))); } return(expr); }); var expression = expressions .DefaultIfEmpty(Expression.Constant(true)) .Aggregate(Expression.AndAlso); return(Expression .Lambda <Func <T, T, bool> >(expression, x, y) .Compile()); }
public static async Task <Document> FixInvocationWithParameters(Document document, IInvocation invocation, bool generateNamedParameters, SemanticModel semanticModel, IMappingSourceFinder mappingSourceFinder, CancellationToken cancellationToken) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var overloadParameterSets = invocation.GetOverloadParameterSets(semanticModel); if (overloadParameterSets != null) { var contextAssembly = semanticModel.FindContextAssembly(invocation.SourceNode); var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator, contextAssembly); var parametersMatch = MethodHelper.FindBestParametersMatch(mappingSourceFinder, overloadParameterSets); if (parametersMatch != null) { var argumentList = parametersMatch.ToArgumentListSyntax(mappingEngine, generateNamedParameters); return(await document.ReplaceNodes(invocation.SourceNode, invocation.WithArgumentList(argumentList), cancellationToken)); } } return(document); }
private string GetArgumentListWithLocalVariables(Document document, IInvocation invocation, bool generateNamedParameters, SemanticModel semanticModel) { var mappingSourceFinder = LocalScopeMappingSourceFinder.FromScope(semanticModel, invocation.SourceNode, AllowedSymbolsForCompletion); mappingSourceFinder.AllowMatchOnlyByTypeWhenSingleCandidate = true; var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var overloadParameterSets = invocation.GetOverloadParameterSets(semanticModel); if (overloadParameterSets != null) { var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator); var mappingContext = new MappingContext(invocation.SourceNode, semanticModel); var parametersMatch = MethodHelper.FindBestParametersMatch(mappingSourceFinder, overloadParameterSets, mappingContext); if (parametersMatch != null) { var argumentList = parametersMatch.ToArgumentListSyntax(mappingEngine, mappingContext, generateNamedParameters); var chunks = argumentList.Arguments.Select(a => a.ToString()); return(string.Join(", ", chunks)); } } return(null); }
/// <summary> /// Inserts single record into target table asynchronously and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="setter">Insert expression. Expression supports only target table record new expression with field initializers.</param> /// <param name="token">Optional asynchronous operation cancellation token.</param> /// <returns>Inserted record.</returns> public static Task <TTarget> InsertWithOutputAsync <TTarget>( this ITable <TTarget> target, [InstantHandle] Expression <Func <TTarget> > setter, CancellationToken token = default) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (setter == null) { throw new ArgumentNullException(nameof(setter)); } IQueryable <TTarget> query = target; var items = query.Provider.CreateQuery <TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, setter), query.Expression, Expression.Quote(setter))); return(items.AsAsyncEnumerable().FirstAsync(token)); }
/// <summary> /// Get connection by Id. /// </summary> /// <param name="connectionId"></param> /// <returns></returns> public ConnectionModel GetConnectionById(int connectionId) { log.Debug(MethodHelper.GetCurrentMethodName() + " Method execution start."); ConnectionModel connectionModel = null; try { using (ConnectionDB connectionDB = new ConnectionDB()) { connectionModel = connectionDB.GetConnectionById(connectionId); connectionModel.ConnectionPassword = EncryptionHelper.Decrypt(connectionModel.ConnectionPassword); return(connectionModel); } } catch (Exception exception) { errorLog.Fatal("Exception " + exception.Message + "\n" + exception.StackTrace); throw; } finally { log.Debug(MethodHelper.GetCurrentMethodName() + " Method execution end."); } }
internal override void InitializeByRef(PropertyInfo propertyInfo, XBindingFlags flags) { base.InitializeByRef(propertyInfo, flags); declaringType = propertyInfo.DeclaringType; declaringTypeHandle = TypeHelper.GetTypeHandle(declaringType); var getMethod = propertyInfo.GetGetMethod((flags & XBindingFlags.NonPublic) != 0); if (getMethod != null) { var _ref = MethodHelper.CreateDelegate <XClassRefValueHandler <TValue> >(getMethod, SignatureLevels.Cast); _get = (obj) => { return(_ref(obj)); }; _set = (obj, value) => { _ref(obj) = value; }; } }
/// <summary> /// Adds or updates connection /// </summary> /// <param name="connectionModel"></param> /// <returns></returns> public OperationDetails AddEditConnection(ConnectionModel connectionModel) { log.Debug(MethodHelper.GetCurrentMethodName() + " Method execution start."); OperationDetails operationDetails = null; try { using (ConnectionDB connectionDB = new ConnectionDB()) { connectionModel.ConnectionPassword = EncryptionHelper.Encrypt(connectionModel.ConnectionPassword); operationDetails = connectionDB.AddEditConnection(connectionModel); return(operationDetails); } } catch (Exception exception) { errorLog.Fatal("Exception " + exception.Message + "\n" + exception.StackTrace); throw; } finally { log.Debug(MethodHelper.GetCurrentMethodName() + " Method execution end."); } }
/// <summary> /// Runs a sample query to test if database connection is successful. /// </summary> /// <param name="connectionString"></param> /// <returns></returns> public int TestConnection(ConnectionModel connection) { log.Debug(MethodHelper.GetCurrentMethodName() + " Method execution start."); try { string connectionString = string.Format("Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = {0})(PORT = {1}))" + "(CONNECT_DATA =(SERVER = DEDICATED)(SID = {2})));User Id= {3};Password= {4};Persist Security Info=True;", connection.IpAddress, connection.PortNumber, connection.SID, connection.ConnectionUsername, connection.ConnectionPassword); using (ConnectionDB connectionDB = new ConnectionDB(connectionString)) { return(connectionDB.TestConnection()); } } catch (Exception exception) { errorLog.Fatal("Exception " + exception.Message + "\n" + exception.StackTrace); throw; } finally { log.Debug(MethodHelper.GetCurrentMethodName() + " Method execution end."); } }
private protected override void InitializeByRef(PropertyInfo propertyInfo, XBindingFlags flags) { base.InitializeByRef(propertyInfo, flags); if (_get == null || _set == null) { var getMethod = propertyInfo.GetGetMethod((flags & XBindingFlags.NonPublic) != 0); if (getMethod != null) { var _ref = MethodHelper.CreateDelegate <XStaticRefValueHandler <TValue> >(getMethod, false); _get = () => { return(_ref()); }; _set = (value) => { _ref() = value; }; } } }
private protected override void InitializeByValue(PropertyInfo propertyInfo, XBindingFlags flags) { base.InitializeByValue(propertyInfo, flags); if (_get == null) { var getMethod = propertyInfo.GetGetMethod((flags & XBindingFlags.NonPublic) != 0); if (getMethod != null) { _get = MethodHelper.CreateDelegate <XStaticGetValueHandler <TValue> >(getMethod, false); } } if (_set == null) { var setMethod = propertyInfo.GetSetMethod((flags & XBindingFlags.NonPublic) != 0); if (setMethod != null) { _set = MethodHelper.CreateDelegate <XStaticSetValueHandler <TValue> >(setMethod, false); } } }
public ActionResult Detail(string Account, string CompCd, string VenderCd, AuthNodeType mode) { try { if (MethodHelper.IsNullOrEmpty(Account, CompCd, VenderCd)) { throw new ArgumentException($"取得技師信息時,并没有给入对应的参数"); } var con = new Conditions <DataBase.TVenderTechnician>(); con.And(x => x.Comp_Cd == CompCd); con.And(x => x.Vender_Cd == VenderCd); con.And(x => x.Account == Account); //con.Include(x => x.TVENDER.TCMPDAT); TvenderTechnician technician = _technicianRepo.Get(con); if (technician == null) { throw new NullReferenceException($"取得不到技師信息,公司编号:{CompCd} , 厂商编号:{VenderCd} ,账号为:{Account}"); } return(View("Edit", new TechnicianListDetailViewModel(technician) { ActionType = mode })); } catch (Exception ex) { _logger.Error(ex.Message); return(View()); } }
/// <summary> /// Get Delivery Point details depending on the UDPRN /// </summary> /// <param name="addressId">Postal Address id</param> /// <returns>returns DeliveryPoint object</returns> public async Task <DeliveryPointDTO> GetDeliveryPointByPostalAddress(Guid addressId) { using (loggingHelper.RMTraceManager.StartTrace("Integration.GetDeliveryPointByPostalAddress")) { string method = typeof(ThirdPartyAddressLocationIntegrationService) + "." + nameof(GetDeliveryPointByPostalAddress); loggingHelper.LogMethodEntry(method, LoggerTraceConstants.ThirdPartyAddressLocationAPIPriority, LoggerTraceConstants.ThirdPartyAddressLocationIntegrationServiceMethodEntryEventId); string methodName = MethodHelper.GetActualAsyncMethodName(); string serviceUrl = configurationHelper.ReadAppSettingsConfigurationValues(DeliveryPointManagerDataWebAPIName); string route = configurationHelper.ReadAppSettingsConfigurationValues(methodName); HttpResponseMessage result = await httpHandler.GetAsync(string.Format(serviceUrl + route, addressId)); if (!result.IsSuccessStatusCode) { // LOG ERROR WITH Statuscode var responseContent = result.ReasonPhrase; throw new ServiceException(responseContent); } DeliveryPointDTO deliveryPointDTO = JsonConvert.DeserializeObject <DeliveryPointDTO>(result.Content.ReadAsStringAsync().Result); loggingHelper.LogMethodExit(method, LoggerTraceConstants.ThirdPartyAddressLocationAPIPriority, LoggerTraceConstants.ThirdPartyAddressLocationIntegrationServiceMethodExitEventId); return(deliveryPointDTO); } }
/// <summary> /// Add new notification to the database /// </summary> /// <param name="notificationDTO">NotificationDTO object</param> /// <returns>Task<int></returns> public async Task <int> AddNewNotification(NotificationDTO notificationDTO) { using (loggingHelper.RMTraceManager.StartTrace("DataService.AddNewNotification")) { int saveChangesAsync = default(int); string methodName = MethodHelper.GetActualAsyncMethodName(); loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionStarted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationDataServiceMethodEntryEventId, LoggerTraceConstants.Title); try { Notification newNotification = new Notification(); GenericMapper.Map(notificationDTO, newNotification); DataContext.Notifications.Add(newNotification); loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionCompleted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationDataServiceMethodExitEventId, LoggerTraceConstants.Title); saveChangesAsync = await DataContext.SaveChangesAsync(); } catch (DbUpdateException dbUpdateException) { loggingHelper.Log(dbUpdateException, TraceEventType.Error); throw new DataAccessException(dbUpdateException, string.Format(ErrorConstants.Err_SqlAddException, string.Concat("notification for:", notificationDTO.NotificationActionLink))); } catch (NotSupportedException notSupportedException) { loggingHelper.Log(notSupportedException, TraceEventType.Error); notSupportedException.Data.Add(ErrorConstants.UserFriendlyErrorMessage, ErrorConstants.Err_Default); throw new InfrastructureException(notSupportedException, ErrorConstants.Err_NotSupportedException); } catch (ObjectDisposedException disposedException) { loggingHelper.Log(disposedException, TraceEventType.Error); disposedException.Data.Add(ErrorConstants.UserFriendlyErrorMessage, ErrorConstants.Err_Default); throw new ServiceException(disposedException, ErrorConstants.Err_ObjectDisposedException); } return(saveChangesAsync); } }
[Pure] // Methods.LinqToDB.ThenLoadFromManyManyFilter public static ILoadWithQueryable <TEntity, TProperty> ThenLoad <TEntity, TPreviousProperty, TProperty>( this ILoadWithQueryable <TEntity, IEnumerable <TPreviousProperty> > source, [InstantHandle] Expression <Func <TPreviousProperty, IEnumerable <TProperty> > > selector, [InstantHandle] Expression <Func <IQueryable <TProperty>, IQueryable <TProperty> > > loadFunc) where TEntity : class { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (selector == null) { throw new ArgumentNullException(nameof(selector)); } var currentSource = ProcessSourceQueryable?.Invoke(source) ?? source; var result = currentSource.Provider.CreateQuery <TEntity>( Expression.Call(null, MethodHelper.GetMethodInfo(ThenLoad, source, selector, loadFunc), currentSource.Expression, Expression.Quote(selector), Expression.Quote(loadFunc))); return(new LoadWithQueryable <TEntity, TProperty>(result)); }
/// <summary> /// Inserts single record into target table and returns inserted record. /// </summary> /// <typeparam name="TTarget">Inserted record type.</typeparam> /// <param name="target">Target table.</param> /// <param name="obj">Object with data to insert.</param> /// <returns>Inserted record.</returns> /// <remarks>Supported Providers: MS SQL</remarks> public static TTarget InsertWithOutput <TTarget>( this ITable <TTarget> target, [InstantHandle] TTarget obj) where TTarget : notnull { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } IQueryable <TTarget> query = target; var items = query.Provider.CreateQuery <TTarget>( Expression.Call( null, MethodHelper.GetMethodInfo(InsertWithOutput, target, obj), query.Expression, Expression.Constant(obj))); return(items.AsEnumerable().First()); }
private void grv_dieuxe_CellClick(object sender, DataGridViewCellEventArgs e) { int i = e.RowIndex; if (e.RowIndex < 0) { return; } //if (e.RowIndex == grv_nhan_vien.Rows.Count-1) // return; DTO_DieuXe dieuxe = grv_dieuxe.Rows[e.RowIndex].DataBoundItem as DTO_DieuXe; txt_madieuxe.Text = dieuxe.ma_dieu_xe; txt_noigiao.Text = dieuxe.noi_giao; txt_noinhan.Text = dieuxe.noi_nhan; txt_sotan.Text = dieuxe.so_tan; cbb_khachhang.SelectedValue = dieuxe.ma_khach_hang.Trim(); //cbb_soxe.SelectedValue = dieuxe.ma_so_xe.Trim(); cbb_soxe.Text = grv_dieuxe.Rows[i].Cells["col_sx"].Value.ToString(); // cbb_soxe.SelectedIndex = 3; // MessageBox.Show(dieuxe.ma_so_xe.Trim()); data_ngaydieuxe.Value = Convert.ToDateTime(dieuxe.ngay_dieu_xe); if (grv_dieuxe.Rows[i].Cells["ngay_ve"].Value.ToString().Trim() != "01/01/0001 12:00:00 SA") { dtpngayve.Value = Convert.ToDateTime(dieuxe.ngay_ve); //MessageBox.Show(grv_dieuxe.Rows[i].Cells["ngay_ve"].Value.ToString() ); } ; cbtinhtrangthanhtoan.SelectedValue = dieuxe.tinh_trang_thanh_toan == "Chưa Thanh Toán" ? 0 : 1; EnableControl(false); MethodHelper.ClearErrorProvider(); btn_luu.Enabled = false; btn_sua.Enabled = true; btn_xoa.Enabled = true; }
public static IEnumerable <MethodInfo> GetSupportedMethods() { yield return(MethodHelper.GetMethodDefinition(() => Enumerable.Intersect <object>(null, null))); yield return(MethodHelper.GetMethodDefinition(() => Queryable.Intersect <object>(null, null))); }
/// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the _values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> private static bool CheckTestMethodSignature(TestMethod testMethod, ParameterSet parms) { if (testMethod.Method.IsAbstract) { return(MarkAsNotRunnable(testMethod, "Method is abstract")); } if (!testMethod.Method.IsPublic) { return(MarkAsNotRunnable(testMethod, "Method is not public")); } #if NETCF // TODO: Get this to work if (testMethod.Method.IsGenericMethodDefinition) { return(MarkAsNotRunnable(testMethod, "Generic test methods are not yet supported under .NET CF")); } #endif ParameterInfo[] parameters = testMethod.Method.GetParameters(); int argsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) { argsProvided = arglist.Length; } if (testMethod.RunState != RunState.Runnable) { return(false); } } Type returnType = testMethod.Method.ReturnType; if (returnType.Equals(typeof(void))) { if (parms != null && parms.HasExpectedResult) { return(MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result")); } } else { #if NET_4_5 if (MethodHelper.IsAsyncMethod(testMethod.Method)) { bool returnsGenericTask = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>); if (returnsGenericTask && (parms == null || !parms.HasExpectedResult && !parms.ExceptionExpected)) { return(MarkAsNotRunnable(testMethod, "Async test method must have Task or void return type when no result is expected")); } else if (!returnsGenericTask && parms != null && parms.HasExpectedResult) { return(MarkAsNotRunnable(testMethod, "Async test method must have Task<T> return type when a result is expected")); } } else #endif if (parms == null || !parms.HasExpectedResult && !parms.ExceptionExpected) { return(MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected")); } } if (argsProvided > 0 && argsNeeded == 0) { return(MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any")); } if (argsProvided == 0 && argsNeeded > 0) { return(MarkAsNotRunnable(testMethod, "No arguments were provided")); } if (argsProvided != argsNeeded) { return(MarkAsNotRunnable(testMethod, "Wrong number of arguments provided")); } #if !NETCF if (testMethod.Method.IsGenericMethodDefinition) { Type[] typeArguments = GetTypeArgumentsForMethod(testMethod.Method, arglist); foreach (object o in typeArguments) { if (o == null) { return(MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method")); } } testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } #endif if (arglist != null && parameters != null) { TypeHelper.ConvertArgumentList(arglist, parameters); } return(true); }
public override string ReceiveData() { var funModel = this.FindFunModel(HeritageId, FunId); if (funModel == null) { return(JsonHelper.SerializeObject(new ResultModel(false, "找不到该功能对应的配置信息!"))); } var cListType = MethodHelper.GetTypeList(GetModelName(funModel.TableName), "HPF_KGFJ_KGFJJL_XGWD"); var ent = JsonHelper.DeserializeJsonToDynamicObject(BusinessJsonStr, cListType); var entData = ent.DATA as IList; var entDataDetail = ent.DATADETAIL as IList; var entPathList = ent.FILEPATHLIST as List <FileInfoEx>; //if (entData.Count != entPathList.Count) // return JsonHelper.SerializeObject(new ResultModel(false, "文件个数与记录条数不符!"));//这个地方不能判断,因为无已发表的简报的情况就附件为空。 var listSql = new List <string>(); var listYsjId = new List <string>(); var kgfjjlid = new Dictionary <string, string>(); var dbContext = DBHelperPool.Instance.GetDbHelper(); if (dbContext == null) { return(JsonHelper.SerializeObject(ToolResult.Failure("数据库连接异常!"))); } var receiveAllFileInfo = entPathList == null? null : CommonBusiness.GetFileListByFileID(entPathList.Select(e => e.FILEID)); foreach (var item in entData) { var nameToValue = item.GetNameToValueDic(); if (nameToValue.ContainsKey("GLYCBTID")) { nameToValue["GLYCBTID"] = HeritageId; } if (nameToValue.ContainsKey("ID")) { nameToValue["ID"] = Guid.NewGuid(); } else { nameToValue.Add("ID", Guid.NewGuid()); } var ysjid = nameToValue["YCDSJID"] + ""; kgfjjlid.Add(ysjid, nameToValue["ID"] + ""); listYsjId.Add(ysjid); listSql.Add(dbContext.insertByParamsReturnSQL(GetModelName(funModel.TableName), nameToValue)); } if (entDataDetail != null) { foreach (var item in entDataDetail) { var nameToValue = item.GetNameToValueDic(); if (nameToValue.ContainsKey("GLYCBTID")) { nameToValue["GLYCBTID"] = HeritageId; } if (nameToValue.ContainsKey("ID")) { nameToValue["ID"] = Guid.NewGuid(); } else { nameToValue.Add("ID", Guid.NewGuid()); } if (nameToValue.ContainsKey("FJJLID")) { nameToValue["FJJLID"] = kgfjjlid["FJJLID"]; } else { nameToValue.Add("FJJLID", kgfjjlid["FJJLID"]); } var ysjid = nameToValue["YCDSJID"] + ""; if (string.IsNullOrEmpty(ysjid)) { return(JsonHelper.SerializeObject(new ResultModel(false, "YCDSJID不能为空!"))); } var fileIds = entPathList.Where(e => e.YCDSJID == ysjid).Select(e => e.FILEID).ToList(); var filePathList = receiveAllFileInfo.Where(e => fileIds.Contains(e.FILEID)).ToList(); var file = entPathList.FirstOrDefault(e => e.YCDSJID == ysjid); if (file != null) { var filePath = receiveAllFileInfo.FirstOrDefault(e => e.FILEID == file.FILEID); if (filePath != null) { nameToValue["WDMC"] = filePath.FILENAME; nameToValue["WDLX"] = filePath.FILETYPE; nameToValue["LJ"] = filePath.RELATIVEPATH; } } listSql.Add(dbContext.insertByParamsReturnSQL(GetModelName(funModel.TableName), nameToValue)); } } if (!CheckIsDock(listSql, listYsjId, funModel.TableName, dbContext)) { return(JsonHelper.SerializeObject(new ResultModel(false, "已经存在对接的数据"))); } return(GetExeListSQL(dbContext, listSql)); }
public static IEnumerable <MethodInfo> GetSupportedMethods() { return(MethodHelper.GetEnumerableAndQueryableMethodDefinitions("Average")); }
/// <summary> /// This Method is added in case we want JsonConverter to serialize only new data, /// be sure to Clear PropertyChanges before beginning to change the data /// </summary> /// <returns></returns> public string GetJsonForPropertyChangesOnly() { return(MethodHelper.CreateNewValuesFromObject(this)); }
public override string ReceiveData() { var funModel = this.FindFunModel(HeritageId, FunId); if (funModel == null) { return(JsonHelper.SerializeObject(new ResultModel(false, "找不到该功能对应的配置信息"))); } //通过xml配置的表名 找到类的路径 反射成 list类 对象 var cListType = MethodHelper.GetTypeListFileEx(GetModelName(funModel.TableName)); //GCHeritagePlatform.Services.PublicMornitor.Model.HPF_RCXC_RCXCYCJL; var ent = JsonHelper.DeserializeJsonToDynamicObject(BusinessJsonStr, cListType); //遗产地发过来的字符串(json格式)的项与我们在model中建的功能类的属性是一一对应的,这里进行赋值 var entData = ent.DATA as IList; var entPathList = ent.FILEPATHLIST as List <FileInfoEx>; //判断文件、照片记录的条数与实际文件的个数是否相符 //if (FunId=="1403"&&entData.Count != entPathList.Count) return JsonHelper.SerializeObject(new ResultModel(false, "文件个数与记录条数不符!")); if (FunId == "1403" && (ent.FILEPATHLIST == null || ent.FILEPATHLIST.Count == 0)) { return(JsonHelper.SerializeObject(new ResultModel(false, "缺少对接文档信息!"))); } var listSqlStr = new List <string>(); var listYSJID = new List <string>(); var dbContext = DBHelperPool.Instance.GetDbHelper(); var receiveAllFileInfo = entPathList == null? null : CommonBusiness.GetFileListByFileID(entPathList.Select(e => e.FILEID)); //判断取到的文件数量和上传到的文件数量是否一样? if (FunId == "1403" && (receiveAllFileInfo.Count != entPathList.Count)) { return(JsonHelper.SerializeObject(new ResultModel(false, "取得的文件与上传文件个数不匹配!"))); } foreach (var item in entData) { var nameToValue = item.GetNameToValueDic(); if (nameToValue.ContainsKey("GLYCBTID")) { nameToValue["GLYCBTID"] = HeritageId; } if (nameToValue.ContainsKey("ID")) { nameToValue["ID"] = Guid.NewGuid(); } else { nameToValue.Add("ID", Guid.NewGuid()); } var ysjid = nameToValue["YCDSJID"] + ""; if (string.IsNullOrEmpty(ysjid)) { return(JsonHelper.SerializeObject(new ResultModel(false, "YCDSJID不能为空!"))); } if (entPathList != null) { var fileIDs = entPathList.Where(e => e.YCDSJID == ysjid).Select(e => e.FILEID).ToList(); var filePathList = receiveAllFileInfo.Where(e => fileIDs.Contains(e.FILEID)).ToList(); switch (FunId) { case "1401": //考古报告信息 { var file = entPathList.Where(e => e.YCDSJID == ysjid).FirstOrDefault(); if (file != null) { var filePath = receiveAllFileInfo.FirstOrDefault(e => e.FILEID == file.FILEID); if (filePath != null) { nameToValue["XGWD"] = filePath.RELATIVEPATH; } //var kgxmjlid = nameToValue["KGXMID"] + ""; //if (!string.IsNullOrEmpty(kgxmjlid)) //{ // var dtForeignKeyTable = this.GetKGFJGZJZID(dbContext, kgxmjlid, "HPF_KGFJ_KGXM"); // var entKGBGXXJL = DataTableToEnt<HPF_KGFJ_KGXM>.FillModel(dtForeignKeyTable); // //取出项目中的YCDSJID=外键ID的记录 // var entKGXMJL = entKGBGXXJL.FirstOrDefault(e => e.YCDSJID == kgxmjlid); // //判断如果存在外键关联,则把外键进行赋值,目前由于鼓浪屿不存在关联,所以不进行关联。 // nameToValue["KGXMID"] = entKGXMJL.ID; //} } } break; case "1403": //考古发掘照片 { //将原来的照片中的现场照片中的关联外键进展记录取出来 var kgfjgzjzid = nameToValue["KGFJJLID"] + ""; //通过外键进展记录在进展表中查询总平台的记录 var dtForeignKeyTable = this.GetKGFJGZJZID(dbContext, kgfjgzjzid, "HPF_KGFJ_KGFJJL"); var entKGFJJZJL = DataTableToEnt <HPF_KGFJ_KGFJJL> .FillModel(dtForeignKeyTable); foreach (var fileinfo in filePathList) { nameToValue["TPLJ"] = fileinfo.RELATIVEPATH; nameToValue["TPMC"] = fileinfo.FILENAME; nameToValue["TPGS"] = fileinfo.FILETYPE; //取出进展中的YCDSJID=外键ID的记录 var entKGFJGZJZ = entKGFJJZJL.FirstOrDefault(e => e.YCDSJID == kgfjgzjzid); if (entKGFJGZJZ == null) { return(JsonHelper.SerializeObject(new ResultModel(false, "未找到考古发掘工作进展记录!"))); } nameToValue["KGFJJLID"] = entKGFJGZJZ.ID; } } break; } } listSqlStr.Add(dbContext.insertByParamsReturnSQL(GetModelName(funModel.TableName), nameToValue)); } if (!CheckIsDock(listSqlStr, listYSJID, funModel.TableName, dbContext)) { return(JsonHelper.SerializeObject(new ResultModel(false, "已经存在对接的数据"))); } return(GetExeListSQL(dbContext, listSqlStr)); }
public override string ReceiveData() { var dockBTYZTBHStructInitClass = GetTableName(FunId); //根据传入两个表名来获取对应的数据结构模型的类型 var eType = MethodHelper.GetTypeList(dockBTYZTBHStructInitClass.MainTableName, dockBTYZTBHStructInitClass.SubordinateTableName); //将Json串按指定的类型进行反序列化为dynamic实体对象 var ent = JsonHelper.DeserializeJsonToDynamicObject(this.BusinessJsonStr, eType); var entBHList = ent.DATA as IList; var entBHJLList = ent.DATADETAIL as IList; var entPathList = ent.FILEPATHLIST as List <FileInfoEx>; var listSqlStr = new List <string>(); var listYSJID = new List <string>(); var dicOldToNew = new Dictionary <string, Guid>(); var dbContext = DBHelperPool.Instance.GetDbHelper(); if (dbContext == null) { return(JsonHelper.SerializeObject(ToolResult.Failure("数据连接异常!"))); } //主表 foreach (var item in entBHList) { var nameToValue = item.GetNameToValueDic(); if (!nameToValue.ContainsKey("YCDSJID")) { return(JsonHelper.SerializeObject(new ResultModel(false, "元数据ID不存在,对接失败!"))); } if (nameToValue.ContainsKey("BHBH")) { string newBHBH; //代码限定,要求对方传来的病害编号是编号ID,而不是具体的编号内容,并且该ID必须是病害调查监测工作情况记录表中的主键 var bIsExistBHBH = GetBHBHByOldDataID(dbContext, nameToValue["BHBH"] + "", out newBHBH); if (!bIsExistBHBH) { return(JsonHelper.SerializeObject(new ResultModel(false, "请先对接病害的工作监测记录!"))); } nameToValue["BHBH"] = newBHBH; } var ysjid = nameToValue["YCDSJID"] + "";//元数据ID var guid = Guid.NewGuid(); //这里保存的是LF的ID dicOldToNew.Add(ysjid, guid); if (nameToValue.ContainsKey("GLYCBTID")) { nameToValue["GLYCBTID"] = HeritageId; } if (nameToValue.ContainsKey("ID")) {//把ID字段赋一个guid nameToValue["ID"] = guid; } else {//没有的增加 nameToValue.Add("ID", guid); } if (!string.IsNullOrEmpty(ysjid)) //有可能对接过来就是 统计过得数据 例如景点日游客量 { listYSJID.Add(ysjid); //防止重复对接 } listSqlStr.Add(dbContext.insertByParamsReturnSQL(dockBTYZTBHStructInitClass.MainTableName, nameToValue)); } //明细 var dicFileRelatedID = new Dictionary <string, Guid>(); foreach (var item in entBHJLList) { var nameToValue = item.GetNameToValueDic(); if (!nameToValue.ContainsKey("YCDSJID")) { return(JsonHelper.SerializeObject(new ResultModel(false, "元数据ID不存在,对接失败!"))); } //将裂缝记录中的老外键ID记录下来,保存的裂缝中的ycdsjid var lfid = nameToValue[dockBTYZTBHStructInitClass.RelatedID] + ""; var guid = Guid.NewGuid(); if (nameToValue.ContainsKey("GLYCBTID")) { nameToValue["GLYCBTID"] = HeritageId; } if (nameToValue.ContainsKey("ID")) { nameToValue["ID"] = guid; } else { nameToValue.Add("ID", guid); } //将裂缝的ID值赋给裂缝记录表中的裂缝ID字段 nameToValue[dockBTYZTBHStructInitClass.RelatedID] = dicOldToNew[lfid]; var ysjid = nameToValue["YCDSJID"] + ""; //这里保存的是裂缝JL的ID dicFileRelatedID.Add(ysjid, guid); listSqlStr.Add(dbContext.insertByParamsReturnSQL(dockBTYZTBHStructInitClass.SubordinateTableName, nameToValue)); } //附件 if (entPathList != null && entPathList.Count > 0) { var fileIds = entPathList.Select(e => e.FILEID).ToList(); var fileInfoList = CommonBusiness.GetFileListByFileID(fileIds); if (fileInfoList == null || fileInfoList.Count != fileIds.Count) { return(JsonHelper.SerializeObject(new ResultModel(false, "文件信息不对应"))); } foreach (var item in fileInfoList) { var entFile = entPathList.FirstOrDefault(e => e.FILEID == item.FILEID); //public string sqlInsertTP = "insert into {0} (ID,MC,TPLJ,{1},TPGS,YCDSJID,RKSJ)values ('{2}','{3}','{4}','{5}','{6}','{7}','{8}')"; var sql = string.Format(this.sqlInsertTP, dockBTYZTBHStructInitClass.RelatedZPTableName, dockBTYZTBHStructInitClass.RelatedJLID, Guid.NewGuid(), item.FILENAME, item.RELATIVEPATH, dicFileRelatedID[entFile.YCDSJID], item.FILETYPE, entFile.YCDSJID, DateTime.Now.ToString()); ///JLID listSqlStr.Add(sql); } } if (!CheckIsDock(listSqlStr, listYSJID, dockBTYZTBHStructInitClass.MainTableName, dbContext)) { return(JsonHelper.SerializeObject(new ResultModel(false, "已经存在对接的数据"))); } return(GetExeListSQL(dbContext, listSqlStr)); }
// Calls method, Converts string data to parameters, as safely as possible. public void Invoke(string[] data) { MethodHelper.Invoke(component, methodInfo, data); }
public static IEnumerable <MethodInfo> GetSupportedMethods() { return(MethodHelper.GetEnumerableAndQueryableMethodDefinitions(nameof(MongoQueryable.Sample))); }
/// <summary> /// Gets the effective Value of this ScriptValue instance /// </summary> /// <param name="arguments">indexer/method/constructor arguments</param> /// <returns>an object that represents the value of this ScriptValue</returns> public virtual object GetValue(ScriptValue[] arguments) { if (!Getable) { throw new ScriptException("Get is not supported for this member"); } if (creator != null) { bool ok; object retVal = creator.InvokeExecutor(Value, arguments, bypassCompatibilityOnLazyInvokation, out ok); if (ok) { return retVal; } } if (ValueType == ValueType.Literal) { return Value; } object tmpValue = Value; if (ValueType == ValueType.PropertyOrField) { if (arguments == null || arguments.Length == 0) { var invokationHelper = tmpValue as InvokationHelper; if (invokationHelper != null) { bool ok; object retVal = invokationHelper.Invoke(null, out ok); if (ok) { return retVal; } } FunctionLiteral fx = tmpValue as FunctionLiteral; if (fx != null && fx.AutoInvokeEnabled) { return ((FunctionLiteral) tmpValue).Invoke(null); } return tmpValue; } if (tmpValue == null) { throw new ScriptException("Indexer Failed for NULL - Value"); } if (tmpValue is Type) { throw new ScriptException("Indexer call for Types not supported"); } object[] parameters = (from t in arguments select t.GetValue(null)).ToArray(); if (!(tmpValue is Array)) { object[] args; Type targetType = tmpValue.GetType(); if (ExplicitType != null) { if (!ExplicitType.IsAssignableFrom(targetType)) { throw new ScriptException("Provided Type is not implemented by the target-object"); } targetType = ExplicitType; } PropertyInfo pi = MethodHelper.GetCapableIndexer(targetType, parameters, out args); if (pi == null) { throw new ScriptException("No capable Indexer found for the provided arguments"); } if (creator != null) { creator.SetPreferredExecutor(new LazyIndexer(pi,parameters.Length != args.Length)); } return pi.GetValue(tmpValue, args); } Array arr = (Array)tmpValue; return arr.GetValue(parameters.Cast<int>().ToArray()); } if (ValueType == ValueType.Method) { SequenceValue ta = (SequenceValue) arguments[0]; SequenceValue a = (SequenceValue) arguments[1]; ScriptValue et = arguments[2]; Type explicitType = null; object[] parameters = (from t in a.Sequence select t.GetValue(null)).ToArray(); Type[] typeParameters = Type.EmptyTypes; if (ta != null) { typeParameters = (from t in ta.Sequence select (Type) t.GetValue(null)).ToArray(); } if (et != null) { explicitType = et.GetValue(null) as Type; } Type type; if (tmpValue == null) { ValueType = ValueType.PropertyOrField; } if (Name == null) { try { if (tmpValue is Delegate) { Delegate dlg = (Delegate) tmpValue; return dlg.DynamicInvoke(parameters); } if (tmpValue is InvokationHelper) { InvokationHelper ih = (InvokationHelper) tmpValue; bool ok; var retVal = ih.Invoke(parameters, out ok); if (ok) { return retVal; } throw new ScriptException($"Failed to call method {Name}. Possible Arguments-mismatch."); } if (tmpValue is FunctionLiteral) { FunctionLiteral fl = (FunctionLiteral) tmpValue; return fl.Invoke(parameters); } } finally { ValueType = ValueType.Method; } } if (tmpValue == null) { throw new Exception("Method call failed for NULL - Value"); } object target = tmpValue; bool isStatic = false; if (tmpValue is Type) { type = (Type)tmpValue; target = null; isStatic = true; } else if (tmpValue is ObjectLiteral) { type = tmpValue.GetType(); ObjectLiteral ol = tmpValue as ObjectLiteral; FunctionLiteral fl = ol[Name] as FunctionLiteral; if (fl != null) { return fl.Invoke(parameters); } } else { type = explicitType??tmpValue.GetType(); } object[] args; #if UseDelegates MethodInvoker method = MethodHelper.GetCapableMethod(type, typeParameters, Name, Value is Type, parameters, out args); #else bool tmpStatic = isStatic; MethodInfo method = MethodHelper.GetCapableMethod(type, typeParameters, Name, ref isStatic, parameters, out args); if (!tmpStatic && isStatic) { args[0] = target; target = null; } #endif if (method == null) { throw new ScriptException(string.Format("No capable Method found for {0}", Name)); } var writeBacks = MethodHelper.GetWritebacks(method, args, a.Sequence); if (creator != null) { creator.SetPreferredExecutor(new LazyMethod(method, tmpStatic, !tmpStatic && isStatic, args.Length != a.Sequence.Length)); } #if UseDelegates if (target != null) { target = target.WrapIfValueType(); } return method(target, args); if (target != null) { /*object[] newArgs = new object[args.Length + 1]; newArgs[0] = target; Array.Copy(args, 0, newArgs, 1, args.Length);*/ args[0] = target; if (!(target is System.ValueType)) { return method.FastDynamicInvoke(args); } return method.DynamicInvoke(args); #else try { return method.Invoke(target, args); } finally { foreach (var wb in writeBacks) { wb.Target.SetValue(args[wb.Index]); } } #endif #if UseDelegates } return method.FastDynamicInvoke(args); #endif } if (ValueType == ValueType.Constructor) { if (tmpValue == null || !(tmpValue is Type)) { throw new ScriptException("Require Type in order to create a new instance"); } ScriptValue[] ta = null; if (arguments[0] != null) { ta = ((SequenceValue)arguments[0]).Sequence; } ScriptValue[] a = ((SequenceValue) arguments[1]).Sequence; object[] parameters = (from t in a select t.GetValue(null)).ToArray(); Type[] typeParameters = ta == null ? Type.EmptyTypes : (from t in ta select (Type) t.GetValue(null)).ToArray(); Type type = (Type)tmpValue; if (typeParameters.Length != 0) { //throw new ScriptException(string.Format("Unexpected usage of generic Type {0}", ((Type)Value).FullName)); type = type.MakeGenericType(typeParameters); } object[] args; ConstructorInfo constructor = MethodHelper.GetCapableConstructor(type, parameters, out args); if (constructor == null) { throw new ScriptException(string.Format("No appropriate Constructor was found for {0}", ((Type)tmpValue).FullName)); } if (creator != null) { creator.SetPreferredExecutor(new LazyConstructor(constructor, args.Length != a.Length)); } return constructor.Invoke(args); } throw new ScriptException("Unexpected Value-Type"); }
public bool CanGetValue(ScriptValue[] arguments) { if (!Getable) { throw new ScriptException("Get is not supported for this member"); } if (creator != null) { bool ok = creator.CanInvokeExecutor(Value,arguments,bypassCompatibilityOnLazyInvokation); //object retVal = creator.InvokeExecutor(Value, arguments, bypassCompatibilityOnLazyInvokation, out ok); if (ok) { return true; } } if (ValueType == ValueType.Literal) { return false; } object tmpValue = Value; if (ValueType == ValueType.PropertyOrField) { if (arguments == null || arguments.Length == 0) { return true; } if (tmpValue == null) { return false; } if (tmpValue is Type) { return false; } object[] parameters = (from t in arguments select t.GetValue(null)).ToArray(); if (!(tmpValue is Array)) { object[] args; PropertyInfo pi = MethodHelper.GetCapableIndexer(ExplicitType??tmpValue.GetType(), parameters, out args); return pi != null; } Array arr = (Array)tmpValue; int[] indices = parameters.Cast<int>().ToArray(); bool retVal = true; for (int i = 0; i < indices.Length; i++) { retVal &= arr.GetLength(i) > indices[i]; } return retVal; } if (ValueType == ValueType.Method) { SequenceValue ta = (SequenceValue)arguments[0]; SequenceValue a = (SequenceValue)arguments[1]; ScriptValue et = arguments[2]; object[] parameters = (from t in a.Sequence select t.GetValue(null)).ToArray(); Type[] typeParameters = Type.EmptyTypes; if (ta != null) { typeParameters = (from t in ta.Sequence select (Type)t.GetValue(null)).ToArray(); } Type type; if (tmpValue == null) { ValueType = ValueType.PropertyOrField; } if (Name == null) { try { if (tmpValue is Delegate) { return true; } if (tmpValue is InvokationHelper) { return true; } if (tmpValue is FunctionLiteral) { return true; } } finally { ValueType = ValueType.Method; } } if (tmpValue == null) { return false; } object target = tmpValue; bool isStatic = false; if (tmpValue is Type) { type = (Type)tmpValue; target = null; isStatic = true; } else if (tmpValue is ObjectLiteral) { type = tmpValue.GetType(); ObjectLiteral ol = tmpValue as ObjectLiteral; FunctionLiteral fl = ol[Name] as FunctionLiteral; if (fl != null) { return true; } } else { type = et?.GetValue(null) as Type ?? tmpValue.GetType(); } object[] args; #if UseDelegates MethodInvoker method = MethodHelper.GetCapableMethod(type, typeParameters, Name, Value is Type, parameters, out args); #else bool tmpStatic = isStatic; MethodInfo method = MethodHelper.GetCapableMethod(type, typeParameters, Name, ref isStatic, parameters, out args); if (!tmpStatic && isStatic) { args[0] = target; target = null; } #endif if (method == null) { return false; } return true; } if (ValueType == ValueType.Constructor) { if (tmpValue == null || !(tmpValue is Type)) { throw new ScriptException("Require Type in order to create a new instance"); } ScriptValue[] ta = null; if (arguments[0] != null) { ta = ((SequenceValue)arguments[0]).Sequence; } ScriptValue[] a = ((SequenceValue)arguments[1]).Sequence; object[] parameters = (from t in a select t.GetValue(null)).ToArray(); Type[] typeParameters = ta == null ? Type.EmptyTypes : (from t in ta select (Type)t.GetValue(null)).ToArray(); Type type = (Type)tmpValue; if (typeParameters.Length != 0) { //throw new ScriptException(string.Format("Unexpected usage of generic Type {0}", ((Type)Value).FullName)); type = type.MakeGenericType(typeParameters); } object[] args; ConstructorInfo constructor = MethodHelper.GetCapableConstructor(type, parameters, out args); if (constructor == null) { return false; } return true; } throw new ScriptException("Unexpected Value-Type"); }