Solving {foo.bar}s – My Experience

Featured

Tags

, , , , , , ,

Recently found some time to attempt Google’s foo.bar challenges. They are really interesting and managed to find the time since fasting and stopped my-self from other works than the work that pays.Hance, I accidentally found the link for foobar or perhaps, the first Easter egg I found in Google.

My impression on them is, they are mainly, the things to do with “Numbers” and there are only two language options Java 1.7 and Python 2.7 (for now), to submit your solutions, so you need to know the basic data-structure APIs in the respective languages (I had to learn about Java Collections for one of the puzzles). No third party packages allowed for Java and for Python also there is a restriction. The attempts I made are kind of militarily related fantasies yet interesting.  I thought to share a very simple one I solved, for which I took around 30 mins to crack it, find a formula and program it. Google gave me 72 hours to solve it, it’s plenty.

Capture

The Problem – as Google Says

Keeping track of Commander Lambda’s many bunny prisoners is starting to get tricky. You’ve been tasked with writing a program to match bunny prisoner IDs to cell locations.
The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda’s space station, and as a result, the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given numerical IDs starting from the corner, as follows:

| 7
| 4 8
| 2 5 9
| 1 3 6 10

Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y is the height from the ground.
For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners).

Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your answer as a string representation of the number.

Solution

So, what they have given here is a number sequence. So if you do some work on this
| 7   12  18   25
| 4    8   13   19
| 2    5    9    14
| 1    3    6    10

You’d get a 2D array.

Now if you take the first slice of it, I get 1,2,4,7 – This can be formulated for [n (n-1) / 2] + 1 where n is the place of the number starting with 1.

Let’s take the second slice, 3,5,8,12 – This also can be formulated to [(n+1)(n) / 2] + 2 again where n is the place of the number starting with 1.

If you see both of the above formulas, there is a pattern, where the counts related to “n” is getting increased by one with the last constant we add. To make our observation on this pattern is correct, let’s analyze the third slice, 6,9,13,18 – and that can be formulated for [(n+2)(n+1) / 2] + 3 where n starts with 1. So we can come to the conclusion that the observed pattern is the one we are looking for.

With this we can get a general formula for the 2D array as below

{[(x + [n – 1])] [([x – 1] + [n – 1])]} / 2 + x

if we normalize this

[(x + n – 1)(x + n – 2)] / 2 + x

Here x is the horizontal position of an element and n is the vertical one, both start from 1. Also we can say n as y since they have mentioned it as y in the problem.

Finally,

[(x + y – 1)(x + y – 2)] / 2 + x

So we’ve derived the formula now and convert this to python.

def answer(x, y):
  z = ((x+y-1)*(x+y-2))/2 + x
  return str(z);

That’s it! This is the solution for the puzzle. Very simple, yes?

Conclusion 

foo.bars from Google are really interesting, you’ll get plenty of time to solve them varying from 48 hours to 72 hours. Find them and solve them – Good Luck – You might land a job at Google Inc.

Link 

Google for it – Good luck again.

Xamarin : Reducing FindViewById() Boilerplate with Genetics

Featured

Tags

,

Often we feel bored with the classic Android Layout finder, the most famous FindViewById() guy. To overcome this recently I found a solution, a Xamarin component called Genetics. This is annotation based DI library and quite easy to use.

To use this, you need to add the component and follow the example. Here is a very simplified version of the same example,

using Android.App;
using Android.Widget;
using Android.OS;
using Genetics.Attributes;
using Genetics;
using System;

namespace GeneInjectTest
{
    [Activity(Label = "GeneInjectTest", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        [SpliceClick(Resource.Id.myButton)]
        private void MyButtonClicked(object sender, EventArgs e)
        {
            Toast.MakeText(this, "ButtonPressed!", ToastLength.Short).Show();
        }
        
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Geneticist.Splice(this);
        }
    }
}

The beauty is, you do need to initialize a button – yeah thats why we use DI in general. But if you need to initialize a button all you need is to call

[Splice(Resource.Id.myButton)]
private Button myButton;

simple nah.

Also this provides make more possibilities as documented. Keep exploring and happy coding.

SQL Server On Linux : ASP WebAPI2 POC

Featured

A good achievement of mine in 2016 was convincing a Friend from Netherlands to use Microsoft Azure to deploy back-end for his mobile app. We had a very long conversation after office hours and he was arguing, instead of Azure, he can host his DB server locally and do the stuff, he had a point, all my arguments were about scaling and enterprise level security but most of the time DEVELOPERS always need to get hands dirty. Also earlier this month another friend of mine wanted me to develop an app for his idea. Developing an app and hosting the app services on Azure is not a big deal but this time I wanted to try things and get hands dirty. Even though my experiences with MySQL and Mongo,  I didn’t try hosting a SQL Server DB before (out side my office work) since “money” but, I thought to try with the new SQL Server on Linux offering, for which I don’t need to care about “money”.

Machine

Didn’t wanted to risk my Acer Aspire P3 tab with Ubuntu 16.04 since many people use it on weekends. But that would be an ideal way of doing it. So decided to create a cheap Ubuntu 16.04 VM on Azure. I have chosen F2 type VM with 4Gigs of RAM residing on East US 2. Its probably the cheapest on since you need 3.5 Gigs of RAM for installing SQL Server on Ubuntu.

azfseriesvms

Installing SQL Server

Its just the matter of executing some commands from SSH. I used WebSSH. But most of the people ( and me also most of the time) use PuTTY. I didn’t install any desktop envs on this machine. Since, Ubuntu executed the following commands (also provided in the documentation)

curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

curl https://packages.microsoft.com/config/ubuntu/16.04/mssql-server.list | sudo tee /etc/apt/sources.list.d/mssql-server.list

sudo apt-get update

sudo apt-get install -y mssql-server

 

Done with installation. Now we have to run the configuration script came with the installation where we need to configure SA account, its just about giving password for the account and set the SQL Server service to start on logon. So, execute. Give password for SA and say “Y” to start the service on startup.

sudo /opt/mssql/bin/sqlservr-setup

After this, verify if things went smoothly by executing

systemctl status mssql-server

 

To install SQL Server tools for Linux be executing the following set of commands

curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | sudo tee /etc/apt/sources.list.d/msprod.list

sudo apt-get update 

sudo apt-get install mssql-tools unixodbc-dev

And to create symlinks to ‘SQLCMD’ and ‘BCP’ under /usr/bin/

ln -sfn /opt/mssql-tools/bin/sqlcmd-13.0.1.0 /usr/bin/sqlcmd 

ln -sfn /opt/mssql-tools/bin/bcp-13.0.1.0 /usr/bin/bcp

 

Endpoint Configuration

Go to the ENDPOINTS tab on VM’s windows and click ADD to add MSSQL and leave the default settings (if Public Port is not set to 1433, set it and save).

azvmports

Now you are OK to connect to the SQL Service service hosted on the VM remotely.

Accessing DB Remotely

Before this, we need to create a Database on our newly created service. So go back to SSH and execute the following

sqlcmd -S localhost -U SA -P '[SA_Password]'

CREATE DATABASE quickcustinfo_db;
GO

Now we have created a new database called quickcustinfo_db.

Go to Visual Studio -> Server Explorer -> Connect To Database

connectiondetails

Note that I have selected SQL Server Authentication and gave SA and my password (this is kind of risky business, still for my POC I have decided to go like this, BUT MANIPULATING DATABASE AS “SA” FROM CLIENT APPLICATIONS IS NOT ADVISED). When I populate the combo box to select database name I will be able to see “quickcustinfo_db”. Select it and Press OK.

Go to the properties of this database and copy the connection string. It will look like

Data Source=qcidbserv.cloudapp.net;Initial Catalog=quickcustinfo_db;User ID=SA;Password=***********

Copy and paste it in a notepad and replace *********** with actual password.

ASP Web API2 Application – Web.config

My idea is to use EF. So created a new WebAPI2 application. Here in the Web.config file, we need to give the above connection string by replacing the default one. So we can avoid data to be seeded and manipulated on (localdb) and put them to our remote database hosted on Linux. So I did the changes like below.

  
    <add name="QuickCustInfoContext" connectionString="Data Source=qcidbserv.cloudapp.net;Initial Catalog=quickcustinfo_db;User ID=SA; Password = '[my_sa_pwd]'"
      providerName="System.Data.SqlClient" />
  

Now its all about creating models and seed the data.

Models

For this POC, I created two models

  • Customer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace QuickCustInfo.Models
{
    public class Customer
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
    }
}
  • Invoice.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace QuickCustInfo.Models
{
    public class Invoice
    {
        public int Id { get; set; }
        [Required]
        public string Title { get; set; }
        public string ShortDesc { get; set; }

        // Foreign Key
        public int CustomerId { get; set; }
        // Navigation property
        public Customer Customer { get; set; }
    }
}

 

Contollers and DataContext

Also create a contoller with option “WebAPI2 controller with actions using Entity Framework” (this is one of the coolest feature I love). Select Customer model first and give a new generic DataContext class and controller name. Do the same for Invoice model with the same DataContext class. Rebuild the project.

In the package manager console execute

Enable-Migrations

 

Now expand the newly created Migrations folder in solution explorer and open Configuration.cs and modify Seed() like below.

namespace QuickCustInfo.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using QuickCustInfo.Models;

    internal sealed class Configuration : DbMigrationsConfiguration
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(QuickCustInfo.Models.QuickCustInfoContext context)
        {
            context.Customers.AddOrUpdate(x => x.Id,
                new Customer() { Id = 1, Name = "Anne" },
                new Customer() { Id = 2, Name = "John" },
                new Customer() { Id = 3, Name = "Balmer" },
                new Customer() { Id = 4, Name = "Trump" }
                );

            context.Invoices.AddOrUpdate(x => x.Id,
                new Invoice() { Id = 100, CustomerId = 1, Title = "Paint", ShortDesc = "Blue Color Paint" },
                new Invoice() { Id = 101, CustomerId = 3, Title = "Pen", ShortDesc = "Red Color Pen" },
                new Invoice() { Id = 102, CustomerId = 2, Title = "Shirt", ShortDesc = "Deedat TShirt" },
                new Invoice() { Id = 103, CustomerId = 4, Title = "Paper", ShortDesc = "Waste Paper" }
                );
        }
    }
}

Note the DbMigrationConfiguration is typed with the thing we gave earlier – QuickCustInfo.Models.QuickCustInfoContext (DataContext).

Again in the Package Manager Console

Add-Migration Initial
Update-Database

Thats it, DONE 🙂

Make Sure Things Went Well

Go to the SSH again, open SQLCMD and execute the below

USE quickcustinfo_db;
SELECT * FROM CUSTOMERS;
GO

and if everything went well,

sqlstatement

Whats Next

Host the WebAPI project to a free tier Azure Web Service offering and call the APIs from your Clients to do the CRUD operation.

Conclusion

POC was successful and make this without any expenses is just the matter of hosting the SQL Server on a local Ubuntu machine.

Things are possible and happy coding.

C# : My Verdict on Pointers

Featured

Tags

,

Originally from here

Earlier I have already published a post on Pointers, which are very fascinating things in C and C++.

A pointer is a variable valued with the memory address another variable. Pointers maintain a common rule, like a variable or constant we need to define a pointer in order to store the variable or constant’s address. Pointers are very efficient, because we directly access to memory location with out code and much closer to the machine language. C# provides Pointer facility to us. But the limitation we have in C# pointers is we can hold only the memory address of value types and arrays. Sometimes this is an advantage because there is no real need of holding memory address of reference types as they might cause us deadlocks.

We define pointers in C# as they are defined in C / C++
[type] *[variable-name];
for example,
int *x;

Lets see an example, where we declare an instance data int a = 15; then declare a pointer which holds the memory location of the instance data a. So the code goes like

int a = 15;
int *pointer = &a;

remember, the followings are also valid, the place of * really doesn’t matter

int a = 15;
int* pointer = &a;

int a = 15;
int * pointer = &a;

but to maintain the code quality and naming conventions we use int *pointer. Now lets make this example real and try to make a console application with this.

using System;

namespace TestPointer
{
    class Program
    {
        static void Main(string[] args)
        {
             int a = 15;
             int* pointer = &a;
             Console.WriteLine(a);
             Console.WriteLine((int)pointer);
             Console.ReadLine();
        }
    }
}

This will return a compile time error, saying

first error

 

 

C# compiler never allow pointer operations by default, however using unsafe keyword we can define unsafe context where pointers can be used. So lets define it,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
using System;

namespace TestPointer
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 15;
            Console.WriteLine(a);
            unsafe
            {
                int* pointer = &a;
                Console.WriteLine((int)pointer);
            }
            Console.ReadLine();
        }
    }
}

Now you can see, from line 13 to 14 we are using pointers and we should define unsafe context for those two lines, Its not a good practice to make unsafe context for all code. Now if we want to run this code, we again get another error

second error

As I mentioned above C# compiler does not allow unsafe codes, we have mentioned the compiler, that we have a unsafe part in our code by defining unsafe context now we have to instruct compiler to compile the code with unsafe. If you use csc.exe to compile the code with command prompt, you have to call csc.exe with /unsafe parameter. So if I want to compile my code with command prompt, I can say,
csc.exe /unsafe TestPointer.cs
Or I can use project properties, and under the “Build” tab of the project properties, I have “Allow Unsafe code”
allow unsafe code
If I run the above code after saving the project properties,
output

using fixed
Garbage collector automatically erase the instance variable a after it becomes unusable. Since objects in the memory are movable this makes garbage collection possible, but when we perform a pointer operation, the data should be in a fixed memory location, so we use fixed keyword. Remember you can’t use local variables, value parameters, and variables created by dereferencing pointers under fixed context, as the location of the variable is already fixed (you can refer more here)

Lets have a look at the example,

class Program
{
    unsafe static void Main(string[] args)
    {
        fixed (int * pointer = &Line.color)
        {
            Console.WriteLine((int)pointer);
        }

        Line line = new Line();
        fixed (int* pointer = &line.a)
        {
            Console.WriteLine((int)pointer);
        }

        Console.ReadLine();
    }
}

class Line
{
    public static int color;
    public int a;
}

But the below code will return a compile time error.

class Program
{
    unsafe static void Main(string[] args)
    {
        int a;
        fixed (int * pointer = &a)
        {
            Console.WriteLine((int)pointer);
        }

        Console.ReadLine();
    }
}

as we are using a already fixed variable.

Conclusion

Really there is no need for using pointers in C#, unless you are using an assembly from C++ that uses pointer. But as a programmer in C# you should know C# has the ability to perform pointer operation.

Happy coding.

Azure Analysis Services

Featured

Tags

, , , ,

Finally “True DevOps” became real for a BI Engineer / Analyst with the introduction of Azure Analysis Services. Even though there are lots of “In Cloud Analysis Services” service providers exist since recent past, nothing was able to reach the capabilities provided by the “On-Premise Microsoft Analysis Services” solution.  With the introduction of Power BI almost everyone was expecting Microsoft’s Analysis Services solution in cloud and with the recent public preview to Azure Analysis Services, Microsoft really made us happy.

2016 – A Happy Year For Microsoft BI Stack Engineers

Microsoft BI stack is a combination of SS*S tools. They are SSIS (SQL Server Integration Services), SSRS (SQL Server Reporting Services) and SSAS (SQL Server Analysis Services). With SQL Server 2016, Microsoft introduced SSIS with cloud, where engineers can create flows to read from and write to cloud storages and connect to Azure data sources. On the other hand, Power BI was highly motivated and recommended to visualize the data. So when it comes to Cloud-based Microsoft BI stack, the missing part was Analysis Services. Now almost near to the end of 2016, Microsoft announced Azure Analysis Services. So, you don’t need to worry about maintaining an on-premise infrastructure for your MS BI solution, just deploy them in cloud.

No Cubes

Current (preview) offering does support tabular models at 1200 compatibility level, which means it runs on SQL Server 2016 instances only. Thus you can only use SSDT for Visual Studio 2015. Unfortunately, there is no support for Cubes (but I found in some Microsoft documents, saying it’s coming soon).

On-Premises Data Gateway

Similar “On-Premises Data Gateway” that used in Power BI can be used to refresh the cloud data in the model.

  1. The gateway cloud service analyzes the query and pushes the request to an Azure Service Bus.
  2. The on-premises gateway polls the Azure Service Bus for pending requests.
  3. The gateway then gets the query, decrypts the credentials, and connects to the data source for execution.
  4. The results are then sent from the data source, back to the gateway and then on to the Azure Analysis Services database.

How to Deploy – With On-Premise Data

This is the most common scenario and It’s very easy.

  1. Loing in Azure Portal and create an Analysis services resource. (When it comes to Roles, Microsoft accounts are not supported. You have to have an account configured with Azure Active Directory).
  2. Download, install, configure and run On-premises data gateway.
  3. Open an existing Tabular project.
  4. Go to Project properties and change “Server” as your Azure Analysis Service server name (which looks like “asazure://[region]..asazure.windows.net/[your instance name])
  5. azureanalysisservices
  6. Finally, deploy the project – Simple.

How to Deploy – Data Stored in Cloud

This is more futuristic scenario, where your data is stored in any form of cloud storage supported by SQL Server Analysis Services. If already created a tabular project to use these data sources, all you have to do is, just change the deployment server name (as mentioned in step 4 above) and deploy the project. Else, you can simply create a Tabular project to use those data sources and deploy them to the newly created Azure Analysis Service.

Options For Cubes

Unfortunately, Microsoft is really focusing on Tabular Model. Its true that their Cube solution is really matured and yeah, it lacks the very latest cloud possibilites. Microsoft, these days seems putting more priorities and investments towards Tabular Model which supports both MDX and DAX. As I mentioned earlier, I found some document saying Cube is coming soon (if I remember properly I saw a video demo, where this guy demos Cubes).

It really worth waiting but if you can’t keep calm, you can always use one of the SQL Server Business Intelligence in Azure Virtual Machines.

Good Luck.

C# : var and Code Writability – Readability Issues

Featured

Tags

, , ,

Recently got a subscription of ReSharper in my company. I am using Visual Studio since 6.0 and its the best IDE ever, probably the best Microsoft product also and after using VS without a tool like ReSharper than all of the sudden installing it and restarting VS, I felt like, WTH delay to open this IDE. My first impression of ReSharper is “They should have made it light weight”.

That is ReSharper’s story and one thing I noticed is the ‘HEAVY’ usage of var in ReSharper. ReSharper does this since he/she/it (hereafter I will call it as he, coz a good friend these days) obviously not a “data aware system” and he really don’t know why we are going to use that data.

So whenever ReSharper say var is that like, we must use, var number = 1990; instead of int number =1992;. For me obviously NO and we shouldn’t do it.

Code Writability
When it comes to code writability, if you think in terms of ‘Extreme Productivity’ and ‘Saving nano seconds’ you could go with var IsReSharperGood = true; instead of bool IsReSharperGood = true; so you can save nano seconds when you code. But its generally good to go with var numbers = new List(){1,2,3,4,5}; rather than List<int> numbers = new List<int>(){1,2,3,4,5};.because you save sometime by not typing 6 characters. other than built-in data types, var is really useful when it comes to other data types. But is this what we really need?

Code Readability
Is software all about writing code? NO. People define a best programmer on how reads and understand the code. In this video Bronwen Grimes says “You don’t have to be a genius to code, Do you have to be a genius to read?”. I don’t know if she mean “code reading” but if it is, my answer, probably is “yes, some kind of”. Because code is totally a different language like “Greek” or “Arabic” which is totally different from the grammar and literature of your language. So you have to be extra careful when reading it. This is why there is a job in the world called “Code Reviewers” exist and thats the main motivation to create something like GitHub.

Imagine you are reading a 14000 LOC class which has a not initiated & instantiated class variable defined as var animals; and when you scroll down to 11235th line you found animals.Add(cow); and in the 11236th line you need to get the count of animals by calling var numberOfAnimals = animals.Count by assuming animals is a List<T> and hit F5… DING..!!! ERROR. Because animals was not really a List<T>. It was a user defined type named Mammals which has a Add() method. You simply misunderstood this since it looked like a collection right? This is a very simple example and this is the place where we need to avoid var. Anther good example is var t = SomeMethod();, now you have to go to the definition of SomeMethod() to see what is that. You should always remember var has no backward compatibility, so you can migrate your code back to C# 2.0 and below (but is there a need for it in a production environment?)

Conclusion

large

This is it, you need to have var if you need your code to taste sweet but too much of it is not motivated. var came with LINQ. Think about the below

var query = from person in students
            where person.MathMarks> 75
            select new { FullName=person.Name, person.Department };

var is useful. For instances like this var is really helpful but not all the places in your code.

C# : Understanding Threads and ThreadPools

Featured

Tags

, , ,

Real world software uses concurrency. As you know concurrency has several advantages, main thing is it simulates several things in one time concept. .NET gives three ways for the developers to achieve concurrency while we write code. They are:

  1. Thread
  2. ThreadPool
  3. Task

Thread

These are very low level elements of concurrency. They have their own stack and OS level resources.

Dont confuse .NET Threads with OS threads actually Threads in .NET are CLR managed ones. We should technically call these threads as “CLR Threads”. Sometimes we call them as ‘Virtual Threads” while calling OS/kernal threads as “Physical Threads”.

When it comes to relationship between physical (kernal) and virtual (managed) threads, there is a one to many relationship between them. One managed thread can use one or more OS (kernal) threads. Its up to the Managed Scheduler  to decide. So a managed thread could use a Windows Fiber to achieve its execution instead of Windows Threads.

Managed threads provides highest degree of control to developers where we can Suspend()Abort() and Resume() threads even these are not a good practices. But they are costly, since they consume an unpredictable amount of memory in stack and they add additional processing overheads since context switch between threads.

In C#, you can do

using System;
using System.Threading;

class Program
{
    static int _progress = 0;
	
    static void Main()
    {
	Thread uiThread = new Thread(new ThreadStart(UpdateProgressBar));
	Thread dataThread = new Thread(new ThreadStart(MoveData));
	uiThread.Start();
	dataThread.Start();
	uiThread.Join();
	dataThread.Join();
    }

    static void UpdateProgressBar()
    {
	_progress++;
    }

    static void MoveData()
    {
	Thread.Sleep(1000);
	Console.WriteLine("Moving data");
    }
}

And even you can uiThread.Abort(). Currently there is no alternative for Thread in .NET with the highest degree of control. There is no maximum number of Threads in .NET, you can use as maximum as your resources allows you to do.

In Visual Studio you can debug threads in the application execution. When your application is running, go to Debug -> Windows -> Threads. In this windows you can search for an specific thread, group and short threads and freeze or thew threads. You can learn more about Threads Window here.

ThreadPool

ThreadPool is a collection of fixed numbered threads during the initialization of the application and then reuse them for new tasks then required. Now every executable has a fixed number of threads in them depending in the available free memory.

threadpool

Since ThreadPool uses a fixed number of threads every-time they won’t let used memory to grow dramatically like Threads do, there are safer than Threads. ThreadPools uses a queue that have Tasks and pick Tasks from the queue,  execute them and once completed put those tasks to another queue that contains the completed tasks.

We can use System.Threading.ThreadPool to create thread pools in .NET and no need to specify how many threads should be there is the pool. ThreadPool manages itself.

ThreadPool class does the following activities

  • Execute tasks
  • post work items
  • Process asynchronous I/O
  • Wait on behalf of other threads
  • Process timers

We can implement ThreadPool as below

using System;
using System.Threading;

class Program
{
	public static void Main()
	{
		// Queue the task.
		ThreadPool.QueueUserWorkItem(ThreadPoolMethod);
		Console.WriteLine("Main thread starts");
                Thread.Sleep(1000);		
		Console.WriteLine("Main thread exits.");
		Console.ReadKey();
	}

	static void ThreadPoolMethod(Object stateInfo)
	{
		Console.WriteLine("Hello from the thread pool.");
	}
}

this will give output like

---------------------------
Main thread starts
Hello from the thread pool.
Main thread exits.
---------------------------

If we comment Thread.Sleep(1000); line, you can notice, Main thread exits before thread pool method gets executed. Using this we can understand ThreadPool used background threads they wont keep the program running once all foreground threads get terminated.

You can define the number of threads to be handled in Threadpool via ThreadPool.SetMaxThreads and ThreadPool.SetMinThreads but its a best practice not to set them and let CLR handles with the default value. In .NET 2.0 and 3.0 the default value of MaxThread has a direct relation with the CPU cores. In .NET 2.0, it was 50 times of CPU cores and in .NET 3.0 it was 250 times of CPU cores but after .NET 4.0 it depends on several other factors also such as the size of virtual address space. You can always determine this by calling ThreadPool.GetMaxThreads. Another useful method is ThreadPool.GetAvailableThreads.

Conclusion is, concurrency in .NET is sexy but you have to be very careful when you handle this, else you will end up in a total disaster. Despite, having some limitations, Threadpool has more advantages over Threads but Tasks are the best practice when we think about concurrency in .NET still they have more limitations yet they are safer than Threadpool or Thread. I will cover them in next post.

=lorem(20,18)

Featured

Tags

, ,

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet nonummy augue. Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy. Fusce aliquet pede non pede. Suspendisse dapibus lorem pellentesque magna. Integer nulla.

Continue reading

C# : Dependency Injection, Simplified

Featured

Tags

, , , , , ,

It has been a buzz word for some intermediate level C# developers, ‘Dependency Injection’ is sometimes really hard to understand because we couldn’t understand the need for it.

In simple words, think about the scenario where you are developing an application which saves some data in a file and that file handling. You might code something like below initially

using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
    sw.WriteLine(something);
}

Here we are defining

  1. Which file to communicate (fileName)
  2. Where to access the file and (the file path which is appended in fileName)
  3. How to access it (other params of the fs object)

Then think about what if we suddenly think we are not going to write this on a File instead we are going for SQLite or some other options. So, it need a complete rewrite of this right. Its ideally something like “We are changing a lot of code in the client”. Here client is that who leverages the service from the file (or DB, in the new (future) scenario).

To handle this scenario there are two common practices.

  1. In client embed the logic of locating the service
  2. Tell the client about some dependency and make an external code which will help the client to find the service.

Both of these are more similar. Its like to achieve practice 1, one easier option is to use practice 2. So we call this as “Dependency Injection” and that extra code we call as “Dependency Injection Framework”. Things like Spring Framework and Hivemind dose the “Dependency Injection Framework” role. Scott Hanselman has a list of them for .NET.

befunky_injection-83290870.jpg

IoC vs DI

IoC, Inversion of Control, people confuse this with Dependency Injection. But understand IoC is a generic team, meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

DI is a form of IoC, it is a solid term, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.

Code demo

public class Computer 
{
	private CPUArchitecture _cpuArch;

	public Computer() 
	{
		this._cpuArch = new CPUArchitecture(); // Computer depends on CPUArchitecture
	}

	public void Add() 
	{
		// Do some add algorithm here
	}
}

public static void Main(string[] args) 
{
	Computer myComputer = new Computer();
	myComputer.Add();
}

Yeah each CPU architecture performs separate functions to perform same functionality. But just think about we are changing the CPUArchitecture to another in future.

public class Computer 
{
	private CPUArchitecture _cpuArch;

	public Computer(CPUArchitecture _cpuArch) // Computer now takes its dependencies as arguments
	{ 
		this._cpuArch = _cpuArch; // No 'new'
	}

	public void DoSomeStuff() {
		// Do something with _cpuArch here
	}
}

public static void Main(string[] args) 
{
	CPUArchitecture cpuArch = new CPUArchitecture(); // CPUArchitecture is constructed here instead
	Computer myComputer = new Computer(cpuArch);
	myComputer.DoSomeStuff();
}

This is a type of a Dependency Injection we call it as Constructor Injection. But this is clear enough to demonstrate the need of why we should inject the dependencies. Hope to meet you with another post with Advanced DI.

C#: BitArray and use-cases

Featured

Tags

, , ,

I started C# programming with a image manipulation program, it was a Windows Phone application and it was a very huge project compared to apps we have now for smart phone. Unfortunately we are still hiding it from the public because people never respect the value of that software when we demo-ed it to some so called Techies in 2013. Six months later, I had “Digital Image Processing” course work my degree program which taught me the real behind the scenes of what I wrote as a code earlier.

Continue reading

C#: a = a + b; and a += b; Are Two Different Things

Featured

Tags

, , , , , ,

After this post, someone contacted me personally and said he is very impressed with this article personally this is the first time someone call or email me for one of my blog post it sounds great right. Last friday, it started in a perfect manner. I got up and got a notification in Viber, same close person from out side Sri Lanka sent me this

AA Isham I want a simple question on the same topic (types and casting) to determine his C# knowledge.

I replied him

Ask for the difference between a = a + b; and a += b;

Funny question right, because all the books and our teachers taught both of them are same. When we were beginners we wrote some code, that returned same results and after we grow up a bit we checked IL code, yeah thats also same like the below,

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       12 (0xc)
  .maxstack  2
  .locals init ([0] int32 a,
           [1] int32 b)
  IL_0000:  nop
  IL_0001:  ldc.i4.s   10
  IL_0003:  stloc.0
  IL_0004:  ldc.i4.s   10
  IL_0006:  stloc.1
  IL_0007:  ldloc.0
  IL_0008:  ldloc.1
  IL_0009:  add
  IL_000a:  stloc.0
  IL_000b:  ret
} // end of method Program::Main

for both of the below,

static void Main(string[] args)
{
    int a = 10;
    int b = 10;
    a = a + b;
}

and

static void Main(string[] args)
{
    int a = 10;
    int b = 10;
    a += b;
}

so what the difference could be, and this seems a foolish question and answer should be “No differences” right? but you are wrong.

293906a

You want proof, okay open Visual Studio, make it two (shift + click on the VS icon on taskbar) make two console applications and write below on each of them

static void Main(string[] args)
{
    short a = 10;
    short b = 10;
    a = a + b;
}
static void Main(string[] args)
{
    short a = 10;
    short b = 10;
    a += b;
}

VS will tell the first one is buggy. Leave it and run the second one, it will run without any errors.

short + short = int

Because this is how C# designers see it. In C# size order for Integral types comes like byte < char < short < int < long and practically type int can cover “most” calculations. Programmers rarely use short or byte when it comes to complex arithmetic. I mean we don’t “practically see 10 short values are added and multiplied and divided and again assigned to short you know. You might argue, but its the “practical” truth and add CIL instruction is optimized towards int. 16 bit arithmetic are too slow. And yeah, arithmetic operations in short are 16 bit ones. If you are interested on why this is slow, read this.

But still they gave option, that runs a += b because there should be an option for adding at-least two short or lesser types and add push it to a short type variable right. So to cover this what they have done is, they added an additional conv.i2 statement which does the job of casting the operation to Int16. For the last code piece above I got the IL code like below

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       13 (0xd)
  .maxstack  2
  .locals init ([0] int16 a,
           [1] int16 b)
  IL_0000:  nop
  IL_0001:  ldc.i4.s   10
  IL_0003:  stloc.0
  IL_0004:  ldc.i4.s   10
  IL_0006:  stloc.1
  IL_0007:  ldloc.0
  IL_0008:  ldloc.1
  IL_0009:  add
  IL_000a:  conv.i2
  IL_000b:  stloc.0
  IL_000c:  ret
} // end of method Program::Main

So, its something like, a += b means a = (short)(a + b);. Which makes your code size bit more than if you have used int. Look at the above IL code also there, the code size is 13 but for the same code size if I have used int it is 12 (look at the first IL code).

So in best practice, do think too small means too optimal really it will cost some other way you don’t know. Read C# specifications well. I mainly want this to who write code in Xamarin free subscription because they have an IL code limitation.

C#: Casting and Type Checking

Featured

Tags

, , , , , , , ,

We all know and have experienced the importance we have for castings in C#. Its just essential if you want to build any system that takes inputs, process and give output. What a basic computer does is the same functionality right? so logically we need casting
EVERYWHERE in computing. Even you can argue, “I am a C# programmer, I write a console application that takes two integers, calculate their sum of it and print the output, so where I have to cast here?” my answer is “CLR does this”.

morph_full

Casts vs Conversion

In simple and understandable words, “casts are basically explicit conversion”. In internal conversions we can pretty much ensure on three things

  1. No special syntax required
  2. They are type safe
  3. No data-loss

Normally we can take conversions from smaller to larger integral types and conversions from derived classes to base classes as good examples for this type of internal conversions. Explicit conversions, require a cast operator. We have to explicitly say the
compiler to forcefully convert the type. So there might be a very possible data-loss.

double pi = 22/7;
int a = (int)pi;

(Un)Boxing vs Casting

Honestly (Un)Boxing is a subset of casting. Boxing means CLI consider a value type as reference type (that involves copying the contents of that particular value type which is on stack to the heap and returning a
reference to the particular object
). This lets a value type to be passed wherever a compatible reference type is expected and also this allows virtual method calls and some other features of reference types to be processed on the value type. Unboxing
is the reverse of this boxing operation (getting back a value type out of a boxed object). Casting is taking a type (say, System.Int32) and consider it as another type (say, System.Double). When you box something in C#, you are casting it to another type.
The difference is that it allocates additional memory as a new reference type is created.

// just a variable 
int number = 0;

// boxing it
object boxed_number = number;

// unboxing (avtually a type casting)
int unboxed_number = (int)boxed_number;

 

as and is

as and is are used in C# to safely cast things. Since C# objects are polymorphic its possible that a base class type variable can hold a derived type so to access the derived type’s method, it is necessary to cast the
value back to the derived type. However this has a risk of InvalidCastException. This is where
as and is comes to the play. is is used to check the compatibility of two objects with a given type and returns
true or false. While as can used only with reference type and will return
null if casting fails. basically

Animal s = cat as Animal;

//above is equivalent to below

Animal s = cat is Animal ? (Animal)obj : (Animal)null;

 

as Makes Readable Code

Think of the below code piece,

(Bat as Mammal).Walk();

Simply you can argue, this is a confusing and a useless way since we are using
as
keyword we are not sure about if BAT is a type of MAMMAL and yet we are invoking a method. And even worse, this code piece can make a meaningful
InvalidCastException to a NullReferenceException we all hate it. But why in some places they have mentioned this kind of a code piece? this is where code readability comes to mind. We know if we are using
as, we are sure about this object can be converted to that type but if it can’t we are happy to accept a
null. However as I said before as can only be used with reference types, by using this style of coding, we can tell code reader that the code involves only reference or unboxing conversions, and furthermore, that BAT is not null.
typeof vs is
typeof and is does almost the same but by stating
is
we can say it can be a derived type or from interface. So again using
is
in necessary places ensures code readability and sometimes. Still to use
typeof properly we have to use GetType()

if (obj1.GetType() == typeof(int));
if (obj1 is int);

 

typeof() vs GetType()

Even though GetType() can be used closely to work with typeof there is a slight different.
typeof is used when you want to get the Type instance representing a specific type.
GetType() gives the runtime type of the object on which it is called, which may be different from the declared type. The below example make a clarification on it.

class A {}

class B : A {}

class Program
{
    static A CreateA()
    {
        return new B();
    }

    static void Main()
    { 
        A a = CreateA();
        Console.WriteLine(typeof(A));     // Writes "A"
        Console.WriteLine(a.GetType());   // Writes "B"
    }
}

Always remember, GetType actually queries a specific assembly (at runtime) for a type that might be defined within the assembly (Similar to new Object().GetType()). typeof on the other hand is determined at compile time.

Using GetType() in some instances might lead us to a null related exception, since this function has been defined something like below

[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();

So when we call this, this will only check from the calling assembly and some few other system assemblies (probably System and mscorlib). It does not check every assembly. So the string parameter inside GetType() sometimes needed to be a fully-qualified assembly
name. Thus in performance, typeof() takes little time than GetType() to get executed. Consider the example below

string name = typeof(Form).AssemblyQualifiedName;
Console.WriteLine(name);

Type type = Type.GetType(name);
Console.WriteLine(type);

This will return the following output

System.Windows.Forms.Form, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Windows.Forms.Form

I hope this will make more sense when you try to understand the above scenario.

This artcle, I originally wrote for Technet. http://social.technet.microsoft.com/wiki/contents/articles/32293.c-casting-and-type-checking.aspx

Variable Parameters, a forgotten classic

Featured

Tags

, , ,

Its was 2004, when I was started to study Pascal lang. I was a better code writer (remember, those days, we write code first on a book,  then we re-write on a MS-DOS machine and compile it) and one day our instructor asked us to write a program to calculate average marks of the students. He didn’t mention, for how many students we are going to calculate the average. I don’t know how other wrote the code, though in that class only 3 were regular attendees, we never look in to others books, we thought it as a very very bad habit. So I write a for loop (I am in love with “for loop” since 2004 and “foreach” since 2011) that iterates some x times (say 10 times, I forgot the exact number that I used) and asked for marks and add it to a predefined variable and then divide the sum with x and print the answer. This was praised by instructor. I was a very beginner to programming and this approach was an excellent one for people like that. This might be the same way how you also have done when your early programming ages.

Now, suppose if someone comes to you and ask to do the same program for un-known number of people, you might use some data structures (List, Stacks, LinkedLists) to make this happen. But you know there is a better, memory saving approach to this. Thats what we call as Variable Parameters. This is a classic concept for most people don’t use this these days in favor of data structures. This is a kind of polymorphism but still really efficient.

A simple example for this in C# might be

using System.IO;
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(string.Format("Maths average for Grade 6 students are {0}",avg(10,20)));
        Console.WriteLine(string.Format("Maths average for Grade 7 students are {0}",avg(20,56,75)));
        Console.WriteLine(string.Format("Maths average for Grade 8 students are {0}",avg(45,36,95,75,46,86,24,59,54)));
        Console.WriteLine(string.Format("Maths average for Grade 9 students are {0}",avg(56,69,75,48,35,91,54,24,75,95,75,14,35,95,00,54,75,55,77,96,89,59,77,66,33)));
        Console.WriteLine(string.Format("Maths average for Grade 10 students are {0}",avg(45,88,66,33,44,77,22,88)));
        Console.WriteLine(string.Format("Maths average for Grade 11 students are {0}",avg(00,00,00,00,00,01,01)));
    }
    
    static double avg(params int[] marks)
    {
        double sum=marks.Sum();
        return sum/marks.Length;
    }
}

Just look at the method avg, that has been implemented with params keyword with int[] this means, this tells that the method has the ability to take variable number of arguments with same data type (here int).

But be careful when you define a param method and be sure to make the param parameter is coming as the very last parameter

public static int SomeCalcFunc(int a, int b, params int[] args)
{
    return args.Sum() + 2 * (a/b);
}

Some extra tips
Comparing to regular method invocations params methods are slower, while they are really useful when designing a library for other programmers to widely use. If you have complete control over all usages of the method, you may not need params because you can simply add the necessary overloads.

New Themes support in Visual Studio Code

Featured

Tags

, , ,

After reading the latest VS Code insiders mail on 9/01/15 I was quite happy because they said, new colour theme support is coming with the 0.8.0 update. Two months before I wrote a post on how to hack VS Code to get colour theme support. And its really happy to see VS Code developers have added this feature finally and with some more surprises.
Code theme
As you can see in the above gif, you can type “theme” in Command Plate or you can get it from File -> Preference -> Color Theme.

At the same time, you can add more themes since, VS Code supports .tmTheme file. So you can download them from http://colorsublime.com/ then move the .tmTheme to [VS Code Installation location]\resources\app\plugins\vs.theme.starterkit\themes and restart the VS Code.

You can edit the theme files as well, just open the .tmTheme and edit it.

Future works for me, I am now working on a Chrome Extension that automatically install new themes for VS Code.

Happy coding guys..

The 2015 General Election, Let The Board Decide

Featured

Tags

, ,

Lots of confusion among the people on who to vote. Specially in my Akkaraipattu because a well known politician is campaigning in a place where most people hate but still people want him. When I was thinking about this, I had an idea. Human make mistake but computers not. So what if let us give a chance to decide on whom to vote to the tiny chiped board that has x84 capabilities…

intel_galileo

Code

void setup() {
  Serial.begin(9600); 
  int x = random(20150817);
  x = x % 2;
  if (x ==1)
    Serial.print("Option 1");
  else
    Serial.print("Option 2");
}

void loop() {
}

Results

Untitled

Fibonacci on Intel Galileo Gen 2

Featured

Tags

, , ,

Fibonacci, I got to know about thing in a programming class back in 2004 when I was learning Turbo Pascal. Since that this is the next program I write after hello world when ever I try a new device, a new compiler or a new platform. The same story continues with the Intel Galileo Gen 2 also.
https://vine.co/v/epWdAvOaPK2/embed/simple
And this the the code…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  int i = 1;
  int a = 0;
  int b = 1;
  int c = 0;
  while (i<=1000)
  {
    f_blink(a);
    c = a + b;
    a = b;
    b = c;
    i++;
  }
   
}

void f_blink(int x)
{
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(x*500);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(x*500); 
}

How I am getting started with IoT

Featured

Tags

, , , , ,

Satheeq got a Intel Galileo from his office and I really don’t understand why he gave it to a girl who returned it back couple of months later without corrupting it.

So he gave it to me, I can do any experiments on it as our agreement says. What he gave was only a board with powersupply and I reused my USB cable and a RJ45 from him. The next saturday I rushed to Libery Plaza where I found a decent micro SD card for LKR 2200 (Life time warranty). Since I have only 5000/- left to survive until my next salary day and I have quite a good amount of money left to spend online I ebayed for cheap products.

Breadboard and Jumper cable wires

These two are very impotent for any electronics project and Lankatronics sell them for almost same amount available in ebay from top selleres from China. This product, I have just ordered comes with a breadboard with 400 tie points and 65 Jumper cables which costs USD 3.88. While same kind of breadboard is available in Lankatronics for LKR 250 and a single Jumper cable for LKR 5, so for 65 jumper cables it will be 325 and seems there is no big margin.

Sensors

This page attempts

Galileo is compatible with existing Arduino shields that fit the Arduino Uno R3

while Intel has a dedicated page for sensors and shields which are big costlier. So I searched though Ebay for Arduino Uno R3 compatible shields and I found quite cheap ones from China, in my personal opinion for a prototype or for a hobby project these kind of cheap ones are enough. Here are some interesting findings, they are from topsellers and having free International shipping

  1. Soil Hygrometer Detection Moisture Sensor Module for Arduino + Probe
  2. MQ-7 Carbon Monoxide CO Gas Sensor Detection Module For Arduino
  3. Water flow sensor flowmeter Hall flow sensor Module

These are just some examples there are more….

Wish me good for my IoT journey guys.. Do a prayer for me.!

Switch to Google : How I did It

Featured

Tags

, , , , ,

Last office week of Ramadan, at office I was waiting for Azure Remote app to import the disk image. It will take about 30 mins while everyone went for lunch. Yes, just a minute before I have published my third Google chrome extension, Switch to Google while I was alone with the PC. It employs chrome.pageAction API to put the icon on addressbar for a partucular URL.

screenshot

Sometimes this doesn’t make sense, why I have to use this? but for me, my default search engine is Bing for no reason and I find good search results there also, for some instances I have to come back to Google, and I was using a small trick there. Bing searches with http://www.bing.com/search?q=this+is+a+search while Google also follows the same thing https://www.google.com/search?q=this+is+a+search so I manually replace bing to google and today it took me 2 minutes to develop this one.

More technically, the manifest file goes like

{
  "name": "Switch to Google",
  "version": "1.0",
  "description": "Tired of being in Bing, on click solution to switch to Google is here",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "page_action" :
  {
    "default_icon" : "icon-19.png",
    "default_title" : "This is Bing"
  },
  "permissions" : [
    "declarativeContent"
  ],
  "icons" : {
    "48" : "icon-48.png",
    "128" : "icon-128.png"
  },
  "author": {
  "name": "Isham Mohamed .MI",
  "email": "ishammohamed@outlook.com",
  "url": "http://ishammohamed.me"
  },
  "manifest_version": 2
}

This points to a background.js file which looks like

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
  // Replace all rules ...
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    // With a new rule ...
    chrome.declarativeContent.onPageChanged.addRules([
      {
        // That fires when a page's URL contains a 'g' ...
        conditions: [
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { urlContains: 'bing.com/search' },
          })
        ],
        // And shows the extension's page action.
        actions: [ new chrome.declarativeContent.ShowPageAction() ]
      }
    ]);
  });
});

function checkForValidUrl(tabId, changeInfo, tab) {
  if (tab.url.indexOf('.bing.com') > -1) 
    chrome.pageAction.show(tabId);
};

chrome.tabs.onUpdated.addListener(checkForValidUrl);

chrome.pageAction.onClicked.addListener(function(tab){
  var currentURL = tab.url.replace("bing","google");
    chrome.tabs.update(tab.id, {url: currentURL});
});

The code is pretty much clear and I am doing the same replace thing with the help of this JS.

Angular For Dummies : Implement Instant Search

Featured

Tags

, , , ,

Disclaimer : This blog post is case sensitive.

Angular is replacing hard coded Ajax these days and its been a very good option as a jQuary alternatively. Honestly Angular and jQuery are two different things, Angular is a framework whole jQuery functions as a library, they have separate functionalities but most people who were depending on jQuery for everything is now coming to Angular because of some good builtin things in Angular such as templating, data binding and routing capabilities in single page apps.

I am not an Angular fanatic, but trying and experimenting something so I can learn the things. In this blog I am going to discuss about a Google Instant search like implementation in Angular

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<p>Name: <input type="text" ng-model="name.Name"></p>
<ul>
  <li ng-repeat="x in names | filter:name">
    <p ng-bind-template="{{x.Country }}"></p>
  </li>
</ul>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function (response) {$scope.names = response.records;});
});
</script>
</body>
</html>

This is a very simple HTML code I got from W3Schools and added some modifications. What this does is… TRY IT 🙂

Lets have a look at the code. Here I have a controller customersCtrl for the app myApp. The functionality of the controller is to fetch results from the URL http://www.w3schools.com/angular/customers.php go to the page and see how its formatted. This is how Angular fetch and decode JSON. The method we are using is $http.get. In case you are wondering what is an $http. Angular has a good documentation for it. On success callback on $http.get the controller created an application object property names. Remember $scope is the application object and $scope.names is its property which stores names which contains the records from the response we get from the $http.get call.

Now lets move to the DOM manipulation, typically we call it a View. There what happens is, we put a repeater with ng-repeat which repeats the items from names this is the same property that was previosuly $scope.names and its filtered with ng-model which is name which gets the Name from the response. Finally it will list Country which have the Name.

Try this code and try to implement your own, so you will get a very clear picture.

Visual Studio Code : A Hacking Guide

Featured

Tags

, , , , ,

We all know Visual Studio Code is a derived version of Atom text editor and Microsoft has added some pepper, salt and sugar to increase its taste so thats why they call it as an IDE rather than a text editor. Atom, it self declare it as a hackable text editor and even have documented how to hack it, but Visual Studio Code doesn’t, thought Microsoft has a page saying customizing visual studio code, they didn’t mention the core part.

I am an insider for Visual Studio code and received the binary for VS Code 0.4.0 for insiders. The email came with the binary attachments says not to distribute it outside because it might annoy users, so I am not giving it here. But today morning only I accidentally noticed there is “Toggle Developer Tools” under Help menu. To be honest I have never used Atom editor before and while drafting this post only I downloaded and installed and noticed the same option in Atom too.

menu togle

I thought this option is there to perform some other work so I clicked on it and found this.

sources

Man, this is opening Google Chrome developer tools. Soooo…. there should be some options to hack it as well and I found the following things. I am not going to more details and I assume you know how to debug a webpage in a browser with F12 tools. (applicable to IE as well :p )

Change background colour of the editor.

You can find it here

Untitled

 

Change font size

Untitled fint size

Remember when you close the IDE all changes will be deleted. So what you can do is change the style sheet manually, you can find it from %AppData%\..\Local\Code\app-{your current version || your current version+0.0.1}\resources\app\client\vs\monaco\ui\workbench\native This path for me comes like %AppData%\..\Local\Code\app-0.4.1\resources\app\client\vs\monaco\ui\workbench\native and under this native.main.cs. A very simple tweak you can try is, open this file and replace all #1E1E1E with #045FB4. Now restart the VS code.. BOOOOOOM…!!

What more…?? find them out and share to the community 🙂 happy {coding}

PS : If the images are too small click on them you will get a bigger image and navigate back for the page and since VS Code is in 0.x.x version level all the things described above are subjected to change.

Caching User Interface In Dynamic UI Scenario

Featured

Tags

, , , ,

Last month I wrote a post on LinkedIn about about a Proposed Model For Dynamic UI in Standalone Apps. I am continuously working on this and this has been a major research for me for couple of years.

We are living in a web centered world, all development tools providers focus on delivering their tools based on a web based stack. Think now we have built an app with dynamic user interface where UI is generated from a script pulled from a server and initially users of our app, what they see is a delay on launch of the app or, a ring something similar to this

But you know this is the same thing we get in browsers, so there seems no actual difference between our app and a browser based app, both loads a webpage and its obvious. Still we know the computations are native in app and only UI logic is coming from sever but the users of the app won’t get satisfied on this behavior.

We can overcome this issue by caching. Caching has been a great methodology for a while now. So the idea, simply is, we store previous UI we got from the server and load it on first launch of the app and if there is a new UI script available, lazy load it.

Why lazy load here?

The idea of Lazy load is, it delays the loading of resources in web related (mainly images in websites). And those images, or resources out of view port wont load until user scrolls there. In this way, we can render the cached UI and on scroll down or any kind of UI invocation, we can give a quick response to user with the new UI. Even we can use on touch event of screen. Again we have to make sure, we are not loading the entire new UI script here, instead we load the necessary part to render the initial view.

s4-flat

Where does the cached script goes?

This is a great question, we have several types of memories in our devices, from internal memories to cloud storage. But for the scenario and for the quick load time, we have to choose “App in memory”. All platforms support this memory and this is very quick to retrieve data. But this has a limitation on loading long scripts, and that’s why again we need to employ lazy load methodology here. If the cached code is way bigger, developers can consider compressing it, but think about compression and decompression time and do compression only if necessary.

That’s all I would like to share with you guys, regarding the caching. Hope to meet you soon with another post on this subject. Its about seeking the best data structure.. (for what??)

Stay thirsty.. Happy coding 🙂

Understanding statics in C#

Featured

Tags

The keyword static is a most confusing when its asked in exams and interviews and they might be the deciding factor sometimes for some companies.
Think this question

OK! I have a static class that implements an interface… and do you think its possible?

Wow.. simple question but we don’t use this kind of scenario in real world, so we go like
consfused

The actual answer is “NOPE” and here I am trying to describe the functionality of static in C#.

1. static class is real
Still some don’t know we have static classes in C#  those who come to C# from Java, they hate Java and they hate Java because they have to define an outer class and inside it they can have a nested static class, simply like

public class A
{

 public static class B
 {
 }
}

but this is useless because this static doesn’t really mean what the static is. This is just like you don’t need to create an object for A to instantiate B. So with this static,

B b = new B();

is a valid statement and you don’t really need to do

A a= new A();
B b = a.new B();

And again they hate Java because to achieve the real static class in Java, they have to make a final class or make a private constructor for the class or make all class members and functions static. This is a huge pain, so they hate Java. But in C# we just directly have

static class SomeStaticClass
{
    public static int Sum(int a, int b)
    {
        return a + b;
    }
}

Eeay piece right.. C# is sweet.
But don’t forget you can’t have instance members inside an static class all members should be static

static class SomeStaticClass
{
    static int a;
    public static int Sum(int a, int b)
    {
        return a + b;
    }
}

See the above example. As most people say DateTime is a best example for static classes, they are created when we need static object for utility classes.

To summerize this I can say, static class are

  • Only contains static member.
  • Can’t be inherited.
  • To be sealed.
  • Can’t contains instance constructor, it can be contains only static member & Private constructor.

2. No override, virtual, abstract in static
Remember an static member can not be marked as override, virtual, abstract this prevents the static member polymorphism and ensures the static functionality. Since static members are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.

3. Some interesting method calls, static base class methods

Look at the below code

public class A
{
    public static void Test()
    {
    }
}

public class B : A
{
}

class Program
{
    static void Main(string[] args)
    {
        B.Test();
    }
}

And do you think this is possible?
I bat, is possible. As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.

4. It really does’t make sense for a static abstract classes and interfaces

Yes it really doesn’t make sense because Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level and this is why overriding really doesn’t work as I said in (2).

5. Constructors

Static classes can not have instance constructors, but and instance class may have an static constructor. still static classes can have static constructor. Why have static constructor is to hold any static data. There is no other use actually. But denote the point that any static constructor in invoked before the default constructor. You can look at the below example

class Program
{
    static void Main(string[] args)
    {
        VM a = new VM(32);
        VM b = new VM(1500);
        Console.ReadKey();
    }
}

class VM
{
    public static readonly DateTime serverFarmStartTime;
    static VM()
    {
        serverFarmStartTime = DateTime.Now;
        Console.WriteLine("First server is avtivated on {0}", serverFarmStartTime);
    }

    public VM(int ovenNo)
    {
        Console.WriteLine("activating VM {0}", ovenNo);
    }
}

The output of this will be

First server is avtivated on 4/8/2015 10:25:03 PM
activating oven 32
activating oven 1500
  • These are some interesting points to remember when you are considering static constructors
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

6. Private static methods

Private static methods are useful sometimes, most of the time in helper / utility classes. They can be used methods that are exposed to outer world but yet not exposed to the outer world by them selves.

We can also have static properties as well, its with the same concept of properties that have static functionality. You can get a good picture on it with the below code

class Program
{
    static void Main(string[] args)
    {
        VM.HddSize = 1000;
        VM a = new VM();
        a.PrintHdd();
        Console.ReadKey();
    }
}

class VM
{
    public static int HddSize { get; set; }
    public void PrintHdd()
    {
        Console.WriteLine("HDD size is {0}", HddSize);
    }
}

I hope I cover the most, If I am missing anything just comment below. Happy coding 🙂

Quick and Easy localization with Xamarin

Featured

Tags

, , , , , , ,

Localization is a very good option an app can provide to users to increase the UX. Most apps from enterprise level to the very basic level, localization is very impotent if we need to target more audience with variety of cultures. Microsoft .NET framework provides us a concept called Satellite Assemblies they contains resource files for several cultures and enable developers easy to localize apps. Xamarin also provides this facility, we don’t need to do anything new but the same way to localize apps in .NET framework works for Xamarin too.

Blog images app in FR
In order to localize the apps first we need to create resource files with the respective cultures (“en-US”, “fr-FR”, “ru-RU”, “de”, “sv and etc.. Get the full list here).

The resource files maintain a naming convention that goes like [resource_file_name].[language_culture_name].resx. For instance say, I have a resource file named “Lang” and the US English culture name will come as “Lang.en-US.resx and the French culture for the same file will come as”Lang.fr-FR.resx

eng resx

fr resx

The above two are the files I have created for this demo. You can notice “Name” property in both files remain same and have the translation for respective languages in values.
Now the coding part starts and we have to define these 2 (and optional 2 comments) lines as the fields in the Main class (or whatever classes we are going to localize

1
2
3
4
// Loading the resurce files containing culture info and set culture to "ru-RU"
string sLangCode = "ru-RU";
ResourceManager resxManager = new ResourceManager("App2.Lang", Assembly.GetExecutingAssembly());
//Loaded the culture info

In line 2. I set the culture information (you can get more cultures from the table I have givend the link above in the post) and in Line 3, ResourceManager("App2.Lang", I call the resource with [Project_Name].[Resource_name] and notice I didnt put the culture identifier here.

Finally I can put the below lines to load the respective culture in the page creation method,

1
2
3
4
5
6
7
8
// Setting the language accordin to Language 
// Set culture by changing sLangCode
Thread.CurrentThread.CurrentUICulture = new CultureInfo(sLangCode);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sLangCode);
// End set culture info

button.Text = resxManager.GetString("TextInButton");
text.Text = resxManager.GetString("TextInTextbox");

So the final code will be something like,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Threading;

namespace App2
{
    [Activity(Label = "App2", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        int count = 1;

        // Loading the resurce files containing culture info and set culture to "ru-RU"
        string sLangCode = "ru-RU";
        ResourceManager resxManager = new ResourceManager("App2.Lang", Assembly.GetExecutingAssembly());
        //Loaded the culture info

        protected override void OnCreate(Bundle bundle)
        {
            


            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            EditText text = FindViewById<EditText>(Resource.Id.editText1);

            // Setting the language accordin to Language 
            // Set culture by changing sLangCode
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(sLangCode);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sLangCode);
            // End set culture info

            button.Text = resxManager.GetString("TextInButton");
            text.Text = resxManager.GetString("TextInTextbox");

            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
        }
    }
}

for Android.

Happy coding 🙂

Delegates in C#, simplified.

Featured

Tags

, , , , ,

Delegates, a main question when it comes to C# interviews. When I faced the internship interview at IFS last October I was asked a question “What is a delegate” I said “It is a way to achieve thread safety”, actually I used delegates in my Imagine cup project in 2013 but when I faced that interviews, I really had a good clear concept of it. I said its thread safety because the reference material I read the day before the interview had many points on Delegates but due to my bad memory I could remember only that point even in that Imagine cup scenario really I used Delegate to avoid some code execution complexities.

Then the interviewer asked me ‘What do you mean by thread safety” so I explained it. Then again he asked me “OK, now how will you explain delegates to a newbie using the points you said”.. this is the moment I had a mini_heart_attack();

In simple words, delegates are the callback functions in C#. (I really forgot this point that time)

image_172FE501

So this JS pseudo code will explain what a callback function is,

function someAction(x, y, someCallback) {
    return someCallback(x, y);
}
 
function calcProduct(x, y) {
    return x * y;
}
 
function calcSum(x, y) {
    return x + y;
}
// alerts 75, the product of 5 and 15
alert(someAction(5, 15, calcProduct));
// alerts 20, the sum of 5 and 15
alert(someAction(5, 15, calcSum));

If you can’t read that simple code, sorry this is not for you actually. So just close this browser tab.

The equivalent to the above Javascript in C# will be something like,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Program
{
    delegate int CalcFunc(int a, int b);

    static void Main(string[] args)
    {
        CalcFunc someCalcFunc = new CalcFunc(SumFunc);
        Console.WriteLine(someCalcFunc(5,6).ToString());

        someCalcFunc = ProdFunc;
        Console.WriteLine(someCalcFunc(5, 6).ToString());

        someCalcFunc = SumFunc;
        Console.WriteLine(someCalcFunc(5, -6).ToString());

        Console.ReadKey();
    }

    static int SumFunc(int sum_a, int sum_b)
    {
        return sum_a + sum_b;
    }

    static int ProdFunc(int prod_a, int prod_b)
    {
        return prod_a * prod_b;
    }
}

Let me explain this,

Line 3 delegate int CalcFunc(int a, int b); declare a delegate CalcFunc that accepts two int parameters and return another int type variable.

Line 7, CalcFunc someCalcFunc = new CalcFunc(SumFunc); instantiate the delegate CalcFunk that calls a method we defined in Line 19, that is SumFunc which SHOULD return the same return type and the same parameter types of the delegate CalcFunc

Line 8, Console.WriteLine(someCalcFunc(5,6).ToString()); I just perform some operations with the delegate instance someCalcFunc

Line 10, I change the reference of the someCalcFunc delegate to another same return type method ProdFunc, I don’t really need to make another instance of this delegate CalcFunc for this purpose, simply someCalcFunc = ProdFunc; works well.

and later I just perform some other operations.

I hope you will be able to catch it. Happy coding 🙂

Constructor chaining and some other good tips with constructors

Featured

Tags

, , , , ,

Blogging after a long time actually, I was bit busy with last exams and migrating to Colombo, Sri Lanka. I have a good news for you guys that I have joined IFS, Sri Lanka as an undergraduate intern that valid from 11th March to 19th June. Here, at IFS, this has a tremendous work place setup and the people as well. Wow thats amazing and I praise god for writing my fate to be here 🙂

So today I have learnt something special, which I didn’t really used even I didn’t read in any books I used for reading on C#. That is CONSTRUCTOR CHAINING.

In simple words, Constructor chaining is calling a constructor from another constructor. The called constructor may reside in the same class of the caller constructor risiding constructor or its super class(In C# we call it as base class). The main advantages of this is we are avoiding boilerplate code as we don’t have to repeat the same operations and even this can be used, if all fields of the class to be initialized.

Lets see a small code for this,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Box
{
    int length; // fields
    int width;
    int height;

    public Box(int len)
        : this(len, len, len)
    { // constructor with one parameter

    }

    public Box(int h, int w, int l)
    { // constructor with three  parameter
        length = l;
        width = w;
        height = h;
    }
}

Here for the Box class I have two overloaded constructors with different signatures, that are Box(int len) in line 7 and public Box(int h, int w, int l) in line 13. First lets have a look at the constructor in line 13, that initialize a box object with three user defined parameters, h, w and l that are height, width and length of the Box class. But in the same box class I need an instance that to represent a cube, where w, h and l are the eual values, so instead of writing another logic for that I can simply create another constructor that calls the constructor in line 13 and put single value to all the variables h and l. Thats what I have done in line 7. So just notice the syntax.

public Box(int len)
        : this(len, len, len)
    { // constructor with one parameter

    }

Here since we chain the constructor in the same class this keyword is being used. So how to chain the constructor in the super class,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Cube:Box
{
    int length;
    public Cube(int l):base(l,l,l)
    {
        this.length = l;
    }

}

class Box
{
    int height, width, length;
    public Box(int h, int w, int l)
    {
        this.height = h;
        this.width = w;
        this.length = l;
    }

    internal int getVolume()
    {
        return height * width * length;
    }
}

See line 4 where I have did something public Cube(int l):base(l,l,l) in this line and this is where I chain the constructor from the base class.

Now in the Box if I try to add another constructor (say I am adding the missing default constructor)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Cube:Box
{
    int length;
    public Cube(int l):base(l,l,l)
    {
        this.length = l;
    }

    public Cube()
    { }

}

This will return a compile time (or say, typing time 😉 exception) in visual studio stating,

Error 1 'OOPIntro_D103.Box' does not contain a constructor that takes 0 arguments 

This is because I am using a non default constructor in the base class. Even, the below also won’t work

class Cube:Box
{
    int length;
    //public Cube(int l):base(l,l,l)
    //{
    //    this.length = l;
    //}

    public Cube()
    { }

}

To overcome this defining the default constructor in the base class is always safe, as below

public Box() {}

So remember to create constructors for the base classes whatever we needed in the child class. And stating default constructor gives the freedom to create any kind of constructor in the child class.
Final example,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Program
{
    static void Main(string[] args)
    {
        Cube c = new Cube(5);
        Console.WriteLine(c.getVolume());
        Console.ReadKey();
    }
}

class Cube : Box
{
    int length;
    public Cube(int l)
        : base(l, l, l)
    {
        this.length = l;
    }

    public Cube(string y)
    { }

}

class Box
{
    int height, width, length;
    public Box() { }
    public Box(int h, int w, int l)
    {
        this.height = h;
        this.width = w;
        this.length = l;
    }

    internal int getVolume()
    {
        return height * width * length;
    }
}

Happy coding 🙂

Retrieve data from Light Sensor with Xamarin Android

Featured

Tags

, ,

Sensors are very interesting things when you are going to develop an exciting software that expose output to environment changes of the device. Today I wanted to check light sensor of my vintage android phone and did it with Xamarin. The code is below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Hardware;

namespace SensorSample
{
  [Activity (Label = "SensorSample", MainLauncher = true, Icon = "@drawable/icon")]
  public class MainActivity : Activity, Android.Hardware.ISensorEventListener
  {
    private SensorManager _senMan;
    float lightSensorValue;
    protected override void OnCreate (Bundle bundle)
    {
      base.OnCreate (bundle);
      SetContentView (Resource.Layout.Main);

      Button button = FindViewById<Button> (Resource.Id.myButton);

      _senMan = (SensorManager)GetSystemService (Context.SensorService);
      Sensor sen = _senMan.GetDefaultSensor (SensorType.Light);
      _senMan.RegisterListener (this, sen, Android.Hardware.SensorDelay.Game);

      button.Click += delegate {
        Toast.MakeText(this, sen.Vendor,ToastLength.Long).Show();
      };
    }
      

    public void OnSensorChanged(SensorEvent s)
    {
      s.Sensor = _senMan.GetDefaultSensor (SensorType.Light);
      lightSensorValue = s.Values [0];
      Toast.MakeText(this, lightSensorValue.ToString("0.00"),ToastLength.Long).Show();
    }

    public void OnAccuracyChanged (Sensor sensor, SensorStatus accuracy)
    {
      //throw new NotImplementedException ();
    }
  }
}

Make Xamarin apps that support Twitter xAuth

Featured

Tags

, , , , , , , , , ,

Twitter’s xAuth is an exciting option which is not available for web based applications but available for desktop and mobile apps that uses Twitter SDK where standard web OAuth flow or PIN-code out-of-band flow is not an option. xAuth access is restricted to approved applications and if your present/past/future app needs it, request if from here https://support.twitter.com/forms/platform. I was using this xAuth in 2012 when I was doing a good solution for blind people for Microsoft Imaginecup contest.

Ok, lets back to the topic, for Xamarin, we have Twitter4j component which is such awesome and very simple component to provide Twitter SDK capabilities. Once you add that component it open its official documentation, that is a small code implementation with access to twitter using a previously created twitter app’s Consumer Key, Consumer Secret, AccessToken and AccessToken Secret. Today I tried to port this code to use with an xAuth enabled app. The code is,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Threading;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

using Twitter4j;
using Twitter4j.Auth;
using Twitter4j.Conf;

namespace TwitterXAuthTestAndroid
{
  [Activity (Label = "TwitterXAuthTestAndroid", MainLauncher = true, Icon = "@drawable/icon")]
  public class MainActivity : Activity
{
    protected override void OnCreate (Bundle bundle)
    {
      base.OnCreate (bundle);

      SetContentView (Resource.Layout.Main);

      // Get our button from the layout resource,
      // and attach an event to it
      Button button = FindViewById<Button> (Resource.Id.myButton);

      ConfigurationBuilder TwitterConfig = new ConfigurationBuilder();
      TwitterConfig.SetOAuthConsumerKey("_my_app's_consumer_key_");
      TwitterConfig.SetOAuthConsumerSecret("_my_app's_consumer_secret);

      IConfiguration TwitterICnfg = TwitterConfig.Build ();

      TwitterFactory factory = new TwitterFactory (TwitterICnfg);

      OAuthAuthorization auth = new OAuthAuthorization (TwitterICnfg);

      AccessToken acctkn = auth.GetOAuthAccessToken ("_my_twitter_user_name_eg_(isham_m_iqbal)", "_my_password_");
      ITwitter twitter = factory.GetInstance(acctkn);

      button.Click += delegate {
        ThreadPool.QueueUserWorkItem(state =>
          {
            try
            {
              twitter.UpdateStatus("Isham_M_Iqbal rocks.. boom....");
            }

            catch(Exception ed)
            {
              Console.WriteLine(ed.Message);
            }
          }
        );
      };
    }
  }
}

Lines 30-32 makes a twitter configuration with my twitter app’s ConsumerKey and ConsumerSecret. After it in line 34 builds the above configuration and pass it to IConfiguration interface. Line 40 is the place, that does the xAuth magic. Refer this code, if you get “The screen name / password combination seems to be invalid.” error, that mean’s your username-password combination is wrong or xAuth wasn’t enabled for your twitter app. I hope you enjoy this post.

Happy coding peeps 🙂

How to implement a Xamarin.Forms app with Xamarin plugins

Featured

Tags

, , , , , , , , , , ,

Recently, obviously last year (in 2014) Xamarin’s James Montemagno posted a blog post titled “Holiday Contest: Create a Plugin for Xamarin” and I also managed to develop a very small plugin for Xamarin.Forms with the help of this video. My plugin can be downloaded from here and the source code is here. The awesome thing in this plugin is, despite its functionality and its validating phone numbers, man, I completed the development of this project with in roughly 30 mins. Wow.. that’s amazing isn’t it. boom..

Another very very interesting thing about this plugin is, I didn’t test it before publish it to Nuget and opensource the code in Github.

Even I tweeted about it. Seriously I didn’t know how to call a plugin / Nuget package in Xamarin.Forms project. My initial thought was its just like importing and calling a Nuget package in Visual Studio but I didn’t succeed it. After tooooooooooooo much of attempts just I have found the way. So lets see how to do it.

Step 1 – Import the Nuget package. Remember you have to import to all the projects of the solution. Ideally you will have 4 folders of projects, one is the common folder for the app where we have to make UI and implement logic. other three folders are for WP, Android and iOS. Please find some help from here to know how to add packages.

Step 2 – Open the App.cs file in the main project folder and make the UI with logic. In my case I am creating an app with a single button, Click event of the button will use the plugin / Nuget package. So my App.cs code comes as

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using Xamarin.Forms;
using PhoneCall.Forms.Plugin.Abstractions;

namespace TestXamForms
{
	public class App
	{
		public static Page GetMainPage ()
		{	
			Button callButton = new Button { Text = "Call Sam" };
			callButton.Clicked += (s, e) => QCall("+65 22456465");

			return new ContentPage { 

				Content = new StackLayout
				{
					VerticalOptions = LayoutOptions.Center,
					Children = {
						callButton
					}
				}
			};
		}

		private static void QCall(string number)
		{
			var notificator = DependencyService.Get<IPhoneCall>();
			notificator.MakeQuickCall (number);
		}
	}
}

Lets have a detailed look on this code.
See the line 3, which is using PhoneCall.Forms.Plugin.Abstractions; this is the place where I call the plugin. While creating a plugin for Xamarin.Forms, we create it with 4 folders one is called “Abstractions” where we implement the interfaces for the plugin, so later we can use these interfaces with other 3 folders (literately projects) which are for WP, Android & iOS (If you can’t get this, please refer the video on creating plugins, I linked that above this page)
After that in the line 11 I have created a button and in the line 12 I have coded for the Click event of it. On the Click event I am calling a method QCall which is implemented from line 26. In line 28 I have created a variable called notifier which calls the IPhoneCall interface in my plugin. To make this done, I use the help of DependencyService class which is a built-in and let shared code to easily resolve Interfaces to platform-specific implementations, allowing you to access features of the iOS, Android and Windows Phone SDKs from your PCL or Shared Project. Then I call a method MakeQuickCall in line 29 which is in the interface to get my job done.
Here in the App.cs class has a static method that returns a Page named GetMainPage(). That method is the place where we create UI and since that method should return a Page we built ContentPage that has StackLayout with the code of lines 14-23 and call the Button we have already created in line 11. In line 19, 20 you can see I have set the Children property of the StackLayout as callButton.

Step 3 – Now open the Android project of the solution and open MainActivity.cs. There just use using PhoneCall.Forms.Plugin.Droid; and initialize this with PhoneCallImplementation.Init ();. Thats all. My MainActivity.cs is

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

using PhoneCall.Forms.Plugin.Droid;

using Xamarin.Forms.Platform.Android;


namespace TestXamForms.Android
{
	[Activity (Label = "TestXamForms.Android.Android", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
	public class MainActivity : AndroidActivity
	{
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			Xamarin.Forms.Forms.Init (this, bundle);

			PhoneCallImplementation.Init ();

			SetPage (App.GetMainPage ());
		}
	}
}

DO the same for the WP and iOS projects as well.

Step 4 – Now click on Run -> Upload to Device.
Note : Set correct target API level for Android.

Thats all peeps. Happy coding. 🙂

Happy New Year with Pal·in·drome

Featured

Tags

, , , , ,

Happy 2015

(never forget to check the quiz below and comment the answer, I might give some prices to a lucky winner, seriously)

Happy New Year to all. May this 2015 brings you a peaceful mind && make you strong, geeky and || or nerdy.

While I come through my twitter timeline today I noticed that the Binary(2015) is a palindrome number, that is 11111011111 wow thats amazing right. So I wanted to create an app to find which years return palindrome binary numbers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;

namespace PalindromeCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            string initial = "";
 
            Console.WriteLine("Enter a Year to check for Palindrome");
            
            string decInput = Console.ReadLine();
 
            string binInput = Convert.ToString(Convert.ToInt32(decInput),2);
 
            int binInputLen = binInput.Length;

            if (binInputLen == 0)
            {
                Console.WriteLine("You did not enter the string");

            }

            else
            {

                for (int j = binInputLen - 1; j >= 0; j--)
                {
                    initial = initial + binInput[j];
                }

                if (initial == binInput)
                {
                    Console.WriteLine(String.Format("Year {0} returns a palindrome binary, that is {1}",decInput,binInput));
                }
                else
                {
                    Console.WriteLine(String.Format("Year {0} does not returns a palindrome binary, which is {1}", decInput, binInput));
                }
                Console.Read();
            }
        }
    }
}

This is hope you enjoy this. Happy coding peeps 🙂


Happy New year again.

 

QUIZ : What is the next.next year to return a octal Palindrome number?
Deadline -> Answer is the deadline, until that the quiz is open.

Attaching disks on Windows Server 2012 R2 VM

Featured

Tags

, , , , , , , ,

I am working on my own download server on Microsoft Azure, the idea is a black box I will never tell it to anyone for now. But for that download server I had to have small small data disk chunks on the Virtual Machine which is running on Windows Server 2012. So I can download them locally as .vhd files later.

http://azure.microsoft.com/en-us/documentation/articles/storage-windows-attach-disk/ this documentation explain how to attach a data disk to a windows virtual machine with the help of the old server manager. I am here to guide you through how to do this with the new metro server manager that comes built-in with Windows Server 2012 R2.

First, go to Azure management portal, open VMs and select the VM, you need to attach the disk, in the below bar you can see “Attach” click on it, select “Attach empty disk” and attach a disk. Its familier to the oldies and if you are new go here http://azure.microsoft.com/en-us/documentation/articles/storage-windows-attach-disk/ and follow up-to “How to: Attach an existing disk” part.

Now, login to the VM, and in the Vm Explorer the new disk is yet to be visible.

So, open sever manager by clicking this

serv man

Now Server Manager is launched and click on File and Storage Services

file storage serv

Now select Disks, which is rounded with red and then you can see the unknown disk there, (rounded in blue)

disk visible

Now right click on it and select “New Volume”

new vol

Now you can see a dialog box and just go though it, where you can set drive letter for the disk, file system of it, size of the disk with several other settings, after everything done correctly you can see the below

final

Now open the windows explorer, you can see the new disk.

expl

Thats all folks.. Hope you will find something useful with this post. 🙂

Get line counts of a TextView in Xamarin Android

Featured

Tags

, , , , , , , ,

Last week I was preparing for a presentation on Xamarin for the newly launched CIS Fortnight meetup where everyone from my department gather for some technical and soft skill sessions. After I got Student Indie subscription from Xamarin, I used to contribute to Xamarin.Android and just a night before the presentation I got a Facebook message from a Czech Republic girl asking how to count the lines of a TextView. I was also not much familiar with that TextView line counting thing. So I tried to go from the sketch to make a solution for her and send it.

That solution contains an app that simply has a Button and a TextView with some predefined text on it. The .Click event of the Button shows the linecount in a Toast

Firstly my Main.axml file goes like this

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/myButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:shrinkColumns="0">
        <TableRow>
            <TextView
                android:id="@+id/question"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Get the line number corresponding to the specified vertical position. If you ask for a position above 0, you get 0; if you ask for a position below the bottom of the text, you get the last line." />
        </TableRow>
    </TableLayout>
</LinearLayout>

Here, to create a TextView that supports text wrapping, I used TableLayout.

My MainActivity.cs is something similar to,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Text;

namespace CountLines
{
[Activity (Label = "CountLines", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;

protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);

// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);

// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<button> (Resource.Id.myButton);
TextView txtview = FindViewById (Resource.Id.question);</button>

button.Click += delegate {
int height = txtview.Height;
int scrollY = txtview.ScrollY;
Layout layout = txtview.Layout;
int lineCount = layout.GetLineForVertical (scrollY + height)+1;

Toast.MakeText(this,lineCount.ToString(),ToastLength.Long).Show();
};

}
}
}

Here, you can see from line 31 to 34 is the place where the magic happens. Height property gets the height of the View super class, here this works for TextView which is inherited from the View class. ScrollY returns the top edge of the displayed part of your view, in pixels. Here our TextView is not scroll able but still I have put this for future consideration. Now the magic method GetLineForVertical help us to get line for the sum of pixel count of the Height and ScrollY. That will be less then 1 of the real lines count so we can add 1 to get the real line count.

Thats all folks, if you are interested on my presentation I have done for the meetup, check it below.

&& you can see me here at your left side of the screen with the proud C# shirt from Xamarin.

Happy coding 🙂

AudioManager in Xamarin.Android

Featured

Tags

, , , ,

AudioManager class in Android provides access to volume and ringer mode control. Since Xamarin has 100% Android coverage, we can use the same class to control system wide volume and ringer via our C# code. We have to invoke Context.getSystemService(Context.AUDIO_SERVICE) to make an instance of the AudioManager class and after getting an instance, we can call it and invoke the methods to control our Audio peripherals in the device.

A very simple code snippet is

1
2
AudioManager am = (AudioManager)this.GetSystemService (Context.AudioService);
am.RingerMode = RingerMode.Vibrate;

and never forget to use

using Android.Media;

if you see in the first two lines of code, in the first line we have used this as the Context to instantiate the AudioManager class. In the second line, we programtically set device’s audio mode to Vibrate.

The same code for Android is something like,

1
2
3
AudioManager am;
am= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

To adjust (say for instance, increase) the ringer volume,

1
am.AdjustSuggestedStreamVolume (Adjust.Raise, Android.Media.Stream.Ring, VolumeNotificationFlags.ShowUi);

we can use this in Xamarin. Here, the first parameter, Adjust.Raise defines, the volume is increasing. The Adjust enum has 3 items, they are Lower, Raise and Same. The second parameter, Android.Media.Stream.Ring defines, it is ringer stream and it has 8 items, they are Alarm, Dtmf, Music, Notification, NotificationDefault, Ring, System and VoiceCall. VolumeNotificationFlags provides some more UX control over the action and it also has 5 enum items.

Get Android device battery percentage in Xamarin

Featured

Tags

, , , ,

Here is the code implementation that shows device battery percentage in Toast. On Android battery level can be quaried using IntentFilter and Context.RegisterReceiver()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace BatteryPerc
{
	[Activity (Label = "Battery Percentage", MainLauncher = true, Icon = "@drawable/icon")]
	public class MainActivity : Activity
	{

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			// Get our button from the layout resource,
			// and attach an event to it
			Button button = FindViewById<Button> (Resource.Id.myButton);

			button.Click += delegate {
				var filter  = new IntentFilter(Intent.ActionBatteryChanged);
				var battery = RegisterReceiver(null, filter);
				int level   = battery.GetIntExtra(BatteryManager.ExtraLevel, -1);
				int scale   = battery.GetIntExtra(BatteryManager.ExtraScale, -1);

				int BPercetage = (int)System.Math.Floor (level * 100D / scale);
				Toast.MakeText(this,BPercetage.ToString(),ToastLength.Long).Show();
			};
		}
	}
}

I hope this will help 🙂 Happy coding 🙂

Xamarin and the easiest ways to create events

Featured

Tags

, , , , ,

Xamarin is a great tool for C Sharpers, and eventually it eases the pain. To be honestly I used to stuck while creating events for Android tools with Java, I am yet to understand what the hell is happening there. Its like a blackbox for me. I just memorize the code or Google for event snippets every time.

This is the sample code to trigger a button on Java

1
2
3
4
5
6
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
 public void onClick(View v) {
	 // Perform action on click
 }
});

But in Xamarin, the C# way is something like below

1
2
3
4
Button btn1 = FindViewById<Button> (Resource.Id.button2);
btn1.Click += delegate {
	//do something here
};

This above code is simply something easier to understand and make the blackbox transparent for the beginners. And notice the line numbers, only 4 lines yet getting the same job done. This is effective right?

For those who are familier with Windows development on C#, Xamarin provides another good old ways to create Events, yes this is a place we are getting the native C# events experience. It is,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
protected override void OnCreate (Bundle bundle)
{
	base.OnCreate (bundle);
	SetContentView (Resource.Layout.Main);
	//other things goes here..
	Button btn1 = FindViewById<Button> (Resource.Id.button1);
	
	//create a Click event for the button
	btn1.Click += DoSomeEvent;
}
private void DoSomeEvent(object sender, EventArgs ea)
{
	//Do something here 🙂
}

This is the beauty of Xamarin, the real tool to create native apps in C#.

Work on Azure with friends

Featured

Tags

,

While working on a project as a group which uses Azure as the backbone of it, Usually companies, buy one Azure subscription and share the authentication details with the project team. But people like MVPs, MSPs and other team members who have MSDN subscription will surely already have Azure subscription for USD 150 per month. Still those projects don’t employ those Azure subscription because those people never wanted to share their Microsoft account’s password with others.

For this kind of issue, Azure comes with a nice (and forgotten) feature to add Administrators to for the current Azure subscription and use them with their (the new guys’) own identity.

Capture

To do this

  • Go to http://manage.windowsazure.com (as the administrator)
  • Scroll the left pane down untill see “Settings”
  • Click on it and select “Administrators”
  • Here you can see your details
  • Now add your co-workers’ email and gooooooo 🙂

Untitled-1

Connect to Azure Cloud Services with connection string.

Featured

Tags

, , ,

A good code is something that does the same job with less lines chars.

We all know about configuration files used in .NET applications we use them from app.config to web.config. But most of the beginners in .NET never employ them efficiently. We all have almost forgot connection strings and System.Configuration namespace. I never see them in many of the codes.

The primary advantage of having Config files is exactly the scenario that you are dealing with (multiple projects and centralized configuration). When it comes specifically with web.config, Storing the encrypted connection string in web.config file is really a good practice. Even for app.config for console and other non web apps in .NET we can use app.config to boost the project efficiency, we never need to call the connection strings again in again in every files or even sometimes, like the below scenario, we never wanted to create a new object to handle the credentials and waste some good memory from the device.

The Good Scenario

In my earlier post, Dummies’ guide to Upload to Azure Cloud Storage I explained how to create a cloud storage service and how to upload a local file to the storage via a C# Console application. Please click the link above and go to that post and see the code ((code.Visible=true) ? "read it carefully" : "scroll down until code visible please";).

There carefully see lines 20-23, that code created 2 objects, sc which is a StorageCredentials object and storageAcc which is a CloudStorageAccount object. Remember both these classes are respictively from Microsoft.WindowsAzure.Storage.Auth and Microsoft.WindowsAzure.Storage namespaces. My argument is those lines are really not necessary and there is no need to use Microsoft.WindowsAzure.Storage.Auth namespace as well by using connection strings to connect with the cloud storage service.

How to do this

Consider the same application. If you tried that sample and implemented yours open that solution/project and open app.config file.

Initially that file might have something like

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

Now add the below lines

1
2
3
4
5
6
<configuration>
    <appSettings>
        <add key="StorageConnectionString" 
          value="DefaultEndpointsProtocol=https;AccountName=paste_the_cloud_service_name_here_eg_somegoodstorage;AccountKey=please_paste_the_accesskey_here" />
    </appSettings>
</configuration>

Remember to change paste_the_cloud_service_name_here_eg_somegoodstorage and please_paste_the_accesskey_here with your credentials. Now the app.config looks something similar to

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="StorageConnectionString" 
         value="DefaultEndpointsProtocol=https;AccountName=somegoodstorage;AccountKey=kdfjhksdjfksjdfkasjdfsdf" />
  </appSettings>
</configuration>

Right, we have just finished configuring the connection string with app.config file.
Now move to Program.cs file there, delete the lines 20 – 23 and as the 20th line add

CloudStorageAccount storageAcc = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

Now hit the F5 key and see whats the good thing happening.

Happy coding folks.

Dummies’ guide to Upload to Azure Cloud Storage

Featured

Tags

, , , , , ,

Let me explain how to upload something to Azure cloud blob with a detailed progression report.
First, create a Cloud storage in Azure and name it as somegoodstorageblog1
Now create a Container in that storage called somegoodcontainer

blog2

blog3

blog4

Now open Visual Studio and create a blank console application.

We need to add Azure Storage references for the current project to continue with out main task. So, go through Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.

There search for Azure Storage and install that package to the project.

blognuget

Now again go to Azure management portal and go to the dashboard of the previously created somegoodstorage storage and get the primary accesskey to access the storage programmatically by

blog31Now come back to Visual Studio and code like the below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System.IO;
using System.Threading;

namespace Azure_Blob_Update_Console
{
    class Program
    {
        static void Main(string[] args)
        {

            StorageCredentials sc = new StorageCredentials("somegoodstorage",
                "please_paste_the_accesskey_here");

            CloudStorageAccount storageAcc = new CloudStorageAccount(sc, true);

            CloudBlobClient cbc = storageAcc.CreateCloudBlobClient();

            CloudBlobContainer cbcontainer = cbc.GetContainerReference("somegoodcontainer");
            CloudBlockBlob filetoupload= cbcontainer.GetBlockBlobReference("somegoodpicture.jpg");
            filetoupload.UploadFromFile(@"C:\VacancyAd.jpg", System.IO.FileMode.OpenOrCreate);
        }
    }
}

If you see line 6 – 9, we are calling all necessary references to the project from those lines.

After that we create a new StorageCredentails object that refers to the cloud storage. You can see we directly say its name somegoodstorage there and please don’t forget to replace the Accesskey.
Line 28 says the file that we are going to create on the Azure storage. If you miss the extension for the file or the file type, you will still get the file but without any filetypes.
Line 29 called the VacancyAd.jpg file from C:\ and upload it.
Again in Line 29, you may notice something System.IO.FileMode.OpenOrCreate this means, system should open a file if it exists; otherwise, a new file should be created. There are several FileMode enumerations are there, read them from http://msdn.microsoft.com/en-us/library/system.io.filemode%28v=vs.110%29.aspx
Thats all folks, easy nah… 😉
Happy coding.

String Interpolation and Expression-bodied methods in C# 6.0

Featured

Tags

, , , ,

We, all C# developers are very much familiar with string.Format(); in C# where we used to

string a = "sample text";
string.Format("This is a {0}",a);

that was awesome but when it comes to use the same methods with more args, it gives a headache and even its sometimes become harder to read the code. Sometimes I personally think why again and again use string.Format();. Now with the new C# Microsoft has provided me an answer that is, String Interpolation. With String interpolation you can just use something like

int a, b = 10;
Console.WriteLine("The value is A is \{a} while B is \{b}");

and even you can depricate that Console also as C# has the feature to using static classes as I said earlier in a blog post.

The next thing I wanted to tell here is Expression bodies methods and properties in C# 6.0, they are just methods, where body contains just a single return statement, for example the like the below.

public override string ToString()
{
   //consider a has been defined
   return "\{a}";
}

and think about how to write this method very quickly to boost the developer efficiency, there is were the expression bodied methods helps. Like Lambda expressions, this expression bodied methods helps to implement a methods with lambda arrow. A good example can be

public override string ToString() => "\{a}";

thats all boom…!!
And we can use this for properties as well, instead of using like below

public int AddedNumbers
{
   get {return a+b;}
}

we can just use

public int AddedNumbers => a+b;

These are just cool isn’t they.
Happy coding and I will catch you soon with another post guys. Have a blessed stay.

The new C# and two good things.

Featured

Tags

, ,

I have installed Visual Studio 2015 on a Virtual machine and it is GREAT..! I am making a post on it with screenshots but for now let me tell about some cool Visual C# 2015 preview features

1 Auto-Properties with initializers.
Now you can code something like

public int id { get; } = 15;

Yes this is coming. And setter is not a must while you implement though the property is still assignable at declaration time with a setter like the below

public int id { get; set; } = 17;

2 Say no to Console.WriteLine();
This is another cool thing, and a dream comes true for us all. Now you can

using System.Console;

and this will never return and error and after this you can directly

WriteLine("This is awesome");
ReadLine();

This is not only for this but we can use any static classes in using and avoid their prefixes when we call their methods. Another good example is

using System.Math;

and just call any method in the Math class which is static.

2.1 Can await in the body of catch / finally clause

private static async Task<string[]> ReturnSomeStringPlease()
{
    try
    {
        using (var reader = File.OpenText("Words.txt"))
        {
            var s = await reader.ReadToEndAsync();
            return s.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
        }
    }
    finally
    {
        using (var reader = File.OpenText("someotherWords.txt"))
        {
            var s = await reader.ReadToEndAsync();
            //this has happened in my life time... yaaaaaayyy!!
            return s.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
        }
    }
}

There are even more things. I will write about them soon.

Opensourcing the code that controls my name

Featured

Tags

, ,

Hi all, if you are following me in twitter (http://twitter.com/isham_m_iqbal) you may notice my twitter name “Isham Mohamed” is periodically changing into 6 languages. It is not a magic, its just a 5 minutes hack and scheduling a Cron job, or Azure Schedule. If want to know the whole story, it here.

if you are familier with Twitter SDK, here is the line of code that controls it
$msg = $tweet->post('account/update_profile', array('name' => $nametodisp));
You can take a look into my repository also here.

I have used Azure WebJobs and Scheduler to schedule this job. It was very very easy. and you can follow the tutorial here.

Got an Inbox invitation

Featured

Tags

, ,

Got a Google Inbox invitation and I hope you all have read about what Inbox is.

B0sUXkKCMAAJvyt

Why you should install it

  1. Its from Google 😀
  2. Snooze feature
  3. Done feature
  4. Awesome UI/UX (They call this as Materiel design)
  5. That innovative ‘Compose‘ ( ) button
    1. Untitled-1
  6. Its Faster
    1. On receiving emails
    2. On sending emails
    3. On attaching files
    4. On ALL other functions

Why you might hate it

  1. Its available only for Android, iOS and Chrome (not the OS but browser)
  2. Its bit confusing (See the update below)

Thats all folks, now enjoys some screen-shots 🙂

B0sVdNiCIAAjr3u

B0sVpY1CIAA4AOX

B0sVhqSCcAIng_a

The sad story on later the day.

Later I introduced Google Inbox to some IT Pros I know, they were struggling on this. They felt this one is a messy thing. They are still very much happy about old Gmail and asked me “What is the invention here, invention means, it should be easier right?” great question it was. Even they didn’t request to send any invitations for them for this. For those who are excited about Google, they always wanted those invites, even now I have sent all my 3 invites to Amalan Dhananjayan (the guy with Google Glass) Mohamed Asfer (A WebGuru) and Ali Akram Ali Uthuan (A medical doctor with geeky brain) All 3 asked me personally via SM. But the common men, say “This is useless” 😦 sadly. I dont see a great future for this over-engineered stuff.

Two noticible UI changes in Windows 10

Featured

I am using Windows 10 since its release on my Acer Aspire Tablet, is so awesome, I am going to upgrade my lappy’s Windows 8.1 to Windows 10 seriously after I will test Visual Studio 2013 on it. I have noticed two things that says, Microsoft is trying to convince the next Windows users the metro way, mixed with old Windows 7 experience.

Toasts as Balloons

Screenshot (30)

I have been a great fan of Balloon tips since Windows XP. I When I was programming with VB 6 on Windows XP, 7 and 8 I never miss Balloon tips notifications on any of my programs. When Windows 8 came to me, I was confusing and even I was thinking about why Microsoft is making to many notification ways, Tiles, Toasts and Balloons? It was little bit confusing to me, but now it seems like Microsoft has combined both Toasts and Balloons into one. Even the way Toasts are being displayed in Windows 10 is better because, all we came from the Windows XP, Vista and 7 background, always looking for the notifications right-bottom of the screen. Though Windows 8’s right -top toasts are optimized for touch, this right-bottom toasts are dismissible by thumb instead of moving the hand to the top screen and using index finger to dismiss.

Screenshot (21)

When Google made the controls of Gmail app for Android to top from bottom it got many negative feedback, but still people are using it because there is no way but most people, from the heart like to interact with Thumbs because they are used to them since they were kids, playing console games with Joysticks. This is very good move by Microsoft by making things that make awesome UXs.

A context menu, optimized for touch

Continuum is being the topic after Joe Belfiore demoed that in the Windows 10 event. Unfortunately its now available in the current Windows 10 technical preview, but I have noticed something silimar to that, that is a better context menu, or you can a right click menu, which pops up when you long press with your fingers on a tile on the new start menu. It looks like

Screenshot (29)

It doesn’t matter, whether the mouse is present on the PC or not, if you touch any tile for a long press, you will get this, but you can’t do this via a mouse and a right click on a tile via mouse seems like

Screenshot (31)

These are something I have noticed in Windows 10 Technical preview, so far sooooooooooooooo coool.. 🙂

Happy Windows 10 previewing 🙂

Experimental Command Prompt in Windows 10 Technical Preview

Featured

Tags

, ,

Untitled
We have a culture, most people think more geeky when they work with command line windows. Command line windows are relatively harder to learn but we can do many task with simple commands rather then clicking several next buttons, that eats time.

The story of cmd.exe on Windows starts with Windows NT operating systems (including Windows 2000 and later). It is the analog of COMMAND.COM in DOS and Windows 9x systems (where it is also called “MS-DOS Prompt”). Some advanced tolls in Windows like dism.exe are still using command line despite they are very new and introduced with Windows 7.

From Windows 10, Microsoft decided to give more flexible experience on their command line, cmd.exe. The main reason behind this are the rise of the Clouds and GIT. Earlier the targeted audience for cmd.exe were IT admins, but now Developers have joined the party so, Microsoft need to optimize cmd.exe for developers, who copy paste things most of the time and need transparent windows.

Open cmd.exe, right click on the title bar and select “Properties”

Untitledz

There you can notice the new “Experimental” tab, now play with it 🙂

Two workarounds before & after installing Windows 10 on Acer Aspire P3

Featured

Tags

, , ,

Don’t like to say much, you all know about Windows 10, its on technical preview now and I would like to say,

I am on Windows 10 Technical Preview now, is more fast and fluid.

I have installed it on my Acer Aspire PIII, which is a decent Windows Tablet.


Problem before installing

have downloaded the Windows 10 Technical Preview, English 64-bit (SHA-1 EB75A3D3C0F621F175B75DC65DB036D0E00EAC43) from the site and copied it to my USB drive.

Then I turned on the tablet, pugged the USB, mounted the .iso file, opened “setup.exe”

I just let it go, it was working like the below

After this screen, the PC got restarted and suddenly I got the below BSOD

after this BSOD, I got this error message, and rolled back to my old Windows version.

I am already familiar with this 0xC1900101 – 0x30018 error when updated windows 8 to 8.1, so I did the following steps

  1. Disabled fast-booting (click here to know about it).
  2. Disabled USB 3.0 on BIOS.
  3. Launched CMD.exe (admin) and executed -> DISM.exe /Online /Cleanup-image /Restorehealth
  4. Then I put the USB into PC, mounted the .iso file, opened “setup.exe”, waited until the PC restarted for the first time (ie, after the process in second images of this blog post finished) and I removed the USB.

Now I waited for sometime, it ran something and finally I got the Windows 10 installed on my Tablet 🙂

Problem after installing

My tablet has a keyboard cover, on which I had a very terrible experience when I was in Windows 8. This tablet came with Windows 8 and after I have upgraded to Windows 8.1 and that time also I came across a problem on connecting the keyboard-cover, I just try to reconnect it and it worked (Here is the documentation to pair it). But for this Windows 10 I had to come with the same experience with some more

When I just paired the keyboard it worked fine, but after I put the tablet to sleep and wake it up, it didn’t work and I was not able to re-pair it again. It didn’t show anything in the immersive control, it was just like the below even when the keyboard is ready to be found.

Screenshot (10)q

To overcome this I,

Opened Control Panel, by right clicking on the start button

Went to -> Control Panel\Hardware and Sound\Devices and Printers

There clicked “Add a device” and added the keyboard successfully.

Screenshot (9)
These are the immediate bugs / problems I have found, hope to find solutions and share with you for the next issues.

After all, I am on….

Screenshot (11)

Happy Windows 10 previewing 🙂

Aliens Looking For Sri Lankan Food – Puzzle

Tags

, , ,

අලුත් අවුරුද්ද is already here and we have diagnosed some Alien Activities in the places below.

alien activity

Federal Intelligence Agency have collected some true information about the landing by cracking alien communication signal, they are

  1. Aliens are looking for a Sri Lankan traditional food item – If we fail to offer it, they will declare a war with us.
  2. Aliens know the usage of ASCII.
  3. Repetitive letters are not used in Alien language, which means they write “freedie” as “fredi” and there is a near one to one mapping with UK English letters.

Now the challenge is to find what is the food, to avoid the war.

Find it.

 

Good Luck