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);
              }
          }
  }  



       

Add Placeholder text in Excel from VB.Net

If you want to display placeholder text in excel cell, so that user can know what should be entered and on entering the placeholder text goes and entered value will be shown, then you need to format cell as custom format and give below formula

General;General;[Color15]”dd-MMM-yyyy”

Below is the VB.Net code , if you want to do through coding

Protected Sub btn_Click(sender As Object, e As EventArgs)
Using wb = New XLWorkbook()
Dim ws = wb.AddWorksheet(“Sheet1”)
Dim cell = ws.FirstCell()
cell.Value = 0.0
‘cell.DataType = XLDataType.DateTime
cell.Style.NumberFormat.Format = BuildWatermarkFormat(“dd-MMM-yyyy”) ‘”_ * # ##0.00_ ;_ * -# ##0.00_ ;_ * “”-“”??_ ;_ @_ “
‘cell.Style.NumberFormat.SetNumberFormatId(43)
‘cell.Value = 0
ws.Columns(“A”).AdjustToContents()
wb.SaveAs(“d:\test.xlsx”)
End Using
End Sub

Public Function BuildWatermarkFormat(ByVal watermarkText As String, Optional ByVal positiveFormat As String = “General”, Optional ByVal negativeFormat As String = “General”, Optional ByVal textFormat As String = “General”) As String
BuildWatermarkFormat = positiveFormat & “;” & negativeFormat & “;[Color15]” & Chr(34) & watermarkText & Chr(34) & “;” & textFormat
End Function

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();
    }
}

Post Bulk Data $ajax type post

function PostBulkData() {
try {

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

for (var ix = 0; ix <= LoadedJsonData.length – 1; ix++) {
var deliveryNoteDetails = {
ID: 0,
Delivery_Note_ID: LoadedJsonData[ix].ID,
Delivery_ID: LoadedJsonData[ix].Delivery_ID,
Del_Date: LoadedJsonData[ix].Del_Date,
Cust_Account_ID: LoadedJsonData[ix].Cust_Account_ID,
Cust_Account_Number: LoadedJsonData[ix].Cust_Account_Number,
Cust_Name: LoadedJsonData[ix].Cust_Name,
Some_ID: LoadedJsonData[ix].Some_ID,
Item_Code: LoadedJsonData[ix].Item_Code,
Item_Decription: LoadedJsonData[ix].Item_Decription,
UOM: LoadedJsonData[ix].UOM,
Del_Qty: LoadedJsonData[ix].Del_Qty,
Status: sts,
AddedOn: empty,
AddedBy: window.sessionStorage.getItem(‘username’),
ModifiedOn: empty,
ModifiedBy: empty
}
SomeArrayData.push(deliveryNoteDetails);
}

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

// var jsonData = JSON.stringify(DeliveryNoteDetailsTransaction);
// var jsonParameters = JSON.stringify(jsonParamsArray);
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.SomeArrayData = SomeArrayData;
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: window.sessionStorage.getItem(“webAPI”) + ‘ControllerNm/GetPostMethdName?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’) {
//updateStatus();
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);
}
}

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;
}