Write data in XML file from an object and Read the same data From XML file using C#.


1.Write and Read data from XML file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace BackToBasic
{
    class XMLToObject
    {
        //TODO : Add Your Code Here

        //Getting the XML data from local folder

        static string path = @"C:\Data\SampleXMLData.xml";

        public static void Main()
        {
            try
            {
                //Create XML file from object
                Student objStudent = new Student();
                Console.WriteLine("Enter Student ID.");
                objStudent.ID = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter Student Name.");
                objStudent.Name = Console.ReadLine().ToString();
                Console.WriteLine("Enter Student Registration Number.");
                objStudent.RegNo = Console.ReadLine().ToString();
                Console.WriteLine("Enter Student Address.");
                objStudent.Address = Console.ReadLine().ToString();
                Console.WriteLine("Enter Student Total Mark.");
                objStudent.TotalMark = int.Parse(Console.ReadLine());
                Console.WriteLine("Enter Studnet Standard.");
                objStudent.Class = Console.ReadLine().ToString();
                Console.WriteLine("Enter Student Grade.");
                objStudent.Grade = Console.ReadLine().ToString();
                Console.WriteLine("Enter Student Contact.");
                objStudent.ContactNumber = Console.ReadLine().ToString();

                int result = CreateXMLFile(objStudent);
                if (result == 0)
                {
                    Console.WriteLine("Wrting Data to XML File failled,Please try again");
                }
                else
                {
                    //Read the XML file which we created now
                    string xmlString = System.IO.File.ReadAllText(path);

                    //Read all XML data and store inside object.
                    Student objstd = (Student)ConvertXMLToObject(xmlString, typeof(Student));

                    //Read all data from object
                    Console.WriteLine();
                    Console.WriteLine("After Successfully Read data from XML file below are the data;");
                    Console.WriteLine();
                    Console.WriteLine("StudnetID : {0}", objstd.ID);
                    Console.WriteLine("Student Name : {0}", objstd.Name);
                    Console.WriteLine("Student Registration Number : {0}", objstd.RegNo);
                    Console.WriteLine("Student Address : {0}", objstd.Address);
                    Console.WriteLine("Studenet Total Mark : {0}", objstd.TotalMark);
                    Console.WriteLine("Student Standard : {0}", objstd.Class);
                    Console.WriteLine("student Grade : {0}", objstd.Grade);
                    Console.WriteLine("Student Contact : {0}", objstd.ContactNumber);
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static Object ConvertXMLToObject(string xml, Type classType)
        {
            StringReader stringReader = null;
            XmlSerializer xmlSerializer = null;
            XmlTextReader xmltextReader = null;
            Object obj = null;
            try
            {
                stringReader = new StringReader(xml);
                xmlSerializer = new XmlSerializer(classType);
                xmltextReader = new XmlTextReader(stringReader);
                obj = xmlSerializer.Deserialize(xmltextReader);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return obj;
        }
        public static int CreateXMLFile(Student student)
        {
            try
            {
                
                System.Xml.Serialization.XmlSerializer writer =
                    new System.Xml.Serialization.XmlSerializer(typeof(Student));

                var path = @"C:\Data\SampleXMLData.xml";
                System.IO.FileStream file = System.IO.File.Create(path);
                writer.Serialize(file, student);
                file.Close();
                return 1;
            }
            catch(Exception ex)
            {
                throw ex;
            }
            
        }
    }
[DataContract(Name ="Studnet")]
   public class Student
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string RegNo { get; set; }
        [DataMember]
        public string Address { get; set; }

        [DataMember]
        public int TotalMark { get; set; }

        [DataMember]

        public string Class { get; set; }

        [DataMember]
        public string Grade { get; set; }
        [DataMember]
        public string ContactNumber { get; set; }
    }
}
Advertisements

A Web Developer should Know.


 

Hi Reader;

Are You working as a web developer ?

Then bellow are the some essential thing you must to know.

Details about this blog coming soon…. 

 

 

Sql Imp Query


 

Select * from(
SELECT 0 as SORTCOLUMN, -1 AS [KEY], ‘Select’ AS [VALUE]
UNION all
SELECT 1 AS SORTCOLUMN, PARAMALLOWEDVALUEID AS [KEY], PARAMETERVALUE AS [VALUE]
FROM ICM_COMMPARAMALLOWDVALUE where PARAMETERID = 1 AND ISACTIVE = 1) tbl order by case when SORTCOLUMN=0 then 3 else 1 end,[value]

Java Script Basic


In this blog I am going to discuss some important and basic concepts of Java Script.

Let’s see one by one;

In JavaScript we declare variable using var keyword; we may assign the variable or we may not.

Key Capsule 1:-

So what happen when we declared

var name;

Capsule 1:- Here name stores by default undefined;

if we print using console.log(name)

o/p :- undefined.

Key Capsule 2:-

var name=”Surya”

    var name;

console.log(name)

What you think what will be the out put ?

O/P :- “Surya”

Capsule 2 :- In java script although I declare the variable once again it won’t loose the value.

Key Capsule 3:-

var result=”sun”+2+3;

console.log(result)

result=2+3+”sun”;

console.log(result)

what you think what is the out put ???

O/p:- “sun”23

5”sun”

Capsule 3:- In java script if any numeric values comes after the string then the Plus (+) operator work like as a concatenation operator where as if the numeric value comes before the string then plus (+) operator works and it show addition of number then it concatenate the string.

Key Capsule 4:-

var studnetName=”Suryakant”;

var studentName=”Rajanikant” ;

console.log(studentName);

var studnetName=”Rahul”;

var studentname=”Raj”;

console.log(studnetName);

console.log(studentname);

What will be the out put ??

O/P:- “Rajanikant”

“Rahul”

“Raj”

Capsule 5:- Why so ?? Because the JavaScript variable are case sensitive; so when I write studnetName and strudnetname both are different variable.

Remember all variable in JavaScript are called as identifier and each variable is an unique identifier.

Key Capsule 6 :-

How to print a string like this;

“The name is “Surykant”; he is a blogger.”

I want to print suryakant with the double quot.

To do this in javascript we have different escape character which can be use to achieve this.

We can write;

var data=”The name is \”Suryakant\”; he is a blogger”.

Same for single quto;

var data=”It\’s looking good.”

Most Important Key Capsule 7:-

Difference between == and === operator

“== “ operator is used to check directly the value where as “===” equality operator check the equality and types.

See bellow examples;

Test Case 1:-

var x=”surya”;

var y= “surya”;

console.log(x==y)

console.log(x===y)

o/p- true

Note :- Here the output true for both the case because both are storing same value and both are of same type

Test Case 2:-

var x=”surya”

var y=new string (“surya”)

console.log(x==y);

o/p- true

Scenario:- Here some of us might think that why it returns true ?

This question also came to my mind; because the second one is reference type; as we know inside reference type variable it stores the address of that value i.e “surya”.

So how both are equal then ??

Here important thing to understand that what actually happen when we comparing the value using double equality operator (“==”).

When we using double equality operator (“==”) to compare then this operator perform a type conversion while comparing two things; so in the above example when we compare x and y, although y is a object type it is converted to string type while comparing so both are get same type with value so it returns as true.

Where as triple equality operator (“===”)  never do any type of conversion while comparing; it only check the type and value if both are same then it returns true other wise returns false.

Key To Remember :– So if we check any two reference/object type variable using triple equality operator (“===”) then it always return false; same for double equality operator (“==”) also return false; but if both are reference type pointing to same location then “===” operator return true.

Confused ????

Let’s clear; both reference type/object type pointing to same location means;

var obj=new string(“surya”);

var obj1=obj

Now if we check; obj===obj then we get output as true.

Capsule 7 :- What we learn form the above :-

Double equality operator(“==”) do conversion before checking while triple equal to operator(“===”) never do any conversion before checking it just check the type and value.

examples :-

var a=1;

var b=”surya”;

var c=new string(“surya”);

Now; a===a   // True ;   b===b // True;  c===c   //True

Again if i declare a new object type variable;

var d=new string(“surya”);

Now;  c===d  // False

Note :- Although ‘c’ and ‘d’ are the same type still it return false because after checking the type it will check the value inside it; both are pointing to different location so both have different value so it return false.

if we write; c==d

Note :- Now what happened both are converted to reference type; and due to both pointing different location; so it return false.

Key To Remember :- Due to the above reason double equality operator (“==”) called as loose equality operator where as triple equality operator (“===”) called as  strict equality operator.

Test Case 3:-

var x=”surya”

var y=new string (“surya”)

console.log(x===y);

o/p:- false

Note :- Here the output is false because “===” operator is used to check type and both having different types so it return false.

Test Case 4:-

var x=new string(“surya”);

var y=new string (“surya”);

console.log(x==y);

o/p:- false

console.log(x===y)

o/p:- false

What is value type and reference type in JavaScript ?

Ans:- In java script data types are classified into two types such as value type and reference type.

Under value type we have data type like;

Int, string,number,Boolean,null and etc.

Where as under reference type we have data type like;

Function,array,object.

Combine this all we said all these are object type.

Note:- Value types are directly stored value in side the variable where as reference type are stored the address of the object and that address pointing to the actual value location.

Key Capsule 8 :

In Java script we have different global methods for Number such as;

  • Number()
  • parseInt()
  • parseFloat()

Important Test Case:-

Test Case 1 :- parseInt(“10 Year”) //O/P- 10

Test Case 2 :- parseInt(“Year 10”) //O/P – NaN

Key Capsule 9:-

In JavaScript we can define an array by using bellow syntax;

Var stdArr=[];

Note:- stdArr is a special type of object which store different type of object inside it.

Join Method in Array:-

In JavaScript the join method is used to convert the array into string but we can specify separator inside join method.

For eg:- var arr=[“Ram”,”Hari”,”Madhu”]

arr.join(“*”);

so the o/p Ram * Hari * Madhu.

Key Capsule 10:-

In JavaScript we use a key word called as “use strict”.

This is indicate that we can not use a variable without declaring it. So if we use a variable without declaring it then it’s gives you an error.

Note :- Use strict can be write at the top of the script.

Use strict

a=2+3;

console.log(a) // Error because we did not declare the variable a.

 

Hope above concept helps you in understanding the basic concept; will see more on coming days.

Thanks for reading; have your feedback in comment box if you have any doubt in any test case.

#Share2Know #Learn Basic #JavaScript

 

 

C# 7.0 Features


C# language some Keys to know:

1. In C# language to know the which dot net version you are using at run time you can use “Enviourment.Version”.
You can also find;
Console.WriteLine(Environment.Version);
Console.WriteLine(Environment.OSVersion);
Console.WriteLine(Environment.ProcessorCount);
Console.WriteLine(Environment.MachineName);

2. C# 7.0 Features :-
— 1. Touples:-
— 2. Tuple Deconstruction :- Any object can be deconstructed by defining a Deconstruct method in the class:
for example :-
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }

public void Deconstruct(out string firstName, out string lastName)
{
firstName = FirstName;
lastName = LastName;
}
}

var person = new Person { FirstName = “John”, LastName = “Smith” };
var (localFirstName, localLastName) = person;

In this case, the (localFirstName, localLastName) = person syntax is invoking Deconstruct on the person.

— An alternative approach for the Person class is to define the Name itself as a Tuple. Consider the following:

Example:- class Person
{
public (string First, string Last) Name { get; }

public Person((string FirstName, string LastName) name)
{
Name = name;
}
}

Then you can instantiate a person like so (where we can take a tuple as an argument):

var person = new Person((“Jane”, “Smith”));

var firstName = person.Name.First; // “Jane”
var lastName = person.Name.Last; // “Smith”

— Touple Intialization :-

You can also arbitrarily create tuples in code:

var name = (“John”, “Smith”);
Console.WriteLine(name.Item1);
// Outputs John

Console.WriteLine(name.Item2);
// Outputs Smith

When creating a tuple, you can assign ad-hoc item names to the members of the tuple:

var name = (first: “John”, middle: “Q”, last: “Smith”);
Console.WriteLine(name.first);
// Outputs John

 

— 3. Out var declaration

The out var declaration is a simple feature to improve readability. It allows a variable to be declared at the same time that is it passed as an out parameter.

A variable declared this way is scoped to the remainder of the body at the point in which it is declared.

In C# 7.0, you can inline the declaration of the variable passed to the out parameter, eliminating the need for a separate variable declaration:-

Example :-

if (int.TryParse(input, out var value))
{
Foo(value); // ok
}
else
{
Foo(value); // value is zero
}

Foo(value); // still ok, the value in scope within the remainder of the body

If some of the parameters that a function returns in out is not needed you can use the discard operator _.

p.GetCoordinates(out var x, out _); // I only care about x

An out var declaration can be used with any existing function which already has out parameters. The function declaration syntax remains the same, and no additional requirements are needed to make the function compatible with an out var declaration. This feature is simply syntactic sugar.

Another feature of out var declaration is that it can be used with anonymous types.
7.0
Example:-
var a = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var groupedByMod2 = a.Select(x => new
{
Source = x,
Mod2 = x % 2
})
.GroupBy(x => x.Mod2)
.ToDictionary(g => g.Key, g => g.ToArray());
if (groupedByMod2.TryGetValue(1, out var oddElements))
{
Console.WriteLine(oddElements.Length);
}

In this code we create a Dictionary with int key and array of anonymous type value. In the previous version of C# it was impossible to use TryGetValue method here since it required you to declare the out variable (which is of anonymous type!). However, with out var we do not need to explicitly specify the type of the out variable.