Selasa, 17 Desember 2013

Xathrya Sabertooth

Xathrya Sabertooth


Disable Automatic Address Configuration – Automatic Private IP Addressing (APIPA)

Posted: 16 Dec 2013 10:48 PM PST

In every Windows Operating System enabled computer, there is a feature Microsoft offers which is APIPA. APIPA is a DHCP failover mechanism for local networks. With APIPA, DHCP clients can obtain IP addresses when DHCP servers are non-functional or the client couldn’t get the IP from server. APIPA exists in all modern versions of Windows except Windows NT.

When DHCP server fails, APIPA allocates IP addresses in the private range 169.254.0.1 to 169.254.255.254. This range is one of Private Network address (hence the name is Automatic Private IP Address).

The method is tested on Windows 8.1 64 bit. The method is generic one, using configuration of Registry entry.

To do, open registry edition. Before we proceed, please remember that incorrectly editing the registry may severely damage system. You can backup any valued data on your machine before making changes to the registry. You can also use the Last Know Good Configuration startup option if problems are encountered after done this guide.

On Windows Vista onward, you will face User Access Control which ask you whether you grant permission for Registry Editor. Choose yes to proceed.

In Registry Editor, navigate to the following registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

Now create a DWORD value (32 bit if there is both 32 and 64 bit DWORD value) with following name:

IPAutoconfigurationEnabled

Set the value to 0.

Close the Registry Editor. To make a change, restart the machine.

Data Structure Alignment in C++ on x86 and x64 Machine

Posted: 16 Dec 2013 10:36 PM PST

Data structure alignment is the way data is arranged and accessed in memory. It consists of two separate but related issues: data alignment and data structure padding.

In this article we will discuss about memory alignment for simple struct.

All of the codes are tested on Windows 8 64-bit using GCC compiler suite. OK, I said I use 64-bit Windows 8, but the title suggest we discuss both 32 and 64 bit, therefore I will also give both code.

Before we start, guess what the output of this program is? Write down your answer, don’t compile it yet.

#include <iostream>  using namespace std;    // Alignment requirements    // char         1 byte  // short int    2 bytes  // int          4 bytes  // double       8 bytes    struct A  {  	char c;  	short s;  };    struct B  {  	short s;  	char c;  	int i;  };    struct C  {  	char c;  	double d;  	int i;  };    struct D  {  	double d;  	int i;  	char c;  };    int main()  {  	cout << "The sizeof A is: " << sizeof(A) << endl;  	cout << "The sizeof B is: " << sizeof(B) << endl;  	cout << "The sizeof C is: " << sizeof(C) << endl;  	cout << "The sizeof D is: " << sizeof(D) << endl;  	return 0;  }

Now read this article.

Definition of Data Alignment

Every data type in C/C++ will have data alignment requirement (in fact, it is mandated by processor architecture, not by language).

MemoryAlignment1

Memory is byte addressable and arranged sequentially. If the memory is arranged as single bank of one byte width, the processor needs to issue 4 memory read cycles to fetch an integer. We can save lot of work when we read all 4 bytes of integer in one memory cycle only. To take such advantage, the memory will be arranged as group of 4 banks.

The memory addressing still be sequential. If bank 0 occupies an address X, bank 1, bank 2 and bank 3 will be at (X + 1), (X + 2) and (X + 3) addresses. If an integer of 4 bytes is allocated on X address (X is multiple of 4), the processor needs only one memory cycle to read entire integer.

Where as, if the integer is allocated at an address other than multiple of 4, it spans across two rows of the banks. Such an integer requires two memory read cycle to fetch the data.

MemoryAlignment2

A variable's data alignment deals with the way the data stored in these banks. It is expressed as the numeric address module of power of 2. For example, the address 0x0001103F modulo 4 is 3; that address is said to be aligned to 4n+3, where 4 indicates the chosen power of 2. The alignment of an address depends on the chosen power of two. The same address modulo 8 is 7.

The natural alignment of int on 32-bit machine is 4 bytes. When a data type is naturally aligned, the CPU fetches it in minimum read cycles.

Similarly, the natural alignment of several data type are listed here:

For 32-bit x86:

  • A “char” (one byte) will be 1-byte aligned
  • A “short int” (two bytes) will be 2-byte aligned
  • An “int” (four bytes) will be 4-byte aligned
  • A “long” (four bytes) will be 4-byte aligned
  • A “double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux (8-byte with -malign-double compile time option).
  • A “long long” (eight bytes) will be 8-byte aligned.
  • A “long double (ten bytes with C++Builder and DMC, eight bytes with Visual C++, twelve bytes with GCC) will be 8-byte aligned with C++Builder, 2-byte aligned with DMC, 8-byte aligned with Visual C++ and 4-byte aligned with GCC.
  • Any “pointer” (four bytes) will be 4-byte aligned. (e.g.: char*, int*)

A notable difference in alignment for 64-bit system when compared to 32-bit system:

  • A “long” (eight bytes) will be 8-byte aligned.
  • A “double“ (eight bytes) will be 8-byte aligned.
  • A “long double“ (eight bytes with Visual C++, sixteen bytes with GCC) will be 8-byte aligned with Visual C++ and 16-byte aligned with GCC.
  • Any “pointer” (eight bytes) will be 8-byte aligned.

So it means, a short int can be stored in bank 0 – bank 1 pair or bank 2 – bank 3 pair. A double requires 8 bytes, and occupies two rows in the memory banks. Any misalignment of double will force more than two read cycles to fetch double data.

As seen before, double variable will be allocated on 8 byte boundary on 32 bit machine and requires two memory read cycles. On a 64 bit machine, based on number of banks, double variable will be allocated on 8 byte boundary and requires only one memory read cycle.

So, we can formulate that a memory address A, is said to be N-byte aligned when A is a multiple of N bytes (where N is power of 2). A memory access is said to be aligned when the datum being accessed is N bytes long and the datum address is N-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by definition byte memory accesses are always aligned.

Structure and Padding to Align the Data

In C/C++, structures are used as a data pack (composite data). It doesn’t provide any data encapsulation or data hiding features (except when we define it with the way we define a class).

As stated before, a good aligned data in memory can ease the fetch process. Because of the alignment requirements of various data types, every member of structure should be naturally aligned. The members of structures allocated sequentially increasing order.

Now, alignment should be used to balance the structure. The term balance here refer to make every member naturally aligned (remember, short int use 2 bytes and can be put on a pair of byte 0-byte 1 or byte 2-byte 3 but not byte 1-byte 2). Therefore we need to do something to make them in correct position (align).

The method we use is padding. Padding is only inserted when a structure member is followed by a member with a larger alignment requirement or at the end of the structure.

There is an alternative way, reordering the members, however C/C++ do not allow the compiler to reorder structure members to save space. This job should be done manually.

So how this stuff works?

Remember, we cannot say that the aggregate size of a struct is only sum of all the components. There exists a padding. The padding boundary also depend on the 32-bit or 64-bit architecture of the CPU and the OS. The alignment is done on the basis of the highest size of the variable in the structure.

Let’s view this little structure. When we count it, we should get 8 bytes as total size:

struct Mix  {  	char Data1;  	short Data2;  	int Data3;  	char Data4;  };

After compilation, appropriate paddings will be inserted to ensure a proper alignment for each of its member:

struct Mix  {  	char Data1;          // 1 byte  	char Padding1[1];  	short Data2;         // 2 bytes  	int Data3;           // 4 bytes  	char Data4;          // 1 byte  	char Padding2[3];  };

We see two padding there, Padding1 and Padding2. Remember that short require 2-bytes alignment. Hence, it cannot be placed right after Data1, because it would be put on Bank 1-Bank 2 pair. We add padding between them so when we fetch the Data2 we will have minimum fetch.

After the Data4, there is also a padding with 3 bytes at the end.

Now the compiled size of the structure is 12 bytes. It is important to note that the last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member (alignment(int) in this case, which = 4

Let’s review the output for previous snippet. If you are confused, first refer to the previous section (Data Alignment)

For 64-bit OS user:

  1. The sizeof A is: 4
  2. The sizeof B is: 8
  3. The sizeof C is: 24
  4. The sizeof D is: 16

For 32-bit Windows user:

  1. The sizeof A is: 4
  2. The sizeof B is: 8
  3. The sizeof C is: 24
  4. The sizeof D is: 16

For 32-bit Linux user:

  1. The sizeof A is: 4
  2. The sizeof B is: 8
  3. The sizeof C is: 16
  4. The sizeof D is: 16

You can also prove it by yourself.

How do we get that?

Structure A

struct A  {  	char c;  	short s;  };

We have two members here, c as character, and s as short integer. Char is 1 byte and Short is 2 bytes. The total should be 3, but it’s 4.

If the short int element is immediately allocated after the char element, it will start at an odd address boundary. Therefore a padding is inserted there so now the structure will be:

struct A  {  	char c;  	char Padding;  	short s;  };

And the total sizeof(A) = sizeof(char) + 1 (padding) + sizeof(short) = 1 + 1 + 2 = 4 bytes.

Structure B

struct B  {  	short s;  	char c;  	int i;  };

We have three members here, s as short integer, c as character, and i as integer. Char is 1 byte, Short is 2 bytes, and Integer is 4 bytes. The total should be 7, but it’s 8.

It has the same reason as first example. As i is immediately after c, it will start at an odd address boundary. Therefore a padding is inserted. Now the structure will be:

struct B  {  	short s;  	char c;  	char Padding;  	int i;  };

And the total sizeof(B) = sizeof(short) + sizeof(char) +  1 (padding) + sizeof(int) = 2 + 1 + 1  + 4 = 8 bytes.

Structure C

struct C  {  	char c;  	double d;  	int i;  };

Now this is the trickiest part.

We have three members here, c as character, d as double float, and i as integer. If your architecture is 64-bit, you get Double as 8 bytes while 32 you get 4 bytes. Other than those, all other value is remain same. Char is 1 byte, and Integer is 4 bytes. The total should be 7, but it’s 8.

Now, the after compilation for x64 we got:

struct C  {  	char c;             // 1 byte  	char Padding1[7];  	double d;           // 8 bytes  	int i;              // 4 bytes  	char Padding2[4];  };

So you would wonder, why the padding Padding1 is 7 bytes instead of 3 bytes? Remember that the boundary is determined by the largest element’s boundary. We have double which is 8 bytes.

So the total size would be: sizeof(C) = sizeof(char) + 7 (padding) + sizeof(double) + sizeof(int) + 4 (padding) = 1 + 7 + 8 + 4 + 4 = 24

Now we see for the x86 Linux (gcc) case:

struct C  {  	char c;             // 1 byte  	char Padding1[3];  	double d;           // 4 bytes  	int i;              // 4 bytes  	char Padding2[4];  };

Here we have double as 4 bytes. As very same argument, we insert padding between c and d. There is padding at the end to meet natural alignment so it fit power of 2 size.

So the total size would be: sizeof(C) = sizeof(char) + 3 (padding) + sizeof(double) + sizeof(int) + 4 (padding)  = 1 + 3 + 4 + 4 + 4 = 16

Structure D

struct D  {  	double d;  	int i;  	char c;  };

We still have three members here, d as double, i as integer, and c as character. Char is 1 byte, double is 8 bytes or 4 bytes depend on which system you are (see previous explanation), and Integer is 4 bytes.

Both 64 and 32 bit will have following alignment after compilation:

struct D  {  	double d;           // 8 bytes  	int i;              // 4 bytes  	char c;		    // 1 byte  	char Padding1[3];  };

So you might expect, the padding is 3 byte at the end of struct so we can’t ensure the size is natural aligned.

So the total size would be: sizeof(D) = sizeof(double) + sizeof(int) + sizeof(char) + 3 (padding) = 8 + 4 + 1 + 3 = 16

Minggu, 08 Desember 2013

Xathrya Sabertooth

Xathrya Sabertooth


Setting Up Raspberry Pi + Smart Card Reader + PHP

Posted: 07 Dec 2013 06:02 AM PST

Smart Card is a pocket-sized card with embedded integrated circuits. It provides identification, authentication, data storage and application processing on simple medium. There are two big categories of smart card: contact and contactless. To identify and authenticate a smart card properly we need a smart card reader. There are many smart card reader and the way we operate is depend on what smart card it can detect.

To detect and use smart card, there is a specification for smart card integration into computing environments. It is called PC/SC (Personal Computer / Smart Card). The standard has been implemented to various operating system: Windows (since NT/9x), Linux, Unix.

We can however create a small device which can make use of smart card reader, instead of using our PC. That’s what we will discuss on this article.

As title suggest, after we have smart card connected we will use PHP as a programming environment.

For this article, we use:

  1. Working Raspberry Pi model B (+SD card)
  2. Raspbian Wheezy release date 2013-09-25
  3. Smart Card Reader, ACR122
  4. USB power hub

Grab the Materials

Make sure the Raspberry Pi is working properly with Raspbian Wheezy installed. Also make sure all the hardware are available.

We need USB power hub as the ACR122 Smart Card Reader gives too high load for Raspberry Pi so we will feed electricity from somewhere else.

Installation

Install the drivers and related package

apt-get install build-essential libusb-dev libusb++-dev libpcsclite-dev libccid

  • build-essential is package for building a application
  • libusb-dev and libusb++-dev are package for user-space USB programming
  • libpcsclite-dev is a middleware to access a smart card using PC/SC (development files) using PC\SC-lite definition
  • libccid is a smart card driver

Install PHP and all needed development tool

apt-get install php5-dev php5-cli php-pear

Once PHP installed, we need a PHP extension for smart card:

pecl install pcsc-alpha

You can see the documentation here.

Configuration

On some case, we need to add an entry to php.ini manually for registering pcsc extension. To do this, open up php.ini and add following entry:

extension = pcsc.so

Kamis, 05 Desember 2013

Xathrya Sabertooth

Xathrya Sabertooth


Ten C++11 Features You Should Know and Use

Posted: 04 Dec 2013 05:52 PM PST

This article will be a resume to several articles discussing individual subject.

There are lots of new additions to the C++ language and standard library after C++11 standard passed. However, I believe some of these new features should become routing for all C++ developers.

Features we are talking about:

  1. auto & decltype
  2. nullptr
  3. Range-based for loops
  4. Override and final
  5. Strongly-typed enums
  6. Smart pointers
  7. Lambdas
  8. non-member begin() and end()
  9. static_assert and type traits
  10. Move semantics

auto & decltype

More: Improved Typed Reference in C++11: auto, decltype, and new function declaration syntax

Before C++11 era, keyword auto was used for storage duration specification. In the new standard, C++ define clearly the purpose to be type inference. Keyword auto is a placeholder for a type, telling the compiler it has to deduce the actual type of a variable that is being declared from its initializer.

auto I = 42;        // I is an int  auto J = 42LL;      // J is an long long  auto P = new foo(); // P is a foo* (pointer to foo)

Using auto means less code for writing typename. The very convenience use of auto would be inferring type for iterator:

std::map<std::string, std::vector<int>> myMap;  for (auto it = begin(map); it != end(map); ++it)  {  //...  }

Here we save lot of works by order compiler to deduce the type of it.

decltype in other hand is a handy keyword to get type of an expression. Here we can inspect what’s going on this code:

short a = 10;  long b = 655351334;  decltype(a+b) c = 5;    std::cout << sizeof(a) << " " << sizeof(b) << " " << sizeof(c) << std::endl;

When we execute this code using proper C++11 compiler, we got variable c as a type used for summation of a and b. We know that when a short is summed with a long, the short variable will be typecasted automatically to type sufficient enough to hold the result code. And the decltype will give us it’s type.

As said before, decltype is used to get type of an expression, therefore it is valid for use to do this:

int function(int a, int b)  {  	return a * b;  }    int main()  {  	decltype(function(a,b)) c = 10;    	return 0;  }

As long as the expression involved is valid.

Now, in C++ we have a new function declaration syntax. This syntax leverage the power of both auto and decltype. Note that auto cannot be used as the return type of a function, so we must have a trailing return type. In this case auto does not tell the compiler it has to infer the type, it only instructs it to look for the return type at the end of the function.

template <typename T1, typename T2>  auto compose(T1 t1, T2 t2) -> decltype (t1 + t2)  {  	return t1+t2;  }

In above snippet, we compose the return type of function from the type of operator + that sums the values of types T1 and T2.

nullptr

More: Nullptr, Strongly typed Enumerations, and Cstdint

Since the inception of C++, zero is used as the value of null pointers. This is a direct influence from C language. The system itself has drawbacks due to the implicit conversion to integral types.

void function(int a);  void function(void* a);    function(NULL);

Now, which one is being called? On smarter compiler, it will gives error saying “the call is ambiguous”.

C++11 library gives solution for this. Keyword nullptr denotes a value of type std::nullptr_t that represents the null pointer literal. Implicit conversions exists from nullptr to null pointer value of any pointer type and any pointer-to-member types, but also to bool (as false). But no implicit conversion to integral types exists.

void foo(int* p) {}    void bar(std::shared_ptr<int> p) {}    int* p1 = NULL;  int* p2 = nullptr;     if(p1 == p2)  {  }    foo(nullptr);  bar(nullptr);    bool f = nullptr;  int i = nullptr; // error: A native nullptr can only be converted to bool or, using reinterpret_cast, to an integral type

Using 0 is still valid for backward compatibility.

Range-based for loops

More: C++ Ranged Based Loop

Ever wonder how could we do foreach statement in C++? Joy for us because C++11 now augmented the for statement to support it. Using this foreach paradigm we can iterate over collections. In the new form, it is possible to iterate over C-like arrays, initializer lists, and anything for which the non-member begin() and end() functions are overloaded.

std::map<std::string, std::vector<int>> map;  std::vector<int> v;  v.push_back(1);  v.push_back(2);  v.push_back(3);  map["one"] = v;    for(const auto& kvp : map)   {    std::cout << kvp.first << std::endl;      for(auto v : kvp.second)    {       std::cout << v << std::endl;    }  }    int arr[] = {1,2,3,4,5};  for(int& e : arr)   {    e = e*e;  }

The syntax is not different from “normal” for statement, okay it is a little different.

The for syntax in this paradigm is:

for (type iterateVariable : collection)  {  // ...  }

Override and final

In C++, there isn’t a mandatory mechanism to mark virtual methods as overriden in derived class. The virtual keyword is optional and that makes reading code a bit harder, because we may have to look through the top of the hierarchy to check if the method is virtual.

class Base   {  public:     virtual void f(float);  };    class Derived : public Base  {  public:     virtual void f(int);  };

Derived::f is supposed to override Base::f. However, the signature differ, one takes a float, one takes an int, therefor Base::f is just another method with the same name (and overload) and not an override. We may call f() through a pointer to B and expect to print D::f, but it’s printing B::f.

C++11 provides syntax to solve this problem.

class Base   {  public:     virtual void f(float);  };    class Derived : public Base  {  public:     virtual void f(int) override;  };

Keyword override force the compiler to check the base class(es) to see if there is a virtual function with this exact signature. When we compile this code, it will triggers a compile error because the function supposed to override the base class has different signature.

On the other hand if you want to make a method impossible to override any more (down the hierarchy) mark it as final. That can be in the base class, or any derived class. If it’s in a derived class, we can use both the override and final specifiers.

class Base   {  public:     virtual void f(float);  };    class Derived : public Base  {  public:     virtual void f(int) override final;  };    class F : public Derived  {  public:     virtual void f(int) override;  }

Function declared as ‘final’ cannot be overridden by ‘F::f’.

Strongly-typed enums

More: Nullptr, Strongly typed Enumerations, and Cstdint

Traditional enums in C++ have some drawbacks: they export their enumerators in the surrounding scope (which can lead to name collisions, if two different enums in the same have scope define enumerators with the same name), they are implicitly converted to integral types and cannot have a user-specified underlying type.

C++11 introduces a new category of enums, called strongly-typed enums. They are specified with the “enum class” keyword which won’t export their enumerators in the surrounding scope and no longer implicitly converted to integral types. Thus we can have a user specified underlying type.

enum class Options { None, One, All };  Options o = Options::All;

Smart pointers

All the pointers are declared in header <memory>

In this article we will only mention smart pointers with reference counting and auto releasing of owned memory that are available:

  • unique_ptr: should be used when ownership of a memory resource does not have to be shared (it doesn’t have a copy constructor), but it can be transferred to another unique_ptr (move constructor exists).
  • shared_ptr: should be used when ownership of a memory resource should be shared (hence the name).
  • weak_ptr: holds a reference to an object managed by a shared_ptr, but does not contribute to the reference count; it is used to break dependency cycles (think of a tree where the parent holds an owning reference (shared_ptr) to its children, but the children also must hold a reference to the parent; if this second reference was also an owning one, a cycle would be created and no object would ever be released).

The library type auto_ptr is now obsolete and should no longer be used.

The first example below shows unique_ptr usage. If we want to transfer ownership of an object to another unique_ptr use std::move. After the ownership transfer, the smart pointer that ceded the ownership becomes null and get() returns nullptr.

void foo(int* p)  {     std::cout << *p << std::endl;  }  std::unique_ptr<int> p1(new int(42));  std::unique_ptr<int> p2 = std::move(p1); // transfer ownership    if(p1)    foo(p1.get());    (*p2)++;    if(p2)    foo(p2.get());

The second example shows shared_ptr. Usage is similar, though the semantics are different since ownership is shared.

void foo(int* p)  {     std::cout << *p << std::endl;  }  void bar(std::shared_ptr<int> p)  {     ++(*p);  }  std::shared_ptr<int> p1(new int(42));  std::shared_ptr<int> p2 = p1;    foo(p2.get());  bar(p1);     foo(p2.get());

We can also make equivalent expression for first declaration as:

auto p3 = std::make_shared<int>(42);

make_shared<T> is a non-member function and has the advantage of allocating memory for the shared object and the smart pointer with a single allocation, as opposed to the explicit construction of a shared_ptr via the contructor, that requires at least two allocations. In addition to possible overhead, there can be situations where memory leaks can occur because of that. In the next example memory leaks could occur if seed() throws an error.

void foo(std::shared_ptr<int> p, int init)  {     *p = init;  }  foo(std::shared_ptr<int>(new int(42)), seed());

No such problem exists if using make_shared.

The last sample shows usage of weak_ptr. Notice that you always must get a shared_ptr to the referred object by calling lock(), in order to access the object.

auto p = std::make_shared<int>(42);  std::weak_ptr<int> wp = p;    {    auto sp = wp.lock();    std::cout << *sp << std::endl;  }    p.reset();    if(wp.expired())    std::cout << "expired" << std::endl;

Lambdas

More: Guide to Lambda Closure in C++11

Lambda is anonymous function. It is powerful feature borrowed from functional programming that in turned enabled other features or powered library. We can use lambda wherever a function object or a functor or a std::function is expected.

You can read the expression here.

std::vector<int> v;  v.push_back(1);  v.push_back(2);  v.push_back(3);    std::for_each(std::begin(v), std::end(v), [](int n) {std::cout << n << std::endl;});    auto is_odd = [](int n) {return n%2==1;};  auto pos = std::find_if(std::begin(v), std::end(v), is_odd);  if(pos != std::end(v))    std::cout << *pos << std::endl;

A bit trickier are recursive lambdas. Imagine a lambda that represents a Fibonacci function. If you attempt to write it using auto you get compilation error:

auto fib = [&fib](int n) {return n < 2 ? 1 : fib(n-1) + fib(n-2);};

The problem is auto means the type of the object is inferred from its initializer, yet the initializer contains a reference to it, therefore needs to know its type. This is a cyclic problem. The key is to break this dependency cycle and explicitly specify the function’s type using std::function.

std::function<int(int)> lfib = [&lfib](int n) {return n < 2 ? 1 : lfib(n-1) + lfib(n-2);};

non-member begin() and end()

Two new addition to standard library, begin() and end(), gives new flexibility. It is promoting uniformity, concistency, and enabling more generic programming which work with all STL containers. These two functions are overloadable, can be extended to work with any type including C-like arrays.

Let’s take an example. We want to print first odd element on a C-like array.

int arr[] = {1,2,3};  std::for_each(&arr[0], &arr[0]+sizeof(arr)/sizeof(arr[0]), [](int n) {std::cout << n << std::endl;});    auto is_odd = [](int n) {return n%2==1;};  auto begin = &arr[0];  auto end = &arr[0]+sizeof(arr)/sizeof(arr[0]);  auto pos = std::find_if(begin, end, is_odd);  if(pos != end)    std::cout << *pos << std::endl;

With non-member begin() and end() it could be put as this:

int arr[] = {1,2,3};  std::for_each(std::begin(arr), std::end(arr), [](int n) {std::cout << n << std::endl;});    auto is_odd = [](int n) {return n%2==1;};  auto pos = std::find_if(std::begin(arr), std::end(arr), is_odd);  if(pos != std::end(arr))    std::cout << *pos << std::endl;

This is basically identical code to the std::vector version. That means we can write a single generic method for all types supported by begin() and end().

template <typename Iterator>  void bar(Iterator begin, Iterator end)   {     std::for_each(begin, end, [](int n) {std::cout << n << std::endl;});       auto is_odd = [](int n) {return n%2==1;};     auto pos = std::find_if(begin, end, is_odd);     if(pos != end)        std::cout << *pos << std::endl;  }    template <typename C>  void foo(C c)  {     bar(std::begin(c), std::end(c));  }    template <typename T, size_t N>  void foo(T(&arr)[N])  {     bar(std::begin(arr), std::end(arr));  }    int arr[] = {1,2,3};  foo(arr);    std::vector<int> v;  v.push_back(1);  v.push_back(2);  v.push_back(3);  foo(v);

static_assert and type traits

static_assert performs an assertion check at compile-time. If the assertion is true, nothing happens. If the assertion is false, the compiler displays the specified error message.

template <typename T, size_t Size>  class Vector  {     static_assert(Size < 3, "Size is too small");     T _points[Size];  };    int main()  {     Vector<int, 16> a1;     Vector<double, 2> a2;     return 0;  }

static_assert becomes more useful when used together with type traits. These are a series of classes that provide information about types at compile time. They are available in the <type_traits> header. There are several categories of classes in this header: helper classes, for creating compile-time constants, type traits classes, to get type information at compile time, and type transformation classes, for getting new types by applying transformation on existing types.

In the following example function add is supposed to work only with integral types.

template <typename T1, typename T2>  auto add(T1 t1, T2 t2) -> decltype(t1 + t2)  {     return t1 + t2;  }

However, there are no compiler errors if one writes

std::cout << add(1, 3.14) << std::endl;  std::cout << add("one", 2) << std::endl;

The program actually prints 4.14 and “e”. But if we add some compile-time asserts, both these lines would generate compiler errors.

template <typename T1, typename T2>  auto add(T1 t1, T2 t2) -> decltype(t1 + t2)  {     static_assert(std::is_integral<T1>::value, "Type T1 must be integral");     static_assert(std::is_integral<T2>::value, "Type T2 must be integral");       return t1 + t2;  }

Move semantics

More: Move Semantics and rvalue references in C++11

C++11 has introduced the concept of rvalue references (specified with &&) to differentiate a reference to an lvalue or an rvalue. An lvalue is an object that has a name, while an rvalue is an object that does not have a name (temporary object). The move semantics allow modifying rvalues (previously considered immutable and indistinguishable from const& types).

A C++ class/struct used to have some implicit member functions: default constructor (only if another constructor is not explicitly defined) and copy constructor, a destructor and a copy assignment operator. The copy constructor and the copy assignment operator perform a bit-wise (or shallow) copy, i.e. copying the variables bitwise. That means if you have a class that contains pointers to some objects, they just copy the value of the pointers and not the objects they point to. This might be OK in some cases, but for many cases you actually want a deep-copy, meaning that you want to copy the objects pointers refer to, and not the values of the pointers. In this case you have to explicitly write copy constructor and copy assignment operator to perform a deep-copy.

What if the object you initialize or copy from is an rvalue (a temporary). You still have to copy its value, but soon after the rvalue goes away. That means an overhead of operations, including allocations and memory copying that after all, should not be necessary.

Enter the move constructor and move assignment operator. These two special functions take a T&& argument, which is an rvalue. Knowing that fact, they can modify the object, such as “stealing” the objects their pointers refer to. For instance, a container implementation (such as a vector or a queue) may have a pointer to an array of elements. When an object is instantiating from a temporary, instead of allocating another array, copying the values from the temporary, and then deleting the memory from the temporary when that is destroyed, we just copy the value of the pointer that refers to the allocated array, thus saving an allocation, copying a sequence of elements, and a later deallocation.

The following example shows a dummy buffer implementation. The buffer is identified by a name (just for the sake of showing a point revealed below), has a pointer (wrapper in an std::unique_ptr) to an array of elements of type T and variable that tells the size of the array.

template <typename T>  class Buffer   {     std::string          _name;     size_t               _size;     std::unique_ptr<T[]> _buffer;    public:     // default constructor     Buffer():        _size(16),        _buffer(new T[16])     {}       // constructor     Buffer(const std::string& name, size_t size):        _name(name),        _size(size),        _buffer(new T[size])     {}       // copy constructor     Buffer(const Buffer& copy):        _name(copy._name),        _size(copy._size),        _buffer(new T[copy._size])     {        T* source = copy._buffer.get();        T* dest = _buffer.get();        std::copy(source, source + copy._size, dest);     }       // copy assignment operator     Buffer& operator=(const Buffer& copy)     {        if(this != &copy)        {           _name = copy._name;             if(_size != copy._size)           {              _buffer = nullptr;              _size = copy._size;              _buffer = _size > 0 > new T[_size] : nullptr;           }             T* source = copy._buffer.get();           T* dest = _buffer.get();           std::copy(source, source + copy._size, dest);        }          return *this;     }       // move constructor     Buffer(Buffer&& temp):        _name(std::move(temp._name)),        _size(temp._size),        _buffer(std::move(temp._buffer))     {        temp._buffer = nullptr;        temp._size = 0;     }       // move assignment operator     Buffer& operator=(Buffer&& temp)     {        assert(this != &temp); // assert if this is not a temporary          _buffer = nullptr;        _size = temp._size;        _buffer = std::move(temp._buffer);          _name = std::move(temp._name);          temp._buffer = nullptr;        temp._size = 0;          return *this;     }  };    template <typename T>  Buffer<T> getBuffer(const std::string& name)   {     Buffer<T> b(name, 128);     return b;  }  int main()  {     Buffer<int> b1;     Buffer<int> b2("buf2", 64);     Buffer<int> b3 = b2;     Buffer<int> b4 = getBuffer<int>("buf4");     b1 = getBuffer<int>("buf5");     return 0;  }

The default copy constructor and copy assignment operator should look familiar. What’s new to C++11 is the move constructor and move assignment operator, implemented in the spirit of the aforementioned move semantics. If you run this code you’ll see that when b4 is constructed, the move constructor is called. Also, when b1 is assigned a value, the move assignment operator is called. The reason is the value returned by getBuffer() is a temporary, i.e. an rvalue.

You probably noticed the use of std::move in the move constructor, when initializing the name variable and the pointer to the buffer. The name is actually a string, and std::string also implements move semantics. Same for the std::unique_ptr. However, if we just said _name(temp._name) the copy constructor would have been called. For _buffer that would not have been even possible because std::unique_ptr does not have a copy constructor. But why wasn’t the move constructor for std::string called in this case? Because even if the object the move constructor for Buffer is called with is an rvalue, inside the constructor it is actually an lvalue. Why? Because it has a name, “temp” and a named object is an lvalue. To make it again an rvalue (and be able to invoke the appropriate move constructor) one must use std::move. This function just turns an lvalue reference into an rvalue reference.

UPDATE: Though the purpose of this example was to show how move constructor and move assignment operator should be implemented, the exact details of an implementation may vary. An alternative implementation was provided by Member 7805758 in the comments. To be easier to see it I will show it here:

template <typename T>  class Buffer  {     std::string          _name;     size_t               _size;     std::unique_ptr<T[]> _buffer;    public:     // constructor     Buffer(const std::string& name = "", size_t size = 16):        _name(name),        _size(size),        _buffer(size? new T[size] : nullptr)     {}       // copy constructor     Buffer(const Buffer& copy):        _name(copy._name),        _size(copy._size),        _buffer(copy._size? new T[copy._size] : nullptr)     {        T* source = copy._buffer.get();        T* dest = _buffer.get();        std::copy(source, source + copy._size, dest);     }       // copy assignment operator     Buffer& operator=(Buffer copy)     {         swap(*this, copy);         return *this;     }       // move constructor     Buffer(Buffer&& temp):Buffer()     {        swap(*this, temp);     }       friend void swap(Buffer& first, Buffer& second) noexcept     {         using std::swap;         swap(first._name  , second._name);         swap(first._size  , second._size);         swap(first._buffer, second._buffer);     }  };

Senin, 02 Desember 2013

Xathrya Sabertooth

Xathrya Sabertooth


Managing Windows Service via Command Line Interface

Posted: 01 Dec 2013 09:02 PM PST

Service is also known as background process, a program which run in background and similar concept to a Unix daemon. A Windows service must conform to the interface rules and protocols of the Service Control Manager, the component responsible for managing Windows services.

As title suggests, we will discuss about how to manage Windows service using Command Line Interface (CLI) not Graphical User Interface (GUI). Specifically we will use two CLI: command prompt and Windows PowerShell. Using a command prompt, we can invoke two different program to fulfill our need: sc.exe and net.exe.

We will use a fictional service serv.exe registered as serv48 as our example.

All examples are done using Administrator privilege, no user privilege involved.

Get Service Status

Get status from a registered service, such as state (running, paused, suspended, stopped), name, etc.

Using sc (command prompt)

sc query serv48

Sample response:

SERVICE_NAME: serv48          TYPE               : 10  WIN32_OWN_PROCESS          STATE              : 1  STOPPED          WIN32_EXIT_CODE    : 0  (0x0)          SERVICE_EXIT_CODE  : 0  (0x0)          CHECKPOINT         : 0x0          WAIT_HINT          : 0x0

Using PowerShell

Get-Service mysql56serv48

Sample response:

Status   Name               DisplayName  ------   ----               -----------  Stopped  Serv48             serv48

Register New Service

Creates a service entry in the registry and service database. In other word, it register the service to windows service component.

Using sc (command prompt)

sc create serv48 binPath=C:\ImportantApp\serv48d.exe DisplayName=serv48

Using PowerShell

New-Service -name serv48 -binaryPathName C:\ImportantApp\serv48d.exe -displayName serv48

Restart Service

This section will restart a service. Actually, a restart means stopping and starting the same service.

Using sc (command prompt)

sc stop serv48  sc start serv48

Using net (command prompt)

net stop serv48  net start serv48

Using PowerShell

Stop-Service serv48  Start-Service serv48

There is also a single command in Powershell to restart a service:

Restart-Service serv48

Resume Service

Resuming a service after the service is suspended.

Using sc (command prompt)

sc continue serv48

Using net (command prompt)

net continue serv48

Using PowerShell

Resume-Service serv48

Set Service

Change or set state of services with some options.

Using sc (command prompt)

sc config serv48 [option=value]

with options available (and possible value) are:

  • type= own,share,interact,kernel,filesys,rec,adapt
  • start= boot,system,auto,demand,disabled,delayed-auto
  • error= normal,servere,critical,ignore
  • binPath= binary pathname to the .exe file
  • tag= yes,no
  • depend= service it’s depended on, separated by / (forward slash)
  • DisplayName= name used to display the service

Using PowerShell

Set-Service serv48 [-option value]

with options available (and possible value) are:

  • ComputerName – specifies one or more computers, the default is local computer.
  • Description – new description for service which will appear in Computer Management.
  • DisplayName – New display name for the service
  • Name – new service name (in our case: serv48)
  • StartupType – Automatic, Manual, Disabled
  • Status – Running, Stopped, Paused

Start Service

Start a service, change the state from stopped to running.

Using sc (command prompt)

sc start serv48

Using net (command prompt)

net start serv48

Using PowerShell

Start-Service serv48

Stop Service

Stopping a service, change state from running to stopped.

Using sc (command prompt)

sc stop serv48

Using net (command prompt)

net stop serv48

Using PowerShell

Stop-Service

Suspend Service

Also known as pause. Pause a service for a moment until it is resumed.

Using sc (command prompt)

sc pause serv48

Using net (command prompt)

net pause serv48

Using PowerShell

Suspend-Service

Build Apache HTTPD for Windows from Source

Posted: 01 Dec 2013 05:47 PM PST

Apache HTTP Server, commonly referred to as Apache, is a popular web server application. It is notably having a key role in initial growth of World Wide Web. Originally based on the NCSA HTTPd server, development of Apache began in early 1995 after work on the NCSA code stalled. Apache quickly overtook NCSA HTTPd as the dominant HTTP server, and has remained the most popular HTTP server in use since April 1996.

In this article we will bring ourselves to build Apache HTTP Server for Windows. Some material used here are:

    1. Windows 8, 64-bit
    2. Apache HTTPD 2.4.7 (latest per November 28th, 2013)
    3. Windows 8 Platform SDK, February 2003 or later
    4. Microsoft Visual Studio 2010
    5. Perl 5.16.3
    6. awk
    7. nasm 2.11.rc1

Also for material building the Apache

    1. apr, apr-util, apr-iconv
    2. PCRE (Perl Compatible Regular Expressions)
    3. zlib library (optional)
    4. OpenSSL libraries (optional)

You should also provide free disk space at least 200MB when compiling. After installation, Apache needs approximately 80 MB of disk space.

In this article, we will use Visual Studio Command Prompt instead of common Command Prompt.

Instead of compiling to x64 code, we will target the x86 architecture.

Opening Visual Studio Command Prompt

As stated before, we use Visual Studio Command Prompt instead of common Command Prompt. I use Visual Studio 2010 (Visual Studio 10) on Windows 8 64-bit. To activate Visual Studio Command Prompt, there are two methods: search & run Visual Studio Command Prompt from Start Screen, run Command Prompt then execute script to set environment variable.

If you want to use first method, make sure you use Visual Studio Command Prompt for amd64 or 64-bit instead of 32-bit.

If you want to do second method, you can do:

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" amd64

Here we execute vcvarsall.bat and set the argument to amd64 to obtain necessary environment variables for the toolchain basically.

Grab the Materials

Source code of Apache HTTPD can be downloaded freely from here. Choose the closest mirror for you.

There are two Perl implementation for Windows: Strawberry Perl and ActiveState perl. I leave you to choose which one. Both can be downloaded from here.

Windows Software Developer Kit (SDK) for Windows 8 can be downloaded freely from here. Download the sdksetup.exe then run it. Choose Windows SDK from options available.

AWK is standard feature of most Unix-like operating system. For Windows, there is an alternative: Brian Kernighan’s http://www.cs.princeton.edu/~bwk/btl.mirror/ site has a compiled native Win32 binary, http://www.cs.princeton.edu/~bwk/btl.mirror/awk95.exe which you must save with the name awk.exe (rather than awk95.exe). It should be installed in environment path or known by Visual Studio.

NASM or Netwide Assembler is the assembler targeting x86 family processor. We can download nasm from it’s official site. The latest (version 2.11rc1 per November 28th, 2013) can be downloaded here. The one I use here is nasm-2.11rc1-installer.exe. Make sure nasm can be executed (the path is in the environment path).

APR (Apache Project Runtime) is used for building Apache. The project is a separated project from Apache HTTPD therefore we need to download it manually. Download it here http://apr.apache.org/download.cgi, select the appropriate mirror for you. The three we should download are: apr 1.5, apr-util 1.5.3, apr-iconv 1.2.1. Download the win32 version source code.

Perl Compatible Regular Expressions is regular expression pattern matching using the same syntax and semantics as Perl 5. It can be downloaded from www.pcre.org. The latest version is 8.33 which can be downloaded from ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.

The zlib library is optional, used for mod_deflate. The current version is 1.2.8 and can be download from http://www.zlib.net/. In this case, the filename is zlib-1.2.8.tar.xz.

OpenSSL libraries is optional, used for mod_ssl and ab.exe with ssl support. You can obtain the OpenSSL for Windows from http://www.openssl.org/source/. Assuming we have downloaded it. In this case, the file name is openssl-1.0.1e.tar.gz.

Pre-Compilation Stage

In this article, I assume awk is installed as C:\Windows\awk.exe which should on the environment path.

Extract the Apache source code. Once it’s extracted we have “httpd-2.4.7” directory (for example: D:\httpd-2.4.7).

Extract the apr package to Apache’s srclib and rename them to apr, apr-iconv, apr-util respectively. Therefore we have three subdirectories apr, apr-iconv, and apr-util inside of “httpd-2.4.7/srclib”.

Extract the PCRE package to Apache’s srclib and rename it to pcre. Therefore we have “httpd-2.4.7/srclib/pcre”.

If you want to include zlib support, extract zlib source code inside Apache’s srclib sub directory and rename the directory to zlib. Therefore, we have “httpd-2.4.7/srclib/zlib”.

If you want to include openssl support, extract openssl source code inside Apache’s srclib sub directory and rename the directory to openssl. Therefore, we have “httpd-2.4.7/srclib/openssl”.

Compilation

The makefile script for Windows is defined as Makefile.win. In this article, we will build all the optional package first, manually.

To compile & build zlib, enter the Apache’s srclib for zlib and invoke the Makefile. Assuming Apache source code is in D:\httpd-2.4.7

cd D:\httpd-2.4.7\srclib\zlib  nmake -f win32\Makefile.msc AS=ml64 LOC="-DASMV -DASMINF -I." OBJA="inffasx64.obj gvmat64.obj inffas8664.obj"  nmake -f win32\Makefile.msc test  copy zlib.lib zlib1.lib

The last command is used to copy zlib.lib as zlib1.lib. We do this because when we compile OpenSSL we need library with this name.

To compile & build openssl, enter the Apache’s srclib for zlib and invoke the Makefile. Assuming Apache source code is in D:\httpd-2.4.7. To prepareOpenSSL to be linked to Apache mod_ssl or the abs.exe project, we can use following commands:

cd D:\httpd-2.4.7\srclib\openssl  perl Configure disable-idea enable-camellia enable-mdc2 enable-zlib VC-WIN64A -ID:\httpd-2.4.7\srclib\zlib -LD:\httpd-2.4.7\srclib\zlib  ms\do_win64a.bat  nmake -f ms\ntdll.mak

The above command configures OpenSSL with Visual C++ Win64 AMD. We disable the IDEA algorithm since this is by default disabled in the pre-distributions and really shouldn’t be missed. If you do however require this then go ahead and remove disable-idea.

Because we use OpenSSL 1.0.1e, we should invoke following command:

echo. > inc32\openssl\store.h

Now go to the top level directory of our Apache HTTPD source code. We will invoke the makefile to build Apache HTTPD.

nmake /f Makefile.win installr

Finally compile and install HTTPd, you can specify INSTDIR= to specify a path of where to install HTTPd as well. You can also specify database bindings by adding DBD_LIST=”mysql sqlite” etc. Also as it points out, don’t forget to add the libraries and includes from the databases to the INCLUDE and LIB

Minggu, 24 November 2013

Xathrya Sabertooth

Xathrya Sabertooth


Installing FTP Server on Arch Linux ARM using VSFTPD

Posted: 23 Nov 2013 11:34 PM PST

File Transfer Protocol (FTP) is a standard network protocol used for transferring files from one host to another host over a TCP-based network. The party involving two side: server and client, in other words it use client-server architecture. One famous FTP server is VSFTPD (Very Secure FTP Daemon).

In this article we will discuss about how to install VSFTPD to Arch Linux ARM, one of Linux distribution for ARM processor. Specifically, I use:

  1. Raspberry Pi model B, for machine
  2. Arch Linux ARM release 2013-07-22

Before we started, make sure you have installed Arch Linux ARM on your device.

Update the Repository

It is a good choice to update the repository as Arch Linux release new package periodically without save the old package. Arch Linux ARM use the very same package manager system like its parent uses. Therefore the command should be similar.

Make sure you have setup the Arch Linux ARM Repository.

To update the repository, do following:

pacman -Syy

Make sure your device can access the internet.

Installation

Installing vsftpd is really straightforward. We can install vsftpd from the Official Repositories by:

pacman -S vsftpd

Package manager will download the required package, depends on your connection. It will also install it automatically once the package are downloaded.

Start / Enable Server

We can enable server, which means the server started everytime we boot the device. Arch Linux use systemd, so to make it run automatically at boot time, do following:

systemctl enable vsftpd.service

While you can make it disabled / not run automatically by:

systemctl disable vsftpd.service

To start it manually, do:

systemctl start vsftpd.service

We can stop the service by:

systemctl stop vsftpd.service

Selasa, 19 November 2013

Xathrya Sabertooth

Xathrya Sabertooth


Mounting Partition from Raw Disk Image on Linux

Posted: 18 Nov 2013 10:40 AM PST

In Linux/Unix or perhaps in every computer system, a term mounting is defined as attaching additional filesystem to the currently accessible filesystem of a computer. As we know, a filesystem is hierarchy of directories (also referred to as a directory tree) that is used to organize files on a computer or storage media.

We might familiar or maybe remember how to mount a partition well. But that’s when the partition is inside a storage media or physical medium. What if the partition we want to access is in form of disk image? Here, we will discuss it.

In this article I use:

  1. Slackware64 14.0
  2. dumped image from 4GB SD-card, using dd

The Theory

Disk Image

A disk image is a single file or storage device containing the complete contents and structure representing a data storage medium or device, such as hard drive, tape drive, floppy disk, optical disc, or USB flash drive. A disk image is usually created by creating a complete sector-by-sector copy of the source medium and thereby perfect replicating the structure and contents of a storage device.

In Linux, we can create disk image using dd utility. Assuming we want to create disk image of a SD-card which is recognized as /dev/sdb as MyDiskImage.img:

dd if=/dev/sdb of=MyDiskImage.img

Partition and Partition Table

As said, disk image is perfect copy of a storage media. Therefore we got very same bit of partition and partition table. Nothing is modified, unless you alter it. Therefore, we can still read the partition table like what we do on physical storage medium.

We can use fdisk to see the partition table of a disk image:

fdisk MyDiskImage.img

Loopback Device

We know that Linux and Unix list all recognized device as device nodes. They are treated like ordinary file and stored on /dev, like /dev/sda for first SCSI storage device we have. However, not many of us know some pseudo-devices on this directory. One of them is loop device /dev/loop*.

This is special node that we will use for mounting an image.

How to Mount

There are some steps we have to do so we can mount a partition inside of disk image.

Know the Offset

We have to know where is the offset of partition. Clearly we need to know where the partition start and where the partition end. Although, we only need the offset of beginning of the partition. To do that, we can use fdisk to peek on partition table. For example:

fdisk MyDiskImage.img

Here’s how my partition looks like.

Disk MyDiskImage.img: 691 MB, 691798016 bytes  255 heads, 63 sectors/track, 84 cylinders, total 1351168 sectors  Units = sectors of 1 * 512 = 512 bytes  Sector size (logical/physical): 512 bytes / 512 bytes  I/O size (minimum/optimal): 512 bytes / 512 bytes  Disk identifier: 0x0002c262                             Device Boot      Start         End      Blocks   Id  System  2013-09-25-wheezy-raspbian.img1            8192      122879       57344    c  W95 FAT32 (LBA)  2013-09-25-wheezy-raspbian.img2          122880     5785599     2831360   83  Linux

What we want to know is the offset, which is in byte-level. However fdisk tell us about sectors. Fortunately we can convert the offset in sector to bytes by multiplying it with the size of sector. In our case, one sector is 512 bytes.

Let say we want to mount partition 2, which is ext4. We calculate the offset for this partition.

122880 * 512 = 62914560

Save this value.

Mount It!

The actual mounting. Mounting process is similar when we mount normal partition. However, this time we use loopback device and use one argument we never use before, “offset”. Basically, offset tell mount utility to skip the data on particular to offset.

Here how we do:

mount -o loop,offset=62914560 MyDiskImage.img /mnt/mount_point

Here we mount partition 2, which is located on 62914560 bytes after the beginning of the file. The partition should be mounted to our mount point (/mnt/mount_point). Unless you have an unknown filesystem, this command shouldn’t be fail.

Jumat, 15 November 2013

Xathrya Sabertooth

Xathrya Sabertooth


Installing SQL Server 2012 on Windows Server 2012

Posted: 14 Nov 2013 11:51 PM PST

Microsoft SQL Server, also called as SQL Server only, is a relational database management system (rdbms) developed by Microsoft. It is used to store and retrieve data as requested by other software applications, be it those on the same computer or those running on another computer across a network (including the Internet). SQL Server use structured query language (SQL), technically they are T-SQL and ANSI SQL.

Some applications are likely high-coupled with Microsoft SQL Server. In simple term, they are works with SQL Server around. This is normal for Windows applications.

In this article we will discuss about how to install Microsoft SQL Server 2012 on Windows Server 2012. SQL Server 2012 has four editions: Enterprise, Standard, Developer, and Express edition. We will use Microsoft SQL Server 2012 Developer edition. This edition only suitable for development process. However this is enough, as the installation process is roughly same for any edition.

Another Extra Info

SQL Server Standard and Enterprise Edition usually used for production, while Developer Edition used for development. If we use one of them, we can also install another tool set beside SQL Server DBMS, for example: SQL Server Reporting Service, SQL Server Analysis Service, and SQL Server Integration Service.

Stage 1: Add New Username to Active Directory

If you have installed Active Directory, you should add new username in your active Directory. This username is used for SQL Server and also this step is always done if you want to create a bigger service such as SharePoint. The username for SQL Service is service and different with other username, so we will create it to new Organizational Unit (OU). Let name it as WINDEV (My machine’s NetBIOS name) so our username would be WINDEV\SQL_Service.

Open “Start screen” and choose “Active Directory Users and Computers“. Right click to your domain controller, in my case it is “windev.xathrya.web.id”. Navigate to New > Organizational Unit. Then create the name you prefer.

create-new-ou

create-new-ou-2

Then, create new user under WINDEV, SQL_Service

create-new-user

Click Next and set the password. Don’t forget to uncheck “User must change the password at next logon” and check “Password never expires”.

Stage 2: SQL Server Installation

If you have the DVD, insert it to tray. If you have the ISO, mount it. Either way, you should have opened and see a setup executable file.  Run it and wait until the installation window appears.

sql-server-1

Click on “Installation” on left pane. Then, click on “New SQL Server stand-alone installation or add features to an existing one”. Wait for next page.

sql-server-2

SQL Server installer will do some checks. It will be decided whether your machine is fulfilling the prerequisites or not for installation.

sql-server-3

Next, enter the product key. As said before, we are using SQL Server 2012 Developer Edition.

sql-server-4

The next screen prompts us to accept the license terms. We can also opt to send anonymous feature usage data to Microsoft.  It is recommended to do this as Microsoft actually uses this data to qualify and prioritize future development efforts.

sql-server-5

SQL Server also checks for updates. However we can exclude the update for now.

sql-server-6

Setup then checks for conditions that may interfere with the installation of setup support files:

sql-server-7

On above window, I would install the SQL Server on same machine as my Domain Controller. In the real world, actually we don’t do this. We have separate machine for Domain Controller and SQL Server.

Next select the setup role in the installation process. We choose "All Features With Defaults,"

sql-server-8

Click next to continue to the Feature Selection. The content would be populated based on our machine. We also install it to default path, so we won’t lay our finger there.

sql-server-9

Setup next checks installation rules.

sql-server-10

Next we determine the instance ID. This is the ID for SQL Server in our machine. It should be unique if it is used in production level when more than one SQL Server is used. In our case, we are only using it for developing so we won’t mess with it.

sql-server-11

Setup will calculate the disk space. Roughly 7GB is required when we install all the features (default features).

Next we do service account configurations. We use WINDEV\SQL_Service for all account, and remember to set the password.

sql-server-12

Database engine configuration includes Authentication Mode and SQL Server Administrators. You can accept the defaults if you want. We use Mixed Mode Authentication (combined with very strong passwords) for my installations. Clicking the Add Current User button adds me to the SQL Server administrators

sql-server-13

Next we have Analysis Services setup. I mostly work with Tabular Model these days.  As before, I click the “Add Current User” button to add this account to the Administrators:

sql-server-14

Accept the defaults for Reporting Services configuration:

sql-server-15

Click on “Add Current User” button.

sql-server-16

Give DRC (Distributed Replay Client) a name. In this case, I use XathWinServ2012Sql:

sql-server-17

Next we have Error Reporting page. Just click on Next.

Then, Installation configuration rules are checked for consistency and readiness.

sql-server-18

Next we will be presented by a confirmation page. When you decided to accept the configuration, click Install to begin installation.

sql-server-19

Installation will take some times. You should grab some food or doing something else.

sql-server-20

When the process come to end, it’s time to celebrate it. You have installed the SQL Server 2012.

Installing DNS Server on Windows Server 2012

Posted: 14 Nov 2013 10:24 AM PST

Domain Name System (DNS) is a hierarchical distributed naming system for computers, services, or any resource connected to the Internet or a private network. It associates various information with domain names assigned to each of the participating entities. Most prominently, it translates easily memorized domain names to the numerical IP addresses needed for the purpose of locating computer services and devices worldwide. By providing a worldwide, distributed keyword-based redirection service, the Domain Name System is an essential component of the functionality of the Internet.

Windows Server 2012 use it’s own DNS server program, named Microsoft DNS. This is the default on any Windows Server.

Like any service on Windows Server 2012, Microsoft DNS is implemented as server role. This article will discuss about how to install DNS service in Windows Server 2012.

Installation

Open “Server Manager” from task bar, if you have not opened it yet.

From “Server Manager” Dashboard, select “Add roles and features”. This will launch the Roles and Features Wizard allowing for modifications to be performed on the Windows Server 2012 instance.

install-ad-1

Select “Role based or features-based” installation from the Installation Type. Roles are the major feature sets of the server, such as IIS. Features provide additional functionality for given role.

install-ad-2

When asked for destination server, select the current server. It should be chosen by default. Click “Next” button to proceed.

install-ad-3

From the Server Roles, choose the option “DNS Server” by checking it. A notice will appear explaining additional roles services or feature are also required to install domain services.

dns-role-1

If you don’t set your machine using static IP address, you will get a warning message. Make sure you set your machine to static IP address so client can resolve your machine. However, you can always ignore it and go to next stage for installation.

dns-role-2

Now we will be brought to “Features” page. Review and select optional features to install during installation of DNS Server. You can check any features but we will leave it as is.

Review the information. Click Next.

dns-role-3

Review the installation. This page will show you information about what will be installed. When ready, press “install” button.

dns-role-4

Installation will take on. It should not be long, but that will depend on your machine. In installation process, a progress bar will be displayed on the screen. Once Active Directory role is installer, it will be displayed on the ‘Server Manager’ landing page.

dns-role-5

Disable Ctrl + Alt + Delt Prompt to Login Windows Server 2012

Posted: 14 Nov 2013 09:54 AM PST

By default, whenever we boot Windows Server 2012 we will be asked to press ctrl + alt + del on logon screen. Sometimes this is annoying and fortunately we can remove it so we can start typing the username and password without pressing ctrl+alt+del.

In this article we will discuss about how to disable Ctrl+Alt+Del prompt.

The Idea

Everytime we login we need to press Ctrl+Alt+Del. This policy is defined by Windows on “Local Security Policies” and can be disabled manually.

How to Enable

Open the “Start” screen, click “Administrative Tools”.

administrative-tool

Double click the “Local Security Policy” icon, expand Local Policies and click Security Options. In the right pane search and open”Interactive logon: Do not require CTRL+ALT+DEL” and choose “Enabled“. Save the policy change by clicking OK.

disable-ctrl-alt-del-1

Enable Sound on Windows Server 2012

Posted: 14 Nov 2013 09:04 AM PST

By default, Windows Server 2012 disables audio. This of course has a reason. Most servers won’t need it. However, you can always enable manually or make it enable by default.

In this article we will discuss about how to enable sound on Windows Server 2012.

The Idea

Sound is a service. Like any other service, it can be manually started or we can set it enabled automatically on every boot time.

How to Enable

Go to Services window. There are two ways to do that. First: Open the “Start” screen, click “Administrative Tools” and open the “Services” shortcut. Second: press CTRL+R (opening Run dialog) and type “services.msc“.

You will see a window for Services.

audio-1

Search for “Windows Audio” service and double click it (or press enter button on it). We will be presented by another window.

If we want it to enable for only this time, click on “Start” button. If you want it to run automatically, set its “Startup type” to “Automatic“. Repeate this process for “Windows Audio Endpoint Builder” service. If you want to use audio immediately, also click the Start button in the Properties window of both services in addition to changing the Startup type.

audio-2