Category Archives: tutorial

ListCollectionView for sorting,filtering data collection


When we wanted to perform filtering, sorting of data over a binded data collection, collection view might be helpful. If the source collection implements INotifyCollectionChanged interface, the changes raised by the CollectionChanged event are reflected to the views.

ListcollectionView Represents the collection view for collections that implement IList as Mictosoft Doc says.

Create a collection view

In order to use ListCollectionView you have to use ObjectModel

using System.Collections.ObjectModel;

Then you can use any list to create ListCollectionView, in this example I used my observable collection of SalesOrder.

ListCollectionView sorderview = null;
collectionview = new ListCollectionView(salesOrderCollection);

Model View Class

class SalesOrderView
    {   public DateTime Date { get; set; }
        public string Customer{ get; set; }        
        public string Amount{ get; set; }
    }

Create a Custom filter

Let’s play with filter, first up all we need to create some custom filter for searching SalesOrders received from customers on a specific date

collectionview.Filter = (e1) =>
                {
                    SaleOrderView sorder = e1 as SaleOrderView ;
                    if (((Convert.ToDateTime(sorder.Date) >= dtp_from.SelectedDate && 
Convert.ToDateTime(sorder.Date) <= dtp_to.SelectedDate)) )
                        return true;
                    return false;
                };

That is it, now you can simply bind the collection view with DataGrid or Listcontrol. For me it is a Grid

 mydatagrid.ItemsSource = collectionview;

Howto start a new activity in Android Studio


Activity in Android studio represent a Window, where you can dispplay controls and handle data etc. You can start as many form/activity the project requires. Just add a new Activity and do the following

Here we goes

  • Create a Intenet object, the first parameter will be the package or Main activity and the second will be the new new activity class
  • Call the startActivity method

Code

Intent intent = new Intent(MainActivity.this, NewActivity.class);
startActivity(intent);

Note: Can also possible to run as many activity with in a activity using the concept Fragment (Learn More about Fragments )
I hope this will help you

SqlAlchemy[SQLite] databse connection in Python-Flask


Flask is a Python framework which can be used to build the web application from scratch. Flask is micro frame work which capable to build websites like Instagram, twitter and anything at programmers will.

SqlAlchemy is a package in Python Flask which simplifies data base connections. The following simple Application will explain ….. how.

This project was built on windows OS and Pycharm IDE

The connection string

from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
 app.config['DATABASE_FILE'] = 'app2.db'
 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
 app.config['SECRET_KEY'] = '123456790'
 db = SQLAlchemy(app)

So the db is like the cursor to the database.

Making of Database enabled Class

The User class exclusively has some database capabilities, such as querying tables. It is a fine example of how inheritance helping to build better applications.

class User(db.Model, UserMixin):
 id = db.Column(db.Integer, primary_key=True)
 username = db.Column(db.String(80), unique=True)
 email = db.Column(db.String(120), unique=True)

How to add font selector property to User-control in VB6


Adding a property to a user control in VB6 requires 4 subroutines to be filled, the Let/Set, Get and property Bags respectively.

Let and get have the variant as return type as an argument, which means any value can be accessed through the property.

Public Property Get Interval() As Variant

Interval = Timer1.Interval

End Property

Public Property Let Interval(ByVal vNewValue As Variant)

Timer1.Interval = vNewValue

PropertyChanged “Interval”

End Property

Suppose you want to change how do you get the Font Dialog within the Property Window. This can be possible with use of stdfont  in place of Variant as follows

Public Property Set Font(ByVal Nfont As StdFont)

Set lbl_Time.Font = Nfont

Refresh

PropertyChanged “Font”

End Property

Public Property Get Font() As StdFont

Set Font = UserControl.lbl_Time.Font

End Property

The complete VB6 Stopwatch Project can be accessible in my GitHub repository

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

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.

Add items to listview using Reader class in C#


Welcome to another code poetry post. Suppose you have a database application and want to display those records from database to a listview, what should you know?. This tutorial will help you.

C# has a neater ways to code with ListView and Database. List View Control work much faster than Grid. Let’s do it with fun.

For this C# project, we need a connection string and method to connect the database, command object which can be used to fetch records from the table. We are already discussed about OLEDB connections (if you are not familiar, attempt a search).

Secondly we need a Reader object which let you move through the records, this method proved to be faster than data views.

How to add items

We are filling listView items with values using following ,
  1. Create List of Strings and gather items
  2. We create ListViewItem object and add those List we are collected to it.
  3. Final step we just fill ListView control with ListViewItem object .

The code

We used a connection method for this project, and called using connect, the rest of the code look like

public void MediceineList(ListView ls, List filter)
        {
            string qstr;
            List lst=new List();

            if (filter[0] == “All”) {
                qstr = “Select * from new_Medicines”;
            }
            else
            {
                qstr = “Select * from new_Medicines where ” + filter[1] + ” =” + filter[0];
            }
            Rs = new OleDbCommand(qstr , conn);

            OleDbDataReader dr = Rs.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            int i = 1;
            while (dr.Read())

            {
                lst.Add(i++.ToString ());
                lst.Add(dr.GetValue(0).ToString());//Pcode
                lst.Add(dr.GetValue(1).ToString ());//PName
                ListViewItem lsvitm = new ListViewItem(lst.ToArray() );
                ls.Items.Add(lsvitm);
                lst.Clear();
            }
            ls.Items.Add(“”);
            ls.Items.Add(“TOTAL: “+ i);
        }
        }

I also used some filtering capabilities. Lets finish the final code and test the application.
 List fltr;

            fltr = new List();
            fltr.Add(“All”);
            db.MediceineList(listView1,fltr);

Accessing child controls in C# with foreach


Simplest way to clear all combo Box/TextBox in Visual Studio C#  2015 is using foreach loop and moving through the control collection.

What about controls grouped within  a group box, things getting complicated,isn’t it? Let me explain how can it get done.

  • First we going through the Base control collection and get each and every control.
  • Secondly we are looking inside each controls if they have child.
  • We further search for the TextBox and ComboBox and do some formatting, or any usual activities you want.

Visual Studio 2015 Tips: Double press Tab after you type foreach for snippet to be inserted, so that you can do more with less time.