Tuesday, 17 February 2015

Calculate elapsed time - C Programming

Welcome to Logically Proven Blog.

This post teaches you how to measure the time taken by a function or a set of statements or a complete program.

It is very important to track the performance of our own application in certain cases where the execution time of a program plays a major role.

To calculate time taken by a process, we use clock() function which is available in a system library time.h. We can make use of available function in this library to calculate the elapsed time of a program.

For example,we want to calculate the execution time of a program, we can call the clock functions at the beginning and at the end of the code for which we measure time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time.

Syntax:
#include <time.h>
 
clock_t start, end;
double elapsed_used;
 
start = clock();
... /* Do your work. */
end = clock();
elapsed_used = ((double)(end - start)) / CLOCKS_PER_SEC;
Example:
#include <stdio.h>
#include <time.h>
 
// A function that terminates when enter key is pressed
void funElapsedTime()
{
 printf("START \n");
 printf("Press enter to stop \n");
 while (1)
 {
  if (getchar())
   break;
 }
 printf("END \n");
}
 
// The main program calls function and calculates the elapsed time
int main()
{
 clock_t start,end;
 start = clock();
 funElapsedTime();
 end = clock();
 //calculate elapsed time
 double elapsed_time = ((double)(end-start)) / CLOCKS_PER_SEC; // in seconds
 
 printf("funElapsedTime took %f seconds to execute \n", elapsed_time);
 return 0;
}
 
 
/*output: START
          Press enter to stop
 
          END
   funElapsedTime took 5.010000 seconds to execute */
So you can include these clock functions anywhere in the program that you want to calculate the elapsed time.

Ref: http://www.gnu.org/software/libc/manual/html_node/CPU-Time.html

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven,
Learn, Teach, Share

File Inclusion and difference between #include "file" and #include

Welcome to Logically Proven Blog.

This post teaches you file inclusion in your ‘C’ application and the difference between #include “file” and #include <file>

File inclusion is an important preprocessor directive of C programming. This directive causes one file to be included in another.

Syntax:

#include "filename"

It causes the entire contents of filename to be inserted into the source code at that point in the program.

We can use the file inclusion for the following benefits –
  • If we have a large program, divide the code into set of related functions to understand and organize your code in a better way. This increases readability of your code.
  • One more benefit of using file inclusion is re-usability. For example we need some macro definitions that requires in all programs that are commonly used. In this case store these macro definitions in a file and just include the file into your application.
The files that are included to have a ‘.h’ extension. The extension stands for “header file”. This header file contains C function declarations and macro definitions and to be shared between several source files.  There are two types – user header files (programmer writes) and compiler header files (that comes with the compiler).

For example, stdio.h header file, this comes along with your compiler.

The related library functions are grouped into different categories and then stored in different header files. For example all mathematical related functions are stored in the header file math.h.

The #include directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current file. Look at the following example to know how the preprocessor processes the #include directives.

For example, if you have a header file header.h as follows,

char *test(void);

and a main program called program.c that uses the header file, like this -

int x;
#include "header.h"
 
int main(void)
{
 puts(test());
 return 0;
}

the compiler will see the same token stream as it would if program.c read

int x;
char *test(void);
 
int main(void)
{
 puts(test());
 return 0;
}


Difference between #include “file” and #include <file>

There are two ways to write #include statement in your program.

#include "filename"
#include <filename>

#include “filename”

This command would look for the file “filename” in the current directory as well as the specified list of directories as mentioned in the include search path (compilers can be set up by selecting directories from the options menu, e.g., Turbo C/C++ compiler) that might have been set up.

#include <filename>

This command would look for the file “filename” in the specified list of directories only.

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven,
Learn, Teach, Share

Friday, 13 February 2015

Session Transaction in Microsoft Access Database - VBA

Welcome to Logically Proven Blog.
This post teaches you "how to implement session transaction while working with data modifications in Microsoft Access database using VBA".

It is a good practice to implement session transaction while you are working with database modification like inserting, updating and deleting.

Using DAO or ADO connection objects, we can perform the database operations in MS Access.

The reason behind to implement session transaction is while you are trying to do some modifications to the database, unfortunately if the operation got failed in middle which leads to major consequences. To avoid these kind of consequences, we can resolve by rolling back to the previous state to achieve database consistency through out the application.

To know more about the database consistency, please understand the ACID properties in database. Please follow the link -  http://en.wikipedia.org/wiki/ACID

Now we see how to implement session transaction in case of DAO and ADO connection objects.

Using DAO Connection Object:

Please follow the example to understand easily.

Sub DAO_transaction()
 
 Dim strSQL As String
 Dim db As DAO.Database
 Dim wrk As Workspace
 
 On Error GoTo TrapError
 
 Set db = CurrentDb
 Set wrk = DBEngine.Workspaces(0)
 
 wrk.BeginTrans
 strSQL = "Update sysInfo Set InvoiceOR=False"
 db.Execute strSQL, dbFailOnError
 wrk.CommitTrans
 
 Exit_Sub :
 Set db = Nothing
 Set wrk = Nothing
 Exit Sub
 
 TrapError :
 
 MsgBox "Failed: " & Err.Description
 wrk.Rollback
 Err.Clear
 Resume Exit_Sub
 
End Sub


In the above example to roll back the transaction we should include On Error GoTo TrapError statement for error handling.

To achieve roll back, we are using DAO workspace object. Queries which modifies data in the database are included between BeginTrans and CommitTrans. When the queries get executed, the data changes will not replicate immediately in the database. The changes replicates only when workspace.CommitTrans is executed. 

If any error occurs inside workspace then the TrapError is called and workspace.Rollback statement executes which Undo all the changes which we did inside workspace.

In the above example we used direct query. Suppose if we want to execute saved queries and to achieve session transaction we have to make use queryDef. 
Please see the below example.

Public Function fnImportSendReceipts()
 
 Dim db As DAO.Database
 Dim rs As DAO.Recordset
 Dim ws As DAO.Workspace
 Dim qdf As DAO.QueryDef
 
 On Error GoTo err_handle
 Set ws = DBEngine.Workspaces(0)
 Set db = CurrentDb
 
 ws.BeginTrans
 
 Set qdf = db.QueryDefs("Qry_UpDateLock")
 qdf.Execute dbFailOnError
 ws.CommitTrans
 
 mem_clean :
  Set qdf = Nothing
  Set rs = Nothing
  Set ws = Nothing
  Set db = Nothing
  Exit Function
 
 err_handle :
  ws.Rollback
  DoCmd.OpenQuery "Qry_ReleaseLock"
  GoTo mem_clean
 
End Function

Using ADO Connection Object:

If  you understand the first scenario, then it is easy to understand this example. We are using different connection objects to connect to the database but the concepts are same.

Sub ADO_Transaction()
 
 Dim cmd As ADODB.Command
 Dim cn As ADODB.Connection
 
 Set cmd = CreateObject("ADODB.Command")
 Set cn = CurrentProject.Connection
 
 cmd.CommandText = "Update sysInfo Set InvoiceOR=False"
 cmd.ActiveConnection = cn
 cmd.ActiveConnection.BeginTrans
 cmd.Execute, , adExecuteNoRecords
 
 If Err <> 0 Then
  cmd.ActiveConnection.RollbackTrans
  Else
   cmd.ActiveConnection.CommitTrans
 End If
 
End Sub

Then it is time to know some exceptions with respect to session transactions.

DoCmd Statement in Transaction Not Affected by Rollback

Why?

Transaction processing in Microsoft Access is valid only on virtual table (VT) objects, such as dynasets. The DoCmd Object starts another Microsoft Jet database engine session to process its arguments.

Because the Jet database engine manages transaction processing, a new session of the Jet database engine contains its own transaction management. The two are mutually exclusive; transactions in one are not managed or affected by transactions in the other.

The simplest workaround for this problem is the QueryDef.Execute method.

Note: The QueryDef.Execute method works only when a QueryDef action is based on an action query (update, insert, delete) that does not return a recordset.


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.


Logically Proven,
Learn, Teach, Share

Wednesday, 11 February 2015

Develop Android/ iOS apps in C#

Create Android/iOS applications using C#.
Using IDEs Dot32 and Xamarin, you can build apps in C#, run and deploy them usingMicrosoft Visual Studio.

Xamarin – http://xamarin.com/

  • Free version includes: Develop apps using Xamarin Studio, deploy to device and deploy to app stores.
  • Xamarin’s Android API exposes almost 100% of the Android’s – so you can build a complete android app in C#.
  • Follow this link to know about Xamarin’s Architecture: Architecture

dot42 – https://www.dot42.com/

  • Free version includes (Community License): Develop and publish free apps on a public market place such as Google Play.
  • It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.

Please share your thoughts on this post in the comments section.

 
biz.