How to check valid object in PropertyDescriptor? - c#

I'm working in WinForms application and used the BindingList datasource. I need to check the whether the object is valid or not with PropertyDescriptor. because
PropertyDescriptor.GetValue(object obj) will works for valid object. but sometimes i has the "TargetInvocationException". So i want to check if that object is valid or not before get the value.
[https://i.stack.imgur.com/VsdeW.png]
here is the stacktrace:
System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.SecurityUtils.MethodInfoInvoke(MethodInfo method, Object target, Object[] args)
at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
--- End of inner exception stack trace ---
at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)

In the case that you will already need to execute the call, it will be far easier and less expensive to just try the call and do something different if it fails.
try
{
PropertyDescriptor.GetValue(...);
}
catch (TargetException ex)
{
// do the thing you would do if the object wasn't valid.
}

Related

Couldnot load type 'Volo.Abp.Authorization.Permissions.IPermissionStateManager' from assembly 'Volo.Abp.Authorization.Abstractions,Version=4.4.2.0,

System.Reflection.TargetInvocationException
HResult=0x80131604
Message=Exception has been thrown by the target of an invocation.
Source=System.Private.CoreLib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionCommonExtensions.BuildServiceProviderFromFactory(IServiceCollection services)
at Volo.Abp.AbpApplicationWithInternalServiceProvider.CreateServiceProvider()
at Volo.Abp.AbpApplicationWithInternalServiceProvider.Initialize()
at Synchronization.Program.Main(String[] args) in .....Synchronization\Program.cs:line 72
Inner Exception 1:
**TypeLoadException: Could not load type 'Volo.Abp.Authorization.Permissions.IPermissionStateManager' from assembly 'Volo.Abp.Authorization.Abstractions, Version=4.4.2.0, Culture=neutral, PublicKeyToken=null'.**
I am trying to invoke my Domain service from the console application. Below is my code
using(
var application = AbpApplicationFactory.Create<SecurityDomainModule>
(options => options.UseAutofac()))
{
application.Initialize();
}
and my securitydomainModule has the code relaed to permission managemnet module and it has dependencies to below modules.
[DependsOn(
typeof(AbpDddDomainModule),
typeof(SecurityDomainSharedModule),
typeof(AbpUsersDomainModule),
typeof(AbpUsersDomainSharedModule),
typeof(AbpAuthorizationModule),
typeof(AbpIdentityEntityFrameworkCoreModule),
typeof(AbpPermissionManagementApplicationContractsModule),
typeof(AbpPermissionManagementDomainModule),
typeof(AbpPermissionManagementDomainSharedModule),
typeof(AbpPermissionManagementDomainIdentityModule),
typeof(AbpPermissionManagementApplicationContractsModule),
typeof(AbpPermissionManagementEntityFrameworkCoreModule)
)]
public class SecurityDomainModule : AbpModule
{..
Why I am getting this typeload exception error and what I need to do to resolve this?

Error when running JSON.NET

I have added the using statement to the class I am running:
using Newtonsoft.Json.Linq;
And I am referencing the Newtonsoft.Json.dll in the same project.
I get no compile-time errors. But I do get a run-time one. I cant even do simple code like this (the hello doesn't show up before crashing):
public void Main()
{
MessageBox.Show("hello");
JObject j = new JObject();
Dts.TaskResult = (int)ScriptResults.Success;
}
I get the following error:
DTS Script Task has encountered an exception in user code: Exception has been thrown by the target of an invocation
With the following StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
Anyone know what this might be causing this?

Import Excel sheet data into SQL Table using SSIS programmatically

I am trying to implement a solution for importing Excel sheet data into a SQL table in SSIS programmatically using C#, through Edit Script task.
Unfortunately, i do not find any simple example on how to achieve similar solution online.
Below is the code which i tried in Edit Script window and it is throwing me the below error.
public void Main()
{
ADODB.Connection conn=new ADODB.Connection();
string strSQL;
object lngRecsAff;
conn.Open(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Engagements\QCRT\SSIS\InputFolder\Order.xlsx;Extended Properties=Excel 12.0","","",0);
strSQL = #"SELECT * INTO [ODBC;Driver={SQL Server};Server=IN45216580W1\SQLEXPRESS;Database=[Northwind]].[dbo].[Order_Test1] FROM [1$]";
conn.Execute(strSQL,out lngRecsAff,0);
Dts.TaskResult = (int)ScriptResults.Success;
}
Error Message:
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80004005): Could not find installable ISAM.
at ADODB.ConnectionClass.Open(String ConnectionString, String UserID, String Password, Int32 Options)
at ST_2d2b7b209a00481087e0c1720214c207.csproj.ScriptMain.Main()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
I am very new to SSIS and What am i doing wrong.

Parsing proprety info C#

Guys i've the following loop, and if is a List i've to loop again, until here i'm okay, but inside this another loop I got a problem, because i've to loop not in "propretyinfo", i've to loop in object of this PropretyInfo and get this values, i've tried a hard parse here :
(List<ItemDeMescla>)objeto.GetValue(objeto, null)
But it was throwing an excepetion, any idea how to parse it and works?
foreach (PropertyInfo objeto in processo.GetType().GetProperties())
{
corpoEmail += CriarLinhaEmail(objeto.Name, Convert.ToString(objeto.GetValue(processo, null)), false);
if (objeto.PropertyType.IsGenericType && (objeto.PropertyType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.List<>)))
{
List<ItemDeMescla> itensMescla = (List<ItemDeMescla>)objeto.GetValue(objeto, null);
foreach (ItemDeMescla item in itensMescla)
{
tabelasAux.Add(CriarTabelaInternaEmail<ItemDeMescla>(item, objeto.Name));
}
}
}
The error stack:
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at SACG.Services.Integracao.Integracao.Utils.MontarCorpoEmail[T](T processo, String mensagem) in c:\Projetos\Cotrijal\Branch\1.8.0.0\Cotrijal\Servicos\SACG.Services.Integracao\Integracao\Utils.cs:line 176
at SACG.Services.Integracao.Integracao.Utils.EnviarEmail[T](T processo, Int32 codigoDaUnidade, String mensagem, String assunto) in c:\Projetos\Cotrijal\Branch\1.8.0.0\Cotrijal\Servicos\SACG.Services.Integracao\Integracao\Utils.cs:line 114
at SACG.Services.Integracao.Integracao.IntegracaoDaExpedicao.SalvarExpedicao(ExpedicaoGraos expedicaoDto, Usuario usuarioLogado) in c:\Projetos\Cotrijal\Branch\1.8.0.0\Cotrijal\Servicos\SACG.Services.Integracao\Integracao\IntegracaoDaExpedicao.cs:line 111
at SACG.Services.Integracao.ExpedicaoDeGraos.RegistrarExpedicao(ExpedicaoGraos expedicao) in c:\Projetos\Cotrijal\Branch\1.8.0.0\Cotrijal\Servicos\SACG.Services.Integracao\ExpedicaoDeGraos.asmx.cs:line 104
Try getting value of an object, instead of PropertyInfo:
(List<ItemDeMescla>)objeto.GetValue(processo, null)
Try
objeto.GetValue(processo, null)
Instead of
objeto.GetValue(objeto, null)

Is there any interesting data I could obtain from Application_End() parameters?

In my ASP.NET application that I deploy on Windows Azure I want to log as many useful data as possible. There's Application_End() method:
protected void Application_End(object sender, EventArgs e)
{
}
which is invoked with sender being System.Web.HttpApplicationFactory and e being just System.EventArgs. With such parameters all I can do is just log their types which isn't very useful.
Can I obtain any useful data from these parameters? Are there cases when Application_End() is invoked with parameters that have other - more useful - actual types?
IIS, class HttpRuntime included, sources can be downloaded. Careful analysis shows that indeed the event parameters are always the same and convey no useful information. The call stack for the event is also useless - it is always
my Application_End(Object sender, EventArgs e)
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Web.HttpApplication.InvokeMethodWithAssert(MethodInfo method, Int32 paramCount, Object eventSource, EventArgs eventArgs)
at System.Web.HttpApplication.ProcessSpecialRequest(HttpContext context, MethodInfo method, Int32 paramCount, Object eventSource, EventArgs eventArgs, HttpSessionState session)
at System.Web.HttpApplicationFactory.Dispose()
at System.Web.HttpRuntime.Dispose()
at System.Web.HttpRuntime.ReleaseResourcesAndUnloadAppDomain(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
but... There is System.Web.Hosting.HostingEnvironment.ShutdownReason that can be retrieved from within Application_End() and that is set by HttpRuntime when the application shutdown is being initiated.
So the "interesting data" is System.Web.Hosting.HostingEnvironment.ShutdownReason.
Also see this closely related question

Categories