QuickFix - 'ObjectDisposedException' error on NewOrderSingle - c#

I'm working on FxPro Ctrader broker (FIX 4.4) and I'm trying to make an FixApi in C# using QuickFix/n library (1.7.0.0).
I stucked at 'NewOrderSingle':
After successful logon I'm trying to make an order:
class TradeConnection : MessageCracker, IApplication
{
public void OnLogon(SessionID sessionID)
{
Write.Info("Account TRADE successful logged " + sessionID);
sendOrder();
}
public void sendOrder()
{
NewOrderSingle oc = new NewOrderSingle();
ClOrdID ID = new ClOrdID("1408479");
Symbol symb = new Symbol("1");
Side side = new Side('1');
OrderQty lots = new OrderQty(1000);
OrdType type = new OrdType('1');
TransactTime TransactTime = new TransactTime(DateTime.Now);
TimeInForce TimeInForce = new TimeInForce('3');
oc.SetField(ID);
oc.SetField(symb);
oc.SetField(side);
oc.SetField(lots);
oc.SetField(type);
oc.SetField(TimeInForce);
send(oc);
}
public void send(QuickFix.Message message)
{
Session.SendToTarget(message, sessionID);
}
}
Unfortunately it isn't working and I get error:
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
Same error appears #
RequestForPositions and OrderStatusRequest
On same account in api that uses NetworkStream rather than QuickFix lib it works fine.

Problem solved.
Forgot to set field TransactTime which counterparty required:
oc.SetField(TransactTime);

Related

EntityState must be set to null, Created (for Create message) or Changed (for Update message)

In my C# console application I am trying to update an account in CRM 2016. IsFaulted keeps returning true.
The error message it returns when I drill down is the following:
EntityState must be set to null, Created (for Create message) or Changed (for Update message).
Also in case it might cause the fault I have pasted my LINQ query at the bottom.
The answers I get from Google states either that I am mixing ServiceContext and ProxyService (which am not, I am not using it in this context). The others says that I am using context.UpdateObject(object) incorrectly, which I am not using either.
Update: Someone just informed me that the above error is caused because I am trying to return all the metadata and not just the updated data. Still I have no idea how to fix the error, but this information should be helpful.
private static void HandleUpdate(IOrganizationService crmService, List<Entity> updateEntities)
{
Console.WriteLine("Updating Entities: " + updateEntities.Count);
if (updateEntities.Count > 0)
{
try
{
var multipleRequest = new ExecuteMultipleRequest()
{
// Assign settings that define execution behavior: continue on error, return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = true
},
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection()
};
foreach (var account in updateEntities)
{
multipleRequest.Requests.Add(
new UpdateRequest()
{
Target = account
});
}
ExecuteMultipleResponse response = (ExecuteMultipleResponse)crmService.Execute(multipleRequest);
if (response.IsFaulted)
{
int failedToUpdateAccount = 0;
foreach (ExecuteMultipleResponseItem singleResp in response.Responses)
{
if (singleResp.Fault != null)
{
string faultMessage = singleResp.Fault.Message;
var account = ((UpdateRequest)multipleRequest.Requests[singleResp.RequestIndex]).Target;
Log.Error($"Error update acc.id: {account.Id}.Error: {singleResp.Fault.Message}.");
failedToUpdateAccount++;
}
}
Log.Debug($"Failed to update {failedToUpdateAccount} accounts.");
}
else
{
Log.Debug("Execute multiple executed without errors");
}
}
catch (Exception ex)
{
Log.Error($"Error while executing Multiplerequest", ex);
}
}
}
// LINQ below
private static List<Account> GetAllActiveCRMAccounts(CRM2011DataContext CRMcontext)
{
Console.WriteLine("Start Getting CRMExistingAccounts ....");
List<Account> CRMExisterendeAccounts = new List<Account>();
try
{
CRMExisterendeAccounts = (from a in CRMcontext.AccountSet
where a.StateCode == AccountState.Active
where a.anotherVariable == 1
select new Account()
{
my_var1 = a.myVar1,
my_var2 = a.myVar2,
AccountId = a.AccountId,
anotherVar = a.alsoThisVar,
}).ToList();
}
catch (FaultException ex)
{
Log.Debug($"GetCRMExistingAccounts Exception { ex.Message}");
Console.WriteLine("GetCRMExistingAccounts Exception " + ex.Message);
throw new Exception(ex.Message);
}
return CRMExisterendeAccounts;
}
And yes, my variables has different names in my system.
The query returns the object just fine with all the correct data.
You can work around this in one of two ways:
1) Create your CRM2011DataContext with the MergeOption set to MergeOption.NoTracking. Entities loaded from a context that is not tracking will have a null EntityState property.
2) You can create a copy of your Entity and save the copy.

AVCaptureFileOutputRecordingDelegate Compile Error when trying to implement Video recording in Xamarin Forms iOS with AVFoundation

I am trying to create a video recording with AVFoundation where I use this project as my standard project. https://github.com/ThatCSharpGuy/Forms-FullCameraPage
Now i am trying to build a start/stop recording function with AVFoundation but I am getting stuck because I am having trouble creating a new instance with AVCaptureFileOutputRecordingDelegate. Project is not able to run because i get the error message: Cannot create an instance of the abstract class or interface "AVFoundation.AVCaptureFileOutputRecordingDelegate".
I found a post that goes through the same problem https://forums.xamarin.com/discussion/33925/avcapturefileoutputrecordingdelegate-compile-error but a solution was not found there.
Below you can see my code where I have commented on every step of the way.
Boolean weAreRecording;
public override async void ViewDidLoad()
{
base.ViewDidLoad();
SetupLiveCameraStream();
SetupEventHandlers();
weAreRecording = false;
}
Inside my SetupLiveCameraStream i additionally add (the project i linked has the rest of the code inside this function):
Console.WriteLine("Configuring output");
output = new AVCaptureMovieFileOutput();
long totalSeconds = 10000;
Int32 preferredTimeScale = 30;
CMTime maxDuration = new CMTime(totalSeconds, preferredTimeScale);
output.MinFreeDiskSpaceLimit = 1024 * 1024;
output.MaxRecordedDuration = maxDuration;
if (captureSession.CanAddOutput(output))
{
captureSession.AddOutput(output);
}
captureSession.SessionPreset = AVCaptureSession.PresetMedium;
... and also:
var mic = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio);
var micInput = AVCaptureDeviceInput.FromDevice(mic);
captureSession.AddInput(micInput);
Then I set up the event handlers.
private void SetupEventHandlers()
{
takeVideoButton.TouchUpInside += startStopPushed;
}
This is my start/stop recording function below where the compile error occurs. I am having trouble creating a new AVCaptureFileOutputRecordingDelegate as I mentioned above with the errormessage Cannot create an instance of the abstract class or interface "AVFoundation.AVCaptureFileOutputRecordingDelegate", I have commented in the code where you can find this:
AVCaptureMovieFileOutput output;
private void startStopPushed (object sender, EventArgs ea)
{
if (!weAreRecording)
{
System.Diagnostics.Debug.WriteLine("start recording");
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var library = System.IO.Path.Combine(documents, "..", "Library");
var urlpath = System.IO.Path.Combine(library, "sweetMovieFilm.mov");
NSUrl url = new NSUrl(urlpath, false);
NSFileManager manager = new NSFileManager();
NSError error = new NSError();
if (manager.FileExists(urlpath))
{
Console.WriteLine("Deleting File");
manager.Remove(urlpath, out error);
Console.WriteLine("Deleted File");
}
AVCaptureFileOutputRecordingDelegate avDel= new AVCaptureFileOutputRecordingDelegate (); //Error message here: Cannot create an instance of the abstract class or interface `AVFoundation.AVCaptureFileOutputRecordingDelegate`
output.StartRecordingToOutputFile(url, avDel);
Console.WriteLine(urlpath);
weAreRecording = true;
}
//we were already recording. Stop recording
else {
output.StopRecording();
System.Diagnostics.Debug.WriteLine("stopped recording");
weAreRecording = false;
}
}
So my question is how can I solve this AVCaptureFileOutputRecordingDelegate problem?
thats because AVCaptureFileOutputRecordingDelegat has abstract function FinishedRecording. You cant create Instance of class having abstract. You need to create subclass of AVCaptureFileOutputRecordingDelegat and implement abstract methods before using it.
create subclass like this:
public class myAvCaptureFileOutPutRecordingDelegate : AVCaptureFileOutputRecordingDelegat
{
public override void FinishedRecording(AVCaptureFileOutput captureOutput, Foundation.NSUrl outputFileUrl, Foundation.NSObject[] connections, Foundation.NSError error)
{
//You can use captureOutput and outputFileUrl here..
//throw new NotImplementedException();
}
}
now, create instance of this class:
AVCaptureFileOutputRecordingDelegate avDel= new myAvCaptureFileOutPutRecordingDelegate();

erlang rpc call to static member function of c# class using NFX

I'm trying to call c# static member function from erlang using nfx. I follow doc http://blog.aumcode.com/2013/10/nfx-native-interoperability-of-net-with.html and I am able to call erlang:now from C# and System.DateTime.UtcNow from erlang. However when I try to call non-System from erlang, I get error
** exception error: no match of right hand side value {error,
"unknown type: 'Program'"}
C# code:
namespace erlangIntegration {
public class Program {
static void Main(string[] args) {
var n = new ErlLocalNode("abc", new ErlAtom("'asdf'"));
n.AcceptConnections = false;
n.Start();
var m = n.CreateMbox("test");
var r = m.RPC("r#myPC", "erlang", "now", new ErlList());
Console.WriteLine("Remote time: {0}", r.ValueAsDateTime.ToString());
System.Console.WriteLine("My simple rpc: " + Program.FixedDate());
System.Console.WriteLine("Done. Press any key to exit.");
System.Console.ReadKey();
}
public static DateTime FixedDate() {
return new DateTime(2000, 12, 12);
}
}
}
erlang calls:
(r#myPC)2> f(Time), {ok, Time} = rpc:call('abc#myPC', 'System.DateTime', 'UtcNow', []), calendar:now_to_local_time(Time).
Above call works returning {{2016,1,18},{11,33,17}}
However
(r#myPC)12> f(Time), {ok, Time} = rpc:call('abc#myPC', 'Program', 'FixedDate', []), calendar:now_to_local_time(Time).
returns error:
** exception error: no match of right hand side value {error,
"unknown type: 'Program'"}
I also tried erlangIntegration.Program and to use System namespace.
How to properly make rpc call to c#?
Erlang requires assembly qualified name as input in rpc:call. So instead of 'Program' output of the following code has to be used:
var obj = new Program();
//type from here has to be used in Erlang's call instead of 'Program'
System.Console.WriteLine("Type: " + obj.GetType().AssemblyQualifiedName);

Backendless API - Create user

I'm trying to use Backendless API on a C# .net 4.5 application, but there is no way to make it work, since I get
"An unhandled exception of type 'System.StackOverflowException'
occurred in weborb.dll."
Code is simple, but doesn't work. The Java sample with Java BE Api worked normally.
public static void init()
{
Backendless.InitApp(APP_ID, SECRET_KEY, VERSION);
}
public static void RegisterUser()
{
BackendlessUser user = new BackendlessUser();
string error;
user.SetProperty("ID", "id");
user.SetProperty("password","12");
try
{
Backendless.UserService.Register(user); //StackOverflow error here
}
catch (BackendlessException exception)
{
error = exception.FaultCode;
}
}
From the linked sample:
static void Main( string[] args )
{
Backendless.InitApp( APP_ID, SECRET_KEY, VERSION_ID );
BackendlessUser loggedInUser = Backendless.UserService.Login( USER_NAME, PASS_WORD );
System.Console.WriteLine( "logged in user - " + loggedInUser.Email );
}
Backendless team solved this for me, link to the sample in the comments.

Error in Custom DibsPaymentMethodService Overriding ProcessCallback

I'm trying to customize the dialogue between uCommerce and DIBS to allow ticket registrations.
So far, I've succeeded in copying the DibsPageBuilder and adding the maketicket parameter. However, I need to customize the callback made to the function ProcessCallcack in the DibsPaymentMethodService class.
I copied the ProcessCallback and its content carefully and added it to my custom class, but when I run the checkout pipeline I keep getting the following error:
UCommerce.Pipelines.PipelineException: Exception occoured while processing pipeline
'UCommerce.Pipelines.Checkout.CheckoutPipeline'. See inner exception for details.
---> System.Security.SecurityException: Payment insufficient to cover order total
for OrderGuid xxx. Please ensure that payments cover the entire value of the order
before checking out. at
Commerce.Pipelines.Checkout.ValidatePaymentsMadeAgainstOrderTotalTask.Execute(PurchaseOrder subject)
at UCommerce.Pipelines.Pipeline`1.Execute(T subject) --- End of inner exception
stack trace ---...
I don't get why the checkout pipeline fail to succeed when I manually override the ProcessCallback with the same code the function usually is made of. In other words, if I don't override ProcessCallback the function runs smoothly, but then I don't get to do my customization. I have to say, that the error occurs before I customize anything.
My current uCommerce platform runs version 2.6.1. The code I've copied is:
public override void ProcessCallback(Payment payment)
{
if (payment.PaymentStatusId != 10000001)
return;
DibsPaymentMethodServiceConfigurationSection instance =
DibsPaymentMethodServiceConfigurationSection.Instance;
string s = HttpContext.Current.Request["transact"];
if (string.IsNullOrEmpty(s))
throw new ArgumentException("transact must be present in query string.");
int result;
if (!int.TryParse(s, out result))
throw new FormatException("transact must be a valid int32");
PaymentStatusCode paymentStatusCode = PaymentStatusCode.Authorized;
if (instance.UseMd5)
{
string parameter1 = this.GetParameter("authkey", "When using md5 \"{0}\" cannot be null or empty", new string[1]
{
"authkey"
});
string parameter2 = this.GetParameter("currency", "When using md5 \"{0}\" cannot be null or empty", new string[1]
{
"currency"
});
string parameter3 = this.GetParameter("amount", "When using md5 \"{0}\" cannot be null or empty", new string[1]
{
"amount"
});
int currencyNumber = new CurrencyCodeTranslater().FromIsoCode(parameter2);
string postMd5Key = new DibsMd5Computer().GetPostMd5Key(result.ToString(), parameter3, currencyNumber);
if (!parameter1.Equals(postMd5Key))
paymentStatusCode = PaymentStatusCode.Declined;
}
payment.PaymentStatus = PaymentStatus.Get((object) paymentStatusCode);
payment.TransactionId = result.ToString();
this.ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
}
Many thanks in advance.
/brinck10

Categories