October 8, 2008

[.NET] - Bind two controls to the same data source with synchronization

Photobucket

This is very common problem, as a newcomer I had spent great deal of time to solve this. Suppose you have two controls viz, Combobox and Listbox on same form and Datasource property of both these controls is same. Then the selection in one control selects same item in other control. This problem occurs because of BindingContext property of controls. By default the BindingContext member of each of the two controls is set to the Form's BindingContext. Thus, the default behavior is for the ComboBox and Listbox to share the same BindingContext, and that's why the selection in the ComboBox is synchronized with the current item of Listbox. If you do not want this behavior, create a new BindingContext member for at least one of the controls.

comboBox1.DataSource = dataset.Tables[ "Items" ]; 
comboBox1.ValueMember = "CustomerID"; 
comboBox1.DisplayMember = "CustomerID"; 

// Set the BindingContext property of ListBox to new BindingContext
listBox1.BindingContext = new BindingContext(); 
listBox1.DataSource = dataset.Tables[ "Items" ]; 
listBox1.ValueMember = "CustomerID"; 
listBox1.DisplayMember = "CustomerID";

[.NET] - Using Anchoring and Docking

Although both anchoring and docking are useful while resizing windows application, the anchor can keep control of its size and its location in relation to control container when the container is not attached to particulae edge of the container, but somewhere in the middle. 

Photobucket
The Docking feature attaches a control to the edge of its container. When a control is docked to an edge of it's container, it will always stick to that edge. The control will also resize itself to fully fit the edge of the container and also resizes as the container is resized. The Dock property of the Form control can be set to any one of the six values, Top, Bottom, Left, Right, Fill, and None.

Photobucket
Anchoring specifies how a control anchors to the edges of its container. When a control is anchored to an edge of its container, the distance between the control and the specified edge remains constant when the container resizes. For example, if a control is anchored to the right edge of its container, the distance between the right edge of the control and the right edge of the container remains constant when the container resizes. A control can be anchored to any combination control edges. If the control is anchored to opposite edges of its container (for example, to the top and bottom), it resizes when the container resizes.

October 7, 2008

[.NET] - Readonly Constants


There are situations where we would decide the value of a constant member at the time of execution. May we also have different constants of different objects of the class. To overcome these shortcomings, C # is amending another known as reading to be used with data members. This amendment seeks to fix the value of using a constructor method, but can not be changed later. Members readonly May be declared as static fields or fields example. When they declared fields example, they may take different values with different objects. Examine the code below:

class Numbers
  {
    public readonly int m;
    public static readonly int n;
    public Numbers (int x)
    {
      m=x;
    }

    static Numbers ()
    {
      n=100;
    }
  }

The value of m is provided at the creation of an object using the constructor with the parameter x. This value remains constant for this object. Remember that the variable is assigned a value of 100, even before the creation of all instances.

[.NET] - Copy Constructors

We know that the manufacturer is a method that has the same name as the class and returns no value. 
It is used to initialize the data subject, we're creating.

There is another type of copy-builder the manufacturer. When you copy one object to another, C # allows you to copy the reference to the first objection to the new object, which means that we now have two references to the same object. To make a real copy, we can use a copy constructor, which is just a standard constructor that takes an object of class as its only parameter. For example, that a copy constructor of the class of students might look. Note that we copy the domain name for the new object.

public Student(Student student)
{
  this.name = student.name;
}

Now we can use this constructor to create a copy. The copy is another object, not just a reference to the original object.

class Student
{
  private string name;
  public Student(string name)
  {
    this.name = name;
  }
  public Student(Student student)
  {
    this.name = student.name;
  }
  public string Name 
  {
    get 
    {
      return name; 
    }
    set 
    {
      name = value; 
    }
  }
}

class Final
{
  static void Main()
  {
    Student student = new Student ("A");
    Student NewStudent = new Student (student);
    student.Name = "B";
    System.Console.WriteLine("The new student's name is {0}", NewStudent.Name);
  }
}

The new student's name is A.

September 19, 2008

[C/C++] - C++ optimizations (general)

1- Use 'int'

Always use the int data type instead of char or short wherever possible. int is always the native type for the machine.

2- Make Local Functions Static

Always declare local functions as static, e.g.,

static void foo()

This means they will not be visible to functions outside the .cpp file, and some C++ compilers can take advantage of this in their optimizations.

3- Avoid Expensive Operations

Addition is faster than multiplication and multiplication is faster than division. Factor out expensive operations whereever possible.

4- Pass By Reference

Always try to pass classes by reference rather than by value. For example, use

void foo(TMyClass &myClass)

rather than

void foo(TMyClass myClass)

5- Use 'op='

Wherever possible, use 'op=' in favour of 'op'. For example, use

myClass += value;

rather than

myClass = myClass + value;

The first version is better than the second because it avoids creating a temporary object.

6- Inline Small Functions

Small, performance critical functions should be inlined using the inline keyword, e.g.,

inline void foo()

This causes the compiler to duplicate the body of the function in the place it was called from. Inlining large functions can cause cache misses resulting in slower execution times.

7- Use Nameless Classes

Whereever possible, use nameless classes. For example,

foo(TMyClass("abc"));

is faster than

TMyClass myClass("abc");

foo(myClass);

because, in the first case, the parameter and the class share memory.

[C/C++] - C++ optimizations for loops, if/else and switch/case statements

1- Optimize For Loops

Where-ever possible, count down to zero rather than up to n. For example, use

for (i = n-1; i >= 0; --i)

rather than

for (i = 0; i <>

The test is done every iteration and it's faster to test against zero than anything else. Note also that

++i

is faster than

i++

when it appears in the third part of the for loop statement.

2- Optimize If Statements

Factor out jumps. For example, use

bar();

if (condition)

{

undoBar();

foo();

}

rather than

if (condition)

{

foo();

}

else

{

bar();

}

Use a profiler and good judgement to decide if undoing the bar() operation is faster than jumping.

3- Optimize Switch Statements

Put the most common cases first.


[C/C++] - C++ optimizations for initialization

1 - Use Initialization Lists

Always use initialization lists in constructors. For example, use

TMyClass::TMyClass(const TData &data) : m_Data(data)

{

}

rather than

TMyClass::TMyClass(const TData &data)

{

m_Data = data;

}

Without initialization lists, the variable's default constructor is invoked behind-the-scenes prior to the class's constructor, then its assignment operator is invoked. With initialization lists, only the copy constructor is invoked.

2 - Initialize on Declaration

Whereever possible, initialize variables at the time they're declared. For example,

TMyClass myClass = data;

is faster than

TMyClass myClass;

myClass = data;

Declaration then initialization invokes the object's default constructor then its assignment operator. Initializing in the declaration invokes only its copy constructor.

3 - Delay Variable Declarations

Leave variable declarations right until the point when they're needed. Remember that when a variable is declared its constructor is called. This is wasteful if the variable is not used in the current scope.

[C/C++] - Online Web Courses for ANSI C/C++ programming

Programming in C - Whatever you’d like to do with Programming in C

C Programming for Technology - There’s absolutely nothing wrong with visiting C Programming for Technology

C Training Courses: C Programming - A Course in Embedded Systems Development using the C Language from GBdirect C Training (UK) - There is nothing better than a good story. It works almost like magic this C Training Courses: C Programming - A Course in Embedded Systems Development using the C Language from GBdirect C Training (UK)

Programming in C - This is a collection of Web pages at this domain about the C Programming Language and includes topics such as the history of the C Programming Language, Primers and Tutorials, Newsgroups, References, Books and Ezines, Advanced C Programming and Products. Programming in C

C Programming Tutorial - Coronado Enterprises - Programming tutorial teaches you the entire C language. It covers the ANSI-C standard. In order to use this programming tutorial you need the source code for all of the example programs. There are 79 source files. C Programming Tutorial - Coronado Enterprises

ANSI C Programming (Hands On Technology Transfer, Inc. (HOTT)) - SeminarInformation.com - This course provides a comprehensive introduction to the C language, emphasizing portability and structured design. 5 days. Keywords: computer, computers,… ANSI C Programming (Hands On Technology Transfer, Inc. (HOTT)) - SeminarInformation.com

Programming Training: Programming in C Course - Programming Courses - Programming in C Training Courses from PTR (People, Training, Results) Wokingham, Berkshire, UK Programming Training: Programming in C Course

ANSI C Programming Classes, ANSI C Training, Learn ANSI C Course in the UK - There is nothing better than a good story. It works almost like magic this ANSI C Programming Classes, ANSI C Training, Learn ANSI C Course in the UK

C+ training C programming courses C++ classes - Short and sweet introduction about c+ training C programming courses C++ classes

Online Programming Courses & Training - eLearners.com - OK, I know you’re all excited about what we can do with Online Programming Courses & Training - eLearners.com

Cgic: an ANSI C library for CGI Programming - Solutions for the world of cgic: an ANSI C library for CGI Programming

CISC 192 C/C++ Programming Syllabus - There’s light at the end of the tunnel, but before you can see it, you must address the following aspects : CISC 192 C/C++ Programming Syllabus

Free C and C++ Programming Training, Courses, and Tutorials - provided by Intelligentedu.com - In depth look at Free C and C++ Programming Training, Courses, and Tutorials - provided by Intelligentedu.com

C++ Programming online training course in Raleigh - C++ Programming training course is available at Raleigh, United States - ASKEDU.net Training Course Catalog - You can browse by learning subjects, classroom locations, or by training schools. Course formats include: classroom, online, e-learning, on-site. C++ Programming online training course in Raleigh

[C/C++] - C/C++ Tutorials

C++ Made Easy And C Made Many C/C++ tutorials to help learn the language today. Also includes a graphics tutorial.

C++ Programming Tutorial Coronado Enterprises Learn how to program in C++ by studying the 12 chapters written by Coronado.

C++ Tutorial For C Users Quick one page C++ tutorial for C programmers. Consists of short code examples.

Code Examples Code Examples from “The C++ Programming Language”. This page contains links to selected code examples from The C++ Programming Language (3rd Edition).

The C++ Programming Language The Computer History Museum’s site for early C++ sources (code, documentation, papers, etc.).

C++ Program Documentation Guidelines BGSU Computer Science: C++ Program Documentation Guidelines.

The Programming Guide Lines Embedded C++ Programming Guide

Bloodshed Software C C++ Great game source code and resources. There’s also OpenGL and DirectX tutorials. A good part of the resources are working with Dev- C++…

C++ Programming Style Guidelines It is difficult to give a complete list of the suggested use of whitespace in C++ code. The examples above however should give a general idea of this issue.

Structure Of A Program Consult the compilers section and the manual or help included with your compiler if you have doubts on how to compile a C++ console program.

Programming In C A tutorial on programming UNIX System Calls and Subroutines using C by AD Marshall.

C++ Programming Tutorials Codersource.Net Contains beginner level tutorials , samples and articles on C++.

Introduction To Object Oriented Programming Using C++ Introduction to object-oriented programming using C++ by Peter Mueller.

An Introduction To Programming Using C++ An introduction to imperative (non-object-oriented) C++ programming.

Tutorial Guide To C++ Programming This document provides an introduction to computing and the C++ programming language. It will teach you how to write, compile, execute and test a C/C++ application.

The Standard Template Library Introduction to the STL.

Doc++ DOC++ is a documentation system for C, C++ , IDL and Java…


[C/C++] - Watching all values of arrays (of free pointers) in Visual Studio C++ debugger

“How do I get Visual Studio debugger to show me the data in the arrays? I don’t want to see just one value at a time; I want to see the values contained in array indices [50] to [100] for example”.

Using for Visual Studio 2005:

If yours were fixed length arrays, getting the value of a range would not be difficult. The debugger would then provide a small + sign beside your array object in the quick watch, and you could expand it to see all the elements.

With free pointers, the debugger cannot do that. Becasue it does not know the length of the array. So you must use some little tricks:

  • Use the managed framework and declare an arraylist object, load it using your native array specifying the length. Your debugger will instantly show all the elements of the array list object expandable/ collapsible with a + sign
  • Write them down to a file on the hard disk ([index]:[value] format), open and inspect the file while debugging.
  • Declare a test only fixed length array (that you can comment later on), copy the contents of the native pointer array to it, and let the debugger do the rest.

September 18, 2008

[WPF] - Some XAML tools for WPF

Photobucket

Expression Blend by Microsoft

Formerly known as Expression Interactive Designer (and "Sparkle"), this application allows you to build next-generation user experiences that take advantage of WPF. Expression Interactive Designer supports vectors, pixel images, 3D content, video and audio, high quality text, and animation.


Photobucket

ZAM 3D by Electric Rain

Zam 3D is a 3D XAML Tool for Microsoft Windows Vista Application Development.
Provides developers and designers with a quick and easy solution for creating 3D interface elements for Microsoft Windows Vista based applications. It also acts as a 3ds to XAML and dxf to XAML converter.


Photobucket

XAML Exporter for Blender by Daniel Lehenbauer

The XAML export script for Blender allows the popular free 3D modeler to be used to create content for WPF applications. 3D scenes created in Blender are exported to .xaml files which can be dynamically loaded or compiled into your WPF applications.


Photobucket

Maya To XAML by Thomas Goddard

This plug-in allows designers to create compelling 3D user interfaces in Maya and export to XAML, the next generation application GUI markup language for windows and the web. Objects created in Maya can be used as hit targets, windows forms controls, and more. Because the objects are kept as vector data in the interface, the user can scale the entire application and keep the same look and feel. Look for future export features like animation, mesh optimization, xml formatting, and the ability to specify the WPF target type template for Maya objects.


Deep Exploration by Right Hemisphere

Deep Exploration Standard Edition enables your extended teams to easily create and deliver visual product communications and collaborate more effectively. Rapidly and easily transform, author, and publish 2D and 3D product graphics and documents on your desktop


Photobucket

Aurora by MOBIFORM Software

Aurora XAML Designer is a customizable authoring and design toolkit for embedding into .NET applications as a WPF control for developing user interfaces and graphics for Windows desktop and web applications. Aurora has a full object model allowing for programmatically generating graphics on the design surface. Developers can access the XAML document tree, toolbars, menu, property panel items and even embed their own WPF components.

Aurora generates the XAML markup required by Visual Studio® for developing .NET 3.5 applications. Aurora authors traditional style dialog boxes and windows using common controls and works in multiple layers like many graphics design products. Aurora has a gallery of royalty-free clip art, supports 2D vector graphics and has powerful brush options for specifying linear, radial, visual, image and video brushes. Unlike some design products and export plug-ins that produce markup completely as paths, the output from Aurora XAML Designer is optimized so that the individual graphics can be easily integrated with .NET code-behind.


September 16, 2008

[WPF] - Some useful books for WPF programmers

Photobucket

Windows Presentation Foundation Unleashed (WPF) (Unleashed) - - Adam Nathan

“This book stands out as one of the easiest to read technical books. The book is in color, is divided into many chapters and sub-chapters, and written in a casual style, which makes it very enjoyable to read. The coverage of the content is top-notch, save for the chapter on data binding which I think lacked better examples. I think this book falls into the category of a cover-to-cover read; meaning it is easy to get through the book in a couple weeks. There are other books that I would recommend as a reference book that contain more detailed technical information. If you are new to WPF and are the type to read complete chapters and books, then definitely start with this one.”

Photobucket

Essential Windows Presentation Foundation (WPF) (Microsoft .NET Development Series) - Chris Anderson

“I thought no one could top Adam Nathan's WPF book, and this one doesn't top it - no what it does it match it but does so without tediously repeating the same material and approach. Chris Anderson's book is the one to read if you want to know the Why's and not just the What's - this is not just because Chris was one of the chief architects but because he explains it all so clearly. The book's organisation is wonderful, WPF has a huge surface area but Chris's presentation of it is effortless, enlightening and entertaining. I wouldn't hesitate to recommend this book.”

Photobucket

Programming Windows Presentation Foundation (Programming) - Chris Sells/Ian Griffiths

“If you are interested in Avalon (WPF) at all, then this is the book you need! It is by far the best book on the subject that's currently available. Sure, this is still beta technology and by now a few new builds have been made available, but updated samples are available online.

Not only will the technology change before it is released, but there will also be a lot of new tools available by the time it ships. For the time being however, this book tells you how things are done without special tools. And it can never hurt to know how things are done under the hood.”

Photobucket

Applications = Code + Markup: A Guide to the Microsoft Windows Presentation Foundation (Pro - Developer) - Charles Petzold

“I have had this book for about 2 weeks now, as Amazon delivered it to me early before the official release. I am a tech book junkie. I buy a lot of tech books. This is the best programming text I have purchased in the last couple of years. Petzold does a great job explaining WPF from both a nuts & bolts prespective and a big picture perspective.

I purchased two other WPF books over the last few months. This book blows both of them away. It was written using the June CTP of the .Net 3.0 framework, which is supposed to be fairly locked down API-wise. All the code works correctly, which I cannot say about my other two books. In the first 5 pages I learned something new about WPF, even though I have been knee deep in the technology for months. Several things that seemed rather mysterious to me in WPF have become crystal clear because of the explanations in this book.

The first half of the book is all C#. The second half is all XAML, acomplishing the same tasks as the first half. This approach really shows the relationship between XAML code and the resulting objects at runtime.”


September 13, 2008

[C/C++] - Tips for STL and Generic Programming

Tip 15: The Location of Template Definitions

Normally, you declare functions and classes in a .h file and place their definition in a separate .cpp file. With templates, this practice isn't really useful because the compiler must see the actual definition (i.e., the body) of a template, not just its declaration, when it instantiates a template. Therefore, it's best to place both the template's declaration and definition in the same .h file. This is why all STL header files contain template definitions.

In the future, when compilers support the "export" keyword, it will be possible to use only the template's declaration and leave the definition in a separate source file.

Tip 16: Standard Base Classes for Function Object

To simplify the process of writing function objects, the Standard Library provides two class templates that serve as base classes of user-defined function objects: std::unary_function and std::binary_function. Both are declared in the header “functional”. As the names suggest, unary_function serves as a base class of function objects taking one argument and binary_function serves as a base class of function objects taking two arguments. The definitions of these base classes are as follows:

template < class Arg, class Res > struct

unary_function

{

typedef Arg argument_type;

typedef Res result_type;

};

template < class Arg, class Arg2, class Res >

struct binary_function

{

typedef Arg first_argument_type;

typedef Arg2 second_argument_type;

typedef Res result_type;

};

These templates don't provide any useful functionality. They merely ensure that arguments and return values of their derived function objects have uniform names. In the following example, the predicate is_vowel, which takes one argument, inherits from unary_function:

template < class T >

class is_vowel: public unary_function< T, bool >

{

public:

bool operator ()(T t) const

{

if ((t=='a')||(t=='e')||(t=='i')||(t=='o')||(t=='u'))

return true;

return false;

}

};

Tip 17: Storing Dynamically Allocated Objects in STL Containers

Suppose you need to store objects of different types in the same container. Usually, you do this by storing pointers to dynamically allocated objects. However, instead of using named pointers, insert the elements to the container as follows:

class Base {};

class Derived : public Base{};

std::vector < Base* > v;

v.push_back(new Derived);

v.push_back(new Base);

This way you ensure that the stored objects can only be accessed through their container. Remember to delete the allocated objects as follows:

delete v[0];

delete v[1];

Tip 18: Treating a Vector as an Array

Suppose you have a vector of int and function that takes int *. To obtain the address of the internal array of the vector v and pass it to the function, use the expressions &v[0] or &*v.front(). For example:

void func(const int arr[], size_t length );

int main()

{

vector <int> vi;

//.. fill vi

func(&vi[0], vi.size());

}

It's safe to use &vi[0] and &*v.front() as the internal array's address as long as you adhere to the following rules: First, func() shouldn't access out-of-range array elements. Second, the elements inside the vector must be contiguous. Although the C++ Standard doesn't guarantee that yet, I'm not aware of any implementation that doesn't use contiguous memory for vectors. Furthermore, this loophole in the C++ Standard will be fixed soon.

Tip 19: Dynamic Multidimensional Arrays and Vectors

You can allocate multidimensional arrays manually, as in:

int (*ppi) [5]=new int[4][5]; /*parentheses required*/

/*fill array..*/

ppi[0][0] = 65;

ppi[0][1] = 66;

ppi[0][2] = 67;

//..

delete [] ppi;

However, this style is tedious and error prone. You must parenthesize ppi to ensure that the compiler parses the declaration correctly, and you must delete the allocated memory. Worse yet, you can easily bump into buffer overflows. Using a vector of vectors to simulate a multidimensional array is a significantly superior alternative:

#include <vector>

#include <iostream>

using namespace std;

int main()

{

vector <vector<int> > v; /*two dimensions*/

v.push_back(vector <int>()); /*create v[0]*/

v.push_back(vector <int>()); /*create v[1]*/

v[0].push_back(15); /*assign v[0][0]*/

v[1].push_back(16); /*assign v[1][0]*/

}

Because vector overloads operator [], you can use the [][] notation as if you were using a built-in two-dimensional array:

cout << v[0][0]

cout << v[1][1] style="">

The main advantages of using a vector of vectors are two: vector automatically allocates memory as needed. Secondly, it takes care of deallocating memory so you don't have to worry about potential memory leaks.

Tip 20: Why You Shouldn't Store auto_ptr Objects in STL Containers

The C++ Standard says that an STL element must be "copy-constructible" and "assignable." These fancy terms basically mean that for a given class, assigning and copying one object to another are well-behaved operations. In particular, the state of the original object isn't changed when you copy it to the target object.

This is not the case with auto_ptr, though: copying or assigning one auto_ptr to another makes changes to the original in addition to the expected changes in the copy. To be more specific, the original object transfers ownership of the pointer to the target, thus making the pointer in the original null. Imagine what would happen if you did something like this:

std::vector <auto_ptr<Foo> > vf;/*a vector of auto_ptr's*/

// ..fill vf

int g()

{

std::auto_ptr <Foo> temp=vf[0]; /*vf[0] becomes null*/

}

When temp is initialized, the pointer of vf[0] becomes null. Any attempt to use that element will cause a runtime crash. This situation is likely to occur whenever you copy an element from the container. Remember that even if your code doesn't perform any explicit copy or assignment operations, many algorithms (std::swap(), std::random_shuffle() etc.) create a temporary copy of one or more container elements. Furthermore, certain member functions of the container create a temporary copy of one or more elements, thereby nullifying them. Any subsequent attempt to the container elements is therefore undefined.

Visual C++ users often say that they have never encountered any problems with using auto_ptr in STL containers. This is because the auto_ptr implementation of Visual C++ (all versions thereof) is outdated and relies on an obsolete specification. When the vendor decides to catch up with the current ANSI/ISO C++ Standard and change its Standard Library accordingly, code that uses auto_ptr in STL containers will manifest serious malfunctions.

To conclude, you shouldn't use auto_ptr in STL containers. Use either bare pointers or other smart pointer classes instead of auto_ptr (such classes are available at www.Boost.org).