"Index was outside the bounds of the array." - when Calling dynamically generated WCF function method - wcf

I have created a dynamic function to my class using MSIL emit statements and I have hosted the class as WCF service.
Emitted code :
Type myMthdParams = new Type[2] {};
myMthdParams[0] = typeof(int);
myMthdParams[1] = typeof(int);
MethodBuilder myMthdBld = myTypeBld.DefineMethod("Add", MethodAttributes.Public | MethodAttributes.Static, typeof(int), myMthdParams);
ILGenerator ILout = myMthdBld.GetILGenerator();
int numParams = mthdParams.Length;
for (byte x = 0; x < numParams; x++)
ILout.Emit(OpCodes.Ldarg_S, x);
if (numParams > 1)
{
for (int y = 0; y < (numParams - 1); y++)
{
ILout.Emit(OpCodes.Add);
}
}
ILout.Emit(OpCodes.Ret);
The method is "int add (int, int)".
This is how the proxy looks from client
public int Add(int in0, int in1) {
ConsoleApplication4.ServiceReference2.AddRequest inValue = new ConsoleApplication4.ServiceReference2.AddRequest();
inValue.in0 = in0;
inValue.in1 = in1;
ConsoleApplication4.ServiceReference2.AddResponse retVal = ((ConsoleApplication4.ServiceReference2.MyDynamicType)(this)).Add(inValue);
return retVal.AddResult;
}
Client call :
var v = client.Add(int, int);
However when I try calling this function from a client side I get the following exception - "An unhandled exception of type 'System.ServiceModel.FaultException`1' occurred in mscorlib.dll"
Additional information: Index was outside the bounds of the array.
Stack trace :
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication4.ServiceReference2.MyDynamicType.Add(AddRequest request)
at ConsoleApplication4.ServiceReference2.MyDynamicTypeClient.ConsoleApplication4.ServiceReference2.MyDynamicType.Add(AddRequest request) in C:\Users\D065085\Documents\Visual Studio 2015\Projects\ConsoleApplication4\Service References\ServiceReference2\Reference.cs:line 238
at ConsoleApplication4.ServiceReference2.MyDynamicTypeClient.Add(Int32 in0, Int32 in1) in C:\Users\D065085\Documents\Visual Studio 2015\Projects\ConsoleApplication4\Service References\ServiceReference2\Reference.cs:line 245
at ConsoleApplication4.Program.Main(String[] args) in C:\Users\D065085\Documents\Visual Studio 2015\Projects\ConsoleApplication4\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Any help is deeply appreciated. Thanks.

Related

Error uploading a document to SQL Server in .Net Core 3.1 Web API

I have a SQL Server stored procedure that is used for uploading a document and returns an ID upon success.
I am storing the parameter file_data into a byte[] type in the Customer_Document_ADD class.
public byte[] file_data { get; set; }
The following is my repository code.
public async Task<int> InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED)
{
await using(SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
// define SqlParameters for the other two params to be passed
var company_idParam = new SqlParameter("#company_id", customer_Document_ADDED.company_id);
var customer_idParam = new SqlParameter("#customer_id", customer_Document_ADDED.customer_id);
var customer_site_idParam = new SqlParameter("#customer_site_id", customer_Document_ADDED.customer_site_id);
var customer_system_idParam = new SqlParameter("#customer_system_id", customer_Document_ADDED.customer_system_id);
var job_idParam = new SqlParameter("#job_id", customer_Document_ADDED.job_id);
var security_levelParam = new SqlParameter("#security_level", customer_Document_ADDED.security_level);
var file_nameParam = new SqlParameter("#file_name", customer_Document_ADDED.file_name);
var file_sizeParam = new SqlParameter("#file_size", customer_Document_ADDED.file_size);
var upload_dateParam = new SqlParameter("#upload_date", customer_Document_ADDED.upload_date);
var document_extParam = new SqlParameter("#document_ext", customer_Document_ADDED.document_ext);
var user_codeParam = new SqlParameter("#user_code", customer_Document_ADDED.user_code);
var user_descriptionParam = new SqlParameter("#user_description", customer_Document_ADDED.user_description);
var reference1Param = new SqlParameter("#reference1", customer_Document_ADDED.reference1);
var reference2Param = new SqlParameter("#reference2", customer_Document_ADDED.reference2);
var reference3Param = new SqlParameter("#reference3", customer_Document_ADDED.reference3);
var reference4Param = new SqlParameter("#reference4", customer_Document_ADDED.reference4);
var file_dataParam = new SqlParameter("#file_data", customer_Document_ADDED.file_data);
//if (file_dataParam.Value == null)
//{
// file_dataParam.Value = "";
//}
file_dataParam.SqlDbType = SqlDbType.Image;
// define the output parameter that needs to be retained
// for the Id created when the Stored Procedure executes
// the INSERT command
var document_idParam = new SqlParameter("#document_id", SqlDbType.Int);
// the direction defines what kind of parameter we're passing
// it can be one of:
// Input
// Output
// InputOutput -- which does pass a value to Stored Procedure and retains a new state
document_idParam.Direction = ParameterDirection.Output;
// we can also use context.Database.ExecuteSqlCommand() or awaitable ExecuteSqlCommandAsync()
// which also produces the same result - but the method is now marked obselete
// so we use ExecuteSqlRawAsync() instead
// we're using the awaitable version since GetOrCreateUserAsync() method is marked async
await context.Database.ExecuteSqlRawAsync(
"EXECUTE [dbo].[Customer_Document_ADD_incentive] #company_id, #customer_id, #customer_site_id, #customer_system_id, #job_id, #security_level, #file_name, #file_size, #upload_date, #document_ext, #user_code, #user_description, #reference1, #reference2, #reference3, #reference4, #file_data, #document_id out",
company_idParam,
customer_idParam,
customer_site_idParam,
customer_system_idParam,
job_idParam,
security_levelParam,
file_nameParam,
file_sizeParam,
upload_dateParam,
document_extParam,
user_codeParam,
user_descriptionParam,
reference1Param,
reference2Param,
reference3Param,
reference4Param,
file_dataParam,
document_idParam);
// the userIdParam which represents the Output param
// now holds the Id of the new user and is an Object type
// so we convert it to an Integer and send
return Convert.ToInt32(document_idParam.Value);
}
}
I'm getting the following error in Postman.
Microsoft.Data.SqlClient.SqlException (0x80131904): The parameterized query '(#company_id int,#customer_id int,#customer_site_id int,#custome' expects the parameter '#file_data', which was not supplied.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at Microsoft.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader(Boolean isInternal, Boolean forDescribeParameterEncryption)
at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRawAsync(DatabaseFacade databaseFacade, String sql, IEnumerable`1 parameters, CancellationToken cancellationToken)
at WebAPI.Repository.Customer_Document_ADDRepository.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_Document_ADDRepository.cs:line 73
at WebAPI.Repository.Customer_Document_ADDRepository.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_Document_ADDRepository.cs:line 97
at WebAPI.Controllers.Customer_Document_ADDController.InsertCustomer_Document_ADDResult(Customer_Document_ADD customer_Document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Controllers\Customer_Document_ADDController.cs:line 38
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
ClientConnectionId:e8f735f0-1ab5-4d53-9ead-01df3ee63c2e
Error Number:8178,State:1,Class:16
All other values are captured except the file. I am getting a null value in the debugger. Why am I unable to upload a file into the database? Thanks in advance.
Firstly,default model binding system cannot bind file to byte[] properties.If you want to bind file to btye[],you can use ByteArrayModelBinder,here is an official link.
Also,if you don't mind to change the type of file_data,you can use
public IFormFile file_data { get; set; }
and then you can convert it to byte[] type with MemoryStream.Here is an official link about upload files in .net core.

Intercept Error Record Cancellation with Forrenkey Bond

I'm creating a web application for the parish in angular.
It is a CRUD web application in which I use SQL Server.
I have the product-list.component page where I created the OnDelete method to be able to delete the single product.
The method is correct, but I have a problem that in the table there are relations to the "CommandRighe" table that inhibit deletion.
I modified the OnDelete method with try catch to be able to intercept the error code and send an error message to the user.
It does not work and I would like to know how to handle the problem in order to send the user an error message telling him that the record cannot be deleted.
How can I do ?
thank you
Moreno
System.Data.Entity.Infrastructure.DbUpdateException non è stata gestita dal codice utente
HResult=-2146233087
Message=Errore durante l'aggiornamento delle voci. Per ulteriori dettagli, vedere l'eccezione interna.
Source=EntityFramework
StackTrace:
in System.Data.Entity.Internal.InternalContext.SaveChanges()
in System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
in System.Data.Entity.DbContext.SaveChanges()
in WebApiSif.Controllers.PRODOTTIController.DeletePRODOTTI(Int32 id) in I:\Angular Project\SifWork\WebApiSif\WebApiSif\Controllers\PRODOTTIController.cs:riga 162
in lambda_method(Closure , Object , Object[] )
in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)
in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
InnerException:
HResult=-2146233087
Message=Errore durante l'aggiornamento delle voci. Per ulteriori dettagli, vedere l'eccezione interna.
Source=EntityFramework
StackTrace:
in System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
in System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
in System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
in System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
in System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
in System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
in System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException:
Class=16
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=1
Message=L'istruzione DELETE è in conflitto con il vincolo REFERENCE "FK_CommandaRighe_PRODOTTI". Il conflitto si è verificato nella tabella "dbo.CommandaRighe", column 'NProdotto' del database "SifDB".
L'istruzione è stata interrotta.
Number=547
Procedure=""
Server=DESKTOP-P3TEF6K\SQLEXPRESS
Source=.Net SqlClient Data Provider
State=0
StackTrace:
in System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
in System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
in System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
in System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
in System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
in System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
in System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
in System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
in System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
in System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
in System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
InnerException:
Message = The DELETE statement conflicts with the REFERENCE constraint "FK_CommandaRighe_PRODOTTI". The conflict occurred in the "dbo.CommandaRighe" table, column 'NProduct' of the "SifDB" database.
The instruction has been interrupted.
onDelete(id: number) {
if (confirm('Confermi la cancellazione del Record ?')) {
try {
this.service.deleteProdotti(id).then(res => { // this.service.deleteProdotti(id).subscribe(res => {
this.service.refreshList();
this.toastr.warning('Cancellazione eseguita con successo', Header_Msg);
});
} catch (error) {
console.error('errore in cancellazione: ' + error);
}
}
}
-----------------------------------------
the overall class is as follows
import {Component, OnInit, SystemJsNgModuleLoader} from '# angular / core';
import {Products} from 'src / app / model / prodotti.model';
import {ProductsListService} from 'src / app / features / products / components / products-list / products-list.service';
import {ToastrService} from 'ngx-toastr';
let Header_Msg = "Product Manager";
#Component ({
selector: 'app-products-list',
templateUrl: './products-list.component.html',
styleUrls: ['./products-list.component.css']
})
export class ProductsListComponent implements OnInit {
constructor (private service: ProductsListService, private toastr: ToastrService) {
}
ngOnInit () {
this.service.refreshList ();
}
populateForm (emp: Products) {
this.service.formData = Object.assign ({}, emp);
}
onDelete (id: number) {
if (confirm ('Confirm the deletion of the record?')) {
try {
this.service.deleteProducts (id) .then (res => {// this.service.deleteProdotti (id) .subscribe (res => {
this.service.refreshList ();
this.toastr.warning ('Successful deletion', Header_Msg);
});
} catch (error) {
console.error ('error in deletion:' + error);
}
}
}
}`enter code here`

Can't get two-way SSL to work with HttpWebRequest

I have a WCF service application that is supposed to connect to another server X to retrieve data. When server X is configured with one-way SSL, the WCF service application is able to connect to it without problem. But when server X is configured with two-way SSL, the WCF service application will have problem connecting to it.
The WCF service application uses a self-signed certificate. This certificate was exported without private key into a .cer file, and imported into server X's trust store. The same exported certificate was used in the WCF service application's codes:
string URL = "https://11.205.112.49:5311/Ping";
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
X509Certificate2 Certificate = new X509Certificate2("F:\\cert.cer");
Request.ClientCertificates.Add(Certificate);
Request.Method = "GET";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
The last line of the codes above will throw WebException with the following message:
The request was aborted: Could not create SSL/TLS secure channel.
The above error does not provide much details.
Help is appreciate.
Thanks in advance.
EDIT:
This is my entire program:
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.IO;
namespace TestTwoWaySSL
{
class Program
{
static void Main(string[] args)
{
HttpWebResponse Response = null;
try
{
string URL = "https://11.205.112.49:5311/Ping";
Console.WriteLine("URL: [{0}].", URL);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
X509Certificate2 Certificate = new X509Certificate2("F:\\cert.pfx", "password");
Request.ClientCertificates.Add(Certificate);
Request.Method = "GET";
Console.WriteLine("Sending request.");
Response = (HttpWebResponse)Request.GetResponse();
Console.WriteLine("Request sent.");
}
catch (WebException webException)
{
Console.WriteLine("Web exception occurred: [{0}].", webException.Message);
Console.WriteLine(webException.StackTrace);
Response = webException.Response as HttpWebResponse;
}
catch (Exception exception)
{
Console.WriteLine("Exception occurred: [{0}].", exception.Message);
Console.WriteLine(exception.StackTrace);
}
Console.WriteLine("Response status code: [{0}].", Response.StatusCode);
Console.WriteLine("Response \"Content-Type\" header value: [{0}].", Response.ContentType);
Console.WriteLine("Response \"Content-Length\" header value: [{0}].", Response.ContentLength);
String ResponseMessageBody = new StreamReader(Response.GetResponseStream()).ReadToEnd();
Console.WriteLine("Response message body: [{0}].", ResponseMessageBody);
}
}
}
When it reaches the line Request.GetResponse(), an AccessVioationException is thrown:
Unhandled Exception: System.AccessViolationException: Attempted to read or write
protected memory. This is often an indication that other memory is corrupt.
at System.Net.UnsafeNclNativeMethods.SafeNetHandles_SECURITY.AcquireCredentialsHandleW(String principal, String moduleName, Int32 usage, Void* logonID, SecureCredential& authData, Void* keyCallback, Void* keyArgument, SSPIHandle& handlePtr, Int64& timeStamp)
at System.Net.SafeFreeCredentials.AcquireCredentialsHandle(SecurDll dll, String package, CredentialUse intent, SecureCredential& authdata, SafeFreeCredentials& outCredential)
at System.Net.SSPISecureChannelType.AcquireCredentialsHandle(String moduleName, CredentialUse usage, SecureCredential& authdata, SafeFreeCredentials& outCredential)
at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)
at System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32 offset, Int32 count, Byte[]& output)
at System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
at System.Net.HttpWebRequest.EndSubmitRequest()
at System.Net.HttpWebRequest.SetRequestSubmitDone(ConnectStream submitStream)
at System.Net.Connection.CompleteConnection(Boolean async, HttpWebRequest request)
at System.Net.Connection.CompleteStartConnection(Boolean async, HttpWebRequest httpWebRequest)
at System.Net.Connection.CompleteStartRequest(Boolean onSubmitThread, HttpWebRequest request, TriState needReConnect)
at System.Net.Connection.SubmitRequest(HttpWebRequest request, Boolean forcedsubmit)
at System.Net.ServicePoint.SubmitRequest(HttpWebRequest request, String connName)
at System.Net.HttpWebRequest.SubmitRequest(ServicePoint servicePoint)
at System.Net.HttpWebRequest.GetResponse()
at TestTwoWaySSL.Program.Main(String[] args)
The problem is that you are missing private key. You are using only the certificate.
Either use pkcs#12 when loading certificate into X509Certificate2 class
X509Certificate2 Certificate = new X509Certificate2("F:\\cert.p12", "p12 password");
or load certificate from store
X509Store store = new X509Store("MY",StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2 certificate = collection.Find(...)[0];
store.Close();

FirebirdClient 5.7 ADO.NET UnknownStatement in fbScript.Parse()

I've used FirebirdClient 2.0 ADO.NET and I'm migrating to FirebirdClint version 5.7 ADO.NET.
This code below does not work in the new version of firebirdClient
If IO.File.Exists(pathScript) Then
txtScript.Close()
Dim fbScript As New FbScript(pathScript)
fbScript.Parse()
If fbScript.Results.Count = 0 Then
Exit Sub
End If
If fbScript.Results.Count > 0 Then
If automatico = False Then
frmImpSintegra.LblTitulo.Text = "Gravando 60I"
End If
Application.DoEvents()
Dim fbConn As New FbConnection(cnEmpresa)
fbConn.Open()
Dim fbBatch As New FirebirdSql.Data.Isql.FbBatchExecution(fbConn)
fbBatch.AppendSqlStatements(fbScript)
fbBatch.Execute(True)
fbConn.Close()
End If
deleteArquivoTemporario()
txtScript = New IO.StreamWriter(pathScript)
End If
This error appears in the line fbScript.Parse ()
The full stacktrace of the exception:
Exception thrown: 'System.ArgumentException' in FirebirdSql.Data.FirebirdClient.dll
System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Exceção não tratada</Description><AppDomain>Livros.vshost.exe</AppDomain><Exception><ExceptionType>System.ArgumentException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>The type of the SQL statement could not be determined. See also UnknownStatement event.
Statement: c:\0556_16122016_081323.txt.</Message><StackTrace> em FirebirdSql.Data.Isql.FbScript.Parse()
em Livros.importacaoSintegra.grava60I(Boolean automatico)
em Livros.importacaoSintegra.importa60I(String linhaTexto, StreamWriter&amp; txtScript, String diaEncerrado60, Boolean chkECF, Boolean automatico, String empresa, Boolean chkDiv60I, Boolean chkTruncar, String Impressoras, Boolean chkValida60I, Boolean chk60I75, Int32 contador)
em Livros.importacaoSintegra.importaSintegraAutomatico(String txtPasta, Boolean automatico, String empresa, String txtMesAno, Boolean Chk74, String txtDataInventario, String txtTipoEstoque, Boolean ChkExcluirRegistro, Boolean chkAtualizarQuantidade, Boolean chkEcf, Boolean chkNf, Boolean ChkAtualizaCodigoInterno, Boolean chkVerCfop, String Cnpj_Empresa1, Boolean chkValida60I, Boolean chkAliquotaReal, Boolean chkDiv60I, Boolean chkTruncar, Boolean chk60I75, String mes1, String ano1, String cnAtual1, String cnEmpresa1, String CnPrincipalEmpresa1, Int32 idArquivoSpe1, Boolean chkSo75)
em Livros.frmImpSintegra.btnConfirmarSinal_Click(Object sender, EventArgs e)
em System.Windows.Forms.Control.OnClick(EventArgs e)
em System.Windows.Forms.Button.OnClick(EventArgs e)
em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
em System.Windows.Forms.Control.WmMouseUp(Message&amp; m, MouseButtons button, Int32 clicks)
em System.Windows.Forms.Control.WndProc(Message&amp; m)
em System.Windows.Forms.ButtonBase.WndProc(Message&amp; m)
em System.Windows.Forms.Button.WndProc(Message&amp; m)
em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)
em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)
em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg)
em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
em Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
em Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
em Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
em Livros.My.MyApplication.Main(String[] Args)
em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
em System.Threading.ThreadHelper.ThreadStart()</StackTrace><ExceptionString>System.ArgumentException: The type of the SQL statement could not be determined. See also UnknownStatement event.
Statement: c:\0556_16122016_081323.txt.
em FirebirdSql.Data.Isql.FbScript.Parse()
em Livros.importacaoSintegra.grava60I(Boolean automatico)
em Livros.importacaoSintegra.importa60I(String linhaTexto, StreamWriter&amp; txtScript, String diaEncerrado60, Boolean chkECF, Boolean automatico, String empresa, Boolean chkDiv60I, Boolean chkTruncar, String Impressoras, Boolean chkValida60I, Boolean chk60I75, Int32 contador)
em Livros.importacaoSintegra.importaSintegraAutomatico(String txtPasta, Boolean automatico, String empresa, String txtMesAno, Boolean Chk74, String txtDataInventario, String txtTipoEstoque, Boolean ChkExcluirRegistro, Boolean chkAtualizarQuantidade, Boolean chkEcf, Boolean chkNf, Boolean ChkAtualizaCodigoInterno, Boolean chkVerCfop, String Cnpj_Empresa1, Boolean chkValida60I, Boolean chkAliquotaReal, Boolean chkDiv60I, Boolean chkTruncar, Boolean chk60I75, String mes1, String ano1, String cnAtual1, String cnEmpresa1, String CnPrincipalEmpresa1, Int32 idArquivoSpe1, Boolean chkSo75)
em Livros.frmImpSintegra.btnConfirmarSinal_Click(Object sender, EventArgs e)
em System.Windows.Forms.Control.OnClick(EventArgs e)
em System.Windows.Forms.Button.OnClick(EventArgs e)
em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
em System.Windows.Forms.Control.WmMouseUp(Message&amp; m, MouseButtons button, Int32 clicks)
em System.Windows.Forms.Control.WndProc(Message&amp; m)
em System.Windows.Forms.ButtonBase.WndProc(Message&amp; m)
em System.Windows.Forms.Button.WndProc(Message&amp; m)
em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)
em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)
em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg)
em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
em Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
em Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
em Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
em Livros.My.MyApplication.Main(String[] Args)
em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
em System.Threading.ThreadHelper.ThreadStart()</ExceptionString></Exception></TraceRecord>
My txt file is:
INSERT INTO REGISTRO_60I12 (TIPO,SUBTIPO,DATA_EMISSAO,NUMERO_SERIE,MODELO,COO,ITEM,PRODUTO_SERVICO,QUANTIDADE,VALOR_LIQUIDO,BASE_CALCULO,ALIQUOTA_SUBSTITUICAO,VALOR_ICMS,MESANO,EMPRESA)VALUES('60','I','2016.12.09','BE090910100010004937','2D',320645,'001','12036',1.000,3.99,0.00,'F',0.00,122016,0556);
Can someone help me?
You are passing the filename to the constructor of FbScript, but this constructor is expecting the actual script content. This leads to the filename c:\0556_16122016_081323.txt to be parsed as if it is a statement, and c:\0556_16122016_081323.txt is not a known Firebird statement.
Instead you should use FbScript.LoadFromFile(pathScript).

Error in creating a dynamic jqGrid , ASP.net MVC 4

First, I would like to tell that i am new on the .net development (MVC 4)
and I am trying to follow this tutorial with entity framework 5 but I keep getting this error " exception of type 'System.NullReferenceException' occurred in jqGridMVC2.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
, even though i tried to cheeck the value for null before.
if(propInfo.GetValue(this, null) != null) {
}
private static object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
// if (obj != null)
// if (propertyInfo.GetValue(obj, null) != null)
return propertyInfo.GetValue(obj, null);
// return 0;
}
at jqGridMVC2.Extensions.GridExtension.GetPropertyValue(Object obj, String property) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Extensions\Grid\GridExtension.cs:line 70
at jqGridMVC2.Extensions.GridExtension.<>c__DisplayClass4`1.<AsJqGridResult>b__2(T item) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Extensions\Grid\GridExtension.cs:line 38
at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__0.MoveNext()
at System.Linq.Enumerable.<SkipIterator>d__4d`1.MoveNext()
at System.Linq.Enumerable.<TakeIterator>d__3a`1.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at jqGridMVC2.Extensions.GridExtension.AsJqGridResult[T](IQueryable`1 source, String column, String sortOrder, Int32 page, Int32 pageSize) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Extensions\Grid\GridExtension.cs:line 41
at jqGridMVC2.Controllers.HomeController.DynamicGridData(String sidx, String sord, Int32 page, Int32 rows) in c:\Users\aal\Documents\Visual Studio 2013\Projects\jqGridMVC2\jqGridMVC2\Controllers\HomeController.cs:line 30
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
Please help me in solving this problem
Thank you in advance.
I just solve the error by this
private static object GetPropertyValue(object obj, string property)
{
foreach (var property1 in obj.GetType().GetProperties()) {
return property1.GetValue(obj, null); //throws exception TargetParameterCountException for String type
}
return 0;
}