How to read field from setting/.cfg file in QuickFIX C++ - visual-c++

I am writing quickfix call for NewOrderSingle/NewOrderCancelRequest/NewOrderStatusRequest.
Inorder to execute this request we need to fill one attribute that is AccountID.
As of now I am filling this attribute in each request individually like this-
So in each request i need to fill it. So i added this Account varibale in .cfg/settings file.
void Application::newOrderSingle44()
{
FIX::Account account("shad_tmp);
FIX44::NewOrderSingle newOrderSingle(
queryClOrdID(), querySide() ,
FIX::TransactTime(),queryOrdType());
newOrderSingle.set( FIX::HandlInst('1') );
newOrderSingle.set( querySymbol() );
newOrderSingle.set( queryOrderQty() );
newOrderSingle.set( queryTimeInForce() );
newOrderSingle.set(account);
queryHeader( newOrderSingle.getHeader() );
if ( queryConfirm( "Send order" ) )
FIX::Session::sendToTarget( newOrderSingle );
}
[SESSION]
BeginString=FIX.4.4
SenderCompID=TD_shad_dev_fix
TargetCompID=SHADSERVER_FIX
SocketConnectPort=10011
SocketConnectHost=10.250.2.8
FileStorePath=store
FileLogPath=log
ConnectionType=initiator
ResetOnLogon=N
ResetOnLogout=N
ResetOnDisconnect=N
ResetSeqNumFlag=N
DataDictionary=/mnt/d/quickfix/spec/FIX44.xml
Account=shad_tem
This is my client code to read from the settings file.
FIX::Initiator * initiator = 0;
try
{
FIX::SessionSettings settings( file );
const FIX::Dictionary& dict = settings.get();
std::string Account;
for (auto it = dict.begin(); it!=dict.end(); it++)
{
if(it->first.find("Account"))
Account = it->second;
}
std::cout<<"Account ID----------->"<<Account<<std::endl;
Application application;
FIX::FileStoreFactory storeFactory( settings );
FIX::ScreenLogFactory logFactory( settings );
if (isSSL.compare("SSL") == 0)
initiator = new FIX::ThreadedSSLSocketInitiator( application, storeFactory, settings, logFactory );
else
initiator = new FIX::SocketInitiator( application, storeFactory, settings, logFactory );
initiator->start();
application.run();
initiator->stop();
delete initiator;
return 0;
}
But this is not working. Can any one please let me know how to read this Account value from setting file??
Let me know is there any other to read this Account value from setting file and save it in any varibale and use it in any requrest . I mean wherever required.

Related

Netsuite: how to add a custom link to the Nav Bar or Header

Is there any way to customize the Nav Bar or the Header to have a custom link?
The use-case is that I have a JIRA issue collector that is driven by javascript. I would like the user to provide feedback from the page they are having issues. However, any solution I can come up with so far takes the user away from the current page.
Example of what I have that takes the user away:
I currently have a Suitelet that is in one of the menus. That Suitelet invokes javascript but even then the user is taken away.
I have a workflow on the case record that calls some Javascript Javascript in one of the UI-based action's conditions is invoked. Similar to #1 but on the case record.
I'm thinking I'm going to need to create and public a chrome extension for my company's domain just to get a pervasive bit of javascript to run for all pages...seems like a sledgehammer.
I hope someone can prove me wrong, but as far as I am aware there is no way to natively inject Javascript or anything into the NetSuite header/navbar - they don't offer customisation to the header/navbar.
I've resorted to creating a Userscript that I load through the Violent Monkey extension for Chrome or Firefox.
Example Userscript Template
// ==UserScript==
// #name NetSuite Mods (Example)
// #namespace Violentmonkey Scripts
// #match *.netsuite.com/*
// #include *.netsuite.com/*
// #grant GM_addStyle
// #version 1.0
// #author Kane Shaw - https://stackoverflow.com/users/4561907/kane-shaw
// #description 6/11/2020, 6:25:20 PM
// ==/UserScript==
// Get access to some commonly used NLAPI functions without having to use "unsafeWindow.nlapi..." in our code
// You can add more of these if you need access to more of the functions contained on the NetSuite page
nlapiSetFieldText = unsafeWindow.nlapiSetFieldText;
nlapiSetFieldValue = unsafeWindow.nlapiSetFieldValue;
nlapiGetFieldText = unsafeWindow.nlapiGetFieldText;
nlapiGetFieldValue = unsafeWindow.nlapiGetFieldValue;
nlapiSearchRecord = unsafeWindow.nlapiSearchRecord;
nlobjSearchFilter = unsafeWindow.nlobjSearchFilter;
nlapiLookupField = unsafeWindow.nlapiLookupField;
nlapiLoadRecord = unsafeWindow.nlapiLoadRecord;
nlapiSubmitRecord = unsafeWindow.nlapiSubmitRecord;
GM_pageTransformations = {};
/**
* The entrypoint for our userscript
*/
function GM_main(jQuery) {
// We want to execute these on every NetSuite page
GM_pageTransformations.header();
GM_pageTransformations.browsertitle();
// Here we build a function name from the path (page being accessed on the NetSuite domain)
var path = location.pathname;
if(path.indexOf('.')>-1) path = path.substr(0,path.indexOf('.'));
path = toCamelCase(path,'/');
// Now we check if a page "GM_pageTransformations" function exists with a matching name
if(GM_pageTransformations[path]) {
console.log('Executing GM_pageTransformations for '+path);
GM_pageTransformations[path]();
} else {
console.log('No GM_pageTransformations for '+path);
}
}
/**
* Changes the header on all pages
*/
GM_pageTransformations['header'] = function() {
// For example, lets make the header background red
GM_addStyle('#ns_header, #ns_header * { background: red !important; }');
}
/**
* Provides useful browser/tab titles for each NetSuite page
*/
GM_pageTransformations['browsertitle'] = function() {
var title = jQuery('.uir-page-title-secondline').text().trim();
var title2 = jQuery('.uir-page-title-firstline').text().trim();
var title3 = jQuery('.ns-dashboard-detail-name').text().trim();
if(title != '') {
document.title = title+(title2 ? ': '+title2 : '')+(title3 ? ': '+title3 : '');
} else if(title2 != '') {
document.title = title2+(title3 ? ': '+title3 : '');
} else if(title3 != '') {
document.title = title3;
}
}
/**
* Changes app center card pages (dashboard pages)
*/
GM_pageTransformations['appCenterCard'] = function() {
// For example, lets make add a new heading text on all Dashboard pages
jQuery('#ns-dashboard-page').prepend('<h1>My New Dashboard Title</h1>');
}
/**
* Convert a given string into camelCase, or CamelCase
* #param {String} string - The input stirng
* #param {String} delimter - The delimiter that seperates the words in the input string (default " ")
* #param {Boolean} capitalizeFirstWord - Wheater or not to capitalize the first word (default false)
*/
function toCamelCase(string, delimiter, capitalizeFirstWord) {
if(!delimiter) delimiter = ' ';
var pieces = string.split(delimiter);
string = '';
for (var i=0; i<pieces.length; i++) {
if(pieces[i].length == 0) continue;
string += pieces[i].charAt(0).toUpperCase() + pieces[i].slice(1);
}
if(!capitalizeFirstWord) string= string.charAt(0).toLowerCase()+string.slice(1);
return string;
}
// ===============
// CREDIT FOR JQUERY INCLUSION CODE: Brock Adams # https://stackoverflow.com/a/12751531/4561907
/**
* Check if we already have a local copy of jQuery, or if we need to fetch it from a 3rd-party server
*/
if (typeof GM_info !== "undefined") {
console.log("Running with local copy of jQuery!");
GM_main(jQuery);
}
else {
console.log ("fetching jQuery from some 3rd-party server.");
add_jQuery(GM_main, "1.9.0");
}
/**
* Add the jQuery into our page for our userscript to use
*/
function add_jQuery(callbackFn, jqVersion) {
var jqVersion = jqVersion || "1.9.0";
var D = document;
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
var scriptNode = D.createElement ('script');
scriptNode.src = 'https://ajax.googleapis.com/ajax/libs/jquery/'
+ jqVersion
+ '/jquery.min.js'
;
scriptNode.addEventListener ("load", function () {
var scriptNode = D.createElement ("script");
scriptNode.textContent =
'var gm_jQuery = jQuery.noConflict (true);\n'
+ '(' + callbackFn.toString () + ')(gm_jQuery);'
;
targ.appendChild (scriptNode);
}, false);
targ.appendChild (scriptNode);
}
You can copy and paste that code as-is into a new Userscript and it will do the following:
Make Browser tabs/windows have useful titles (shows order numbers, customer names, vendor names etc - not just "Sales Order")
Change the header background to red (as an example)
Add a new heading to the top of all "Dashboard" pages that says "My New Dashboard Title" (as an example)

How to display flash message in Kohana 3

I have to show message after insert some data in database. I'm using Kohana. Is there a way to do that with flash messages? It's better than header refresh.
Well sort of. You could use the Session::get_once() function. But this only let you retrieve a variable once, and you cannot use it again in the same request. While you want a flash message to persist a full request cycle. To manage that you'll need a wrapper class, something like this.
class Flash {
private $session;
private $messages = array();
private static $_instance; // Singleton object
public static function instance() {
if ( ! isset( self::$_instance ) ) {
self::$_instance = new Flash();
}
return self::$_instance;
}
private function __construct() {
$this->session = Session::instance();
$this->messages['current'] = $this->session->get_once('flash');
if( ! is_array($this->messages['current'] ) ) {
$this->messages['current'] = array();
}
}
public function add( $key, $message === null ) {
if ( is_null( $message ) ) {
$message = $key;
$key = null;
}
$this->messages['new'][$key] = $message;
$this->session->set('flash', $this->messages['new'] );
return true;
}
public function get( $item = null ) {
if( $item === null ) {
return $this->messages['current'];
}
if( ! array_key_exists($item, $this->messages['current']) ) {
return null;
}
return $this->messages['current'][$item];
}
}
Usage:
$flash = Flash::instance();
$flash->add('A random message');
$flash->add('some_key', 'Some message');
$flash->get(); // array( 0 => 'A random message', 'some_key' => 'Some message')
$flash->get('some_key'); // 'A Random message'
What it does basically is on initialization it retrieves the current message from the session, using the get_once() function. The variable is nou out of the Session object, so it will only last this request. Everytime you add a variable, it will immediately persisted to the Session object.
There is just one problem; if you are using ajax calls, the messages will only be available on the initial php request, not on subsequent ajax calls. And there is also no restriction whatsoever on what kind of variable you are storing (but it must be serializable). You'll have to build in some checks for that too.
warning: the class is not tested, so it would surprise me if you do not get a syntax error ;)
And to go a step further: you would need an extra refresh anyway. The request flow should be like this imo:
Request 1: User is presented form
Request 2: User posts the form, which is processed. Data is inserted in database. When done, user is redirected
Request 3: A confirmation page is shown (can be "thank you", or the detail page, whatever).
You would set the flash message in request 2, and show it in 3. I would not directly show the thank you page on request 2, because when the user refreshes, the form will be posted again.
Use this module. Works perfectly :)

Check if a given user is in the security group of a given path

I have a simple job which I don't know how to accomplish, and as deeper I search it I got lost deeper.
I need to write a method which returns the FileSystemAccessRule of a given user(I am given his samAccountName, objectGUID) over a given folder path.
I've done adding or removing FileSystemAccessRule's to a path before like this:
var fSecurity = Directory.GetAccessControl(physicalPath);
fSecurity.AddAccessRule(new FileSystemAccessRule(samAccountName, FileSystemRights.FullControl, AccessControlType.Allow));
fSecurity.RemoveAccessRule(new FileSystemAccessRule(samAccountName, FileSystemRights.FullControl, AccessControlType.Allow));
Directory.SetAccessControl(physicalPath, fSecurity);
Checking if the given user has some certain the access rights over a path a similiar job? Or should go to another way? Something like DirectoryEntry or LDAP or Active Directory or so?
What I want is a method which maybe looks like this:
FileSystemAccessRule[] GetAccessRulesOfTheUserOverPath(string samAccountName, string folderPath)
{
/// how?
}
Thanks to some answers on SO I've come up with an answer. Although it is not the exact answer to my question, it fulfills my need. On this question's answers I found the solution. This solution tells me if the given FileSystemRights is bound to the current windows user on acl(AuthorizationRuleCollection) of given folder.
Almost all answers in the question I've referred to are giving the result, In my opinion the most accurate one is #Olivier Jacot-Descombes's answer since it calculates the allow rules, deny rules, and inherited rules precedences over each other.
So what I did is this:
WindowsIdentity _currentUser;
WindowsPrincipal _currentPrincipal;
using ( new Impersonator(userName, passwordOfTheUser) )
{
_currentUser = WindowsIdentity.GetCurrent();
_currentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
}
if ( !Directory.Exists(path) ) throw new Exception("Directory does not exist");
var di = new DirectoryInfo(path);
var directoryACLs = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
///rw_accessRules list consists of the rules for ReadWrite permissons.
bool auth_RW = rw_accessRules.All(aR => HasFileOrDirectoryAccess(_currentUser, _currentPrincipal, aR, directoryACLs));
And here is the ``HasFileOrDirectoryAccess` method:
bool HasFileOrDirectoryAccess ( WindowsIdentity _currentUser, WindowsPrincipal _currentPrincipal, FileSystemRights right, AuthorizationRuleCollection acl )
{
bool allow = false;
bool inheritedAllow = false;
bool inheritedDeny = false;
foreach ( FileSystemAccessRule currentRule in acl )
{
// If the current rule applies to the current user.
if ( _currentUser.User.Equals(currentRule.IdentityReference) || _currentPrincipal.IsInRole((SecurityIdentifier)currentRule.IdentityReference) )
{
if ( currentRule.AccessControlType.Equals(AccessControlType.Deny) )
{
if ( ( currentRule.FileSystemRights & right ) == right )
{
if ( currentRule.IsInherited )
{
inheritedDeny = true;
}
else
{ // Non inherited "deny" takes overall precedence.
return false;
}
}
}
else if ( currentRule.AccessControlType.Equals(AccessControlType.Allow) )
{
if ( ( currentRule.FileSystemRights & right ) == right )
{
if ( currentRule.IsInherited )
{
inheritedAllow = true;
}
else
{
allow = true;
}
}
}
}
}
if ( allow )
{ // Non inherited "allow" takes precedence over inherited rules.
return true;
}
return inheritedAllow && !inheritedDeny;
}
I first impersonate for the given user, get his principal and identity, then check if he has the authority of the given rule set.
This one works for my case, but you'll notice that we need password of the user that we want check the permissions of. If there is any way to do this without the password, it will be great.

Read file metadata via Windows Search from MFC program

I would like to read metadata of a DWG/AutoCAD file via Windows Search indexing service. I'm talking about properties that can be accessed with the right click in explorer without opening AutoCAD.
I have an MFC dialog based application written in Visual C++ 2005 and from inside this app I would like to access metadata (such as author, creation date etc.) of the given file. This was done by iFilter but it is deprecated since Windows XP and will be gone in Windows 8 (and LoadIFilter is not present in VS2005). Now from what I understand, it can be done with windows search - correct me if I'm wrong. Every example I found (msdn included) shows how to give data about your own files to windows search for indexing though. What I need is to know how to ask Windows Search about metadata for a given file.
Thanks
t.g.wilk
EDIT:
Here's what I've come up with so far:
BOOL WSQ_DoQuery( const wchar_t *constr, const wchar_t *querystr, VARIANT &result ) {
HRESULT hr = 0;
BOOL ret;
// Get the ADO connection
_Connection *con = NULL;
hr = CoCreateInstance( CLSID_Connection, NULL, CLSCTX_ALL, IID__Connection, (LPVOID *)&con );
if ( SUCCEEDED(hr) ) {
_Recordset *rs = NULL;
// Convert wide strings to BSTR as required by ADO APIs
BSTR bconstr = SysAllocString( constr );
BSTR bquerystr = SysAllocString( querystr );
if ( bconstr && bquerystr ) {
// Open the connection
hr = con->Open( bconstr, NULL, NULL, 0 );
if ( SUCCEEDED(hr) ) {
// Execute the query
hr = con->Execute( bquerystr, NULL, 0, &rs );
if ( SUCCEEDED(hr) ) {
// Display the results
ret = WSQ_GetCDate( rs ,result);
rs->Release();
} else {
TRACE( "Failed to execute query, %08x\r\n", hr );
} // if
} else {
TRACE( "Failed to open ADO connection, %08x\r\n", hr );
} // if
} else {
TRACE("Failed to convert wide to BSTR\r\n" );
} // if
con->Release();
if ( bconstr ) {
SysFreeString( bconstr );
}
if ( bquerystr ) {
SysFreeString( bquerystr );
}
} else {
TRACE("Failed to get connection, %08x\r\n", hr );
} // if
return ret;
} // DoQuery
The connection string (constr) is
provider=Search.CollatorDSO.1;EXTENDED PROPERTIES="Application=Windows"
as returned by ISearchQueryHelper.
And the query (querystr) is
SELECT System.Document.DateCreated FROM SystemIndex WHERE System.FileName LIKE 'filename%' AND DIRECTORY='file:C:\path\to\file'
The problem now is that I get an exception:
First-chance exception at 0x77c5fc56 in fraudTest.exe: Microsoft C++ exception: CNLBaseException at memory location 0x0012d6d0..
on this line
hr = con->Open( bconstr, NULL, NULL, 0 );
followed by the empty result from the query (this code is from WSQ_GetCDate):
rs->get_EOF( &eor );
while ( eor != VARIANT_TRUE ) { //this never executes }
Suprisingly SUCCEEDED(hr) returns true after the exception.
Where have I made en error and how to try and find it?
Thanks
t.g.wilk
I didn't solve this particular problem, but I learned that I don't need Windows Search to get the file metadata. The keyword to look for is "properties" instead of meta-data. I got my piece of code from Windows SDK v7.0 sample application named PropertyEdit.

Store and read password to/from keychain using Monotouch

EDIT: Issue has been resolved. To contribute a bit to the community I setup some helper methods and an example how to use them on my blog. Find it here KeyChain MT example
--
Original question:
Running iOS4.2 on Simulator and iPad.
I'm trying to store and read a password from the keychain using the code below. My inspiration for the code was https://github.com/ldandersen/scifihifi-iphone/ but I can't get it to work. What am I missing?
// Create a record.
SecRecord o = new SecRecord ( SecKind.GenericPassword );
o.Service = "myService";
o.Label = "myService";
o.Account = "test#test.com";
// The super secret password.
o.Generic = NSData.FromString ( "secret!", NSStringEncoding.UTF8 );
// Add to keychain.
SecKeyChain.Add ( o );
// Now cerate another recored to query what we just saved.
o = new SecRecord ( SecKind.GenericPassword );
o.Service = "myService";
o.Account = "test#test.com";
// Query as record.
SecStatusCode code;
var data = SecKeyChain.QueryAsRecord ( o, out code );
// This will tell us "all good!"...
Console.WriteLine ( code );
// But data.Generic is NULL and this line will crash. :-(
Console.WriteLine ( NSString.FromData ( data.Generic, NSStringEncoding.UTF8 ) );
Rather than use SecRecord's .ValueData try this:
Console.WriteLine(NSString.FromData(data.Generic, NSStringEncoding.ASCIIStringEncoding));
Generic returns NSData from where SecKind.GenericPassword's are stored.

Resources