Generate Nested Menu from datatable using c# as ul list

public JsonResult GetCategories()
        {
            nDownloadEntities entities = new nDownloadEntities();
            List<Category> categories = entities.Categories.ToList();

            var sb = new StringBuilder();

            var roots = GetRoots(categories);
            string unorderedList = GenerateUL(roots, categories, sb);

            return Json(unorderedList, JsonRequestBehavior.AllowGet);
        }

        [NonAction]
        private List<Category> GetRoots(List<Category> categories)
        {
            var roots = categories.Where(x => x.ParentId == 0).ToList();
            return roots;
        }

        [NonAction]
        private string GenerateUL(List<Category> parents, List<Category> categories, StringBuilder sb)
        {
            sb.AppendLine("<ul>");

            if (parents.Count > 0)
            {
                foreach (Category category in parents)
                {
                    string line = String.Format(@"<li>{0}", category.CategoryText);
                    sb.Append(line);

                    List<Category> subMenu=categories.Where(x=>x.ParentId==category.CategoryId).ToList();
                    if (subMenu.Any())
                    {
                        var subMenuBuilder = new StringBuilder();
                        sb.Append(GenerateUL(subMenu, categories, subMenuBuilder));
                    }
                    sb.Append("</li>");
                }
            }

            sb.Append("</ul>");
            return sb.ToString();
        }

References :
http://stackoverflow.com/questions/14137811/generate-nested-menu-from-datatable-using-c-sharp-as-ul-list-not-asp-net-menu-co

Keywords :

ul , li , treeview , menu , recursive

How to add JavaScript library in MVC project

JavaScript :

BundleConfig.RegisterBundles(BundleTable.Bundles);
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
            "~/Scripts/jquery-ui-{version}.js"));
@Scripts.Render("~/bundles/jqueryui")

CSS :

bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
              "~/Content/themes/base/jquery.ui.core.css",
              "~/Content/themes/base/jquery.ui.resizable.css",
              "~/Content/themes/base/jquery.ui.selectable.css",
              "~/Content/themes/base/jquery.ui.accordion.css",
              "~/Content/themes/base/jquery.ui.autocomplete.css",
              "~/Content/themes/base/jquery.ui.button.css",
              "~/Content/themes/base/jquery.ui.dialog.css",
              "~/Content/themes/base/jquery.ui.slider.css",
              "~/Content/themes/base/jquery.ui.tabs.css",
              "~/Content/themes/base/jquery.ui.datepicker.css",
              "~/Content/themes/base/jquery.ui.progressbar.css",
              "~/Content/themes/base/jquery.ui.theme.css"));
@Styles.Render("~/Content/themes/base/css")

References :
http://stackoverflow.com/questions/20081328/how-to-add-jqueryui-library-in-mvc-5-project

Keywords : 

References ,  Script , Bundle

Get CPU and Memory usage of system in C#

PerformanceCounter cpuCounter=new PerformanceCounter("Processor", "% Processor Time", "_Total");
PerformanceCounter ramCounter= new PerformanceCounter("Memory", "Available MBytes");

// The method nextValue() always returns a 0 value on the first call. So you have to call this method a second time
cpuCounter.NextValue();
Thread.Sleep(1000);
var cpuUsage = cpuCounter.NextValue();
string cpuUsageStr = string.Format("{0:f2} %",cpuUsage);

var ramAvailable = ramCounter.NextValue();
string ramAvaiableStr = string.Format("{0} MB", ramAvailable);

References :
http://stackoverflow.com/questions/4679962/what-is-the-correct-performance-counter-to-get-cpu-and-memory-usage-of-a-process
http://stackoverflow.com/questions/2181828/why-the-cpu-performance-counter-kept-reporting-0-cpu-usage

Android Xamarin SQLite

public class Person
{
     [PrimaryKey, AutoIncrement]
     public int ID { get; set; }

     public string FirstName { get; set; }

     public string LastName { get; set; }

     public override string ToString()
     {
        return string.Format("[Person: ID={0}, FirstName={1}, LastName={2}]", ID, FirstName, LastName);
     }
}
string dbPath = Path.Combine (
        Environment.GetFolderPath (Environment.SpecialFolder.Personal),
        "database.db3");
using SQLite;
var db = new SQLiteConnection (dbPath);
db.CreateTable<Stock> ();
db.Insert (newStock); // after creating the newStock object
var stock = db.Get<Stock>(5); // primary key id of 5
var stockList = db.Table<Stock>();

References :
https://developer.xamarin.com/recipes/android/data/databases/sqlite/
https://developer.xamarin.com/guides/cross-platform/application_fundamentals/data/part_2_configuration/
https://developer.xamarin.com/guides/cross-platform/application_fundamentals/data/part_3_using_sqlite_orm/

Show a Dialog using DialogFragment in Xamarin Android

Let us first define the layout for your fragment. In this example, I have used two TextViews and Button. My layout looks as follows:

<?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"
    android:padding="10dp">
    <TextView
        android:text="Lorem ipsum"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit...."
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:layout_marginTop="10dp" />
    <Button
        android:text="Close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/CloseButton"
        android:layout_marginTop="10dp" />
</LinearLayout>

Now let us inflate the layout from OnCreateView() method. My DialogFragment class looks as follows:

public class DialogFragment1 : DialogFragment
	{
		public static DialogFragment1 NewInstance(Bundle bundle){
			DialogFragment1 fragment = new DialogFragment1 ();
			fragment.Arguments = bundle;
			return fragment;
		}

		public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			// Use this to return your custom view for this Fragment
			View view =  inflater.Inflate(Resource.Layout.DialogFragment1Layout, container, false);
			Button button = view.FindViewById<Button> (Resource.Id.CloseButton);
			button.Click += delegate {
				Dismiss();
				Toast.MakeText(Activity ,"Dialog fragment dismissed!" , ToastLength.Short).Show();
			};

			return view;
		}
	}

We are pretty much done!. Add the following code snippet in your Activity to instantiate and display the dialog:

FragmentTransaction ft = FragmentManager.BeginTransaction();
//Remove fragment else it will crash as it is already added to backstack
Fragment prev = FragmentManager.FindFragmentByTag("dialog");
if (prev != null) {
	ft.Remove(prev);
}

ft.AddToBackStack(null);

// Create and show the dialog.
DialogFragment1 newFragment = DialogFragment1.NewInstance(null);

//Add fragment
newFragment.Show(ft, "dialog");

References :
http://javatechig.com/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android

Show a Dialog using AlertDialog in Xamarin Android

//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder (this);
alert.SetTitle ("Confirm delete");
alert.SetMessage ("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.");
alert.SetPositiveButton ("Delete", (senderAlert, args) => {
	Toast.MakeText(this ,"Deleted!" , ToastLength.Short).Show();
});

alert.SetNegativeButton ("Cancel", (senderAlert, args) => {
	Toast.MakeText(this ,"Cancelled!" , ToastLength.Short).Show();
});

Dialog dialog = alert.Create();
dialog.Show();

References :
http://javatechig.com/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android

Communicate over TCP Socket and Serialize data with json format in C#

Client :

Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            socket.Connect("127.0.0.1",9011);

            Console.WriteLine("connected...");

            Person person=new Person(){Name = "Mahmood"};

            string jsonData = JsonConvert.SerializeObject(person);
            byte[] dataBytes = Encoding.Default.GetBytes(jsonData);

            socket.Send(dataBytes);

            Console.WriteLine("sent...");

            byte[] buffer=new byte[1024*4];
            int readBytes = socket.Receive(buffer);
            MemoryStream memoryStream = new MemoryStream();

            while (readBytes>0)
            {
                memoryStream.Write(buffer, 0, readBytes);

                if (socket.Available > 0)
                {
                    readBytes = socket.Receive(buffer);   
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("read...");

            byte[] totalBytes = memoryStream.ToArray();

            memoryStream.Close();

            string readData = Encoding.Default.GetString(totalBytes);

            Greeting response = JsonConvert.DeserializeObject<Greeting>(readData);

            Console.WriteLine(response.Msg);

            Console.ReadKey();

Server :

            Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint=new IPEndPoint(IPAddress.Any, 9011);

            socket.Bind(endPoint);
            socket.Listen(5);

            while (true)
            {
                Console.WriteLine("waiting for new connection...");

                Socket newSocket = socket.Accept();

                MemoryStream memoryStream = new MemoryStream();

                Console.WriteLine("new connection...");

                byte[] buffer=new byte[1024];

                int readBytes = newSocket.Receive(buffer);

                while (readBytes>0)
                {
                    memoryStream.Write(buffer,0,readBytes);

                    if (socket.Available > 0)
                    {
                        readBytes = newSocket.Receive(buffer);    
                    }
                    else
                    {
                        break;
                    }
                }

                Console.WriteLine("data received...");

                byte[] totalBytes = memoryStream.ToArray();

                memoryStream.Close();

                string readData = Encoding.Default.GetString(totalBytes);

                Person p= JsonConvert.DeserializeObject<Person>(readData);

                Greeting g = SayHello(p);

                string dataToSend = JsonConvert.SerializeObject(g);

                byte[] dataToSendBytes = Encoding.Default.GetBytes(dataToSend);

                newSocket.Send(dataToSendBytes);

                newSocket.Close();

                Console.WriteLine("data sent...");
            }

Communicate over TCP Socket and Serialize data with binary format in C#

Client :

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect("127.0.0.1", 9011);

            Console.WriteLine("connected...");

            BinaryFormatter formatter=new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            Person person = new Person() { Name = "Mahmood" };

            formatter.Serialize(memoryStream,person);

            byte[] dataBytes = memoryStream.ToArray();
            socket.Send(dataBytes);

            Console.WriteLine("sent...");

            memoryStream = new MemoryStream();
            byte[] buffer = new byte[1024 * 4];
            int readBytes = socket.Receive(buffer);
            
            while (readBytes > 0)
            {
                memoryStream.Write(buffer, 0, readBytes);

                if (socket.Available>0)
                {
                    readBytes = socket.Receive(buffer);
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("read...");
            formatter=new BinaryFormatter();

            // set position to 0 or create a new stream
            memoryStream.Position = 0;
            Greeting response = (Greeting) formatter.Deserialize(memoryStream);

            Console.WriteLine(response.Msg);

            memoryStream.Close();
            socket.Close();

            Console.ReadKey();

Server :

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, 9011);

            socket.Bind(endPoint);
            socket.Listen(5);

            while (true)
            {
                Console.WriteLine("waiting for new connection...");

                Socket newSocket = socket.Accept();

                Console.WriteLine("new connection...");

                byte[] buffer = new byte[1024];

                int readBytes = newSocket.Receive(buffer);
                MemoryStream memoryStream = new MemoryStream();

                while (readBytes > 0)
                {
                    memoryStream.Write(buffer, 0, readBytes);

                    if (socket.Available>0)
                    {
                        readBytes = newSocket.Receive(buffer);
                    }
                    else
                    {
                        break;
                    }
                }

                Console.WriteLine("data received...");

                BinaryFormatter formatter=new BinaryFormatter();
                memoryStream.Position = 0;
                Person p = (Person) formatter.Deserialize(memoryStream);

                memoryStream.Close();

                Greeting g = SayHello(p);

                formatter=new BinaryFormatter();
                memoryStream=new MemoryStream();

                formatter.Serialize(memoryStream,g);

                newSocket.Send(memoryStream.ToArray());

                memoryStream.Close();
                newSocket.Close();

                Console.WriteLine("data sent...");