Category Archives: http://schemas.google.com/blogger/2008/kind#post

How to INSTALL DJANGO ON WINDOWS 7?


‘Django’ was one of the popular Python framework, which can be used to create beautiful dynamic website from scratch. Write less and do more that is the frameworks mean to. You don’t need to start from the beginning, Django will take care of that.

How to get my copy of Django?

Well, it is a free framework free of cost, you can download and use Django 1.6.5 or later along with Python 3.3 or prior version on Windows/Linux/Mac or on almost any Computer OS.

Installing Django on Windows 7 and later

Make sure that you have latest Python version installed on your computer. You can download it from Python.org. Extract the Django .Zip/.tar file, using Winzip or 7zip (preferably C:/, root directory).
Setting Python paths on windows will let you run it from any drive, learn how to.
Let’s install the Django, issue the following command using Power Shell or command prompt (Run->PowerShell).

C:/> CD django1.6.5
C:/>django1.6.5> Python setup.py install

And it will run the python script for installation. All file required will be automatically copied to the Python Lib\site-package folder securely. After the process you can safely delete the extracted folder from the C:\ drive.

Installing Django on Linux

On Linux you have prebuilt Python on it, so no need to install it separately. Just extract Django .tar file and run the setup script.
Verifying the Django installation

Run the following on Python prompt

>>> import django
>>> print (django.get_version())

Will result in displaying the current version as (if everything went right)
1.6.5

That’s all

VB6: List all printers using code in Windows


Listing all printers with name, Port in VB6 is simple as listing default printer port using Kernel32 library . Today we going show you how to do this.

As usual we start with function declaration, then define a new function which add all information into a list box. Here we goes

Kernel32 GetProfileString method

Declare Function GetProfileString Lib “kernel32.dll” Alias “GetProfileStringA” (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long) As Long

Add printer information into a list box

Public Sub GetPrinterList(lstPrinter As ListBox)
Dim PrintData As Printer
Dim defprinterpos%
For Each PrintData In Printers
‘ Add printer name and port to list
lstPrinter.AddItem PrintData.DeviceName & ” at: ” & PrintData.Port
‘ Check for default printer
If PrintData.DeviceName = Printer.DeviceName Then defprinterpos = lstPrinter.NewIndex
Next
lstPrinter.ListIndex = defprinterpos%
End Sub

This sub procedure will take list box as argument, and add printer to this list box.

Call the sub

The final line of code just invoke the procedure and see what we have. 
Happy coding

VB6: List default printer using code in Windows


kernel32 hold lots of interesting function that you may not utilized yet. With the Profile String  functionality programmers can list default printer name, with serial port, Driver etc. Is that interesting. 


Just create a bunch of function and call it.

Declare the function

Declare Function GetProfileString Lib “kernel32.dll” Alias “GetProfileStringA” (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long) As Long

Define the GetDefaultPrinter function

Public Function GetDefaultPrinter() As Printer
    Dim strBuffer As String * 254
    Dim iRetValue As Long
    Dim strDefaultPrinterInfo As String
    Dim tblDefaultPrinterInfo() As String
    Dim objPrinter As Printer
    ‘ Retreive current default printer information
    iRetValue = GetProfileString(“windows”, “device”, “,,,”, strBuffer, 254)
    strDefaultPrinterInfo = Left(strBuffer, InStr(strBuffer, Chr(0)) – 1)
    tblDefaultPrinterInfo = Split(strDefaultPrinterInfo, “,”)
    For Each objPrinter In Printers
        If objPrinter.DeviceName = tblDefaultPrinterInfo(0) Then
            ‘ Default printer found !
            Exit For
        End If
    Next
    ‘ If not found, return nothing
    If objPrinter.DeviceName tblDefaultPrinterInfo(0) Then
        Set objPrinter = Nothing
    End If
    Set GetDefaultPrinter = objPrinter
End Function

Use the function to list default  

Private Sub Command8_Click()
Dim objPrinter As Printer
Set objPrinter = GetDefaultPrinter()
Text2.Text = “Default printer is: ” + objPrinter.DeviceName & _
Chr(13) & ” Driver name is: ” + objPrinter.DriverName _
& Chr(13) & ” Port is: ” + objPrinter.Port
Set objPrinter = Nothing
End Sub

How to get Computer Name using VB6 Code


Accessing system property is pretty easy with VB6 code. This can be useful when programmers need to refer the system name in the code.

Steps

  • Declare the GetComputerNameA function which resides in the kernel32 library
  • Create function to fetch the Computer Name.
  • Use the function

The Kernel function

 Declare Function GetComputerNameA Lib “kernel32” (ByVal lpBuffer As String, nSize As Long) As Long

Get the computer name

Public Function GetComputerName() As String
Dim sResult As String * 255
GetComputerNameA sResult, 255
GetComputerName = Left$(sResult, InStr(sResult, Chr$(0)) – 1)
End Function

Calling the function

Text1.Text = GetComputerName

VB6: Load Picture in Data Report using code


Usually we can access each section of data report in Visual Basic 6 using code by the following manner DataReport1.sections(“head”).controls(“label1″.caption =”Total Amount”.
But this method not going to work when you want to load a custom image from your local drive.

Custom image in Data Report

You can simply do the task by following these steps
  • Place a Data Report image control on a form
  • Create an object for storing image object

Dim img
set img=DataReport1.sections(“head”).controls(“image1”)

  • Load image with LoadPicture method 

img.picture=loadpicture(“filelocation\filename.jpg”)

Create custom form controls in C#.Net


.Net frame provide rich set of control to design  application GUI with a drag and drop actions. Sometime we love to have extend these control features. This can be achieved using Windows Forms Control Library Projects. Let’s learn how to do.

Extended TextBox control

Our extended control have following features
  • Custom got focus color
  • Custom Lost focus color
  • New Methods
Using the new Text Box you can enable different Leave/Enter colors. The example look like simple but it will demonstrate how you can add new properties for using at run time and design time.

Quick start

  1. Add New  Windows Forms Control Library project in Visual Studio .Net 2012/15.
  2. Drag a Text Box to the user control
  3. Rename the User control as “CPTextBox” where CP stands for Code Poet.
    Windows Forms Control Library Project
Now we need a Windows Application to test our CPTextBox, add a new project by,
  1. Go to File – Add – New Project – Windows Form Application (name it as testProject)
  2. Go to Solution Explorer – There is your two project, right click the Windows Application Project, and choose Set as Start Up Project.

We are almost ready to make changes to our custom control. Double click our custom control  and the following methods and drop properties to our code.

namespace CodePoetControls
{

public partial class CPTextBox: UserControl
{
Color Ecolor;
Color Lcolor;

public CPTextBox()
{
InitializeComponent();
textBox1.BackColor = Color.White;

}

private void textBox1_Enter(object sender, EventArgs e)
{
textBox1.BackColor = Ecolor;
}
private void textBox1_Leave(object sender, EventArgs e)
{
textBox1.BackColor = Lcolor;
}

public string GetText()
{
return (textBox1.Text);
}

[Browsable(true)]
[Category(“Extented Properties”)]
[Description(“Get input Text”)]
[DisplayName(“BoxText”)]
public string BoxText
{
set
{

textBox1.Text = value.ToUpper().Trim();

}
get
{
return (textBox1.Text  );
}
}
[Browsable(true) ]
[Category(“Extented Properties”)]
[Description (“Set Focus Color”)]
[DisplayName(“Enter Color”)]
public Color  EnterColor
{
set
{
Ecolor  = value ;
base.OnEnter(new EventArgs() );
}
get
{
return (Ecolor );

}
}

[Browsable(true)]
[Category(“Extented Properties”)]
[Description(“Set Lost Focus Color”)]
[DisplayName(“Leave Color”)]
public Color LeaveColor
{
set
{
Lcolor  = value;

}
get
{
return (Lcolor );
}
}

}
}

Compiling the User Control project.

After you successfully add the necessary code portion and ready to make your control usable. Right click the Custom control project and Build. It will generate necessary .dll files for your project.

Testing the Control

For using the control , go to the second project, open the Form. The Tool Box will show your new Control, just drag and drop CPTextBox.

The Properties Windows Categorized view will showcased your new Controls Extended Properties and try to change the Leave Color and Enter Color respectively.

If you wish to have more changes to the control, go to the custom control project and make necessary changes and Rebuild.

Distributing and using the control

Distributing and using the Dll file. For working with the new control you only need the compiled Dll not the custom project. You can add it by

  • Right click Tool Box – Choose Items
  • Brow the Dll of your custom control
  • Enable the control and it will be available on your control box.

Note:

The following code snippet will make your properties available at design time and can be accessible by using Properties.
        [Browsable(true)]
        [Category(“Extented Properties”)]
        [Description(“Set Lost Focus Color”)]
        [DisplayName(“Leave Color”)]

Using the existing Property name as Display Name will hide the default, for example if you use Text as Display Name for your property and the default property will be discarded and will be unavailable.

That’s all I have today
 

Forming C# string with multiple values using curly braces


In the last post we discussed about mutable string object, which is derived from the list which is mutable object. Today we will learn how make string with different type of values for console programs.

The boast string will help you to understand the concept. Actually C# has pretty neater treatment with strings. Start a fresh COnsole Application project and here is what we usually do when we have thing like this

            int count=20;
            float am=100 ;
            string symbol=” $”;
            string boastStr=”minutes”;
            double   min=2.50;
  Console.Write(“Boast string : I have finished ” + count + ” Apples and Oranges ( ” + am + symbol + “) in ” + min + ” ” + boastStr + ” , wow”) ;

The message is just a joke , lol.

 You can put values inside within a single string by using a { }, curly braces and cardinals instead of the old fashioned + operator, but limited to console only. It will look like,
“I have to reach the station at {0}”, min . Can also use many variables in a string.

Lets convert our boast string too

            Console.WriteLine (“\nBoast string : I have finished {0} Apples and Oranges (  {1} {2}  ) in   {3}  {4} , wow”,count,am,symbol,min,boastStr );

Remember it’s only work with Console.Write().
C# Tips

Expensive strings and stringBuilder class in C#


As we know strings are a group of characters, usually composed of letters, numerals and special symbols etc. C# string type is immutable  object, i.e, they can be created once, after that they can’t be modified.

Diagnostic Tools in C#

Immutable string

Usually you may argue that it is a non sense, I am talking about. Let’s consider the following line of code

string str=” Some string” 

str+=” Some other string” 

Here firstly we created  string variable str and add some initial string value and trying to add  new string “Some other string” with the old one. Even Though there is + operator appeared after the variable, the string variable can’t be modified, instead C# will create a new string by combining the both strings. As a result more and more memory occupied.

Build mutable strings with StringBuilder

This problem can be simply fixed with in built C# class StringBuilder which is mutable object. Following example will clarify the  idea. Create a console application which will execute a series of sample string for a specific times, say 1000.

            string str=””;
for(int i = 0; i <= 10000; i++)
{
str += “Sample C# string”;
}
Console.WriteLine(“String numbers are:” + str);
Console.ReadKey();

Above code will result in extravagant use of memory and may slash the speed of the program, by using the string builder, it can be rewritten as ,

            string str=””;
StringBuilder sb = new StringBuilder() ;
for(int i = 0; i <= 10000; i++)
{
sb.Append (” Sample C# strings “);
}
str = sb.ToString();
Console.WriteLine(“String numbers are:” + str);
Console.ReadKey();

Open the Diagnostic Tool in Visual Studio 2013/15 to find out memory usage. As the program get more complex you can find out that StringBuilder uses less memory than immutable  string. StringBuilder also come with

Auto complete Box

Add auto complete box for datagrid in C#


As we learned how to add an auto complete option for TextBox control in C#, we can also add this feature where a Text entry works. We are back with Datagrid example here. All you have to do is follow these steps.

  1. Drag and drop a Datagrid control to your C# Windows Application.
  2. Find Data Grid’s  EditingControlShowing event using the Properties window.
  3. Create a TextBox for auto completion, using DataGridViewEditingControlShowingEventArgs object.
  4. Check for exact column where we want to place auto completion box.
  5. Create auto completion string set using AutoCompleteStringCollection class.
  6. Fill Auto completion Mode,Source and custom source properties

The Code

 String t = dataGridView1.Columns[1].HeaderText;
            if (t.Equals(“Items”))
            {
                TextBox auto = e.Control as TextBox;
                if (auto!=null) {
                    AutoCompleteStringCollection autotxt = new AutoCompleteStringCollection();
                    auto.AutoCompleteMode = AutoCompleteMode.Suggest;
                    auto.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    autotxt.Add(“Citrizine”);
                    autotxt.Add(“CDT”);
                    autotxt.Add(“DAXIRGIN”);
                    autotxt.Add(“CX4”);
                    autotxt.Add(“DNT-Tab”);
                    auto.AutoCompleteCustomSource = autotxt;
                }
            }
It’s looks like simple, sin’t it?

Auto complete TextBox in C#


An Autocomplete Textbox is a must have for a commercial application, it can bring user friendly features to you application.
Lets learn how to add a Auto complete feature, here is the plan


Code poet’s steps

  1. First we make up the Autocomplete string collection.
    1. Create AutoCompleteStringCollection
    2. Add items to the collection.
  2. Set Autocomplete mode
  3. Set Auto complete source as custom source
  4. Set auto complete custom source as Autocomplete string collection.
  5. That is all

Code

AutoCompleteStringCollection a = new AutoCompleteStringCollection();
            a.Add(“Babool”);
            a.Add(“Ice Bowl”);
            a.Add(“Mango”);
            a.Add(“Mangoose”);
            a.Add(“Chiken”);
            a.Add(“Fruits”);
            textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            textBox1.AutoCompleteCustomSource = a;

As you see you can just type the letters Man  and a new list will populate, as result of the AutoCompleteMode.Suggest code, can replace it with append or appendSuggest which will automatically complete text as you type.