Friday, May 20, 2016

Read xml file into list with C#


      1.Create an xml file in below format

  xml version="1.0" encoding="utf-8" ?>
   <ArrayOfProduct>
     <Product>
       <Id>1</Id>
       <Name>product 1</Name>
       <Price>20000</Price>
     </Product>
     <Product>
       <Id>2</Id>
       <Name>product 2</Name>
       <Price>15000</Price>
     </Product>
   </ArrayOfProduct>

      2.Create a property class for the xml file

public class Product
       {
              public int Id { getset; }
              public string Name { getset; }
              public float Price { getset; }
}



3. Include these namespaces

using System.Xml.Serialization;
using System.IO;     

4.       Read xml to list

List<Product> lstProduct;
//Datas/Product.xml is the relative path of xml file.
string folderPath = System.Web.HttpContext.Current.Server.MapPath("~/Datas/Product.xml"); 
       XmlSerializer serializer = new XmlSerializer(typeof(List<Product>));
       using (FileStream fs = new FileStream(folderPath, FileMode.Open,FileAccess.Read))
       {
     //Deserialize to Product list.
            lstProduct = (List<Product>)serializer.Deserialize(fs);
       }
//lstProduct contains the result.

5.   Read Xml as a generic method
 /// 
        /// Read the xml to list.
        /// 

        /// Class Name.

        /// Relative path of xml file."
        /// List of objects of specific type.

        public List ReadXml(string relativePath)
        {
            List lstResult = null;
            try
            {
                string folderPath = System.Web.HttpContext.Current.Server.MapPath(relativePath);
                XmlSerializer serializer = new XmlSerializer(typeof(List));
                using (FileStream fs = new FileStream(folderPath,FileMode.Open, FileAccess.Read))
                {
                    lstResult = (List)serializer.Deserialize(fs);
                }
            }
            catch (Exception ex)
            {

            }
            return lstResult;
}


           6.     Call the generic method

       //Read Product.xml to list of products.
List<Product> lstProduct = ReadXml<Product>("~/Datas/Product.xml");

Tuesday, March 4, 2014

Use MVC Html.BeginForm with GET method and action parameter

@using (Html.BeginForm("Details", "Home", new { name = Model.Name }, 
                        FormMethod.Get, new { name = "foo_bar" }))

Saturday, March 1, 2014

HomeController inherit from BaseController, but didn't run a function in BaseController

I try make internationalization using this tutorial, the problem is that the basecontroller is not execute.

public class BaseController : Controller
    {
        protected override void ExecuteCore()
        {
           ........
            base.ExecuteCore();
        }

    }

 public class HomeController : BaseController
    {
        public ActionResult Index()
        {
           ...
            return View();
        }
}

Thursday, February 27, 2014

jquery timepicker dateFormat Validation

jquery-ui-timepicker-addon.js: How to set  dateformat?


 $("#EventDate").datetimepicker({ dateFormat: 'dd/MM/yy', timeFormat: "hh:mm tt" });
It does not work with the culture globalize.

Monday, February 24, 2014

Solved : Google Map API Get the error - Cannot read property 'value' of null

I have the following JavaScript file, if I comment the file, there will be no error.


// <!-- This code tells the browser to execute the "Initialize" method only when the complete document model has been loaded. -->
$(document).ready(function () {


    var geocoder;
    var map;

    var componentForm = {
        street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'
    };

    var options = {
        //  types: ['(cities)']
        types: ['geocode'] //this should work !
    };

    var input = document.getElementById('Address');
    var dlCountry = document.getElementById('Country');
    //alert(input.id);
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var place = autocomplete.getPlace();
        //alert('place');
        //// Get each component of the address from the place details
        //// and fill the corresponding field on the form.
        var addressNoCountry = '';
        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType]) {
                var val = place.address_components[i][componentForm[addressType]];
                if (addressType != 'country') {
                    //alert('i='+i+':'+val +'-1-'+ addressType +'-2-'+ componentForm[addressType]);

                    if (addressNoCountry == '')
                    { addressNoCountry = val; }
                    else
                    {
                        if (addressType == 'route')
                        { addressNoCountry = addressNoCountry + ' ' + val; }
                        else
                            addressNoCountry = addressNoCountry + ', ' + val;
                    }
                    //$('#SearchLocation').val(val);
                    //document.getElementById(addressType).value = val;
                }
                else {
                    $("#hidCountry").val(val);
                }
            }
        }
        //alert(addressNoCountry);
        $("#hidAddress").val(addressNoCountry);
        //alert($("#hidCountry").val());
        $("#Country").val($("#hidCountry").val());
        //dlCountry.val(addressNoCountry);
        LoadAddress();
    });

    onMapLoaded();
});

function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 8,
        center: latlng
    }
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    //alert(map);
}

function onMapLoaded() {
    //alert("1");
    $("#Address").blur(function (evt) {
        LoadAddress();

    });

}

function LoadAddress() {
    var address = jQuery.trim($("#Address").val());
    if (address.length < 1)
        return;
    //alert(address);

    //map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    //alert(map);
    geocoder.geocode({ 'address': address }, function (results, status) {
        //alert(status);
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            //alert(results[0].geometry.location.lat());
            // $("#Location").val(results[0].geometry.location);
            var geolocation = results[0].geometry.location;
            $("#Location").val(geolocation.lat() + "," + geolocation.lng());
            //alert($("#Location").val());
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

Sunday, February 23, 2014

Google Map API Get the error - Cannot read property 'value' of null

I got the following error from the JavaScript:
TypeError: Cannot read property 'value' of null
http://localhost:51654:11

In the _layout.cshtml page 
head
....
JavaScript link :maps.google.com/maps/api/js?sensor=false&libraries=places
...
head

If I add the following code in the view page, no error in the page
   maps.google.com/maps/api/js?sensor=false
I cannot figure out what is the wrong?

Wednesday, February 19, 2014

Learning Angular 1 month

In the website thegospelevent.com, I created google maps by using JQuery, the problem is: In the detail page, the google map did not show "Zoom toolbar", when I refreshed several times, the "Zoom toolbar" will show. so I am using Angularjs, it works like charm.

 *Notes:
 angular.element(document).ready(function () {
    angular.bootstrap($("#appElement"), ['myApp']);
        //// appElement is the html element on which you define ng-app, myApp is the name of the app
 });

 For jquery :
       $(document).ready(function (){ });