Download image from url in C#

Simply You can use following methods.

using (WebClient client = new WebClient()) 
  {
    client.DownloadFile(new Uri(url), @"c:\temp\image35.png");

     //OR 

    client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
   }

If You don’t know the Format(.png, .jpeg etc) of Image

public void SaveImage(string filename, ImageFormat format) {

    WebClient client = new WebClient();
    Stream stream = client.OpenRead(imageUrl);
    Bitmap bitmap;  bitmap = new Bitmap(stream);

    if (bitmap != null) 
      bitmap.Save(filename, format);

    stream.Flush();
    stream.Close();
    client.Dispose();
}

References
https://stackoverflow.com/questions/24797485/how-to-download-image-from-url

Post data using HTTP in C#

Currently the preferred approach. Asynchronous. Ships with .NET 4.5; portable version for other platforms available via NuGet.

using System.Net.Http;

POST

using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
       { "thing1", "hello" },
       { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();
}

GET

using (var client = new HttpClient())
{
    var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx");
}

References
http://stackoverflow.com/questions/4015324/http-request-with-post

Keywords
http , method , get , C# , .NET

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