Saturday, 29 September 2018

Call Api in C#



using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
namespace AjayApi.Models
{
public class ApiCall
{
//public clsService()
//{
// ServiceUrl = "https://api.xxxx.xxx/api";
//}
public ApiCall(string strUrl)
{
ServiceUrl = strUrl;
}
readonly string ServiceUrl;
public string strMethodName { get; set; }
public string strMethodArgument { get; set; }
public string strMethodType { get; set; }
public string RestServiceResponce()
{
string strResult = string.Empty;
try
{
Uri objUrl = new Uri(string.Format("{0}/{1}", ServiceUrl, strMethodName));
HttpWebRequest objRequest = WebRequest.Create(objUrl) as HttpWebRequest;
objRequest.Method =
string.IsNullOrWhiteSpace(strMethodType) ? "GET" : strMethodType;
objRequest.ContentType = "application/json";
WebProxy objWebProxy = new WebProxy();
objWebProxy.IsBypassed(objUrl);
objRequest.Proxy = objWebProxy;
if (!string.IsNullOrEmpty(strMethodArgument))
{
try
{
using (var streamWriter = new StreamWriter(objRequest.GetRequestStream()))
{
streamWriter.Write(strMethodArgument);
}
}
catch { }
}
using (HttpWebResponse objResponce =
objRequest.GetResponse() as HttpWebResponse)
{
StreamReader objReader =
new StreamReader(objResponce.GetResponseStream());
strResult = objReader.ReadToEnd();
objRequest.KeepAlive = false;
objResponce.Close();
}
}
catch (Exception ex) { strResult = ex.Message; }
return strResult;
}
}
}


Get Method Call

using System.Web.Script.Serialization;
JavaScriptSerializer os =
new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };
string Baseurl = "http://localhost:51037/";
public ActionResult Index()
{
ApiCall api = new ApiCall("http://localhost:51037/api");
api.strMethodName = "ApiSubject?QueryType=selectSubject&subjectId=1";
// Subjects1 s = new Subjects1();
//===
// Subjectfield ss = new Subjectfield();
// ss.QueryType = "insert";
// ss.SubjectId = "0";
//ss.Subject = "sub00";
//ss.Active = "A";
//ss.Date = "";
//ss.UserId = "1";
//=====
// s.QueryType = "selectSubject";
// s.SubjectId = "1";
// api.strMethodArgument = os.Serialize(s);
//api.strMethodArgument = "{ QueryType = selectSubject, subjectId = 1 }";
api.strMethodType = "GET";
string dd = api.RestServiceResponce();
ViewBag.Title = "Home Page";
//GetApi();
return View();
}


Call Other the "GET" Method


using System.Web.Script.Serialization;
JavaScriptSerializer os =
new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };
string Baseurl = "http://localhost:51037/";
public ActionResult Index()
{
ApiCall api = new ApiCall("http://localhost:51037/api");
api.strMethodName = "ApiSubject";
//Subjects1 s = new Subjects1();
//===
Subjectfield ss = new Subjectfield();
ss.QueryType = "insert";
ss.SubjectId = "0";
ss.Subject = "sub00";
ss.Active = "A";
ss.Date = "";
ss.UserId = "1";
//=====
// s.QueryType = "selectSubject";
// s.SubjectId = "1";
api.strMethodArgument = os.Serialize(ss);
//api.strMethodArgument = "{ QueryType = selectSubject, subjectId = 1 }";
api.strMethodType = "POST";
string dd = api.RestServiceResponce();
ViewBag.Title = "Home Page";
//GetApi();
return View();
}
















transition in angular 6 using style





import { Component, OnInit } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
selector: 'app-test-transition',
templateUrl: './test-transition.component.html',
styleUrls: ['./test-transition.component.css'],
animations: [
trigger('toggleState', [
state('true', style({ height: '100px', width: '200px', background: '#FFFF00'})),
state('false', style({ height: '200px', width: '400px', background: '#00FF00' })),
// transition
transition('* => *', animate('900ms')),
])
],
})
export class TestTransitionComponent implements OnInit {
shouldToggle=true;
constructor() { }

ngOnInit() {
}
handleClick=function () {
this.shouldToggle = !this.shouldToggle;
}

}



<p>
test-transition works!
</p>
<div>
<div class="div1" [@toggleState]="shouldToggle">

</div>
<input type="button" value="Change" (click)="handleClick()">
</div>







Sunday, 23 September 2018

startTimer in angular4




times = {
year: 31557600,
month: 2629746,
day: 86400,
hour: 3600,
minute: 60,
second: 1
}
timeLeft: number = 70;
interval;
m:number;
s:number;
startTimer() {
alert("start");
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
this.m = Math.floor( this.timeLeft / 60);
this.s = this.timeLeft%60;
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p style="color: black;">{{timeLeft}} Seconds Left....</p>
<p style="color: black;">{{m}}:{{s}}</p>



Tuesday, 18 September 2018

Sql, read tables thos id in anther table in a One column

questionIds
1,6,7,2,3,4,5,8,13,14




DECLARE @xml AS XML,
@str AS VARCHAR(100),
@delimiter AS VARCHAR(10);
select @str=QuestionIds from dbo.ExamQuestions
SET @delimiter = ',';
SET @xml = CAST('<X>' + REPLACE(@str, @delimiter, '</X><X>') + '</X>' AS XML);

--select @xml
select * from dbo.question where questionId in(
SELECT [N].value( '.', 'varchar(50)' ) AS value FROM @xml.nodes( 'X' ) AS [T]( [N] )
)

Monday, 17 September 2018

Api get Multiples Tables in JSONObject

Results res;
DbConnection db;
List<SqlParameter> prm;
// GET: api/ApiTest
public List<Dictionary<string, DataTable>> Get()
{
// JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
res = new Results();
db = new DbConnection();
SqlDataReader dr;
List<Dictionary<string, DataTable>> litable =
new List<Dictionary<string, DataTable>>();
Dictionary<string, DataTable> d;

DataSet dset = new DataSet(); //Creating instance of DataSet

string sql = "";
sql = " select * from dbo.subject; " +
" select * from dbo.topic ;" +
" select * from dbo.subTopic ;";

dset = db.GetMultipalTable(sql);

foreach (DataTable t in dset.Tables)
{
d = new Dictionary<string, DataTable>();

d.Add(t.TableName.ToString(), t);

litable.Add(d);
}

//while (dr.Read())
//{
// var t1 = dr[0];
//}

//if (dr.NextResult())
//{
// while (dr.Read())
// {
// var ttt = dr[1];
// }
//}
//if (dr.NextResult())
//{
// while (dr.Read())
// {
// var ttt = dr[3];
// }
//}



//dr.Close();
return litable;
}

Data Base Connection C#

public class DbConnection
{
//string cs = @"Data Source=xxx.xxx.xx.xx; Network Library=DBMSSOCN;
//Initial Catalog=xxxxx;user id=x;password=xxxxx";
string cs = @"Data Source=.; Initial Catalog=xxx;Integrated
Security=SSPI;";
//string cs1 = ConfigurationManager.ConnectionStrings["DBCS"].
//ConnectionString;

public DataSet GetMultipalTable(string sql)
{
DataTable dt;
DataSet dset = new DataSet(); //Creating instance of DataSet

try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql, con);


//da.Fill(dset, "student_detail");
// Filling the DataSet with the records returned by SQL
// statemetns written in sqldataadapter
da.Fill(dset);
// Filling the DataSet with the records returned by SQL
// statemetns written in sqldataadapter
//dataGridView1.DataSource = dset.Tables["student_detail"];
// Binding the datagridview

//dt = new DataTable();
//da.Fill(dt);

}
}
catch (Exception ex)
{
dset = null;
}
return dset;
}


public DataTable GetTable(string sql)
{
DataTable dt;
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql, con);

dt = new DataTable();
da.Fill(dt);
}
}
catch (Exception ex)
{
dt = null;
}
return dt;
}
public SqlDataReader GetSqlDateReader(string sql)
{
SqlDataReader dr;

try
{
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
dr = cmd.ExecuteReader();
}
catch (Exception ex)
{
dr = null;
}
return dr;
}
public int CURDtData(string sql)
{
int result = 0;
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);

result = cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception ex) { }
return result;
}
public int insertData(string sql)
{
return CURDtData(sql);
}
public int updateData(string sql)
{
return CURDtData(sql);
}
public int DeleteData(string sql)
{
return CURDtData(sql);
}


//-----------------------------------
public DataTable GetTable(string sql, List<SqlParameter> prm)
{
DataTable dt;
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter(sql, con))
{
da.SelectCommand.Parameters.AddRange(prm.ToArray());
dt = new DataTable();
da.Fill(dt);

da.SelectCommand.Parameters.Clear();
}
con.Close();
}
}
catch (Exception ex) { dt = null; }
return dt;
}
public SqlDataReader GetSqlDateReader(string sql, List<SqlParameter> prm)
{
SqlDataReader dr;
try
{
SqlConnection con = new SqlConnection(cs);
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddRange(prm.ToArray<SqlParameter>());
dr = cmd.ExecuteReader();

cmd.Parameters.Clear();
}
con.Close();
}
catch (Exception ex) { dr = null; }
return dr;
}
public int CURDtData(string sql, List<SqlParameter> prm)
{
int result = 0;
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddRange(prm.ToArray<SqlParameter>());
result = cmd.ExecuteNonQuery();
return result;

cmd.Parameters.Clear();
}
con.Close();
}
}
catch (Exception ex) { return 0; }
}
public int InsertData(string sql, List<SqlParameter> prm) {
return CURDtData(sql, prm); }
public int UpdateData(string sql, List<SqlParameter> prm) {
return CURDtData(sql, prm); }
public int DeleteData(string sql, List<SqlParameter> prm) {
return CURDtData(sql, prm); }
}

Thursday, 13 September 2018

directive AngularJS


//====ajay
app.directive('toggle', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (attrs.toggle == "tooltip") {
$(element).tooltip({
trigger: "hover"
});
}
if (attrs.toggle == "popover") {
$(element).popover({
trigger: "hover"
});
}
if (attrs.toggle == "popover1") {
$(element).popover({
trigger: "click"
});
}
}
};
});
//=====ajay
app.directive('numbersOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9]/g, '');
// var transformedInput = text.replace(/([0-9]*[.])?[0-9]/g, '');

if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return undefined;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
//===
app.directive("floatingNumberOnly", function () {
return {
require: 'ngModel',
link: function (scope, ele, attr, ctrl) {

ctrl.$parsers.push(function (inputValue) {
console.log(inputValue);
var pattern = new RegExp("(^[0-9]{1,9})+(\.[0-9]{1,4})?$", "g");
if (inputValue == '')
return '';
var dotPattern = /^[.]*$/;

if (dotPattern.test(inputValue)) {
console.log("inside dot Pattern");
ctrl.$setViewValue('');
ctrl.$render();
return '';
}

var newInput = inputValue.replace(/[^0-9.]/g, '');
// newInput=inputValue.replace(/.+/g,'.');

if (newInput != inputValue) {
ctrl.$setViewValue(newInput);
ctrl.$render();
}
//******************************************
//***************Note***********************
/*** If a same function call made twice,****
*** erroneous result is to be expected ****/
//******************************************
//******************************************

var result;
var dotCount;
var newInputLength = newInput.length;
if (result = (pattern.test(newInput))) {
console.log("pattern " + result);
dotCount = newInput.split(".").length - 1; // count of dots present
if (dotCount == 0 && newInputLength > 9) { //condition to restrict "integer part" to 9 digit count
newInput = newInput.slice(0, newInputLength - 1);
ctrl.$setViewValue(newInput);
ctrl.$render();
}
} else { //pattern failed
console.log("pattern " + result);
// console.log(newInput.length);

dotCount = newInput.split(".").length - 1; // count of dots present
console.log("dotCount : " + dotCount);
if (newInputLength > 0 && dotCount > 1) { //condition to accept min of 1 dot
console.log("length>0");
newInput = newInput.slice(0, newInputLength - 1);
console.log("newInput : " + newInput);

}
if ((newInput.slice(newInput.indexOf(".") + 1).length) > 4) { //condition to restrict "fraction part" to 4 digit count only.
newInput = newInput.slice(0, newInputLength - 1);
console.log("newInput : " + newInput);

}
ctrl.$setViewValue(newInput);
ctrl.$render();
}

return newInput;
});
}
};
});
///======
app.directive('selectWatcher', function ($timeout) {
return {
link: function (scope, element, attr) {
var last = attr.last;
if (last === "true") {
$timeout(function () {
$(element).parent().selectpicker('val', '0');
$(element).parent().selectpicker('refresh');
});
}
}
};
});

// Bottstrap Tooltip & Popover
app.directive('toggle', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
//if (attrs.toggle == "tooltip") {
// $(element).tooltip({
// trigger: "hover"
// });
// }
// if (attrs.toggle == "popover") {
// $(element).popover({
// trigger: "hover"
// });
// }
}
};
});

// scope message convert to html
app.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
// Incase value is a TrustedValueHolderType, sometimes it
// needs to be explicitly called into a string in order to
// get the HTML string.
element.html(value && value.toString());
// If scope is provided use it, otherwise use parent scope
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);

// Only Numeric
app.directive('numericOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {

modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g, '') : null;

if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}

return transformedInput;
});
}
};
});

// No Special Cracter
app.directive('noSpecialChar', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == null)
return '';
cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
};
});

// Items Reverse
app.filter('reverse', function () {
return function (items) {
return items.slice().reverse();
};
});

// Number and Dot value
app.directive('validNumber', function () {
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}

ngModelCtrl.$parsers.push(function (val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace(/[^0-9\.]/g, '');
var decimalCheck = clean.split('.');

//if (!angular.isUndefined(decimalCheck[1])) {
// decimalCheck[1] = decimalCheck[1].slice(0, 2);
// clean = decimalCheck[0] + '.' + decimalCheck[1];
//}

if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});

element.bind('keypress', function (event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});


// IP Address
app.directive('ipaddress', function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
ctrl.$validators.ipaddress = function (modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
return false;
}
var matcher;
if ((matcher = viewValue.match(/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/)) != null) {
var i;
var previous = "255";
for (i = 1; i < 5; i++) {
var octet = parseInt(matcher[i]);
if (octet > 255) return false;
}
return true;
} else {
return false;
}
};
}
};
});

var compareTo = function () {
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function (scope, element, attributes, ngModel) {

ngModel.$validators.compareTo = function (modelValue) {
return modelValue == scope.otherModelValue;
};

scope.$watch("otherModelValue", function () {
ngModel.$validate();
});
}
};
};

app.directive("compareTo", compareTo);

//Run material design lite
app.run(function ($rootScope, $timeout) {
$rootScope.$on('$viewContentLoaded', function (event) {
$timeout(function () {
componentHandler.upgradeAllRegistered();
}, 0);
});
$rootScope.render = {
header: true,
aside: true
};
});


app.directive("tooltipx", function () {
return {
link: function (scope, element, attrs) {

$(element).on("mouseover", function () {
$(this).append("<span>" + attrs.tooltipx + "</span>");
});

$(element).on("mouseout", function () {
$(this).find("span").remove();
});

scope.$on("$destroy", function () {
$(element).off("mouseover");
$(element).off("mouseout");
});
}
};
});

app.directive('convertNumber', function () {
return {
require: 'ngModel',
link: function (scope, el, attr, ctrl) {
ctrl.$parsers.push(function (value) {
return parseInt(value, 10);
});

ctrl.$formatters.push(function (value) {
return value.toString();
});
}
};
});
app.directive('fieldMatch', ["$parse", function ($parse) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var me = $parse(attrs.ngModel);
var matchTo = $parse(attrs.fieldMatch);
scope.$watchGroup([me, matchTo], function (newValues, oldValues) {
ctrl.$setValidity('fieldmatch', me(scope) === matchTo(scope));
}, true);
}
};
}]);

jquery Function getQueryStrings(), randomString(len), refresh(),precise_round(num,decimals)





function getQueryStrings() {
var assoc = {};
var decode = function (s) {
return decodeURIComponent(s.replace(/\+/g, " "));
};
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');

for (var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}

return assoc;
}

function randomString(length) {

var result = '';
var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}

function refresh() {
$(".refresh a i").addClass('fa-spin');
window.location.reload();
}

function precise_round(num, decimals) {
var sign = num >= 0 ? 1 : -1;
return (Math.round((num * Math.pow(10, decimals)) + (sign * 0.001)) / Math.pow(10, decimals)).toFixed(decimals);
}


IIS deployment support details

  Node JS - IIS deployment support details node: http://go.microsoft.com/?linkid=9784334 IISNode: https://github.com/azure/iisnode/releases/...