Tag Archives: postaweek

Reading and Writing Json objects in C#


JSON objects are fast to read. From Python to C# JSON objects are widely used for the database as well as data transaction purposes, some of them are simple, some others are complicated.

So let begins with a simple C# Projects

JSON STRINGS in C#
SERIALIZATION OF JSON STRINGS in C#

Todo

  1. Build a class for constructing JSON string
  2. Write to JSON text file
  3. Read from the file back to JSON class

How to Property binding in C#


I love the data binding features rather than anything else in my visual studio. I am going to demonstrate binding feature in c#.

We have an MDI form called ‘Master’ and a Label on it and another child form in My C# Project. The child simply shows ‘company’ with ‘codes’.

Task: Want to display Company name on Master when the user double-click the company.

How to, do this, we can achieve this with global variables, maybe, but need to refresh the label every time. But the binding feature offers the better solution for this.

  1. We need to create the property to access label control  Text in master as follows
private string foo="My Company";
 public string Company
 { 
 
 set{

foo=value;
 
 }
 get { return foo; }
 }

Now place the label data binding code just below the Initialize section of the ‘Master’.

InitializeComponent();
lbl_company.DataBindings.Add("Text", this, "Company");

The code will work every time when the label Text changes. Actually, we need to change the value of the label when company property altered, which require a two-way binding. This is possible with the INotifyPropertyChanged interface.

Property Binding with Control -c#

How to data bind controls in C#

Our Master class need to be modified as follows Continue reading

How to change the Back color of MDI Form – C#


As a C# programmer, you may have used Back Color property for changing the color of the background for control as well as Windows form. You can also found that this not works with MDI Parent form.

MDI is the container for child forms or control, actually, it’s inherited from the panel [leave it no…lol].

Ok, all you want to repaint all the controls in it, even though there are no controls were placed, think about the inherited panel. All we have to do is try to cast every control as MDIClient and loop through it and change the color as follows

MdiClient ctlMDI;

// Loop through all of the form's controls looking
 // for the control of type MdiClient.
 foreach (Control ctl in this.Controls)
 {
 try
 {
 // Attempt to cast the control to type MdiClient.
 ctlMDI = (MdiClient)ctl;
 // Set the BackColor of the MdiClient control.
 ctlMDI.BackColor = Color.Gold;
 }
 catch (InvalidCastException exc)
 {
 // Catch and ignore the error if casting failed.
 }
 }

Place the code on Load Event of MDI Parent Form

Create and read simple JSON_STRING in Android Studio


JSON_STRING strings are similar to Dictionary and List in Python, they can be searched quickly. JSON_STRING can be used to store data for your application.

This post will teach you how to create and read JSON_STRING objects in Android Studio/Eclipse Android apps.

  1. Go ahead and create a simple activity app
  2. Switch to Android View
  3. Create simple JSON_STRING as follows in the MainActivity.Java class
    String JSON_STRING = "{\"DSLR\":{\"Model\":\"Sony Alpha 58\",\"Sensor\":APC}}";

    [Drop the above code at the beginning of the OnCreate method]

  4. Open main_activity.xml [can find under res/layout]
  5. Drag and Drop two TextView control to the Form.
  6. Change the name of the controls in the content_main.xml file as ‘model’ and ‘sensor’ respectively
  7. Now create variable to read a string from JSON and assign the values to controls
String model, sensor;
TextView Model, Sensor;
Model = (TextView) findViewById(R.id.model);
Sensor = (TextView) findViewById(R.id.sensor);
try {
 // get JSONObject from JSON file
 JSONObject obj = new JSONObject(JSON_STRING);
 // fetch JSONObject named employee
 JSONObject dslr = obj.getJSONObject("DSLR");
 // get employee name and salary
 model = dslr.getString("Model");
 sensor = dslr.getString("Sensor");
 // set employee name and salary in TextView's
 Model.setText("Model: "+model);
 Sensor.setText("Sensor: "+sensor);

} catch (JSONException e) {
 e.printStackTrace();
}

Alt+Enter to auto import libraries. Here the JSONObject will help you to fetch ‘DSLR’ String. In our example, we have one only one JSON string so that used two Text views only.

Remember JSON strings are case sensitive.

You can download the source code from GitHub

RSS / ATOM Feed Parsing in Python


Feeds are good for showing content from one website to another. Feeds are basically XML file with user define tags. As Python fan, I found reading content from a RSS feed in python is very simple and interesting. Most of the sites have feeds.

In our example we are using SEBI’s feed, which will provide latest events in Indian Stock Exchange market.

First you need the parsing package from Pypi[Python Package Index]. You can Install the package using pip command as follows

pip install feedparser

Import the package and use it

import feedparser
#Programmer : MANOJ AP
#Email: develprm@outlook.com
feed = feedparser.parse("https://www.sebi.gov.in/sebirss.xml")

feed_title = feed['feed']['title']
feed_entries = feed.entries

for entry in feed.entries:
    article_title = entry.title
    article_link = entry.link
    article_published_at = entry.published # Unicode string
    article_published_at_parsed = entry.published_parsed # Time object  
    print "{}[{}]".format(article_title.encode('utf-8'), article_link.encode('utf-8'))
    print "Published at {}" .format(article_published_at)

The feedparser.parse accept a RSS feed and turn into Python object, as we know can access the elements in as in a list(feed[‘feed’][‘title’]). feed.entries return the feed elements, we can use a for loop to traverse through the elements

You are welcome to use the source code, SEBI Reader project

Create a simple Jason File


Like XML files JSON file can hold data in the form of  list or list of list. If you are familiar with Python list, it can be simplified. Using your favorite text editor you can create a Jason file.

JSON file can be used to store data for static web pages or can be used to transfer data between application. Let’s look at the very simple Jason file.

"institution":
[{
"name" : "RMHS MELATTUR",
"location" : "Melattur",
"catagory":"School",
"landmark":"Opp. GOVT. Hospital PMNA",
"distance":"12.km",
"Office phone":"947854545",
"district" :"Malappuram",
"web" :"http://rmhs.com",
"email" :"rmhs@outlook.com",
"course_offering" :["Plus Comp. Science","Plus Science"]
}]

In the above example we have a list called institution, and lots of keys and values, say location is a key and Melattur is the key value, you can identify the value with the key.  Each key is separated with a ‘.’ operator. and you can also have sub list which can be included within a ‘[‘ and ‘]’.

Can I hold more than one information in a Jason? yes. In the following format, within the same list.

{
"institutions":
[{
"name" : "RMHS MELATTUR",
"location" : "Melattur",
"catagory":"School",
"landmark":"Opp. GOVT. Hospital PMNA",
"distance":"12.km",
"Office phone":"947854545",
"district" :"Malappuram",
"web" :"http://rmhs.com",
"email" :"rmhs@outlook.com",
"course_offering" :["Plus Comp. Science","Plus Science"]
},
{
"name" : "NSS School",
"location" : "Manjeri",
"catagory":"School",
"landmark":"Opp. Municipality",
"distance":"12.km",
"Office phone":"947854545",
"district" :"Malappuram",
"web" :"http://rmhs.com",
"email" :"rmhs@outlook.com",
"course_offering" :["Plus Comp. Science","Plus Science"]
},
{
"name" : "MODEL School",
"location" : "Pandikkad",
"catagory":"School",
"landmark":"Opp.Buss stand",
"distance":"12.km",
"Office phone":"947854545",
"district" :"Malappuram",
"web" :"http://rmhs.com",
"email" :"rmhs@outlook.com",
"course_offering" :["Plus One Comp. Science","Plus One Science"]
},
{
"name" : "CENTRAL SCHOOL",
"location" : "Perinthelmanna",
"catagory":"School",
"landmark":"Opp. GOVT. Hospital PMNA",
"distance":"12.km",
"Office phone":"947854545",
"district" :"Malappuram",
"web" :"http://rmhs.com",
"email" :"rmhs@outlook.com",
"course_offering" :["Plus One Comp. Science","Plus One Science"]
},
{
"name" : "NSS COLLAGE",
"location" : "Palakkad",
"catagory":"Collage",
"landmark":"Opp. GOVT. Hospital PMNA",
"distance":"12.km",
"Office phone":"947854545",
"district" :"Palakkad",
"web" :"http://rmhs.com",
"email" :"rmhs@outlook.com",
"course_offering" :["BSc Comp. Science","BSc Physics,BSc Maths"]
},
{
"name" : "MES BED COLLAGE",
"location" : "Edathanattukara",
"catagory":"Collage",
"landmark":"Opp. GOVT. Hospital PMNA",
"distance":"12.km",
"Office phone":"947854545",
"district" :"Malappuram",
"web" :"http://rmhs.com",
"email" :"rmhs@outlook.com",
"course_offering" :["SS,MALAYALAM,ENGLISH"]
}
 ]
}

The file extension must be.json.

In the next post, we will learn how to read a Jason file in Python.

How to host webpages on github for free


GitHub is my favorite place to host my personal web apps. It is one of the finest places to host your web-based [ Python, Javascript, Django etc ] static websites.

Features I love

  • You can keep source code on the web
  • Discuss with others
  • Initially, you can host a static web page [can make static dynamic apps, with Python, we will discuss it later]
  • Make changes from your computer and commit and push changes to the repository you made, changes will go online

How to host a website on GitHub?

  • The first thing you need to do the GitHub software.Download and Install
  • Prepare your website on your PC
  • Create a repository with the following format on Github.com

username.github.io

  • The username and subdomain should match to host the website completely, otherwise the page not go live. You can try additional website by creating another Organization and then repository
  • Click the clone download the button on GitHub Pages

2018-02-18_122237

  • Open GitHub on the PC, File-Clone Repository
  1. Choose the Repository Folder first, say D:/Github [ where your source code will reside ]
  2. Paste the clone link and it will create a folder username.github.io
  3. Copy all of your web pages and folders to the new folder.

2018-02-18_115018

  • Now you need to made first commit to the master[only master branch commit will affects the website]
  • Finally Push all changes back the GitHub and your site will go online.

Check mine

 

 

Change DataGridView column style at runtime in C#


How to change DataGridview column style at runtime in Visual Studio C#.Net?

Simply get the column from the Gridview with the help of subclass of GridView. The code will look like

DataGridViewComboBoxColumn products = new DataGridViewComboBoxColumn();
products = (DataGridViewComboBoxColumn)dataGridView1.Columns[ITEM.Index];
products.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
products.FlatStyle = FlatStyle.Flat;

All changes made to the object products will change the dataGridView1.Columns[ITEM.Index] since the object point to the dataGridveiw column ITEM.

* It resembles pointers in C, where a value changes in a pointer also reflect the variable.

How to use dataView rowfilter for searching rows in C#.Net


You can simply use SQL query statements to retrieve desired data from database server with C# and ADO.Net. But there are plenty of ways to search your localized version of data which is stored in dataSet and dataView.

We already learn how to use Find and Findrow methods for searching data in Visual Studio App. This post will show how to use row filter property of  DataView for sorting data rows.

  1. First up all you need to create Data adaptor, dataSet, and dataView.
  2. In our example, I have a date field in the database table, so that I can filter for specific date ranges as follows
 Common.AccountReportDV.RowFilter = "invoicedate>='" + dateTimePicker1.Value.ToShortDateString() + "' and invoicedate<='" + dateTimePicker2.Value.ToShortDateString() + "'";

Here common is a public static class where kept the Database functions. The above statement will be looking for data between the two dates.

You have to use Common.AccountReportDV and not Common.AccountReportDV.Table.rows  for retrieving the result as follows.

foreach (DataRowView row in Common.AccountReportDV)
 { 

console.WriteLine(row["<column name here>"]);

 }

DataRowView is a special class which helps to access data rows in a DataView object.

Add column names to listview using dataSet in C#


When we need to populate various reports, usually we also need to supply customized column names too. We can easily grab column name from the database using objects like DataSet in C#

In our example, we use SQL database objects as follows.

AccountReportAdapter = new SqlDataAdapter(sql, con);
AccountReportDS = new DataSet();
AccountReportAdapter.Fill(AccountReportDS);

Get started with a foreach statement and store the names into a List collection object.

List<string> hds = new List<string>();

hds.Clear();
foreach (DataColumn c in Common.AccountReportDS.Tables[0].Columns)
{
hds.Add(c.ColumnName.ToString());
}

The hds list simply store the column name, just like an array does. Later we can use the list for supplying heads for ListView  as follows

public void ReportHeader(List<string> ar)
{
ColumnHeader headers = new ColumnHeader();
listView1.View = View.Details;
headers.Text = ” “;
headers.Width = 0;
listView1.Columns.Add(headers);
foreach (var htext in ar)
{
headers = new ColumnHeader
{
Text = htext.ToString(),
Width = htext.ToString().Length * 20
};
listView1.Columns.Add(headers);
}
}

if (hds != null) ReportHeader(hds);