Tuesday, 22 December 2015

The remote server returned an error: (400) Bad Request. using (WebResponse resp = req.GetResponse())

try
        {
            HttpWebRequest req = WebRequest.Create(UnitInfoServiceUrl) as HttpWebRequest;
            req.Credentials = new NetworkCredential("", "");
            req.KeepAlive = false;
            string result;
            using (WebResponse resp = req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
                {
                    result = reader.ReadToEnd();

                }
            }
        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                Response.Write(string.Format("Error code: {0}", httpResponse.StatusCode));
                using (Stream data = response.GetResponseStream())
                using (var reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    Response.Write(text);
                  dynamic stuff1 = JsonConvert.DeserializeObject(text);
                  string Error = stuff1.ERROR;
                    Response.Write(Error );
                }
            }
         
        }

Date and Time picker different formate

http://xdsoft.net/jqplugins/datetimepicker/

Friday, 11 December 2015

print function for particular div in js

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Tuesday, 8 December 2015

Clearing the textbox values onclick and displaying onblur

HTML:
<input type="text" value="" onClick="Clear();" id="textbox1>
Javascript :
function Clear()
{    
   document.getElementById("textbox1").value= "";
  
}
function keephere(){    
   document.getElementById("textbox1").value= "name";
  
}

 <input type="text" ... onkeyup="JavaScript: Clear()" 
onmouseup="JavaScript: keephere()" >

Wednesday, 2 December 2015

Http request call code behind site

  string UnitInfoServiceUrl = "http://pramod.com/APHS_SAP_SERVICES/Unit_Info";

            HttpWebRequest req = WebRequest.Create(UnitInfoServiceUrl) as HttpWebRequest;
            req.Credentials = new NetworkCredential("pramod", "password@1");
            req.KeepAlive = false;
            string result;
            using (WebResponse resp = req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                    Session["APHSUnit_Info"] = result;
                }
            }

            dynamic stuff = JsonConvert.DeserializeObject(result);
            string SUCCESS = stuff.SUCCESS;
            rblUnitsCompany.Items.Clear();
            foreach (var item in stuff.MESSAGE)
            {
                if (ddlcity.SelectedItem.Text.Trim().ToLower() == Convert.ToString(item.CITY).Trim().ToLower())
                {
                    rblUnitsCompany.Items.Add(new ListItem((item.CITY.ToString() + "-" + Convert.ToString(item.UNIT_CODE)), Convert.ToString(item.UNIT_CODE)));

                }
            }

Web service .ASMX call code behind site

 public string WebServiceCallsession(string username, string methodName)
    {
        WebRequest webRequest = WebRequest.Create("https://pramod.com/Uservalidate.asmx");//http://localhost/AccountSvc/DataInquiry.asmx
        HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
        httpRequest.Method = "POST";
        httpRequest.ContentType = "text/xml; charset=utf-8";
        httpRequest.Headers.Add("SOAPAction: http://tempuri.org/" + methodName);
        httpRequest.ProtocolVersion = HttpVersion.Version11;
        httpRequest.Credentials = CredentialCache.DefaultCredentials;
        Stream requestStream = httpRequest.GetRequestStream();
        //Create Stream and Complete Request            
        StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

        StringBuilder soapRequest = new StringBuilder("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
        soapRequest.Append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
        soapRequest.Append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>");
        soapRequest.Append("<KillSession xmlns=\"http://tempuri.org/\"> <as_user_id>" + username + "</as_user_id><as_flag>DUPLICATELOGIN</as_flag></KillSession>");
        soapRequest.Append("</soap:Body></soap:Envelope>");

        streamWriter.Write(soapRequest.ToString());
        streamWriter.Close();
        //Get the Response  
        HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
        StreamReader srd = new StreamReader(wr.GetResponseStream());
        string resulXmlFromWebService = srd.ReadToEnd();
        return resulXmlFromWebService;
    }

Thursday, 19 November 2015

To prevent document mode quirks

To prevent quirks mode, define a 'doctype' like :

Make sure you use the right doctype.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

or just

<!doctype html>

Make sure you take into account that adding this tag,

<meta http-equiv="X-UA-Compatible" content="IE=Edge">





Wednesday, 18 November 2015

Save files in database site and retrieve files

 ======Aspx =========
<form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="InsertDoc" OnClick="InsertDoc_Click" />
        <asp:Button ID="Button2" runat="server" Text="InsertXls" OnClick="InsertXls_Click" />
        <asp:Button ID="Button3" runat="server" Text="InsertImage" OnClick="InsertImage_Click" />
        <asp:Button ID="Button4" runat="server" Text="InsertPdf" OnClick="InsertPdf_Click" /><br /><br />
        <asp:LinkButton ID="LinkButton1" runat="server" OnClick = "Retreive_Doc">Download Doc</asp:LinkButton>
        <asp:LinkButton ID="LinkButton2" runat="server" OnClick = "Retreive_Xls">Download xls</asp:LinkButton>
        <asp:LinkButton ID="LinkButton3" runat="server" OnClick = "Retreive_Image">Download Image</asp:LinkButton>
        <asp:LinkButton ID="LinkButton4" runat="server" OnClick = "Retreive_Pdf">Download Pdf</asp:LinkButton>
    </div>
    </form>
======c sharp code=========
using System;
using System.Data;
using System.Data.SqlClient ;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
 
    protected void InsertDoc_Click(object sender, EventArgs e)
    {
        // Read the file and convert it to Byte Array
        string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
        string filename = Path.GetFileName(filePath);

        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();

        //insert the file into database
        string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        InsertUpdateData(cmd);
    }
    protected void InsertXls_Click(object sender, EventArgs e)
    {
        // Read the file and convert it to Byte Array
        string filePath = Server.MapPath("APP_DATA/Testxls.xlsx");
        string filename = Path.GetFileName(filePath);

        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();

        //insert the file into database
        string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-excel";
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        InsertUpdateData(cmd);
    }
    protected void InsertImage_Click(object sender, EventArgs e)
    {
        // Read the file and convert it to Byte Array
        string filePath = Server.MapPath("APP_DATA/TestImage.jpg");
        string filename = Path.GetFileName(filePath);

        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();

        //insert the file into database
        string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "image/jpeg";
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        InsertUpdateData(cmd);
    }

    protected void InsertPdf_Click(object sender, EventArgs e)
    {
        // Read the file and convert it to Byte Array
        string filePath = Server.MapPath("APP_DATA/TestPdf.pdf");
        string filename = Path.GetFileName(filePath);

        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();

        //insert the file into database
        string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/pdf";
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        InsertUpdateData(cmd);
    }

    protected void Retreive_Doc(object sender, EventArgs e)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }
    protected void Retreive_Xls(object sender, EventArgs e)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 2;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }
    protected void Retreive_Image(object sender, EventArgs e)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }

    protected void Retreive_Pdf(object sender, EventArgs e)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 4;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }

    private Boolean InsertUpdateData(SqlCommand cmd)
    {
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            return false;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
    }

    private DataTable GetData(SqlCommand cmd)
    {
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;
        }
        catch
        {
            return null;
        }
        finally
        {
            con.Close();
            sda.Dispose();
            con.Dispose();
        }
    }

    private void download (DataTable dt)
    {
        Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = dt.Rows[0]["ContentType"].ToString();
        Response.AddHeader("content-disposition", "attachment;filename="
        + dt.Rows[0]["Name"].ToString());
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }

 
}
======web config=========
<connectionStrings>
    <add name="conString" connectionString="Data Source=server;database=dbFiles;uid=sa;pwd=Admin@123"/>
  </connectionStrings >

=====Db==============
/****** Object:  Table [dbo].[tblFiles]    Script Date: 11/19/2015 11:43:46 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tblFiles](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[ContentType] [nvarchar](50) NULL,
[Data] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Tuesday, 17 November 2015

Angular Js my notes

Response.AppendHeader("Access-Control-Allow-Origin", "*")

AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.

AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS expressions binds data to HTML the same way as the ng-bind directive.

If you remove the ng-app directive, HTML will display the expression as it is, without solving it:

Application explained:

The AngularJS application is defined by  ng-app="myApp". The application runs inside the <div>.

The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.

The myCtrl function is a JavaScript function.

AngularJS will invoke the controller with a $scope object.

In AngularJS, $scope is the application object (the owner of application variables and functions).

The controller creates two properties (variables) in the scope (firstName and lastName).

The ng-model directives bind the input fields to the controller properties (firstName and lastName).

$http is an AngularJS service for reading data from remote servers.
=========================================================

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="">

<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>

<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
<p>{{name}}</p>


<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>


<div data-ng-app="" data-ng-init="firstName='John'">

<p>The name is <span data-ng-bind="firstName"></span></p>

AngularJS expressions are written inside double braces: {{ expression }}
<p>My first expression: {{ 5 + 5 }}</p>
</div>
=========================================================
<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>
=========================================================
AngularJS numbers are like JavaScript numbers:

<div ng-app="" ng-init="quantity=1;cost=5">

<p>Total in dollar: {{ quantity * cost }}</p>
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>

</div>
=========================================================
AngularJS strings are like JavaScript strings:

<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>

</div>
=========================================================
AngularJS objects are like JavaScript objects:

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is {{ person.lastName }}</p>
<p>The name is <span ng-bind="person.lastName"></span></p>

</div>
=========================================================
AngularJS arrays are like JavaScript arrays:

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>
<p>The third result is <span ng-bind="points[2]"></span></p>

</div>
=========================================================
<div ng-app="" ng-init="quantity=1;price=5">

Quantity: <input type="number" ng-model="quantity">
Costs:    <input type="number" ng-model="price">

Total in dollar: {{ quantity * price }}

</div>
=========================================================
The ng-repeat directive used on an array of objects:

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
</div>
=========================================================
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">

<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

</div>
=========================================================
<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
    }
});
</script>
=========================================================
Adding Filters to Expressions
A filter can be added to an expression with a pipe character (|) and a filter.

<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | uppercase }}</p>

</div>

The orderBy filter orders an array by an expression:

<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
  <li ng-repeat="x in names | orderBy:'country'">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

<div>
=========================================================
Filtering Input
An input filter can be added to a directive with a pipe character (|) and filter followed by a colon and a model name.
The filter filter selects a subset of an array:

<div ng-app="myApp" ng-controller="namesCtrl">

<p><input type="text" ng-model="test"></p>

<ul>
  <li ng-repeat="x in names | filter:test | orderBy:'country'">
    {{ (x.name | uppercase) + ', ' + x.country }}
  </li>
</ul>

</div>
=========================================================
AngularJS $http is a core service for reading data from web servers.
$http.get(url) is the function to use for reading server data.
Display the Table Index ($index)
Using $even and $odd

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>

<ul>
  <li ng-repeat="x in names">
    {{ $index + 1 }}
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function(response) {$scope.names = response.records;});
});
</script>

{
"records": [
  {
    "Name" : "Alfreds Futterkiste",
    "City" : "Berlin",
    "Country" : "Germany"
  },
  {
    "Name" : "Berglunds snabbköp",
    "City" : "LuleÃ¥",
    "Country" : "Sweden"
  }
]
}

Application explained:

The AngularJS application is defined by ng-app. The application runs inside a <div>.

The ng-controller directive names the controller object.

The customersCtrl function is a standard JavaScript object constructor.

AngularJS will invoke customersCtrl with a $scope and $http object.

$scope is the application object (the owner of application variables and functions).

 $http is an XMLHttpRequest object for requesting external data.

$http.get() reads JSON data from http://www.w3schools.com/angular/customers.php.

If success, the controller creates a property (names) in the scope, with JSON data from the server.
=========================================================
The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
<button ng-disabled="mySwitch">Click Me!</button>
=========================================================
The ng-show directive shows or hides an HTML element.

<p ng-show="true">I am visible.</p>

<p ng-show="false">I am not visible.</p>
=========================================================
The ng-click directive defines an AngularJS click event.

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="count = count + 1">Click me!</button>

<p>{{ count }}</p>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 0;
});
</script>
=========================================================
The ng-hide directive can be used to set the visibility of a part of an application.
The value ng-hide="true" makes an HTML element invisible.
The value ng-hide="false" makes the element visible.

<div ng-app="myApp" ng-controller="personCtrl">

<button ng-click="toggle()">Toggle</button>

<p ng-hide="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John",
    $scope.lastName = "Doe"
    $scope.myVar = false;
    $scope.toggle = function() {
        $scope.myVar = !$scope.myVar;
    };
});
</script>
=========================================================

<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script src="myApp.js"></script>
<script src="myCtrl.js"></script>

myApp.js

var app = angular.module("myApp", []);

myCtrl.js

app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName= "Doe";
});
=========================================================
Form
<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset1()">RESET</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName: "John", lastName: "Doe"};
 $scope.master1 = {firstName: "", lastName: ""};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
 $scope.reset1 = function() {
        $scope.user = angular.copy($scope.master1);
    };
    $scope.reset();
});
</script>

The ng-app directive defines the AngularJS application.

The ng-controller directive defines the application controller.

The ng-model directive binds two input elements to the user object in the model.

The formCtrl function sets initial values to the master object, and defines the reset() method.

The reset() method sets the user object equal to the master object.

The ng-click directive invokes the reset() method, only if the button is clicked.

The novalidate attribute is not needed for this application, but normally you will use it in AngularJS forms, to override standard

HTML5 validation.
=========================================================
Form validation
Example Explained
The AngularJS directive ng-model binds the input elements to the model.

The model object has two properties: user and email.

Because of ng-show, the spans with color:red are displayed only when user or email is $dirty and $invalid.

Property Description
$dirty The user has interacted with the field.
$valid The field content is valid.
$invalid The field content is invalid.
$pristine User has not interacted with the field yet.

<h2>Validation Example</h2>

<form  ng-app="myApp"  ng-controller="validateCtrl"
name="myForm" novalidate>

<p>Username:<br>
  <input type="text" name="user" ng-model="user" required>
  <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
  <span ng-show="myForm.user.$error.required">Username is required.</span>
  </span>
</p>

<p>Email:<br>
  <input type="email" name="email" ng-model="email" required>
  <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  <span ng-show="myForm.email.$error.required">Email is required.</span>
  <span ng-show="myForm.email.$error.email">Invalid email address.</span>
  </span>
</p>

<p>
  <input type="submit"
  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid">
</p>

</form>

<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
    $scope.user = 'John Doe';
    $scope.email = 'john.doe@gmail.com';
});
</script>
=========================================================

</body>
</html>

Live images, files save in c sharp

 <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>


protected void Button1_Click(object sender, EventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TextBox1.Text.Trim());
        string filname = TextBox1.Text.Trim();
        filname = string.Format("{0:MMMMyyyyHHmmssFFFF}", DateTime.Now) + filname.Substring(filname.LastIndexOf("/") + 1);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        if ((response.StatusCode == HttpStatusCode.OK ||
                   response.StatusCode == HttpStatusCode.Moved ||
                   response.StatusCode == HttpStatusCode.Redirect) &&
                   response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
        {
            using (Stream inputStream = response.GetResponseStream())
            using (Stream outputStream = File.Create(Server.MapPath("images") + "\\" + filname + ""))
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                do
                {
                    bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                    outputStream.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
            }
        }
    }

Thursday, 5 November 2015

On Submit Security per-pus option for captcha

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           Session["CheckRefreshQ"] = Server.UrlDecode(System.DateTime.Now.ToString());
        }
     
    }
 #region Page Pre Render
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CheckRefreshQ"] = Session["CheckRefreshQ"];
    }
    #endregion

 protected void imgBtnSubmit_Click(object sender, EventArgs e)
    {
if (Session["CheckRefreshQ"].ToString() == ViewState["CheckRefreshQ"].ToString())
                {
                    Session["CheckRefreshQ"] = Server.UrlDecode(System.DateTime.Now.ToString());
                     }
                else
                {
                   
                }
     }

File dump by sql Store procedure

Create PROCEDURE [dbo].[SP_NAVupload]
AS
BEGIN
--Truncate Temp Current NAV Table Data
Truncate Table tblNavdailyTemp
--Truncate Temp Current NAV Table Data

Bulk Insert tblNavdailyTemp
From 'D:\1DailyNAV.csv' -- Full Path and File Name
With
(
fieldterminator = ',',
rowterminator = '\n',
FIRSTROW = 2
)

Declare @Rcounttemp1 As int;
Set @Rcounttemp1 =(Select Count(Nav_date)
From [tblNavdaily] With(NOLOCK)
Where Convert(varchar, Nav_date, 110) = (Select Top 1 Convert(varchar, Nav_date, 110) From tblNavdailyTemp))
if(@Rcounttemp1 = 0)
Begin
--print 'in'
--Dump Current NAV Table Data to History NAV Table
Insert into tblNavHistory
(fund_id,benchmark_value,fund_value,value_insdate,benchmark_id,isChecked)
Select (Select Distinct fund_id
From [tblFundsMaster] With(NOLOCK)
Where fund_status = 'Y' And
fund_code = A.rls_fundcode And
IsNull(fund_code,'') <> ''),
NULL, A.nav_value, A.nav_date, NULL, 1
From [tblNavdaily]  As A
Where A.nav_date > (Select Max(value_insdate)
From tblNavHistory With(NOLOCK))
--Dump Current NAV Table Data to History NAV Table

--Truncate Current NAV Table Data
Truncate Table [tblNavdaily]
--Truncate Current NAV Table Data

--Dump Temp Current NAV Table Data to Current NAV Table Data
Insert Into [dbo].[tblNavdaily]
([RLS_FUNDCODE],[CREDENCE_FUNDNAME],[NAV_DATE],[NAV_VALUE],Upload_Date)
Select [RLS_FUNDCODE], [CREDENCE_FUNDNAME], [NAV_DATE], [NAV_VALUE], GetDate()
From tblNavdailyTemp With(NOLOCK)
--Dump Temp Current NAV Table Data to Current NAV Table Data
end
END

Monday, 2 November 2015

Transaction use in storeprocedure

 begin transaction
--do here your sql work
        if (@@error = 0)
begin
commit Transaction
select 'Insert successfully'
end
 else
begin
 Rollback Transaction
 select 'Error in Insert'+CAST(@@error as varchar(88))
end

Tuesday, 8 September 2015

Add dynamic DataTable Columns , Rows data

============c sharp code====================
  DataTable _dt1 = new DataTable();
        DataColumn col11 = new DataColumn("InvestmentObject");
        col11.DataType = System.Type.GetType("System.Int32");
//System.Type.GetType("System.String");
        _dt.Columns.Add(col11);

        int I;
        for (I = 0; I <= ddlInvestmentObject.Items.Count - 1; I++)
        {
            if (ddlInvestmentObject.Items[I].Selected)
            {
                DataRow researchRow1 = _dt1.NewRow();
                researchRow[col11] = Convert.ToInt32(ddlInvestmentObject.Items[I].Value);
                _dt1.Rows.Add(researchRow1);
            }
        }
        _admin.strInvestmentObject = GetXMLOfDataTable(_dt1);
================Function create here===================
 public static string GetXMLOfDataTable(DataTable dtToProcess)
        {
            string strOutput = "";
            try
            {
                dtToProcess.TableName = "Table";

                StringWriter sw = new StringWriter();

                dtToProcess.WriteXml(sw);
                strOutput = sw.ToString();
            }
            catch (Exception ex)
            {
            }


            return strOutput;
        }

===============DATA Query=======================
Decalre @xmlLanguage xml
DELETE FROM tb_InvestmentObject_SchemeMaster_Mapping WHERE Scheme_ID = @Scheme_ID
SELECT
ISNULL(cast(Colx.query('data(InvestmentObject)') as varchar(max)),'0') as [InvestmentObject]
INTO #TMPLanguage2 FROM @InvestmentObject.nodes('DocumentElement/Table') AS Tabx(Colx)
insert into tb_InvestmentObject_SchemeMaster_Mapping([Scheme_Id],[InvestmentObject_Id])
select @Scheme_ID,[InvestmentObject] from #TMPLanguage2

Thursday, 27 August 2015

Write folder file in c#

string[] filePaths = Directory.GetFiles(@"d:\test\");
        foreach ( var kk in filePaths)
        {
           
            Response.Write(Path.GetFileName(kk)+"<br>");
        }

Wednesday, 19 August 2015

Gridview url concatenate

NavigateUrl='<%# Eval("Id", "~/Details.aspx?Id={0}") %>'
PostBackUrl=' <%# FundName_url(Eval("DisplayName", "https://abc.com?schemeName={0}")) %>'
Multi parameter:-
NavigateUrl='<%# string.Format("~/Details.aspx?Id={0}&Name={1}&Country={2}",
HttpUtility.UrlEncode(Eval("Id").ToString()), HttpUtility.UrlEncode(Eval("Name").ToString()), HttpUtility.UrlEncode(Eval("Country").ToString())) %>'

Monday, 13 July 2015

Google SMTP function for C sharp code

var client = new SmtpClient
{
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("yourGmailUsername", "yourGmailPassword"),
Host = "smtp.gmail.com"
};
var message = new MailMessage
{
// Setup your MailMessage instance here...
}
client.Send(message);

changes date format code behid site C sharp

<system.web>
    <globalization uiCulture="es" culture="es-US" />
</system.web>

 Ex:- 7/13/2015 3:04:00 PM

Thursday, 7 May 2015

Json call after function call

 $.ajaxSetup({
        async: false
     });

     functionname();
 
    $.ajaxSetup({
        async: true
    });

Tuesday, 20 January 2015

get data table details in SQl

SELECT COLUMN_NAME 'All_Columns',DATA_TYPE ,character_octet_length  FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Tb_TVShow'