JavaScript

Wednesday 13 January 2016

Create ZIP file with multiple file in a folder



   first you can add system.io.compression.filedirectory
 then create a file and move it a folder then compress it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileNamewithExtension = DateTime.Now.Ticks.ToString() + ".txt";
            string filePath = @"C:\AbhishekData\" ;
            string fileName = filePath + fileNamewithExtension;
            using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
            {
                string s = "My Name is abhishek";
                byte[] byteArray = Encoding.ASCII.GetBytes(s);
                fs.Write(byteArray, 0, byteArray.Length);
                fs.Flush();
                fs.Close();
              
                string zipPath = @"C:\AbhishekData\"+ DateTime.Now.Ticks.ToString()+".zip";
                if (!Directory.Exists(@"C:\AbhishekData\myabc"))
                {
                    Directory.CreateDirectory(@"C:\AbhishekData\myabc");
                    File.Move(fileName, @"C:\AbhishekData\myabc\"+ fileNamewithExtension);
                    ZipFile.CreateFromDirectory(@"C:\AbhishekData\myabc", zipPath,CompressionLevel.Fastest,true);
                }
                else
                {
                    File.Move(fileName, @"C:\AbhishekData\myabc\"+ fileNamewithExtension);
                    ZipFile.CreateFromDirectory(@"C:\AbhishekData\myabc", zipPath, CompressionLevel.Fastest, true);
                }
            }
        }
    }
}

Tuesday 13 October 2015

Create Cross Page Posting in web api through angular javascript

Develop you first web api application Using .Net IDE

   [ActionName("GetValues")]
        public IEnumerable<string> Get(string UserName, string Password)
        {
            return new string[] { "value1", "value2" };
        }

This API return array of string then we consume
using angular javascript

var phoneCateApp = angular.module('PhoneCatApp', ['ngRoute']);

phoneCateApp.controller('PhoneCateController', function ($scope, $http) {
   
    $http({
        url: 'http://localhost:52600/api/Values/GetValues',
        method: "GET",
     
        contentType: "application/json",
        headers : { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
  
        data: '{ UserName: fsdfsda, Password: fsdfsda }'
    }).success(function (data) { $scope.PhoneList = data; });

});

inject the ngRoute in angular javascript

then set the web.config web api

 <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
      </customHeaders>
    </httpProtocol>

in <system.webserver>


Then your application call all your rest service successfully

Wednesday 24 June 2015

Form Validation throgh Angular js

 i am searching on internet then found many missing thing on validation on form when you are beginner and learning in angular js
I am follow few step of validation of angular js then validate my form. validation script
   var d = angular.module('myapp', []);
    d.controller('HomeController', function($scope) {
      $scope.loginForm = {
        UserName: '',
        password: '',
        email: '',
        Gender: [{
          value: 0,
          text: '--select--'
        }, {
          value: 1,
          text: 'Male'
        }, {
          value: 2,
          text: 'female'
        }]
      }
      $scope.form = $scope.loginForm.Gender[0].value

      $scope.validate = function(model) {

        $scope.form1.$submitted = true;
        $scope.selectedGender = document.getElementById('ddlGender').value == '0'
        if ($scope.selectedGender) {
          return false;
        }
        if ($scope.form1.$valid) alert(1);

      }
      $scope.onSelectChange = function() {
        $scope.selectedGender = document.getElementById('ddlGender').value == '0'
      }

    })

Name This is required
Password This is required
Gender this is required

Friday 27 March 2015

Post List of object using ajax in server side



  This is simple step how to send data client side to server side using javascript and jquery
/// arry your object u can store value of json type
  var array = [];
        function SendData() {
            if (array.length > 0) {
                var json_Parse = JSON.stringify(array);
             
                console.log(json_Parse);
                $.ajax({
                    type: "post",
                    url: "LargeDataPageLoad.aspx/GetString",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: '{ "obj":' + json_Parse + ' }',
                    success: function (response) {
                        response ? alert("It worked!") : alert("It didn't work.");
                        onCustomerClick();
                    },
                    error: function (xhr, status, error) {
                        alert(error);
                    }
                });
           
            }
       
         }

Thursday 26 March 2015

Best way manipulate data in json array get server side using client side

 
 <script type="text/javascript">
        $(document).ready(function () { });
        function onCustomerClick() {
            $("#CustomerDetails").html('');
            $("#CustomerDetails").append('<table widht="100%" id="newTable"  cellpadding="5">' +
            '<tr><th>&nbsp;</th><th>&nbsp;</th><th>CustomerCode</th><th>Customer Name</th><th>Name On Card</th><th>Created Date</th><th>&nbsp;</th></tr>');
            var optionHTML = '';
            optionHTML += '<select>';
            $.ajax({
                type: "post",
                url: "LargeDataPageLoad.aspx/LoadHugeData",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $.each(response, function (key, value) {

                        var json_data = JSON.parse(value);
                        console.log();
                        for (var index = 0; index < json_data.dt.length; index++) {

                            var selectId = "select_" + index;
                            var d = new Date(json_data.dt[index]["CreatedDate"]);
                            $("#newTable").append('<tr><td>' + (index + 1) + '</td><td><input type="checkbox" onchange="enableDropdown(this,' + selectId + ')" id="chk_' + index + '"/></td><td>' + json_data.dt[index]["CustomerCode"] + '</td><td>'
                                                     + json_data.dt[index]["NameOnCard"] + '</td><td>'
                                                     + json_data.dt[index]["CustomerName"] + '  <td>' + d.toLocaleDateString()
                                                     + '</td><td id="td_' + index + '"></td></tr>'

                                               );

                            { $('#td_' + index).append('<select id="select_' + index + '" disabled="disabled" >'); }
                            for (var option = 0; option < json_data.dtOption.length; option++) {
                                if (option == 0)
                                    $('#select_' + index).append('<option value="-1">-Select-</option>');
                                $('#select_' + index).append('<option  value="' + json_data.dtOption[option]["Value"] + '">' + json_data.dtOption[option]["Name"] + '</option>');

                            }
                            $('#td_' + index).append('</select></td>');
                            //$('#td_' + index).html(optionHTML);
                        }
                        //                        $.each(value, function (key1, value1) {
                        //                            console.log(key1);
                        //                            var json_data = JSON.parse(value1);
                        //                            for (var index = 0; index < json_data.length; index++) {
                        //                                $("#newTable").append('<tr><td>' + json_data[index]["CustomerCode"] + '</td><td>'
                        //                             + json_data[index]["NameOnCard"] + '</td><td>'
                        //                             + json_data[index]["CustomerName"] + '</td>'

                        //                           );
                        //                            }

                        //                        });

                    });
                },
                error: function (xhr, status, error) {
                    alert(error);
                }
            });

            $("#CustomerDetails").append('</table>');
        }
        var array = [];

        function enableDropdown(value, ddlValue) {

            var ddlId = '#' + ddlValue.id;
            var splitValue = ddlId.split('_');
            var json_data = { id: parseInt(splitValue[1]) };

            $(ddlId).attr('disabled', !document.getElementById(value.id).checked);
            if (document.getElementById(value.id).checked) {
                array.push(json_data);
              
            } else {
              $.grep(array, function (n, i) {
                 if(typeof n != "undefined")
                if (n.id == parseInt(splitValue[1])) {
                  
                    var index = array.indexOf(array[i]);
                  
                    if (index > -1) {
                        array.splice(index, 1);
                    }
                }
                return array;
            });
            }
            console.log(array);
        }
    </script>

Friday 31 May 2013

Creat google map your website

<script type="text/javascript">
var map;
var infowindow;
 var k =0
var lat = [28.6312870,28.634244 ,28.634401,28.626969]
var lang =[77.2270520, 77.22220300000004, 77.222125,77.22228300000006]
var destination =['Lalit House', 'Nirulas', 'Costa Coffee','British Council']
function initialize()
{
  var pyrmont = new google.maps.LatLng(28.6312870, 77.2270520);
  map = new google.maps.Map(document.getElementById('googleMap'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: pyrmont,
    zoom: 15
  });

 
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  var placeLoc = '(28.6312870, 77.2270520)';
  for(var i =0 ; i< lat.length; i++)
    {
  if(i < lang.length){
  for(var j =0 ; j < lang.length; j++)
  {
  var items = new google.maps.LatLng(lat[i++],lang[j])
   if(j< destination.length){
    createMarker(items,destination[k])
        }
     k++;
      }
    }
  }
}
function createMarker(place,name)
{
  var marker = new google.maps.Marker({ map: map, position:place });
  google.maps.event.addListener(marker, 'click', function()
  {
    infowindow.setContent(name+"<div><a href=\"\">More Info</a></div>");
    infowindow.open(map, this);                 
  });
}
google.maps.event.addDomListener(window, 'load', initialize);

    </script>
<div id="googleMap" style="width:400px; height:300px;" runat="server"></div>

Tuesday 30 April 2013

Create XML file usign C# and then create sub node in existing file

 string file = @"c:\bb.xml";  
        // declearation 
       // parent node
        
        XmlElement subnode = xdoc.CreateElement("subnode");
       // Checking File Exist or not
        if (File.Exists(file))
        {
            xdoc.Load(@"C:\bb.xml");
            xdoc.DocumentElement.AppendChild(userinfo(txtuser.Text, txtpass.Text));
            xdoc.Save(file);
        }
        else
        {
            subnode.AppendChild(userinfo(txtuser.Text, txtpass.Text));
            xdoc.AppendChild(subnode);
            xdoc.InsertBefore(xdoc.CreateXmlDeclaration("1.0", "utf-8", null), subnode);
            xdoc.Save(file);
        }


// then create the xml node using this methods


XmlNode node = xdoc.CreateElement("Info");
        XmlNode user_node = xdoc.CreateElement("user");
        user_node.InnerText = user.ToString();
        node.AppendChild(user_node);
        XmlNode pass_node = xdoc.CreateElement("password");
        pass_node.InnerText = pass;
        node.AppendChild(pass_node);
        return node;