JSON Deserialization on REST API C#

When facing with REST API, normally the best way to handle the data results would be to use JSON as your content-type , don’t forget to include the library System.Web.Script.Serialization is used alongside.  Let’s look at the code on how to simple it is to parse the data coming from your Web API request (REST DATA).

Normally you would be given a credential to access your API, depending on authentication, for this example we’ll be using just the basic one.

string restURL = "http://rest.com/api/v1/params"; 
WebRequest req = WebRequest.Create(restUrl);
            req.Method = "GET";
            req.ContentType = "application/json";
            req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username+":"+password));
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
 if(resp.StatusCode == HttpStatusCode.OK) 
{
StreamReader reader = new StreamReader( resp.GetResponseStream());
 
 var objText = reader.ReadToEnd();
 
 var obj = JsonConvert.DeserializeObject<APiObj>(objText);
 //do whatever you want with this object
}        

Now you’ll have to create POCO class here to map your results to your object.

public class APiObj
    {
        [JsonProperty("result")]
         public List<MembershipObj> MemberData { get; set; }
    }
 
    //actual data object from SNOW
    public class MembershipObj {
 
        [JsonProperty("amount")]
        public string Amount { get; set; }
 
        [JsonProperty("city")]
        public string City { get; set; }
 
        [JsonProperty("contact")]
        public string Contact { get; set; }
 
        [JsonProperty("email")]
        public string Email { get; set; }
 
        [JsonProperty("first_name")]
        public string FirstName { get; set; }
  }

And that’s it, as you can see it’s really easy you just need to be aware about the way your results is structured, JSON results will always be in an array just keep that in mind.

 

 

How to move Excel data into Database in C#

Just recently, one of my project requires me to move all data from Excel format into the database, since the solution was really simple, I thought I’d share it.

Using the already provided library from Microsoft Office , we can easily manipulate the data inside each cell.

First, we need to add reference to the Excel Interop DLL (Microsoft.Office.Interop.Excel.DLL) , if you can’t find this , simply browse thru your microsoft office folder, and add excel.exe it already includes that DLL. Now you’re ready.

Add before the namespace: Using Microsoft.Office.Interop.Excel

Declare some private variables for later use:

private static Excel.Workbook MyBook = null; 
private static Excel.Application MyApp = null;
private static Excel.Worksheet MySheet = null;
MyApp = new Excel.Application();
MyApp.Visible = false;
MyBook = MyApp.Workbooks.Open("c:\worksheet.xls");
MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
var lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row; // how many rows

Then the easy part. Reading the contents of your spreadsheet.

List<Person> person new List<Person>();
for (int index = 2; index <= lastRow; index++)
{
    System.Array MyValues = (System.Array)MySheet.get_Range("A" + 
       index.ToString(), "D" + index.ToString()).Cells.Value;
    person.Add(new Person{
      Name = MyValues.GetValue(1,1).ToString(),
      Employment = MyValues.GetValue(1,2).ToString(),
      Email = MyValues.GetValue(1,3).ToString(),
      Phone= MyValues.GetValue(1,4).ToString()
    });
}

Then the inserting it into a database is much easier, since you now have the object filled with data (Person object) you can either pass this to a method that processes your CRUD or simple use it here if you don’t have any db layer. Here’s an example:

using (var db = DBContext())
{
   foreach (var p in person) {

   TBL_PERSON _person = new TBL_PERSON
   {
     Name = p.Name,
     Employment = p.Employment,
     Email = p.Email,
     Phone = p.Phone
    }
};

   db.TBL_PERSON.InsertOnSubmit(_person);
}

db.SubmitChanges();
}

Hope this helps out anyone who has the same task.

Solution adapted from: Nanda Kumar Chimtan
Working-with-Excel-Using-Csharp

How to create custom textbox in AngularJS and wire it with Jquery

So this week, I was task to do a project that requires dynamic input. How do you approach something like this in AngularJS was my question. I know I can use a lot of formatters from AngularJS but I decided to go the easy route, no complication.

So here’s an easy way to create input type=’text’ the Jquery way, then I call the scope (controller) from jquery let’s say $scope.MyFunction. Here’s how it’s done.

First inside your AngularJS once a button is clicked from your html (or cshtml):

on  my html a simple <div id=’myTextBox’></div>

$scope.OnclickCreateTextBox = function (operation,id) {
alert(operation);
//edit or delete resolution
if (operation == 'UPDATE')
{
$('#myTextBox' + id).html('<input type="text" style="width:300px;" id="txtNew1" value="' +
name + '"><i class="glyphicon glyphicon-check" style="color:green" onclick="EditDeleteResolution('+id+')"></i>');
//newTextBoxDiv.appendTo("#TextBoxesGroup");
}
};

//on jquery wire it like so:
function EditDeleteResolution(parm1) {
angular.element(document.getElementById('resTextBox' + parm1)).scope().myFunction(parm1);
}

There it is, if you have any question post them below.