Tuesday, 10 February 2015

Dealing with Optimistic Concurrency in Entity Framework - dotnet

Welcome to Logically Proven Blog.
This post teaches you “How to deal with Optimistic Concurrency in Entity Framework”.

In a real world situation it is quite possible that database values might have got changed after selecting them for modification. In such cases, your update operation might be overwriting changes made by someone else. That is why it becomes important to detect if concurrency violation has occurred.

Detecting Concurrency Violation:

Entity framework can be configured to use optimistic concurrency while updating database records. That means no locks are held on the data being modified. The data is updated only if the database values at the time of fetching the data and the database values currently stored in the database match.

In your SQL Server database table, just add an extra column “UpdateToken” of type rowversion. The rowversion data type ensures that the column holds a different value every time that record is updated. A rowversion column is automatically updated by the SQL Server and it won’t play any direct role in your application data. It allows us to detect if a record has been changed after the initial selection. However, merely adding a rowversion column is not sufficient. In the entity framework designer you also need to set the ConcurrencyMode property of the UpdateToken to Fixed.

Changing this setting will cause EF (Entity Framework) to use the UpdateToken column in the WHERE clause of the UPDATE queries it generates. This way a row is updated only when the value of UpdateToken at the time of initial fetch matches with the current value in the database. If they don’t match no record is updated and EF concludes that there was a concurrency violation. 














Code: 
public void DetailsView1_UpdateItem(int EmployeeID)
{
 EmployeeDbEntities db = new EmployeeDbEntities();
 Employee item = db.Employees.Find(EmployeeID);
 TryUpdateModel(item);
 System.Threading.Thread.Sleep(15000);
 try
 {
  db.SaveChanges();
 }
 catch (DbUpdateConcurrencyException ex)
 {
  lblErr.Text = ex.Message;
 }
}
The code then halts the execution for 15 seconds. This is done purely for the sake of testing. Adding this delay will allow you to switch to the physical database table and modify its data manually to test the concurrency violation. An alternative is set a breakpoint at SaveChanges() method to halt the execution and then change the database values manually.

Handling Concurrency Violation:

Once you detected concurrency violation, the next step is to decide what action to take. There are three approaches that you can take:
  • Do nothing. Simply show the error message to the user and exit from the data modification stage.
  • Update the entity under consideration from the latest data from the database table. Then show that data to the user so that he can take the necessary action.
  • Forcefully update the database table with the values from the entity.
The first approach is quite easy and that is what you used in the preceding example. The second approach requires you to load database values in an entity and present them to the user. You can do that in the catch block as shown below:

...
catch (DbUpdateConcurrencyException ex)
{
 lblErr.Text = "Concurrency violation! Please review the latest values shown above.";
 ex.Entries.Single().Reload();
 DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
}

As you can see the DbUpdateConcurrencyException class provides access to the entity causing the error. The Reload() method called on an entity loads the values from the database into that entity. You then change the mode of the DetailsView to ReadOnly so that user can read the new values.

In the third approach, you make the current database values as the original values and then attempt SaveChanges() again. This approach is as shown below:
...
catch (DbUpdateConcurrencyException ex)
{
 lblErr.Text = "Concurrency violation! Attempting to force save to the database.";
 var emp = ex.Entries.Single();
 emp.OriginalValues.SetValues(emp.GetDatabaseValues());
 db.SaveChanges();
}

Here, you set the OriginalValues of the entity under consideration to the current values from the database (obtained by calling GetDatabaseValues()). You then attempt SaveChanges() again.

These kinds of concurrency detections are very much useful when the updates to the table are from multiple places. For example, consider a banking application.

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

Monday, 9 February 2015

Robot class in Java - Type automatically and Capture screen with Robot class

Welcome to Logically Proven Blog.
This post teaches you what Robot class is and how to make use of Robot class in Java. We are going to look at some examples how to use this Robot class.

Before jumping into the main concept, let me tell you about the package “java.awt”. Because the Robot class is a part of “java.awt” package.

What is a Package?

A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders organized on your computer to keep images in one folder, videos in one folder. The software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things in an organized by placing then into related classed and interfaces into packages.



 The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the “Application Programming Interface” or “API for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the file system; a socket object allows for the creation and use of network sockets. This allows you, the programmer, to focus on the design and organize a particular application in a well manner, rather than the infrastructure required to make it work.
 
Package java.awt Description

This package contains all the classes for creating user interfaces and for painting graphics and images. A user interface object such as a button or a scrollbar is called, in AWT terminology, a component. The component class is the root of all AWT components.

Some components fire events when a user interacts with the components. For example, click on a button or mouse hover on a particular component. The AWTEvent class and its subclasses are used to represent the events that AWT components can fire.

 A container is a component that can contain components and other containers. A container can also have a layout manager that controls the visual placement of components in the container. The AWT package contains several layout manager classes and an interface for building your own layout manager.

Each Component object is limited in its maximum size and its location because the values are stored as an integer. Also, a platform may further restrict maximum size and location coordinates. The exact maximum values are dependent on the platform. There is no way to change these maximum values, either in Java code or in native code. These limitations also impose restrictions on component layout. If the bounds of a Component object exceed a platform limit, there is no way to properly arrange them within a Container object. The object's bounds are defined by any object's coordinate in combination with its size on a respective axis.

java.awt.Robot

public class Robot extends Object

Class object is the root of the class hierarchy. Every class has object as a super class. All objects, including arrays, implements the methods of this class.

Robot class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events.

AWTException - if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true.

SecurityException - if createRobot permission is not granted

 Sample programs that make use of “Robot” class

Typing on computer without typing manually

This program opens an editor like Notepad where the program will start typing automatically.

To open an editor-
 Runtime.getRuntime().exec("notepad.exe");

To type in notepad, we can make use of Robot class.
Thread.sleep(500);
r.keyPress(KeyEvent.VK_H);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_I);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_S);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_SPACE);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_I);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_S);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_SPACE);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_R);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_O);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_B);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_O);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_T);
A Starting delay of 5 seconds because to give a time to open the notepad editor, else our program writes anywhere else. After each letter some delay seems to be somebody typing.

Screenshot

Follwing is the program to capture a screen of particular dimension.

Dimension d_size = Toolkit.getDefaultToolkit().getScreenSize();
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(d_size));
File path_to_save = new File("Robot.jpg");
ImageIO.write(img, "JPG", path_to_save); 
Here Dimension gets your screen size and puts dimension in the d_size variable. createScreenCapture function takes a screenshot. ImageIO.write is responsible for writing the screenshot as a JPG file.

 Get Pixel Color

Using this program you can get the color of a pixel at the given screen coordinates.
The parameters are the X and Y positions of pixel.
public Color getPixelColor(int x,int y)
Similarly you can use the Robot class for moving the mouse to avoid the system from sleeping in certain cases, press the mouse buttons, key press, key release etc.

Please refer Robot class in java.awt package for more details,

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

Logically Proven,
Learn, Teach, Share

Friday, 6 February 2015

How to zip and unzip a folder/file using C#

Welcome to Logically Proven Blog.
This post teaches you how to zip and unzip a folder/file using C#.

It has been a year since .NET Framework 4.5 got released.
Due to lack of communication from Microsoft releases, .Net developers are unaware of the important features listed in latest frameworks.
 
These are some good features available in .Net Framework 4.5.
Feature 1: async and await
Feature 2: Zip Facility (Zip compression)
Feature 3: Regex Timeout (Time Out)
Feature 4: Profile Optimization (Improved start-up performance)
Feature 5: Garbage Collector (background cleanup)
 
Only one or two features are known to developers and other features just stay on MSDN and end up like archived documents.
 
For example, the time you ask a .NET developer what is new in the core framework .NET 4.5 most of them will just say async and await (at least with people whom I have interacted have just talked about those features).
Again it’s very difficult to run through all the new features. Because the features may not sound interesting depending on what you are working currently on.
 
Now this post going to explain the feature 2, i.e., Zip facility (Zip compression). Without awaiting you much, let get into details.

Zip is one of the most accepted archive file formats. Zip format is supported in almost all operating systems with some built-in name.
 
In Windows operating system it’s implemented by the name “Compressed folders”.
In MAC OS it’s implemented by the name “Archive utility”.
 
Now in .NET we did not have built-in support for implementing Zip compression. Many developers where using third party components like “DotnetZip”.

In .NET 4.5, the Zip feature is baked in the framework itself, inside the namespace System.IO.Compression.
 
The first step is you need to reference two namespaces:
 
System.IO.Compression.FileSystem
System.IO.Compression
 
The next step is to add the below two namespaces in your .cs file:
 
using System.IO;
using System.IO.Compression;
 
ZipFile is a class provides static methods for creating, extracting, and opening zip archives.
 
If you want to Zip files from a folder you can use the CreateFromDirectory function as shown below:
 
ZipFile.CreateFromDirectory(@"D:\data",@"D:\data.zip");
 
If you wish to unzip, you can use the ExtractToDirectory function as shown in the below code.
 
ZipFile.ExtractToDirectory(@"D:\data.zip", @"D:\data\unzip");
 
 
For more details on this topic:

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

Logically Proven
learn, teach, share

Thursday, 5 February 2015

'undef' and 'pragma' directives - 'C' Programming

Welcome to Logically Proven blog.

This post teaches you the C preprocessor directives which are not very commonly used. They are

1. #undef
2. #pragma

To understand these directives, you must know what is a macro and ifdef directives. If you don't know please have a look into the previous post in this blog.

#undef directive

At certain times, it may necessary to cause the defined name to become "undefined". This can be accomplished by using the directive "#undef". 

In order to undefine a macro that has been earlier defined.

Syntax: #undef macro template

Example: 
#include <stdio.h>
#define INTEL
int main()
{
#undef INTEL //undefined the INTEL directive
#ifdef INTEL
 printf("INTEL code\n");
#else
 printf("Other than INTEL\n");
#endif
 
printf("Common code");
 
return 0;
}
 
/* Output: Other than INTEL
           Common code
*/
In this example, even though you defined the INTEL directive before main function, the compiler executes the statement in the else "Other than INTEL" because we are undefined the INTEL directive. The #undef directive cause the definition of INTEL to be removed from the system.

All subsequent #ifdef INTEL statements evaluate to FALSE. 

#pragma directive

This directive is another special-purpose directive that you can use to turn on or off certain features. For example you can use this directive often when you want to run some statements before the main function, before terminating the program and also to format, suppress warnings etc.

Pragmas vary from one compiler to another. 

In case of  Microsoft C compiler that deal with formatting source listings and placing comments in the object file generated by the compiler. 

Turbo C/C++ compiler has got a pragma that allows you yo suppress warnings generated by a compiler.

We will see these pragmas and how we can make use of.

(a) #pragma startup and #pragma exit
         These directives allow us to specify functions that are called before main() or just before the program terminates. 

Example:
#include <stdio.h>
 
void Intialize();
void CleanUp();
 
#pragma startup Intialize
#pragma exit CleanUp
 
int main()
{
 printf("\nInside main");
}
 
void Intialize()
{
 printf("\nBefore Main");
}
 
void CleanUp()
{
 printf("\nBefore Exit");
}
 
/* Output:  Before Main
     Inside main
     Before Exit
*/
Note: The functions Initialize() and CleanUp() should neither receive nor return any value. 

(b) Prioritized Pragmas:
         If you want two functions to get executed at start-up, then their pragmas should be defined in the reverse order or you can mention the priorities of the directives to decide which one should run first.

Syntax:
#pragma startup [priority]
#pragma exit [priority]
Where priority is optional integral number.
For user, priority varies from 64 to 255.
For C libraries, priority varies from 0 to 63.
Default priority is 100.

startup:
Lower value - Higher priority (executes first).
Higher value - Lower Priority (executes last).

exit:
Higher value - Higher priority (executes first).
Lower value - Lower priority (executes last).

Example:
#include <stdio.h>
 
void Function1();
void Function2();
#pragma startup Function1 123
#pragma startup Function2       //default priority - 100
#pragma exit Function2          //default priority - 100
#pragma exit Function1 123
 
int main()
{
 printf("\nInside main");
 return 0;
}
 
void Function1()
{
 printf("\nInside Function1");
}
 
void Function2()
{
 printf("\nInside Function2");
}
 
/* Output:
 Inside Function2
 Inside Function1
 Inside main
 Inside Function1
 Inside Function2
*/
(c) #pragma warn
     This directive tells the the compiler whether to suppress a specific warning or not.
Some warn pragmas -
#pragma warn -rvl //return value
#pragma warn -par   //parameter not used
#pragma warn -rch   //unreachable code
The minus sign (-) is to suppress the warnings and plus sign (+) is to flash the warnings on compilation.

Example -
int function1() //no return value
{
 int a = 5;
}
 
void function2(int x) //parameter not used
{
 printf("\nInside f2");
}
 
int function3() //unreachable code
{
 int x = 6;
 return x;
 x++;
}
 
int main()
{
 function1();
 function2(7);
 function3();
 return 0;
}
If you add these pragmas with minus sign, all these warnings will be suppressed on compilation. 
It is a bad practice to suppress warnings but at times it becomes useful to suppress them.

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

Logically Proven
learn, teach, share

 
biz.