Saturday, December 20, 2014

Saturday, December 13, 2014

MSVCRT.DLL causing application to fail loading , application failed to link with msvcrt.dll (entry point not found).

This will happen due to two reason

1) Visual C++  run-time is not installed properly

2) An Operating system  incompatible dll is used with the application (See all dlls are compatible and of correct version).

These may happen when situations like dlls for advanced version of OS is used in a lower version of OS if there is no problem with visual studio run time.

Convert WString to String

#include<stdio.h>
#include<conio.h>
#include<string>
#include<windows.h>

void main( )

{

wstring strWS = L"wstring test";

wprinft("Output before conversion:%s",strWS);

string strConv(strWS .begin( ),strWS .end( ));

printf("Result after conversion:%s",strConv);

_getch( );

}

Error Message: Side-by-side configuration is incorrect

Application/Service does not start and an error message says “The application has failed to start due to a side-by-side configuration error”.

Reason

This happens on computers which do not have Microsoft Visual C++ runtime installed or you are using a debug dll or exe in a system which doesn't have visual studio.


Install all available Windows updates and the latest Windows service pack and check if this already solves the problem.

If this doesn't help, turn off Windows' User Account Control (UAC). Now download and install one of the following packages, depending on which Live version you are using:
Live 32-bit - Microsoft Visual C++ 2008 SP1 Redistributable Package (x86)
Live 64-bit - Microsoft Visual C++ 2008 SP1 Redistributable Package (x64)

Please ensure you only install the 2008 version of the SP1 Redistributable Package as later versions (e.g. 2010) will not resolve this issue.

Reboot your computer and launch Application.
Additional Notes

The issue should not take place anymore with the latest Application updates: from application 9.0.5, the Microsoft Visual C++ is included in the program installer.

Installing the latest Live version will take care of installing this component.

Friday, June 20, 2014

HTTP JSON POST REQUEST C++ EXAMPLE WORKING :-)

#include <Windows.h>
#include <WinInet.h>
#include <tchar.h>
#include<iostream>
#include<stdio.h>
#include<conio.h>
#pragma comment (lib, "Wininet.lib")
#pragma comment (lib, "urlmon.lib")
void Request(LPSTR data);
int main(int argc, _TCHAR* argv[])
{
char data[1024];
char* posturi ="{\"type\":\"Point\",\"coordinates\":[-105.01628,39.57422]}";
wsprintfA( data, posturi);
wsprintfA(data,posturi);
Request(data);
system("pause");
return 0;
}


void Request(LPSTR data)
{
try{
//Retrieve default http user agent
char httpUseragent[512];
DWORD szhttpUserAgent = sizeof(httpUseragent);
//ObtainUserAgentString( 0, httpUseragent, &szhttpUserAgent );

char m[5];


HINTERNET internet = InternetOpen(_T(" Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(internet==NULL)
{
std::cout<<"InternetOpen failed";
}
if(internet != NULL)
{

HINTERNET connect = InternetConnect(internet, _T("geojsonlint.com"), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if(connect==NULL)
{
std::cout<<"InternetConnect failed";
}
if(connect != NULL)
{

HINTERNET request = HttpOpenRequest(connect, _T("POST"), _T("/validate"), _T("HTTP/1.1"), NULL, NULL,
INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP  |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_NO_AUTH |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_RELOAD, NULL);
if(request==NULL)
{
std::cout<<"HttpOpenRequest failed";
}
if(request != NULL)
{
int datalen = 0;
if(data != NULL) datalen = strlen(data);
                LPCWSTR RH=_T("Connection: keep-Alive\r\n");
HttpAddRequestHeaders(request,RH,_tcslen(RH),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
LPCWSTR RH1=_T("Content-Type: application/json\r\n");
HttpAddRequestHeaders(request,RH1,_tcslen(RH1),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
LPCWSTR RH3=_T("Accept-Language: en-US,en;q=0.8\r\n");
HttpAddRequestHeaders(request,RH3,_tcslen(RH3),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
LPCWSTR RH4=_T("Accept: */*\r\n");
HttpAddRequestHeaders(request,RH4,_tcslen(RH4),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
LPCWSTR RH5=_T("Accept-Encoding: gzip,deflate,sdch\r\n");
HttpAddRequestHeaders(request,RH5,_tcslen(RH5),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);

HttpSendRequestA(request, NULL, 0, data, datalen);
DWORD StatusCode = 0;
DWORD StatusCodeLen = sizeof(StatusCode);
HttpQueryInfo(request, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &StatusCode, &StatusCodeLen, NULL);
if(StatusCode==200)
{
std::cout<<"Sucess=200";
}
else
{
std::cout<<"failed="<<StatusCode;
}

InternetCloseHandle(request);
}
}
InternetCloseHandle(connect);
}
InternetCloseHandle(internet);
}
catch(...) {}
}

Wednesday, June 4, 2014

How to Convert UCHAR array to WString and String?

#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <string>

void main()
{
UCHAR s[32]="@abcdefghijklmnopqrstuvwxyz!";
char temp[32]={0};
std::wstring strws;
memcpy(&temp[0],&s[0],sizeof(s)/sizeof(UCHAR));
std::string str=temp;
    strws.assign(str.length( ),L' ' );
std::copy(str.begin( ),str.end( ),strws.begin( ));
    printf("WString equivalent of UCHAR=%ls",strws.c_str( ));
getch( );
}

Thursday, April 24, 2014

How to Delete a Directory without looking its contents using SHFileOperation

BOOL MyFileOperations :: DeleteImageDirectory(Cstring strDirectory)
{  
     Cstring strDirectoryName;
      SHFILEOPSTRUCT shFile;
      int nResult = 0;
      strDirectoryName = strDirectory;
      ZeroMemory (&shFile, sizeof(SHFILEOPSTRUCT));

      shFile.wFunc     = FO_DELETE;
      strDirectoryName = strDirectoryName +_T('\0\0');
      shFile.pFrom     = strDirectoryName.c_str();
      shFile.pTo       = NULL;
      shFile.fFlags    = FOF_SILENT + FOF_NOCONFIRMATION;
      nResult          = SHFileOperation(&shFile);
      if(nResult != 0)
      {              
           MsgBox("Error");
           return FALSE;
      }
      else
      {
           MsgBox("Sucess");    
      }  
      return TRUE;

}

Monday, April 21, 2014

A simple Technique to Convert CString to Char or char[ ] array

char mychar;

CString myCString,myLetter;

myCString=_T("From this I want 1st Character");

myLetter=myCString.Mid(0,1);//Now myLetter="F"

 TCHAR* pmyLetter;
 
pmyLetter=myLetter.GetBuffer();

myLetter.ReleaseBuffer();

 TCHAR pszmyLetter[1];
     
_stprintf(pszmyLetter,_T("%s"),pmyLetter);
               
mychar=pszmyLetter[0];//Now sucessfully mychar='F'


Like wise you can do for character array char[] also from CString I know this is not professional but going through all conversions i failed to acheieve sucessful conversion in Visual Studio 2013 so this method works for me fine with out any debug errors or assertion warnings.

Hope this will help you :-)

Friday, April 18, 2014

ATL Service PreMessageLoop is not Called or ATL Service is cannot be Registered


I had a problem as I mentioned above and I solved in a way as follows

Step 1:-

          Check your Service APPID is registered in HKEY_CLASSES_ROOT

             In this See AppID folder by Expanding it you can see AppID of different Application

         See whether your AppID of ATL service is there

          Your ATL Service AppID is given in the <class>ServiceModule  .cpp file

           It is mentioned along with DECLARE_REGISTRY_APPID_RESOURCEID

         It will look like some thing like this

          DECLARE_REGISTRY_APPID_RESOURCEID(IDR_MYService,"{6F201537-FA02-47DA-B778-A7D5E27CEDF2}")

          this is your AppID for Application see this is registed in Registry

  Run->regedit->HKEY_CLASSES_ROOT->AppID find 6F201537-FA02-47DA-B778-A7D5E27CEDF2

          if this doesnot exists that means your application is not registered and the service fails to start up

Step 2:- To Register service and Make it Startup

            Right Click Visual Studio Icon->Run As Administrator

            Open your ATL project want to register

             Project->Linker->Per-user Redirection set to No (If Project is 2010 and above else Yes)
     
             Project->Linker->Register Output Set to Yes

Now Re-build apllication and run see the ATL service is registed and works fine

Remove (_CRT_SECURE_NO_WARNINGS) in Visual Studio

Not automatically, no. You can create a project template as BlueWandered suggested or create a custom property sheet that you can use for your current and all future projects.

Open up the Property Manager (View->Property Manager)
In the Property Manager Right click on your project and select "Add New Project Property Sheet"
Give it a name and create it in a common directory. The property sheet will be added to all build targets.
Right click on the new property sheet and select "Properties". This will open up the properties and allow you to change the settings just like you would if you were editing them for a project.
Go into "Common Properties->C/C++->Preprocessor"
Edit the setting "Preprocessor Definitions" and add _CRT_SECURE_NO_WARNINGS.
Save and you're done.
Now any time you create a new project, add this property sheet like so...

Open up the Property Manager (View->Property Manager)
In the Property Manager Right click on your project and select "Add Existing Project Property Sheet"
The benefit here is that not only do you get a single place to manage common settings but anytime you change the settings they get propagated to ALL projects that use it. This is handy if you have a lot of settings like _CRT_SECURE_NO_WARNINGS or libraries like Boost that you want to use in your projects.

How Convert LPCSTR to LPCTSTR in VC++ (Nothing works)

If Nothing works for you Try this I succeeded

Create a Dummy Helper Structure

typedef struct _tag_myconvhelper
{
    CString myhelper;
}MYCONVHELPER;

In your Program don't forget to include tchar.h and CString

create an object for _tag_myconvhelper

MYCONVHELPER objmyconhelper;

LPCSTR lpszfromstring =_T("This is the String");

objmyconhelper.myhelper = lpszfromstring ;

LPCTSTR lpsztostring = objmyconhelper.myhelper;

Windows automatically converts it for you no need of complex conversion method :-)

How to Covert a Simple CString to LPCSTR in VC++

CString Str1("This is my CString");

CString Str1Ref(Str1);//Ref CString

CStringA StrA(Str1Ref);//a helper String

LPCSTR lpszmyString =StrA; // Now lpszmyString  contains This is my CString


Error #error : Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version

This Occurs when you Use MFC dependcy in VC++ other than MFC Application

How to Remove This Error:

In Visual Studio

Goto Project->Properties->Configuration Properties->General

You can see a Row Named Use of MFC from that Select Use MFC in a Shared DLL from Combo Box
then click Apply and Ok the error is removed after a Build :)

VC++ shows error VCEnd exited with code 2147024891

Starting from Windows Vista, including Vista, Win2008 Server, Windows7, build process cannot write to HKEY_CLASSES_ROOT (HKCR) hives unless the process is started as administrator. To be able to register in non-administrator mode, VS2008 and VS2010 offer the feature of "registrer per user". The registration information is written to HKEY_CURRENT_USER (HKCU).

You can set Linker -> General -> Per User ReDirections to "true" if Linker -> General -> Register Output is set to "true if you use the built registration step of the project system.

If you have your own custom registration step, you can use the per user registration command: regsvr32 /s /n /i:user "xxxx.dll".

If VS2010 is installed on Windows XP, you don't need to have the elevated privilege or per user registration to register your application since the security requirement is OS specific.

ATL Project in VS2010 RC - how should I run VS2010.

RefLink :-http://social.msdn.microsoft.com/Forums/vstudio/en-US/82ed3690-c622-4262-a965-33eb3870dcfc/registering-service-in-vsnet2010-build-event-gets-following-error-regservervcend-exited-with?forum=msbuild

Error LNK2019 when using GetFileVersionInfoSize()

I am getting same error, while upgrading the VS6.0 application to VS2013 platform.
a. error LNK2019: unresolved external symbol _GetFileVersionInfoSizeA@8 referenced in function _main
b. error LNK2019: unresolved external symbol _GetFileVersionInfoA@16 referenced in function _main
c. error LNK2019: unresolved external symbol _VerQueryValueA@16 referenced in function _main

Resolution:
I found that it is due to missing reference to library "Version.lib".
a. For VS6.0 add it to Project Setting->Link->library modules
b. For VS2012 or 2013 add to Project Properties->Linker->Input->Additional Dependancies
Type Version.lib and Click Ok problem Solved :)



Courtesy: Stack Over Flow


Reason:

The functions GetFileVersionInfo and GetFileVersionInfoSize are defined in Version.dll and Version.lib so make sure, you are liking to the appropriate libraries.

Thursday, April 3, 2014

Simple Trick to get Date&Time with Milliseconds (Batch File with Note Pad)

Type the following code in Notepad

@echo off
:start
echo Date:%date% Time:%time%
goto start

Save text file  as <anyname>.bat   

For Eg : time.bat

Double click this batch file

See...what happens



Tuesday, March 25, 2014

How to Convert CString to TCHAR*

There are two methods for converting a CString variable to TCHAR* variable

Basically CString belongs to ATL/MFC shared class / DLL you can convert CString into either string or a TCHAR variable of <tchar.h>

The exmaple below shows two implementations

#include<iostream>
#include<atlmfc.h>
#include<tchar.h>

int main( )
{

  CString strMyCS1("This is Method 1");

 TCHAR* pszmyTCHAR1=new TCHAR[strMyCS1.GetLength( )+1];

_tcscpy(pszmyTCHAR1,strMyCS1);

_tprintf("\n %s",pszmyTCHAR1);

delete[ ] pszmyTCHAR; //It is importatnt to use delete if you use new keyword

CString strMyCS2(_T("This is Method 2"));

TCHAR* pszmyTCHAR2=strMyCS2.GetBuffer( );

_tprintf("\n %s",pszmyTCHAR2);

strMyCS2.ReleaseBuffer( );

system("pause");

return 0;

}

output:

This is Method 1
This is Method 2
press any key....






Using brace initialization for any class, struct, or union VC++ 2013

In modern C++, you can use brace initialization for any type, without the equals sign.You can use brace initialization for any class, struct, or union. If a type has a default constructor, either implicitly or explicitly declared, you can use default brace initialization (with empty braces). For example, the following class may be initialized by using both default and non-default brace initialization:

#include<string>
#include<iostream>
using namespace std;

class CBraceInitializer
{
public:
CBraceInitializer(){ cout << "\nThis is Empty constructor Initializer"; }
CBraceInitializer(string StringVar) :m_mystring{ StringVar }{ cout << "\nString intilaized:" << m_mystring; }
CBraceInitializer(int IntVar, double Doublevar) :m_myint{ IntVar }, m_mydouble{ Doublevar }
{
cout << "\nInteger intilaized:" << m_myint << "\nDouble Initialized:" << m_mydouble;
}
CBraceInitializer(string StringVar, double Doublevar) :m_mystring{ StringVar }, m_mydouble{ Doublevar }
{
cout << "\nString intilaized:" << m_mystring;
cout<<"\nDouble Initialized:" << m_mydouble;
}
CBraceInitializer(string StringVar, double Doublevar, int IntVar) :m_mystring{ StringVar }, m_mydouble{ Doublevar }, m_myint{ IntVar }
{
cout << "\nString intilaized:" << m_mystring;
cout << "\nDouble Initialized:" << m_mydouble;
cout << "\nInteger intilaized:" << m_myint<<"\n";
}
int m_myint;
string m_mystring;
double m_mydouble;
};

int main()
{
CBraceInitializer objCBraceInitializer1{};
CBraceInitializer objCBraceInitializer2;

CBraceInitializer objCBraceInitializer3{"Brace String Intializer"};
CBraceInitializer objCBraceInitializer4("Function String Intializer");

CBraceInitializer objCBraceInitializer5{1,0.01};
CBraceInitializer objCBraceInitializer6(2,0.02);

CBraceInitializer objCBraceInitializer7{"Brace init with Double",0.03};
CBraceInitializer objCBraceInitializer8("Function init with Double", 0.04);

CBraceInitializer objCBraceInitializer9{ "Brace init with Double&int", 0.05,3 };
CBraceInitializer objCBraceInitializer10("Function init with Double&int", 0.06,4);

system("pause");

return 0;

}

output:

This is Empty constructor Initializer
This is Empty constructor Initializer
String intilaized:Brace String Intializer
String intilaized:Function String Intializer
Integer intilaized:1
Double Initialized:0.01
Integer intilaized:2
Double Initialized:0.02
String intilaized:Brace init with Double
Double Initialized:0.03
String intilaized:Function init with Double
Double Initialized:0.04
String intilaized:Brace init with Double&int
Double Initialized:0.05
Integer intilaized:3

String intilaized:Function init with Double&int
Double Initialized:0.06
Integer intilaized:4
Press any key to continue . . .

Thursday, March 20, 2014

C++ Program to Find Week Number of a Given Date

The program gives the week number of a Given Date Where Weeks are ISO weeks Starts on Sunday and Ends on Saturday

#include<windows.h>
#include<time.h>
#include<iostream>
#include<conio.h>
#include<tchar.h>
#include <string>
#include<atltime.h>
#include<tchar.h>
using namespace std;
#define SECONDS_IN_A_DAY 86400
#define ConfigIntervalDays 7
int dayofweek(int d, int m, int y);
int getMonthEndDay(int Month,int Year);
bool checkIfLeapYear(int Year);
int WeekofYearFinder(int Day,int Month,int Year);
enum DayOfWeek {Sun=0,Mon,Tue,Wed,Thr,Fri,Sat};
void main()
{
time_t tmNow = time(NULL);
    CTime tmCurrent(tmNow);      
     
      CTime         tmStartOfDay(tmCurrent.GetYear(),tmCurrent.GetMonth(),tmCurrent.GetDay(),1,0,0);
      CTime nPrevEndTime = tmStartOfDay.GetTime();
      CTime nPrevStartTime = tmStartOfDay.GetTime() - ConfigIntervalDays*SECONDS_IN_A_DAY;
 int Year,Month,Day;
      Year=nPrevStartTime.GetYear();
      Month=nPrevStartTime.GetMonth();
      Day=nPrevStartTime.GetDay();
 int i=WeekofYearFinder(Day,Month,Year);
Year= nPrevEndTime.GetYear();
Month=nPrevEndTime.GetMonth();
     Day=nPrevEndTime.GetDay();
 int j=WeekofYearFinder(Day,Month,Year);
 if(i==j)
 {
 cout<<"\n Both Start Time and End Time Belongs to same week";
 cout<<"\n Week:"<<i;
 }
 else
 {
          cout<<"\n Start Time and End Time Belongs to different weeks";
 cout<<"\n Start Time Week:"<<i;
 cout<<"\n End Time Week:"<<j;
 }
 getch();
}

int dayofweek(int d, int m, int y)
{
    static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
    y -= m < 3;
    return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}

int getMonthEndDay(int Month,int Year)
{
   int daysInMonth=0;
   switch(Month)
   {
   case  2:
        daysInMonth = checkIfLeapYear(Year) ? 29 : 28;
        break;
   case 4:
   case 6:
   case 9:
   case 11:
         daysInMonth = 30;
         break;
   default:
          daysInMonth = 31;
          break;
   }
  return daysInMonth;
}

bool checkIfLeapYear(int Year)
{
return (!(Year % 4) && (Year % 100)) || !(Year % 400);
}

int WeekofYearFinder(int Day,int Month,int Year)
{
  if(Day<1|| Day>31 ||Month<1||Month>12||Year<1000)
  {
return 0;
  }
   int wofy=0;
   bool breakFlag=false;
   int EndDay;
   int PrevMonthEnd=0;
   int PrevMonthEndDay=0;
   for(int j=1;j<=12;j++)
   {
     EndDay=getMonthEndDay(j,Year);//Get the Day number which Month Ends Eg:31/MM/YYYY
if(j>1)
{
PrevMonthEnd=dayofweek(PrevMonthEndDay,j-1,Year);//Get the Day number which Previous Month Ends Eg:30/MM/YYYY
}
for(int i=1;i<=EndDay;i++)
{
       if(i==1)//check if day is 1/MM/YYYY
  {
  if((dayofweek(i,j,Year)>Sun && !(PrevMonthEnd<=Sat))||j==1)//Check if  Day 1 > sunday and Previous Month not Ends in Sunday
  {
             wofy++;
  }
  else if(dayofweek(i,j,Year)==Sun)//Check if Day 1 is Sunday
      {
           wofy++;
      }
  }
  else if(dayofweek(i,j,Year)==Sun)//Check Which are the other days other than Day 1 falls on Sunday
  {
           wofy++;
  }

      if(i==Day && j==Month)//If Iteration matches to Given Date exits entire loop
 {
 breakFlag=true;
 break;
 }
}
if(breakFlag)
{
break;
}
PrevMonthEndDay=getMonthEndDay(j,Year);
//Sets the Previous Month's End Date Day Number Eg: 30/MM/YYY
   }
return wofy;
}

Friday, March 14, 2014

How to Concatenate or Append TCHAR Strings

#include<windows.h>
#include<vector>
#include<map>
#include<list>
#include<conio.h>
#include<tchar.h>
using namespace std;

void main(void)
 {

TCHAR* String1;

TCHAR* String2;

TCHAR* String3;

TCHAR* Mystring;

String1="Hi  ";
String2="Welcome  ";
String3="to Know My C++ Blog";

_stprintf(Mystring,_T("%s%s%s"),String1,String2,String3);

_tprintf("\n\n Mystring:%s",Mystring);

getch( );
}

Output:
Mystring:Hi Welcome to Know My C++ Blog



Tuesday, March 11, 2014

C++/VC++ Program to Move a File to Folder and Move a Folder to Folder

//MoveTest.CPP
#include<windows.h>
#include<iostream>
#include<conio.h>
#include<tchar.h>
using namespace std;
void MoveFiletonewLoc(void);
void MoveFoldertonewLoc(void);
int main()
{
int choice;
cout<<"\n********File and Directory mover*********\n\n";
cout<<"1.Move File to another location\n";
cout<<"2.Move Folder to another location";
cout<<"\n\n Enter your choice:";
cin>>choice;
switch(choice)
{
case 1:MoveFiletonewLoc();
break;
case 2:MoveFoldertonewLoc();
break;
   default:cout<<"\nWrong Choice";
            exit(0);
}
getch();
return 0;
}

void MoveFiletonewLoc(void)
{
TCHAR Source[256];
memset(Source,0,256);
    TCHAR Destination[256];
memset(Destination,0,256);
_tprintf("\n\nEnter the file location:");
_tscanf("%s",Source);
_tprintf("\n\nEnter the destination location:");
_tscanf("%s",Destination);
int i=MoveFile(Source,Destination);//Moves Files to Folder
if(i>0)
{
_tprintf("\n\nFile moved to location %s Sucessfully",Destination);
}
else
{
_tprintf("\n\nFile moved to location %s UnSucessful",Destination);
}
}

void MoveFoldertonewLoc(void)
{
TCHAR Source[256];
memset(Source,0,256);
    TCHAR Destination[256];
memset(Destination,0,256);
_tprintf("\n\nEnter the folder location:");
_tscanf("%s",Source);
_tprintf("\n\nEnter the destination location:");
_tscanf("%s",Destination);
SHFILEOPSTRUCT fop={};
fop.wFunc=FO_MOVE;
fop.pFrom=Source;
fop.pTo=Destination;
if(!SHFileOperation(&fop))//Moves Folder to Folder
{
_tprintf("\n\nFolder moved to location %s Sucessfully",Destination);
}
else
{
_tprintf("\n\nFolder moved to location %s UnSucessful",Destination);
}
}

OUTPUT:




Monday, March 10, 2014

COMMONLY USED HEADER FILES IN VISUAL C++


WINDOWS.H is a master include file that includes other Windows header files, some of which also
include other header files. The most important and most basic of these header files are:


  •  WINDEF.H         :Basic type definitions.
  •  WINNT.H           :Type definitions for Unicode support.
  •  WINBASE.H       :Kernel functions.
  •  WINUSER.H       :User interface functions.
  •  WINGDI.H          :Graphics device interface functions.

These header files define all the Windows data types, function calls, data structures, and constant
identifiers. They are an important part of Windows documentation. You might find it convenient to use
the Find In Files option from the Edit menu in the Visual C++ in Visual Studio to search through these
header files. You can also open the header files in the Developer Studio and examine them directly.

Some of the header Files like Shalwapi.h , audiomediatype.h ,Bits.h ,Error.h etc... are defined in Windows Platforms SDK

For that you see ProgramFiles->Microsoft SDKs->Windows->v6.0A->Include

This will appear only if you install Windows Platform SDK or Visual Studio 2010 or Higher

Hello World Equivalent in WIndows API

//HelloBlog.CPP

#include <windows.h>

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow)
{
MessageBox (NULL, TEXT ("Hello, Welcome to Know My C++ BLOG!"), TEXT ("KNOW MY C++ BY SREEYUSH"), 0) ;
return 0 ;
}

Sunday, March 9, 2014

How to Compare two CASE SENSITIVE TCHAR Strings are equal or not? if _tcscmp() not working fine

#include <windows.h>
#include <iostream>
#include "Shlwapi.h"
#include <tchar.h>
#include <conio.h>

using namespace std;
void main( void )
{
TCHAR *String1="This is my String";
TCHAR *String2="This iS my String";
int m_equality=0;
int ScanLineLength,EndLineLength;
ScanLineLength = _tcslen(String1);
EndLineLength=_tcslen(String2);
  if (ScanLineLength==EndLineLength)
  {
    for (int k=0;k<EndLineLength;k++)
    {
      if (String1[k]!=String2[k])
       {
  break;
  }
 else
 {
         m_equality++;
       }
     }
    if(m_equality==EndLineLength)
    {
      cout << "Both Strings are Equal";
    }
   else
    {
      cout << "Both Strings are not Equal";
    }
 }
  else
  cout << "Both Strings are not Equal";
getch();
}

OUTPUT:
Both Strings are not Equal

Note : if you use _tcscmp( ) or _tcsicmp( )  both are case insensitive comparers

Saturday, March 8, 2014

Shlwapi.h not found or FilePathRemoveSpec or Linker Error of FilePathRemoveSpec Solved

 I Solved the Problem with including Shlwapi.h and Using FilePathRemoveSpec

I did the Following Steps

1. Install Microsoft Platform SDK

After installing it you will get a Folder like this in your Program Files

Srep 1:You will Find a folder named Microsoft SDKs in your program files






















Step 2: Check whether Shlwapi.h is Included in that folder Windows->v6.0->Include





















Step 3: Add Path to VC++ Directories both Include and Lib






























































Step 4: Add External dependencies for the project


























Step 5 : Browse there and Type Shlwapi.lib in the Window and Click ok

Now your Visual Studio Can run the Following code works Fine :

#include <windows.h>
#include <iostream>
#include <conio.h>
#include "Shlwapi.h"

void main( void )
{
// Path to include file spec.
char buffer_1[ ] = "C:\\TEST\\sample.txt"; 
char *lpStr1;
lpStr1 = buffer_1;

// Print the path with the file spec.
cout << "The path with file spec is          : " << lpStr1 << endl;

// Call to "PathRemoveFileSpec".
PathRemoveFileSpec(lpStr1);

// Print the path without the file spec.
cout << "\nThe path without file spec is       : " << lpStr1 << endl;
getch();
}

OUTPUT:
==================
The path with file spec is          : C:\TEST\sample.txt

The path without file spec is       : C:\TEST






























Using _strdup , _tcsdup , _mbsdup

The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space.
_wcsdup and _mbsdup are wide-character and multibyte-character versions of _strdup. The arguments and return value of _wcsdup are wide-character strings; those of _mbsdup are multibyte-character strings. These three functions behave identically otherwise.

_UNICODE & _MBCS not defined:Use _strdup  defined in <string.h>
_MBCS defined:Use _mbsdup defined in <mbstring.h>
_UNICODE defined: Use _wcsdup defined in <string.h> or <wchar.h>
TCHAR.H routine : Use _tcsdup

Syntax:
char *_strdup(const char *strSource);
char *_tcsdup(const char *strSource);
wchar_t *_wcsdup(const wchar_t *strSource);
unsigned char *_mbsdup(const unsigned char *strSource);

strSource:
Null-terminated source string.
Return Value:
Each of these functions returns a pointer to the storage location for the copied string or NULL if storage cannot be allocated.
Example:
// _strdup.c
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
void main( void )
{
   char buffer[] = "This is the buffer text";
   char *newstring;
   printf( "Original: %s\n", buffer );
   newstring = _strdup( buffer );
   printf("Copy:     %s\n", newstring );
   free( newstring );
   getch();
}

Output:
Original: This is the buffer text
Copy:This is the buffer text



// _tcsdup.cpp
#include <string.h>
#include <iostream.h>
#include <malloc.h>
#include <conio.h>
int main( void )
{
   char buffer[] = "This is the buffer text";
   char *newstring;
   cout<< "Original:"<< buffer;
   newstring = _strdup( buffer );
   cout<<"Copied string:"<<newstring;
   free(newstring);
   getch();
return 0;
}
Output:
Original: This is the buffer text
Copied string:This is the buffer text


Friday, March 7, 2014

Usage of #pragma comment in Visual C++ & C++/CLI

Adding the Pragma Directives  will tell the linker what additional input files are needed. The link will link the object files generated by the compiler and link them with the additional libraries to generate the ultimate module(.exe or .dll files).
This work can also be done in the properties dialog of the project. You can add the .lib files in the property below:
Configuration Properties -> Linker -> Input -> Additional Dependencies.
The input files will be part of the linker command in the end. Below is a simple sample shows how the input files are used in the link command:
link /dll a.obj b.lib c.lib
In short Places a comment record into an object file or executable file.

Syntax:
#pragma comment( comment-type [,"commentstring"] )

comment-type

1.compiler:Places the name and version number of the compiler in the object file
2. exestr:  At link time this string is placed in the executable file
3.lib:Places a library-search record in the object file. 
4.linker:Places a linker option in the object file.
5.user:Places a general comment in the object file

Examples:

#pragma comment( lib, "emapi" ) //lib comment-type
#pragma comment( compiler ) //compiler comment type
#pragma comment( user, "Compiled on " __DATE__ " at " __TIME__ )  //user comment type


For more reference see also:

http://msdn.microsoft.com/en-us/library/7f0aews7.aspx


Sunday, March 2, 2014

Do I need a copy constructor?

Standard C++ makes heavy use of copy constructors because they are needed to support proper memory management. Referring to ref objects through handles, coupled with garbage collection, means that you don’t need copy constructors nearly as often in C++/CLIIn standard C++ the compiler will give you a default copy constructor if you do not pro-vide one. This is not the case in C++/CLI, so if you want to provide copy construction for your classes, you will need to write a copy constructor.

// UsingTrackingRefrence.cpp : main project file.

#include "stdafx.h"

using namespace System;

ref class MyClass
{
int value;
String ^str;
public:
MyClass(int v, String ^s) :value(v), str(s){}

MyClass(const MyClass %other)
{
Console::WriteLine("Copy constructor Called");
value = other.value;
str = other.str;
}
int getValue(){ return value; }
void setvalue(int v){ value = v; }
String ^getString(){ return str; }
};

int main(array<System::String ^> ^args)
{
    Console::WriteLine("\nCopy Construction");
MyClass ^one = gcnew MyClass(1, "Class One");

MyClass ^onecopy1 = one;
       Console::WriteLine("\nValue of Copy one Class:Value:{0},Str:{1}", onecopy1->getValue(),                        onecopy1->getString());
MyClass onecopy2 = *one;
onecopy2.setvalue(4);
Console::WriteLine("\nValue of one:{0}", one->getValue());
Console::WriteLine("\nValue of oneCopy2:{0}", onecopy2.getValue());
Console::WriteLine("\nStr of one:{0}", one->getString());
Console::WriteLine("\nStr of oneCopy2:{0}", onecopy2.getString());
Console::ReadKey();
    return 0;
}

OutPut:

Copy Construction

Value of copy one Class:Value:1,Str:Class one
Copy constructor called

Value of one:1
Value of oneCopy2:4

Str of one:Class one
Str of oneCopy2:Class one


Saturday, March 1, 2014

Implementing the destructor and finalizer for a class in C++

Destructor:

A destructor is executed when you no longer need an object. To provide a destructor for a class, add a member function that has the same name as the class but is preceded by a tilde character (~).

Finalizer :

Finalizers are called when the garbage collector finally reclaims the object’s memory. You will need a finalizer if you have unmanaged resources, such as pointers to unmanaged classes, file handles, window handles, graphic device contexts, and so on. If you don’t have any of those—and you’ll only tend to do that when you are working with unmanaged code—you probably don’t need a finalizer.

A finalizer is a member function that has the same name as the class but is preceded by an exclamation mark (!).

//MyClass.h Header File
using namespace System;
ref class MyClass
{
String ^name;
public:
MyClass(String ^objectName); // constructor
~MyClass(); // destructor
!MyClass(); // finalizer
void DoSomething(); // 'work' method
};

///MyClass.CPP File

#include "stdafx.h"
using namespace std;
#include "MyClass.h"

MyClass::MyClass(String ^objectName)
{
name = objectName;
Console::WriteLine("Constructor called for {0}", name);
}

MyClass::~MyClass()
{
Console::WriteLine("Destructor called for {0}", name);
}

MyClass::!MyClass()
{
Console::WriteLine("Finalizer called for {0}", name);
}

void MyClass::DoSomething()
{
Console::WriteLine("DoSomething called for {0}", name);
}

//Using the finalizer in Main Program

#include "MyClass.h"
int main(array<System::String^>^ args)
{
MyClass ^m1 = gcnew MyClass("m1");
m1->DoSomething();
Console::WriteLine();
Console::WriteLine("End of program");
Console::WriteLine();
return 0;
}

Output similar to the following appears:

Constructor for m1
DoSomething called
End of Program
Finalizer called for m1




Member initialization lists in Constructor VC++

Here We Can Take a Simple Example of Credit Card Dummy Code:

//Create A headrer File Named CreditCardAccount.h Copy This code to that
ref class CreditCardAccount
{
public:
CreditCardAccount(long number, double limit);
void SetCreditLimit(double amount);
bool MakePurchase(double amount);
void MakeRepayment(double amount);
void PrintStatement();
long GetAccountNumber();

private:
long AccountNumber;
double CurrentBalance;
double CreditLimit;
};

********************************************************************
//Create A CPP File Named CreditCardAccount.CPP Copy This code to that

#include "stdafx.h"
#include "CreditCardAccount.h"

#using <mscorlib.dll>
using namespace System;

void CreditCardAccount::SetCreditLimit(double amount)
{
CreditLimit = amount;
Console::Write("\nCredited Amount:");
Console::Write(amount);
}

bool CreditCardAccount::MakePurchase(double amount)
{
if (CurrentBalance + amount > CreditLimit)
{
return false;
}
else
{
CurrentBalance += amount;
return true;
}
}

void CreditCardAccount::MakeRepayment(double amount)
{
CurrentBalance -= amount;
Console::Write("\nPaid Amount:");
Console::Write(amount);
}

void CreditCardAccount::PrintStatement()
{
Console::Write("\nCurrent Balance:");
Console::Write(CurrentBalance);
}

long CreditCardAccount::GetAccountNumber()
{
return AccountNumber;
}

CreditCardAccount::CreditCardAccount(long number, double limit)
:AccountNumber(number),CreditLimit(limit),CurrentBalance(0.0)
{
}//Member initialization lists in Constructor

##############################################################
//Create A CLR PROJECT named "CreditOrganizer " Copy This code to

// CreditOrganizer.cpp : main project file.

#include "stdafx.h"
#include "CreditCardAccount.h"

using namespace System;

int main(array<System::String ^> ^args)
{
CreditCardAccount ^myAccount;
myAccount = gcnew CreditCardAccount(1235,2500);
myAccount->SetCreditLimit(1000);
myAccount->MakePurchase(1000);
myAccount->MakeRepayment(7000);
long num = myAccount->GetAccountNumber();
Console::Write("\nAccount Number:");
Console::Write(num);
myAccount->PrintStatement();
Console::ReadKey();
    return 0;
}


How to Generate Random Occurance of a Number in C++?

You can use Microsoft's Inbuilt Data-type Called Random in C++/CLI

// RandomNumberOccurance.cpp : main project file.

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
Random ^r = gcnew Random();//This is inbuilt data type in MS VC++
int randomnumber;
int throws = 0;
do{
randomnumber = r->Next(1, 7);
Console::WriteLine(randomnumber);
throws++;
} while (randomnumber != 6);

Console::Write("You took");
Console::Write(throws);
Console::Write("To get 6");
Console::ReadKey();
    return 0;
}

This program shows random occurance of number 6 by taking interval from 1 to 7 , thorws shows the count at which time 6 occurs in random tries