Json file – dataset – xml – text file

If you want to map the columns of json and xml file and then convert it to .txt file, Below is the code

private static void APIJsonData()
{
string json = File.ReadAllText(@"C:\SourceCode\Files\JsonFiles\jsondata.json");
var dataset = ReadDataFromJson(json, XmlReadMode.InferTypedSchema);
string xmlFileName = @"C:\SourceCode\Files\XmlFiles\" + "jsontoxml" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".xml";
DataSet ds = new DataSet();
dataset.WriteXml(xmlFileName);
XmlDocument doc1 = new XmlDocument();
doc1.Load(xmlFileName);
 using (StreamWriter sw = new StreamWriter(@"C:\SourceCode\Files\TextFiles\" + "xmltoTxt" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".txt"))
        {
            PrintNode(doc1.ChildNodes[1], sw);
            sw.Close();
        }

        var stringjsonData = json;

    }

private static void PrintNode(XmlNode xNode, StreamWriter writer){
bool printComma=false;int Cnt = 0;
// Check if the current node has just one level of child nodes

if (xNode.ChildNodes[0].ChildNodes.Count == 1){
//print the child nodes
writer.Write("'");

           
foreach (XmlNode chNode in xNode.ChildNodes)
            {
                Cnt++;
                printComma = false;
                XmlNodeList innerNodeList = chNode.ChildNodes;

                if (innerNodeList.Count > 1)
                {
                    if (chNode.Name != chNode.PreviousSibling.Name)
                    {
                        printComma = true;
                        writer.Write(writer.NewLine);
                        foreach (XmlNode innerNode in innerNodeList)
                        {
                            writer.Write(chNode.Name + "."+ innerNode.Name + " | ");
                        }
                    }
                }
                else
                {
                    printComma = true;
                    writer.Write(xNode.Name +"."+ chNode.Name);
                }

                if (Cnt != xNode.ChildNodes.Count)
                {
                    if (printComma == true)
                    {
                        writer.Write(",");
                    }
                }
            }
                writer.Write(writer.NewLine);
        }
        else
        {
            foreach (XmlNode chNode in xNode.ChildNodes)
            {
                // recursively calling the method to get to the Node where the node will have only one level of child nodes.  
                PrintNode(chNode, writer);
            }
        }

        ////////////////////////////////////////////////////////

        int count = 0;  
        // Check if the current node has just one level of child nodes  
        if (xNode.ChildNodes[0].ChildNodes.Count == 1)  
        {  
            //print the child nodes  
            writer.Write("'");
            foreach (XmlNode chNode in xNode.ChildNodes)
            {
                count++;
                XmlNodeList innerNodeList = chNode.ChildNodes;

                if (innerNodeList.Count > 1)
                {
                    writer.Write(writer.NewLine);
                    foreach (XmlNode innerNode in innerNodeList)
                    {
                        writer.Write(innerNode.InnerText + " | ");
                    }
                }
                else
                {
                    writer.Write(chNode.InnerText);
                }

                if (count != xNode.ChildNodes.Count)
                {
                     writer.Write(",");
                }
            }
            writer.Write(writer.NewLine);  
        }
      else
         {
              foreach (XmlNode chNode in xNode.ChildNodes)
              {
                      // recursively calling the method to get to the Node where the node will have only one level of child nodes.  
                    PrintNode(chNode, writer);
              }
          }
  }  



       

Abstraction

It is used to hide unwanted data and shows only the required properties and methods.

Examples : Laptop, Car, Console.Writeline(“Hello”);

Laptop Example :

using System;
using System.Text;

namespace ns
{
public class Laptop
{
private string brand;
private string model;
public string Brand
{
get { return brand; }
set { brand = value; }
}

    public string Model
    {
        get { return model; }
        set { model = value; }
    }

    public void LaptopDetails()
    {
        Console.WriteLine("Brand: " + Brand);
        Console.WriteLine("Model: " + Model);
    }

    public void LaptopKeyboard()
    {
        Console.WriteLine("Type using Keyword");
    }

    private void MotherBoardInfo()
    {
        Console.WriteLine("MotheBoard Information");
    }

    private void InternalProcessor()
    {
        Console.WriteLine("Processor Information");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Laptop l = new Laptop();
        l.Brand = "Dell";
        l.Model = "Inspiron 14R";
        l.LaptopDetails();
        Console.WriteLine("\nPress Enter Key to Exit..");
        Console.ReadLine();
    }
}

}

Car Example :

The things a car driver should know are as follows.

  1. Name of the Car
  2. The color of the Car
  3. Gear
  4. Break
  5. Steering

So these are the things that should be exposed and know by the car driver before riding the car.

The things which should be hidden to a Car rider as are follows

  1. The engine of the car
  2. Diesel Engine
  3. Silencer

The things a car driver should know are as follows.

  1. Name of the Car
  2. The color of the Car
  3. Gear
  4. Break
  5. Steering

So these are the things that should be exposed and know by the car driver before riding the car.

The things which should be hidden to a Car rider as are follows

  1. The engine of the car
  2. Diesel Engine
  3. Silencer

So these are the things which should be hidden to a car driver.

namespace AbstractionDemo
{
    public class Car
    {
        private string _CarName = "Honda City";
        private string _CarColur = "Black";
        public string CarName
        {
            set
           {
               _CarName = value;
            }
            get
            {
                return _CarName;
            }
        }
        public string CarColur
        {
            set
            {
                _CarColur = value;
            }
            get
            {
                return _CarColur;
            }
        }

        public void Steering()
        {
            Console.WriteLine("Streering of the Car");
        }
   
       public void Brakes()
        {
            Console.WriteLine("Brakes of the Car");
        }

        public void Gear()
        {
            Console.WriteLine("Gear of the Car");
        }

        private void CarEngine()
        {
            Console.WriteLine("Engine of the Car");
        }

        private void DiesalEngine()
        {
            Console.WriteLine("DiesalEngine of the Car");
        }
        
        private void Silencer()
        {
            Console.WriteLine("Silencer of the Car");
        }
    }
}
Abstraction in C# - Exposing the class members

Abstraction in C# - Hiding the class members
Consuming car class :
public class Program
{
    public static void Main()
    {
        //Creating an instance of Car
        Car CarObject = new Car();

        //Accessing the Public Properties and methods
        string CarName = CarObject.CarName;
        string CarColur = CarObject.CarColur;

        CarObject.Brakes();
        CarObject.Gear();
        CarObject.Steering();

        //Try to access the private variables and methods
        //Compiler Error, 'Car._CarName' is inaccessible due to its protection level
        CarObject._CarName;

        //Compiler Error, 'Car.CarEngine' is inaccessible due to its protection level
        CarObject.CarEngine();
    }
}

Get Distance Between Latitude and Longitude Points

private void Button_Clicked(object sender, EventArgs e)

{

double distanceInKM = GetDistanceBetweenPoints(position.Latitude, position.Longitude, dbLat1, dbLong1);

double mr = 0.0010000;

double km = distanceInKM / 1000;

double mtrs = km / mr;

if (dbradius < mtrs)
{
await DisplayAlert(“Alert”, “You are out of range,Should be within range to check out”, “OK”);
return;
}

}

 

public double GetDistanceBetweenPoints(double lat1, double long1, double lat2, double long2)
{
double distance = 0;

double dLat = (lat2 – lat1) / 180 * Math.PI;
double dLong = (long2 – long1) / 180 * Math.PI;

double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
+ Math.Cos(lat2) * Math.Sin(dLong / 2) * Math.Sin(dLong / 2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 – a));

//Calculate radius of earth
// For this you can assume any of the two points.
double radiusE = 6378135; // Equatorial radius, in metres
double radiusP = 6356750; // Polar Radius

//Numerator part of function
//double nr = Math.Pow(radiusE * radiusP * Math.Cos(lat1 / 180 * Math.PI), 2);
////Denominator part of the function
//double dr = Math.Pow(radiusE * Math.Cos(lat1 / 180 * Math.PI), 2)
// + Math.Pow(radiusP * Math.Sin(lat1 / 180 * Math.PI), 2);
//double radius = Math.Sqrt(nr / dr);

double nr = Math.Pow(radiusE * radiusE * Math.Cos(lat1), 2) + Math.Pow(radiusP * radiusP * Math.Sin(lat1), 2);
double dr = Math.Pow(radiusE * Math.Cos(lat1), 2) + Math.Pow(radiusP * Math.Sin(lat1), 2);
double radius = Math.Sqrt(nr / dr);

//Calaculate distance in metres.
distance = radius * c;
return distance;
}

Getting Web API Responses

public HttpResponseMessage GetAuthUserDetails(string username, string password)
{

string JsonStringBuilder = string.Empty;

if (CheckUser(username, password))
{
string jwtToken = JwtAuthManager.GenerateJWTToken(username);

SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings[“sqlConn”].ToString());
SqlCommand sqlCmd = new SqlCommand(“<procedureName>”);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue(“@username”, username);
sqlCmd.Parameters.AddWithValue(“@password”, _Encrypt(password));
sqlConn.Open();
sqlCmd.Connection = sqlConn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
DataTable dt = new DataTable();
da.Fill(dt);
sqlCmd.Dispose();
sqlConn.Close();

if (dt.Rows.Count > 0)
{
dt.Columns.Add(“resStatus”, typeof(System.String));
foreach (DataRow row in dt.Rows)
{
row[“resStatus”] = “success”;
}
dt.AcceptChanges();
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
var res = JSONString.Replace(“[“, “”).Replace(“]”, “”);

return Request.CreateResponse(HttpStatusCode.OK, JsonConvert.DeserializeObject(res));

}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, “No Records Found”);
}
}
else
{
return new HttpResponseMessage()
{
Content = new JsonContent(new
{

status=”failed”,
message = “Invalid Username and Password” //return exception
})
};

}
}

/////////**************************************************************************

public HttpResponseMessage GetUserDetails(int UserID,int num)
{

string JsonStringBuilder = string.Empty;
try
{
SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings[“sqlConn”].ToString());
SqlCommand sqlCmd = new SqlCommand(“<procName>”);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue(“@UserID”, UserID);
sqlCmd.Parameters.AddWithValue(“@num”, num);
sqlCmd.Parameters.AddWithValue(“@Action”, “GetUserDetails”);
sqlConn.Open();
sqlCmd.Connection = sqlConn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
DataTable dt = new DataTable();
da.Fill(dt);
string From = dt.Rows[0][“From”].ToString();
string To = dt.Rows[0][“To”].ToString();
string Hours = dt.Rows[0][“TSHIFT”].ToString();
sqlCmd.Dispose();
sqlConn.Close();

if (dt.Rows.Count > 0)
{
//dt.Columns.Add(“status”, typeof(System.String));
//foreach (DataRow row in dt.Rows)
//{
// row[“status”] = “success”;

//}
dt.Columns.Remove(“From”);
dt.Columns.Remove(“To”);
dt.Columns.Remove(“TSHIFT”);
dt.AcceptChanges();
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
var res = “\”attendance\”:” + JSONString;
string Status = “\”resStatus\”:” + JsonConvert.SerializeObject(“success”) ;

string JSONTimeFrom = “\”From\”:” + JsonConvert.SerializeObject(From);
string JSONTimeTo = “\”To\”:” + JsonConvert.SerializeObject(To);

string JSONHours =”\”Hours\”:”+ JsonConvert.SerializeObject(Hours);

var arrayOfObjects = “{“+res + “,” + JSONTimeFrom+”,”+ JSONTimeTo + “,”+ Status + “,”+ JSONHours+”}” ;

return Request.CreateResponse(HttpStatusCode.OK, JsonConvert.DeserializeObject(arrayOfObjects));
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, “No Records Found”);
}
}
catch (Exception Ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, Ex.Message);
}

}

 

 

JQuery Ajax function to post multiple object to C# Web API

JQuery Ajax function: 

function insertLoadedData() {
try {

var result = confirm(“Do you want to update?”);
if (result == true) {
var empty = ”;
var DeliveryNoteDetailsArrayData = []
var sts = ”;

for (var ix = 0; ix <= insertLoadedJsonData.length – 1; ix++) {

var deliveryNoteDetails = {
ID: 0,
Delivery_Note_ID: insertLoadedJsonData[ix].ID,
Delivery_ID: insertLoadedJsonData[ix].Delivery_ID,
Del_Date: insertLoadedJsonData[ix].Del_Date,
Cust_Account_ID: insertLoadedJsonData[ix].Cust_Account_ID,
Cust_Account_Number: insertLoadedJsonData[ix].Cust_Account_Number,
Cust_Name: insertLoadedJsonData[ix].Cust_Name,
Trip_Number: insertLoadedJsonData[ix].Trip_Number,
Item_Code: insertLoadedJsonData[ix].Item_Code,
Item_Decription: insertLoadedJsonData[ix].Item_Decription,
UOM: insertLoadedJsonData[ix].UOM,
Del_Qty: insertLoadedJsonData[ix].Del_Qty,
Status: sts,
AddedOn: empty,
AddedBy: window.sessionStorage.getItem(‘username’),
ModifiedOn: empty,
ModifiedBy: empty
}
DeliveryNoteDetailsArrayData.push(deliveryNoteDetails);
}

var jsonParamsArrayData = []
var jsonParams = {
Trip_Number: window.localStorage.getItem(‘tripNumber’),
}
jsonParamsArrayData.push(jsonParams);

var scannedArrayData = [];
var scannedData = {
SlNo: ‘NoData’
}
scannedArrayData.push(scannedData);

var signatureArrayData = [];
var signData = {
Sign: ‘NoData’
}
signatureArrayData.push(signData);

var EmptyscannedArrayData = [];
var scannedData = {
SlNo: ‘NoData’
}
EmptyscannedArrayData.push(scannedData);

var postData = {};
postData.DeliveryNoteDetailsArrayData = DeliveryNoteDetailsArrayData;
postData.jsonParamsArrayData = jsonParamsArrayData;
postData.scannedArrayData = scannedArrayData;
postData.signatureArrayData = signatureArrayData;
postData.EmptyscannedArrayData = EmptyscannedArrayData;

$.ajax({
type: ‘POST’,
async: true,
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded; charset=UTF-8’
},
dataType: “json”,
// url: ‘http://localhost:1312/api/Blog?type=json&#8217;,
url: window.sessionStorage.getItem(“webAPI”) + ‘DeliveryDetails/GetPostDeliveryNoteDetailsTransaction?type=json’,
data: postData,
beforeSend: function(xhr) {
if (isEmpty(window.localStorage.getItem(‘token’))) {
//xhr.setRequestHeader(‘Authorization’, “Bearer ” + window.localStorage.getItem(‘token’));
//xhr.setRequestHeader(“X-Requested-With”, “XMLHttpRequest”);
}
$(“#loading-img”).css({
“display”: “block”
});
},
success: function(data) {
if (data == ‘Success’) {
alert(‘Status Updated’);
window.location = “Master.html”
return true;
} else {
alert(‘Failed while inserting transaction details’);
$(“#loading-img”).css({
“display”: “none”
});
return;
}

},
error: function(xhr, status, error) {
$(“#loading-img”).css({
“display”: “none”
});
alert(xhr.responseText);
}
});
} else {
return;
}

} catch (err) {
alert(err.message);
}
}

 

Web API method:

//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
[HttpPost]
public HttpResponseMessage GetPostDeliveryNoteDetailsTransaction([FromBody]JObject data)
{
DataTable dtJsonDeliveryNoteDetails = (DataTable)JsonConvert.DeserializeObject(data[“DeliveryNoteDetailsArrayData”].ToString(), (typeof(DataTable)));
DataTable dtJsonParameters = (DataTable)JsonConvert.DeserializeObject(data[“jsonParamsArrayData”].ToString(), (typeof(DataTable)));
DataTable dtjsonScannedData = (DataTable)JsonConvert.DeserializeObject(data[“scannedArrayData”].ToString(), (typeof(DataTable)));
DataTable dtjsonSignatureData = (DataTable)JsonConvert.DeserializeObject(data[“signatureArrayData”].ToString(), (typeof(DataTable)));
DataTable dtjsonEmptyScannedData = (DataTable)JsonConvert.DeserializeObject(data[“EmptyscannedArrayData”].ToString(), (typeof(DataTable)));

}