Split a char array by delimiter in C++

by on Mar.01, 2014, under C++

There are a few ways to accomplish this.

//..
char* buffer = "this*is*a*simple*test";
string delimiter = "*";
string s(buffer);
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
	token = s.substr(0, pos);
	cout<<token<<endl;
	s.erase(0, pos + delimiter.length());
}
cout<<s<<endl;
//..

Prints

this
is
a
simple
test

 

//..
char* buffer = "this*is*a*simple*test";
char* s;
s = strtok (buffer ,"*");
while (s != NULL)
{
	printf ("%s\n",s);
	s = strtok (NULL, "*");
}
//..

Prints

this
is
a
simple
test

 

Comments Off more...

HTTP POST and GET Requests with WinInet and C++

by on Feb.27, 2014, under C++

InternetOpenA
InternetConnectA
HttpOpenRequestA
HttpSendRequestA
InternetCloseHandle

Method to make POST or GET requests:

void Request(int Method, LPCSTR Host, LPCSTR url, LPCSTR header, LPSTR data)
{
try{
	//Retrieve default http user agent
	char httpUseragent[512];
	DWORD szhttpUserAgent = sizeof(httpUseragent);
	ObtainUserAgentString( 0, httpUseragent, &szhttpUserAgent );
 
	char m[5];
 
	if(Method == GET)
		strcpy(m, "GET\0");
	else 
		strcpy(m, "POST\0");
 
	//http://msdn.microsoft.com/en-us/library/windows/desktop/aa385096%28v=vs.85%29.aspx
	HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(internet != NULL)
	{
		//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384363%28v=vs.85%29.aspx
		HINTERNET connect = InternetConnectA(internet, Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
		if(connect != NULL)
		{
			//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384233%28v=vs.85%29.aspx
			HINTERNET request = HttpOpenRequestA(connect, m, url, "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)
			{
				int datalen = 0;
				if(data != NULL) datalen = strlen(data);
				int headerlen = 0;
				if(header != NULL) headerlen = strlen(header);
 
				//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384247%28v=vs.85%29.aspx
				HttpSendRequestA(request, header, headerlen, data, datalen);
 
				//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384350%28v=vs.85%29.aspx
				InternetCloseHandle(request);
			}
		}
		InternetCloseHandle(connect);
	}
	InternetCloseHandle(internet);
}
catch(...) {}
}

Usage:

//POST Request
char user[64] = "test123";
char pass[64] = "f4g5h6j7k8";
char data[1024];
char* posturi = "user=%s&pass=%s";
wsprintfA( data, posturi,  user, pass);
Request(POST, "localhost", "/testing/index.php", "Content-Type: application/x-www-form-urlencoded", data);
 
//---------------------------
 
//GET Request
char URL[1024];
char* geturi = "/testing/index.php?user=%s&pass=%s";
wsprintfA( URL, geturi, user, pass );
Request(GET, "localhost", URL, NULL, NULL);

Includes/Definitions:

//..
#include <Windows.h>
#include <WinInet.h>
#pragma comment (lib, "Wininet.lib")
#pragma comment (lib, "urlmon.lib")
#define POST 1
#define GET 0
Comments Off more...

Retrieve the User-Agent HTTP

by on Feb.26, 2014, under C++

ObtainUserAgentString retrieves the User-Agent HTTP request header string that is currently being used.

//..
#pragma comment (lib, "urlmon.lib")
//..
char httpUseragent[512];
DWORD szhttpUserAgent = sizeof(httpUseragent);
ObtainUserAgentString( 0, httpUseragent, &szhttpUserAgent );
printf("%s\n", httpUseragent);
//..
Comments Off more...

How to force page not to be cached in PHP

by on Feb.22, 2014, under PHP

header function

header('Expires: Fri, 01 Jan 1990 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, pre-check=0, post-check=0');
header('Pragma: no-cache');
//...
Comments Off more...

Search Google Programmatically with Java

by on Feb.10, 2014, under Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Google_Search {
    private final String _url;
    private URL _url_obj;
    private HttpURLConnection _connection;
    private final String _userAgent;
    private int _responseCode;
    private StringBuffer _totalResults;
    private final int _quantity;
    private final int _start;
    private final String _searchTerm;
 
    public Google_Search(String SearchTerm){
        _url = "http://www.google.com";
        _userAgent = "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2)" + 
                " Gecko/20100115 Firefox/3.6)";
        _quantity = 100;
        _start = 0;
        _searchTerm = SearchTerm;
    }
 
 
    public int ResponseCode(){
        return _responseCode;
    }
 
    public StringBuffer GetResults(){
        return _totalResults;
    }
 
    public void Search(){
        try {
            _url_obj = new URL(_url + "/search?num="+_quantity+"&start=" + 
                    _start + "&hl=en&meta=&q=%40\"" + _searchTerm + "\"");
            _connection = (HttpURLConnection) _url_obj.openConnection();
            _connection.setRequestMethod("GET");
            _connection.setRequestProperty("User-Agent", _userAgent);
            _responseCode = _connection.getResponseCode();
            BufferedReader in;
            in = new BufferedReader(new InputStreamReader(
                    _connection.getInputStream()));
            _totalResults = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null){
                _totalResults.append(inputLine);
            }
            in.close();                
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }
}
Comments Off more...

Call Google Search API in Java

by on Jan.28, 2014, under Java

We will need gogole-gson, a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

package google_search;
 
import com.google.gson.Gson;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
 
public class Google_Search { 
 
    public static void main ( String[] args ) throws Exception { 
        GetGoogleResults("programming");
    }
 
    private static void GetGoogleResults(String term) throws Exception { 
        String google; String charset = "UTF-8"; 
        URL url; Reader reader; 
        Google results;
 
        google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=8&q=";
 
        url = new URL(google + URLEncoder.encode(term, charset));
        reader = new InputStreamReader(url.openStream(), charset);
        results = new Gson().fromJson(reader, Google.class);
 
        if(results.getResponseData()!=null)
        {
            for(int i=0;i<results.getResponseData().getResults().size();i++)
            {
                System.out.println("Title: " + results.getResponseData().getResults().get(i).getTitle());
                System.out.println("Url: " + URLDecoder.decode(results.getResponseData().getResults().get(i).getUrl(), "UTF-8"));
                System.out.println("Content: " + results.getResponseData().getResults().get(i).getContent());
                System.out.println();
            }
        }
    }
}
 
class Google 
{
    private ResponseData responseData;
    public ResponseData getResponseData() { return responseData; }
    public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
 
    static class ResponseData 
    {
        private List<Result> results;
        public List<Result> getResults() { return results; }
        public void setResults(List<Result> results) { this.results = results; }
    }
 
    static class Result 
    {
        private String url;
        private String titleNoFormatting;
        private String content;
        public String getUrl() { return url; }
        public String getTitle() { return titleNoFormatting; }
        public String getContent() { return content; }
        public void setUrl(String url) { this.url = url; }
        public void setTitle(String title) { this.titleNoFormatting = title; }
        public void setContent(String content) { this.content = content; }
    }
}
Comments Off more...

Extract executable assembly/version information

by on Dec.28, 2013, under C#

Methods we are going to use:

GetFileVersionInfo Retrieves version information for the specified file.

GetFileVersionInfoSize Determines whether the operating system can retrieve version information for a specified file. If version information is available, GetFileVersionInfoSize returns the size, in bytes, of that information.

VerQueryValue Retrieves specified version information from the specified version-information resource. To retrieve the appropriate resource, before you call VerQueryValue, you must first call the GetFileVersionInfoSize function, and then the GetFileVersionInfo function.

Code:

[DllImport("version.dll")]
public static extern bool GetFileVersionInfo(string sFileName,
	  uint handle, uint size, IntPtr infoBuffer);
 
[DllImport("version.dll")]
public static extern int GetFileVersionInfoSize(string sFileName,
	  out uint handle);
 
[DllImport("version.dll")]
unsafe public static extern bool VerQueryValue(IntPtr pBlock,
	  string pSubBlock, out IntPtr pValue, out uint len);
 
void GetExeInfo(String f)
{
    try
    {
       if (!File.Exists(f)) return;
       uint handle = 0;
 
       uint size = (uint)GetFileVersionInfoSize(f, out handle);
       if (size > 0)
       {
	    IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal((int)(size));
 
	    if (GetFileVersionInfo(f, handle, size, buffer))
	    {
		uint len = 0;
		IntPtr Info = IntPtr.Zero;
 
		if (VerQueryValue(buffer, @"\VarFileInfo\Translation", out Info, out len))
		{
			short wLang = System.Runtime.InteropServices.Marshal.ReadInt16(Info, 0);
			short wCp = System.Runtime.InteropServices.Marshal.ReadInt16(Info, 2);
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\CompanyName", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\FileDescription", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\FileVersion", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\InternalName", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\LegalCopyright", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\LegalTrademarks", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\OriginalFileName", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\ProductName", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\ProductVersion", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\Comments", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\PrivateBuild", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
 
			if (VerQueryValue(buffer, @"\StringFileInfo\" + (wLang).ToString("X4") + (wCp).ToString("X4") + @"\SpecialBuild", out Info, out len))
				Console.WriteLine(Marshal.PtrToStringAnsi(Info));
	        }
    	    }
	}
    }
    catch { }
}
Comments Off more...

Codedom example

by on Dec.22, 2013, under C#

The CodeDOM provides types that represent many common types of source code elements. You can design a program that builds a source code model using CodeDOM elements to assemble an object graph. This object graph can be rendered as source code using a CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.

Some common uses for the CodeDOM include:

> Templated code generation: generating code for ASP.NET, XML Web services client proxies, code wizards, designers, or other code-emitting mechanisms.

> Dynamic compilation: supporting code compilation in single or multiple languages.

Example:

private void compile(String filename){
	CompilerParameters options = new CompilerParameters();
	CompilerResults results = default(CompilerResults);
 
	Dictionary<string, string> providerOptions = new Dictionary<string, string>();
	providerOptions.Add("CompilerVersion", "v3.5");
 
	CSharpCodeProvider compiler = new CSharpCodeProvider(providerOptions);
 
	options.GenerateInMemory = false;
	options.GenerateExecutable = true;
	options.OutputAssembly = "myexecutable.exe";
	options.TreatWarningsAsErrors = false;
	options.WarningLevel = 3;
	options.CompilerOptions = "/platform:x86 /target:winexe /optimize+ /debug-";
	options.IncludeDebugInformation = false;
 
	options.ReferencedAssemblies.Add("System.dll");
	options.ReferencedAssemblies.Add("System.Data.dll");
	options.ReferencedAssemblies.Add("System.Drawing.dll");
	options.ReferencedAssemblies.Add("System.Windows.Forms.dll");
 
	if (compiler.Supports(GeneratorSupport.EntryPointMethod))
		options.MainClass = "MyNamespace.Program";
 
	results = compiler.CompileAssemblyFromFile(options, new String[] { filename });
	if (results.Errors.Count > 0)
	{
		foreach (CompilerError error in results.Errors)
			Console.WriteLine("Error: " + error.ErrorText + "\r\nLine: " + error.Line);
	}
	else
	{
		//...
	}
}
Comments Off more...

Lock vs Monitor

by on Dec.15, 2013, under C#

lock Statement

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The section Threading (C# and Visual Basic) discusses threading.

The lock keyword calls Enter at the start of the block and Exit at the end of the block. A ThreadInterruptedException is thrown if Interrupt interrupts a thread that is waiting to enter a lock statement.

In general, avoid locking on a public type, or instances beyond your code’s control. The common constructs lock (this), lock (typeof (MyType)), and lock (“myLock”) violate this guideline:

lock (this) is a problem if the instance can be accessed publicly.

lock (typeof (MyType)) is a problem if MyType is publicly accessible.

lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances. You can’t use the await keyword in the body of a lock statement.

Monitor Class

Provides a mechanism that synchronizes access to objects.

The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

Monitor has the following features:

> It is associated with an object on demand.

> It is unbound, which means it can be called directly from any context.

> An instance of the Monitor class cannot be created.

The following information is maintained for each synchronized object:

> A reference to the thread that currently holds the lock.

> A reference to a ready queue, which contains the threads that are ready to obtain the lock.

> A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object.

A lock statement is equivalent to:

Monitor.Enter(myObject);
try
{
}
finally
{
   Monitor.Exit(myObject);
}
Comments Off more...

Threads and Critical Sections in C/C++

by on Dec.13, 2013, under C, C++

InitializeCriticalSectionAndSpinCount

Initializes a critical section object and sets the spin count for the critical section. When a thread tries to acquire a critical section that is locked, the thread spins: it enters a loop which iterates spin count times, checking to see if the lock is released. If the lock is not released before the loop finishes, the thread goes to sleep to wait for the lock to be released.

InitializeCriticalSection

Initializes a critical section object.

InitializeCriticalSectionEx

Initializes a critical section object with a spin count and optional flags.

EnterCriticalSection

Waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.

LeaveCriticalSection

Releases ownership of the specified critical section object.

DeleteCriticalSection

Releases all resources used by an unowned critical section object.

CreateThread

Creates a thread to execute within the virtual address space of the calling process.

Critical Section Objects

A critical section object provides synchronization similar to that provided by a mutex object, except that a critical section can be used only by the threads of a single process. Event, mutex, and semaphore objects can also be used in a single-process application, but critical section objects provide a slightly faster, more efficient mechanism for mutual-exclusion synchronization (a processor-specific test and set instruction). Like a mutex object, a critical section object can be owned by only one thread at a time, which makes it useful for protecting a shared resource from simultaneous access. Unlike a mutex object, there is no way to tell whether a critical section has been abandoned.

 

//..
CRITICAL_SECTION MyCriticalSection;
 
int main( void )
{
    HANDLE  MyHandle;
    DWORD   MyThreadIdArray[MAX_THREADS];
    int     MyThreadData = 10;
    //...
    if (!InitializeCriticalSectionAndSpinCount(&MyCriticalSection, 0x00000400) ) 
        return -1;
 
    //...
    MyHandle = CreateThread(NULL, 0, MyThreadFunction, &MyThreadData , 0, &MyThreadIdArray[i]);
 
    //...
    DeleteCriticalSection(&MyCriticalSection);
}
 
DWORD WINAPI MyThreadFunction( LPVOID lpParameter )
{
    //...
    EnterCriticalSection(&MyCriticalSection); 
 
    //...
    LeaveCriticalSection(&MyCriticalSection);
 
    ///...
    return 1;
}
Comments Off more...

%d bloggers like this: