Sunday, January 21, 2018

Read arbitary bits

#define READ_VALUE(n, p, i) ((n) >> (p)) & ((1 <<(i)) - 1)

The above macro return the byes of specified position

Tuesday, March 19, 2013

Read XML using C++


Using this class you can read tag and value of a XML file and add the values in to a std::list.



//ReadXML.h

#include
#include
#include
#include
#import rename_namespace(_T("MSXML"))

class CReadXML
{
public:
CReadXML();
~CReadXML();
HRESULT CreateAndInitDOM(IXMLDOMDocument **ppDoc);
HRESULT VariantFromString(PCWSTR wszValue, VARIANT &Variant);
void LoadDOM( std::string pFileName, std::list>& values );
std::wstring String2WS (const std::string& s);
std::string ConvertWCSToMBS(const wchar_t* pstr, long wslen);
std::string ConvertBSTRToString(BSTR bstr);
BOOL CheckSubNodes( IXMLDOMNode *pNode );
void ReadNodeValues( IXMLDOMNode *pNode, std::list>& values );
void ReadSubNode( IXMLDOMNode *pNode, std::list>& values );

};


//ReadXML.cpp

#include
#include "ReadXML.h"
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms765465(v=vs.85).aspx

// Macro to verify memory allcation.
#define CHK_ALLOC(p)        do { if (!(p)) { hr = E_OUTOFMEMORY; goto CleanUp; } } while(0)

// Macro that calls a COM method returning HRESULT value.
#define CHK_HR(stmt)        do { hr=(stmt); if (FAILED(hr)) goto CleanUp; } while(0)

// Macro that releases a COM object if not NULL.
#define SAFE_RELEASE(p)     do { if ((p)) { (p)->Release(); (p) = NULL; } } while(0)


CReadXML::CReadXML()
{

}

CReadXML::~CReadXML()
{

}

// Helper function to create a DOM instance.
HRESULT CReadXML::CreateAndInitDOM(IXMLDOMDocument **ppDoc)
{

HRESULT hr = CoCreateInstance( __uuidof(MSXML::DOMDocument30), NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)ppDoc);
if (SUCCEEDED(hr))
{
// these methods should not fail so don't inspect result
(*ppDoc)->put_async(VARIANT_FALSE);
(*ppDoc)->put_validateOnParse(VARIANT_FALSE);
(*ppDoc)->put_resolveExternals(VARIANT_FALSE);
}
return hr;

//NOT WORKING, IF "xmlns=" IS IN XML FILE
//HRESULT hr = CoCreateInstance(__uuidof(MSXML::DOMDocument60), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(ppDoc));
//   if (SUCCEEDED(hr))
//   {
//       // these methods should not fail so don't inspect result
//       (*ppDoc)->put_async(VARIANT_FALSE);
//       (*ppDoc)->put_validateOnParse(VARIANT_FALSE);
//       (*ppDoc)->put_resolveExternals(VARIANT_FALSE);
//   }


}

// Helper function to create a VT_BSTR variant from a null terminated string.
HRESULT CReadXML::VariantFromString(PCWSTR wszValue, VARIANT &Variant)
{
HRESULT hr = S_OK;
BSTR bstr = SysAllocString(wszValue);
CHK_ALLOC(bstr);

V_VT(&Variant)   = VT_BSTR;
V_BSTR(&Variant) = bstr;

CleanUp:
return hr;
}

std::wstring CReadXML::String2WS (const std::string& s)
{
       std::wstringstream ws;

ws << s.c_str();
std::wstring sLogLevel = ws.str();
return sLogLevel;


// std::wstring ws;
//ws.assign (s.begin (), s.end ());
// return ws;
}

std::string CReadXML::ConvertWCSToMBS(const wchar_t* pstr, long wslen)
{
    int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);

    std::string dblstr(len, '?');
    len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */,
                                pstr, wslen /* not necessary NULL-terminated */,
                                &dblstr[0], len,
                                NULL, NULL /* no default char */);

    return dblstr;
}

std::string CReadXML::ConvertBSTRToString(BSTR bstr)
{
    int wslen = ::SysStringLen(bstr);
    return ConvertWCSToMBS((wchar_t*)bstr, wslen);
}

void CReadXML::LoadDOM( std::string pFileName, std::list>& values )
{
HRESULT hr = S_OK;

IXMLDOMDocument *pXMLDom = NULL;
IXMLDOMParseError *pXMLErr = NULL;
IXMLDOMNodeList *NodeList = NULL;
IXMLDOMNode *pNode = NULL;

std::wstring wspFileName;

BSTR bstrXML = NULL;
BSTR bstrErr = NULL;
BSTR bstrQuery2 = NULL;

VARIANT_BOOL varStatus;
VARIANT varFileName;
VariantInit(&varFileName);

//Initialize COM Library:
CoInitialize(NULL);

CHK_HR(CreateAndInitDOM(&pXMLDom));  

wspFileName = String2WS(pFileName);

// XML file name to load
CHK_HR(VariantFromString( wspFileName.c_str(), varFileName));

CHK_HR(pXMLDom->load(varFileName, &varStatus));

if (varStatus == VARIANT_TRUE)
{
CHK_HR(pXMLDom->get_xml(&bstrXML));
//printf("XML DOM loaded from stocks.xml:\n%S\n", bstrXML);

bstrQuery2 = SysAllocString(L"Object"); // For find the tag Object.  Please replace this with your tag name.  If you need to read all values, then replace "Object" with " ".  But the problem is that, then each tags consider as each item, can not separate the child nodes.  For a better out put specify the tag name, where you want to start.

CHK_ALLOC(bstrQuery2);
CHK_HR(pXMLDom->getElementsByTagName(bstrQuery2, &NodeList));

if(NodeList)
{
//get the length of node-set
long length = 0;
CHK_HR(NodeList->get_length(&length));

for (long i = 0; i < length; i++)
{
if ( pNode ) pNode->Release();

CHK_HR( NodeList->get_item(i, &pNode) );

if(pNode )
{
if( CheckSubNodes( pNode ) == TRUE )
{
ReadSubNode( pNode, values );
}
else
{
ReadNodeValues( pNode, values );
}
}
}
}
}
else
{
// Failed to load xml, get last parsing error
CHK_HR(pXMLDom->get_parseError(&pXMLErr));
CHK_HR(pXMLErr->get_reason(&bstrErr));
printf("Failed to load DOM from %S. %S\n", varFileName, bstrErr);
}

CleanUp:
SAFE_RELEASE(pXMLDom);
SAFE_RELEASE(pXMLErr);
SAFE_RELEASE(NodeList);
SAFE_RELEASE(pNode);

SysFreeString(bstrXML);
SysFreeString(bstrErr);
SysFreeString(bstrQuery2);

VariantClear(&varFileName);
}

void CReadXML::ReadSubNode( IXMLDOMNode *pNode, std::list>& values )
{
HRESULT hr = S_OK;
HRESULT hResult;

IXMLDOMNode *pIAttrNode = NULL;
IXMLDOMNodeList *NodeList = NULL;
IXMLDOMNamedNodeMap *pDOMNamedNodeMap = NULL;
long length = 0;
std::pair pPair;

if( pNode )
{
CHK_HR( pNode->get_childNodes(&NodeList) );
if( NodeList )
{
CHK_HR( NodeList->get_length(&length) );

for( int i = 0; i < length; i++ )
{
if (pIAttrNode) pIAttrNode->Release();

CHK_HR( NodeList->get_item(i, &pIAttrNode));

if(pIAttrNode )
{
if( CheckSubNodes( pIAttrNode ) == TRUE )
{
ReadSubNode( pIAttrNode, values );
}
else
{
ReadNodeValues( pIAttrNode, values );
}
}
}
}
}

CleanUp:
SAFE_RELEASE(NodeList);
}

BOOL CReadXML::CheckSubNodes( IXMLDOMNode *pNode )
{
HRESULT hr = S_OK;
IXMLDOMNodeList *NodeList = NULL;
long length = 0;
VARIANT_BOOL varStatus = FALSE;

if( pNode )
{
CHK_HR( pNode->get_childNodes(&NodeList) );
if( NodeList )
{
CHK_HR( NodeList->get_length(&length) );

if( length > 0 )
varStatus = TRUE;
else
varStatus = FALSE;
}
}

CleanUp:
SAFE_RELEASE(NodeList);

return varStatus;
}

void CReadXML::ReadNodeValues( IXMLDOMNode *pNode, std::list>& values )
{
HRESULT hr = S_OK;

IXMLDOMNode* pParNode = NULL;

//Variables to store item's name, parent, text and node type:
BSTR bstrItemText, bstrItemNode, bstrNodeType;
std::pair pPair;

CHK_HR( pNode->get_nodeTypeString(&bstrNodeType));
//We process only elements (nodes of "Text" type):
BSTR temp = L"text";

if (lstrcmp((LPCTSTR)bstrNodeType, (LPCTSTR)temp)==0)
{
CHK_HR( pNode->get_parentNode( &pParNode ) );
if( pParNode )
{
CHK_HR( pParNode->get_nodeName(&bstrItemNode) );
//printf("Text: %ls\n", bstrItemNode);

CHK_HR( pNode->get_text(&bstrItemText) );
//printf("Text: %ls\n", bstrItemText);

pPair.first = ConvertBSTRToString(bstrItemNode);
pPair.second = ConvertBSTRToString(bstrItemText);
values.push_back( pPair);
}
}

CleanUp:
SAFE_RELEASE(pParNode);

}



For using this class create a C++ application and add the above files into that application.  After that create an object of the class "CReadXML" and call the function "LoadDOM".

eg:

        std::list> values;
CReadXML* pCReadXML = new CReadXML();
pCReadXML->LoadDOM("response_tunnel.xml", values);

After the function call you will get the values of XML file in the std::list values!.

Enjoy...!




Wednesday, February 13, 2013

Squiz Matrix

-->

Squiz Matrix

Install the following packages, for checking available packages, first you install "aptitude”, using the command “sudo apt-get install aptitude”, using “ / “ for find the packages, and use “ q” for quit from aptitude

Needed packages for Squiz Matrix
  1. vim
  2. apache2
  3. postgresql-9.1.7 or latest
  4. php5
  5. php5-cli
  6. php5-pgsql
  7. php-pear
  8. php5-curl
  9. php5-ldap
  10. php5-gd
  11. postfix
  12. cvs
  13. curl
  14. postfix
  15. PEAR

Use this command for install the above packages, if any one is existing, then ignore it from the list
Execute the following commands, as root or use sudo before the command...


apt-get update
apt-get install apache2 postgresql-9.1 php5 php5-cli php5-pgsql php-pear php5-curl php5-ldap php5-gd postfix cvs curl vim postfix

pear upgrade PEAR

pear install MDB2 Mail Mail_Mime XML_HTMLSax XML_Parser Text_Diff HTTP_Client Net_URL I18N_UnicodeNormalizer Mail_mimeDecode Mail_Queue HTTP_Request Image_Graph-0.8.0 Image_Color Image_Canvas-0.3.4 Numbers_Roman Numbers_Words-0.16.4 pear/MDB2#pgsql


Select “ local “ when you install postfix and enter the name


Settings for PostgreSQL

// Edit Postgres config
vim /etc/postgresql/9.1/main/pg_hba.conf
// Use trust for both
# Database administrative login by UNIX sockets
local all postgres trust
# "local" is for Unix domain socket connections only
local all all trust
// Restart Postgres
etc/init.d/postgresql restart
// Create users and DB
createuser -SRDU postgres matrix
createuser -SRDU postgres matrix_secondary
createdb -U postgres -O matrix -E UTF8 squiz_matrix
createlang -U postgres plpgsql squiz_matrix

Install Matrix

mkdir /home/websites
cd /home/websites
// Checkout and install Matrix
curl -O http://public-cvs.squiz.net/cgi-bin/viewvc.cgi/mysource_matrix/scripts/dev/checkout.sh?view=co
mv checkout.sh\?view\=co checkout.sh
sh checkout.sh mysource_4-12-3

Set Domain name

vim /etc/hosts
add the line

Init Matrix

// Init the main config
cd /home/websites/squiz_matrix
php install/step_01.php /home/websites/squiz_matrix
// Edit the main config file
vim data/private/conf/main.inc
// The following configuration settings need to be completed as a minimum

define('SQ_CONF_SYSTEM_ROOT_URLS', 'www.squizserver.com
');
define('SQ_CONF_DEFAULT_EMAIL', 'sabeesh.cs@sterian.com');
define('SQ_CONF_TECH_EMAIL', 'sabeesh.cs@sterian.com');
// Edit Database file
vim data/private/conf/db.inc
// Update the PHP array
$db_conf = array (
       'db' => array (
          'DSN' => 'pgsql:dbname=squiz_matrix',
          'user' => 'matrix',
          'password' => '',
          'type' => 'pgsql',
          ),
       'db2' => array (
          'DSN' => 'pgsql:dbname=squiz_matrix',
          'user' => 'matrix',
          'password' => '',
          'type' => 'pgsql',
          ),
       'db3' => array (
          'DSN' => 'pgsql:dbname=squiz_matrix',
          'user' => 'matrix_secondary',
          'password' => '',
          'type' => 'pgsql',
          ),
       'dbcache' => NULL,
       'dbsearch' => NULL,
       );

return $db_conf;

// Init database schema
php install/step_02.php /home/websites/squiz_matrix
// Install core asset types
php install/compile_locale.php /home/websites/squiz_matrix
php install/step_03.php /home/websites/squiz_matrix
php install/compile_locale.php /home/websites/squiz_matrix

Fix Permissions

Do this process as root user / use sudo before each command
chmod -R 755 /home/websites/squiz_matrix
cd /home/websites/squiz_matrix
chown -R www-data:www-data data cache
chmod -R g+w data cache

Apache

// Edit apache virtual hosts file
vim /etc/apache2/sites-enabled/000-default
//Remove existing, need to check this



ServerName server.example.com
DocumentRoot /home/websites/squiz_matrix/core/web

Options -Indexes FollowSymLinks


Order deny,allow
Deny from all


Order allow,deny
Allow from all


php_flag engine off



Order allow,deny
Deny from all


Order allow,deny
Deny from all


Alias /__fudge /home/websites/squiz_matrix/fudge
Alias /__data /home/websites/squiz_matrix/data/public
Alias /__lib /home/websites/squiz_matrix/core/lib
Alias / /home/websites/squiz_matrix/core/web/index.php/


// Restart apache
/etc/init.d/apache2 restart

Cron Setup

// Edit apache user cron file
crontab -u www-data -e
( select option 4 for editer )

// Add cron jobs
*/15 * * * * php /home/websites/squiz_matrix/core/cron/run.php
0 0 * * * /home/websites/squiz_matrix/scripts/session_cleanup.sh /home/websites/squiz_matrix
*/15 * * * * php /home/websites/squiz_matrix/packages/bulkmail/scripts/run.php

Install JRE 

 
 sudo apt-get purge openjdk*

After that, go and download Java JRE package from http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html
When prompted, save the download. Please select the 32 or 64 bit .tar.gz version file from the list.
After saving the file, go back to your terminal and run the below commands to extract the java packages you downloaded.
tar -xvf ~/Downloads/jre-7u13-linux-i586.tar.gz
Next, create your java 7 folder by running the commands below.
sudo mkdir -p /usr/lib/jvm/jre1.7.0
Then move all the extracted files and folders into the java 7 folder.
sudo mv jre1.7.0_13/* /usr/lib/jvm/jre1.7.0/
Next, run the commands below to install / update java 7
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jre1.7.0/bin/java 0
Next, create a plugin folder in your home directory by running the commands below.
mkdir ~/.mozilla/plugins 
Finally, link the java plugin to your profile.
ln -s /usr/lib/jvm/jre1.7.0/lib/i386/libnpjp2.so ~/.mozilla/plugins/

Load Firefox, Tools->Add-ons, select java, ( Quick java ) and install.

Load the “ www.squizserver.com “ and enjoy!

Tuesday, April 24, 2012



Prevent Expand\collapse event of treeview and load our functionality, if shift button is pressed.

Add Event "PreviewMouseDown" for the treeview,


pTreeView->PreviewMouseDown += gcnew System::Windows::Input::MouseButtonEventHandler(this, &OnPreviewMouseDown);



void OnPreviewMouseDown( System::Object^ sender, System::Windows::Input::MouseButtonEventArgs^ e)
{

if(System::Windows::Input::Keyboard::IsKeyDown(System::Windows::Input::Key::LeftShift) ||System::Windows::Input::Keyboard::IsKeyDown(System::Windows::Input::Key::RightShift))
{
System::Windows::Controls::TreeView^ pTreeView   = nullptr;
System::Windows::DependencyObject^ pDependencyObject = (System::Windows::DependencyObject^)e->OriginalSource;

pTreeView = (System::Windows::Controls::TreeView^)sender;
FindAncestor(pDependencyObject,System::Windows::Controls::TreeViewItem::typeid);
if(pDependencyObject)
{
System::Windows::Controls::TreeViewItem^ pTreeViewItem = (System::Windows::Controls::TreeViewItem^)pDependencyObject;
int iType = m_pCtrlAdmin->GetTreeitemType( (int)pTreeViewItem->Tag );
if( pTreeViewItem->Items->Count > 0 )
{
SetTreeviewAllItemState(iType);
e->Handled = true;
}

}

}
}



void FindAncestor(System::Windows::DependencyObject^% pDependencyObject,System::Type^ pType)
{
if(pDependencyObject->GetType() == pType)
return;
else
{
pDependencyObject = System::Windows::Media::VisualTreeHelper::GetParent(pDependencyObject);
if(pDependencyObject)
FindAncestor(pDependencyObject,pType);
else
return;
}
}


void SetTreeviewAllItemState(int iType)
{
    //Write your functionality

}


Thursday, October 27, 2011

Paper setting and read it in C++/CLI

Paper setting and read it in C++/CLI

[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = System::Runtime::InteropServices::CallingConvention::StdCall)]
static int DocumentProperties( System::IntPtr hwnd, System::IntPtr hPrinter, [MarshalAs(UnmanagedType::LPWStr)] System::String^ pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);

void OnBtnPropertiesClick( Object^ sender, RoutedEventArgs^ e )
{

System::Windows::Controls::ComboBoxItem^ pComboBoxItem = nullptr;
System::Printing::PrintQueue^ CurrentPrinter = nullptr;

pComboBoxItem = (System::Windows::Controls::ComboBoxItem^)m_CWPFDlgPrintPreview->m_CWPFDlgPrintPreview->CmbPrinter->SelectedItem;
if( pComboBoxItem->Tag != nullptr )
{
CurrentPrinter = (System::Printing::PrintQueue^)pComboBoxItem->Tag;
}

if( CurrentPrinter )
{
HWND pHWND = NULL;
System::IntPtr pHandle = System::IntPtr::Zero;
pHWND = m_CWPFDlgPrintPreview->GetHWND();

if( pHWND )
pHandle = (System::IntPtr)pHWND;

System::Printing::Interop::PrintTicketConverter^ PrintTicketConverter = nullptr;
PrintTicketConverter = gcnew System::Printing::Interop::PrintTicketConverter( CurrentPrinter->FullName, CurrentPrinter->ClientPrintSchemaVersion );
array ^myDevMode = PrintTicketConverter->ConvertPrintTicketToDevMode(CurrentPrinter->UserPrintTicket, System::Printing::Interop::BaseDevModeType::UserDefault);
System::Runtime::InteropServices::GCHandle^ pinnedDevMode = System::Runtime::InteropServices::GCHandle::Alloc(myDevMode, GCHandleType::Pinned);
System::IntPtr pDevMode = pinnedDevMode->AddrOfPinnedObject();
int result = DocumentProperties(pHandle, IntPtr::Zero, CurrentPrinter->FullName, pDevMode, pDevMode, 14);

if (result == 1)
{
CurrentPrinter->UserPrintTicket = PrintTicketConverter->ConvertDevModeToPrintTicket(myDevMode);
pinnedDevMode->Free();
// int PrintCopyCount = CurrentPrinter->UserPrintTicket->CopyCount->Value;
// SetPageOrientation(CurrentPrinter.UserPrintTicket.PageOrientation);
//SetCurrentPaper(CurrentPrinter->UserPrintTicket->PageMediaSize);
// ExecuteSetPrintingOptions(null);

m_CWPFDlgPrintPreview->PreparePrintContent();


}
}



void* WPFDialog::CWPFDlgPrintPreview::GetPrintQueue()
{

System::Runtime::InteropServices::GCHandle pGCHandle;
System::Windows::Controls::ComboBoxItem^ pComboBoxItem = nullptr;
System::Printing::PrintQueue^ l_pPrintQueue = nullptr;
System::Object^ pObject = nullptr;
void* pPrintQueueVoid;

if( m_CWPFDlgPrintPreview->CmbPrinter->SelectedIndex >= 0 )
{
pComboBoxItem = (System::Windows::Controls::ComboBoxItem^)m_CWPFDlgPrintPreview->CmbPrinter->SelectedItem;

if( pComboBoxItem->Tag != nullptr )
l_pPrintQueue = (System::Printing::PrintQueue^)pComboBoxItem->Tag;
}

if( l_pPrintQueue )
{
pObject = (System::Object^)l_pPrintQueue;

if( pObject )
{
pPrintQueueVoid = GCHandle::ToIntPtr(GCHandle::Alloc(pObject)).ToPointer();
}
}

return pPrintQueueVoid;


}


Load Print propertie from C++/CLI

Load Print propertie from C++/CLI

void OnProperties()
{
HANDLE hPrinter = NULL;
int sizeOfDevMode = 0;
DWORD dwRet = 0;
DEVMODE *pDevMode1 = NULL;
PRINTER_DEFAULTS pd;
BOOL bFlag;
LONG lFlag;

System::Drawing::Printing::PrinterSettings^ printerSettings = gcnew System::Drawing::Printing::PrinterSettings();
std::string pDevice = m_CWPFDlgPrintPreview->GetPrinterName();
System::String^ pPrinterName = gcnew System::String( pDevice.c_str() );

printerSettings->PrinterName = pPrinterName;

HWND pHWND = NULL;
System::IntPtr pHandle = System::IntPtr::Zero;
pHWND = m_CWPFDlgPrintPreview->GetHWND();

if( pHWND )
pHandle = (System::IntPtr)pHWND;

//pd.DesiredAccess = PRINTER_ALL_ACCESS;
pd.DesiredAccess = PRINTER_ACCESS_USE;
System::IntPtr thPrinter = (System::IntPtr)hPrinter;

if( !OpenPrinter(pPrinterName, thPrinter, pd) )
return;


IntPtr hDevMode = printerSettings->GetHdevmode();
IntPtr pDevMode = GlobalLock(hDevMode);
Int32 fMode = 0;
int sizeNeeded = DocumentPropertiesSize(pHandle, thPrinter, pPrinterName, pDevMode, pDevMode, fMode);
IntPtr devModeData = Marshal::AllocHGlobal(sizeNeeded);

//fMode = DM_OUT_BUFFER;

fMode = DM_IN_BUFFER | DM_PROMPT | DM_OUT_BUFFER;

DocumentProperties(pHandle, thPrinter, pDevice, devModeData, pDevMode, fMode);
GlobalUnlock(hDevMode);
printerSettings->SetHdevmode(devModeData);
printerSettings->DefaultPageSettings->SetHdevmode(devModeData);
GlobalFree(hDevMode);
Marshal::FreeHGlobal(devModeData);

}

Tuesday, August 16, 2011


For printing, in c++, we need to find the printer's aspect ratio. For get the printer/monitor's aspect ratio use this function


GetAspectRatio( HDC p_hDC, int& p_nAspectX, int& p_nAspectY )
{
//p_hDC is printer's /Monitor's handle

HDC l_hScreenDC = GetDC(NULL);
p_nAspectX = GetDeviceCaps( l_hScreenDC, LOGPIXELSX ) / GetDeviceCaps( p_hDC, LOGPIXELSX );
p_nAspectY = GetDeviceCaps( l_hScreenDC, LOGPIXELSY ) / GetDeviceCaps( p_hDC, LOGPIXELSY ) ;
}