Dec 9, 2017

Differences Between JavaScript And TypeScript

Javascript
Typescript
It is a scripting language.
It is an object oriented programming language(not pure).
There is no static typing. ex: var num.
Here it is static typing (We can declare a variable in multiple ways). ex: var num : number.
It doesn't have interfaces .
It has interfaces.
It has no optional parameter feature.
It has optional parameter feature.
No generics are supported
Supports generics.
No modules support.
Number, string etc. are the objects.
Supports Modules .
Number, string etc. are the interfaces.

Simple Type Script Function

Step 1 :
 create a simple web application using Visual studio 

Step 2:
 add type script file  with name of TSFunction.ts



Step 3:

write a class 

class TSFunction {

    public authorname: string = "";
}

Step4:

compile the code and you can see respective JS file below the TS file tree view.

Step 5:

add homepage.html and drag the TSFunction.js file to the head section

<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="TSFunction.js"></script>

</head>

Step 6:

After adding this reference you can call the TS fucntion class by creating the object and you can access the metods as like our C# code. below is the code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="TSFunction.js"></script>
</head>
<body>
    <script>
        var TS = new TSFunction();
        TS.authorname = "Vamsi function";
        var name = TS.authorname;
        alert(TS.authorname)
        alert(name)

        var ts = new TSFunction();
        ts.authorname = "MY Test function";
        var name = ts.authorname;
        alert(name)
    </script>
</body>

</html>

Step 7:
 Build the solution and you can see any errors under intelligence tab if nothing good to go



Step  8:
Browse the html page and find the out put




Dec 3, 2017

Simple TypeScript Application.!

Here is the simple TypeScript  application using the Visual studio.

Open Visual studio 2017- I have installed the express version it's free to for all from Visual studio community

Step 1:

Create project from the below screen

Step 2 :

Choose type script templates from left and select Blank node.js console application from below screen


Step 3: after creation of the project solution is like this



Step 4: open the app.ts filed and paste the below code.


var message: string = "Hello this is type script sample";

console.log(message);

step 5: run the project and verify the out put in command prompt

Here is the out put:


that's we are done with hello world Type script program.

as i told type script is a super set of java script.

the moment you compile the code it converts into java script

Type script code before conversion:

var message: string = "Hello this is type script sample";

console.log(message);

after conversion to Pure java script

//Generated by typescript 
var message = "Hello this is type script sample";

console.log(message);


What is Type Script ?

TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical super set of JavaScript.


TypeScript may be used to develop JavaScript applications for client-side or server-side (Node.js) execution.

TypeScript is designed for development of large applications and compiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs.

The TypeScript compiler is itself written in TypeScript and compiled to JavaScript.

TypeScript lets you write JavaScript the way you really want to.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

TypeScript is pure object oriented with classes, interfaces and statically typed like C# or Java.

The popular JavaScript framework Angular 2.0 is written in TypeScript.

Mastering TypeScript can help programmers to write object-oriented programs and have them compiled to JavaScript, both on server side and client side.



Jan 30, 2016

Updating a temporary table from another table by matching column values.

Hello,

Im new to this Forum and I need to update a temporary table based on matching values from another table.For example i have two tables

table1                                                    

month(varchar)  sales(int)                        

1                              -

2                               -
3                               -
4                               -
5                               -
  table2
month(varchar)      sales(int)
2                              100
4                               50
5                               100
In this example i need to update  the  table1 sales column with table2 sales column by matching the month value of both the tables..


ans is 
UPDATE t1 SET t1.sales=t2.sales
FROM table1 t1 INNER JOIN table2 t2 ON t1.MONTH=t2.MONTH


You can simply try the left outer join:

create table #table1 (month varchar(10), sales int)
insert into #table1 values ('1',null)
insert into #table1 values ('2',null)
insert into #table1 values ('3',null)
insert into #table1 values ('4',null)
insert into #table1 values ('5',null)
create table #table2 (month varchar(10), sales int)
insert into #table2 values ('2',100)
insert into #table2 values ('4',50)
insert into #table2 values ('5',100)
select a.[month], b.sales from #table1 a left outer join #table2 b
on a.[month]=b.[month]
drop table #table1
drop table #table2

If you want to update table1 

Please try the below query
update a set a.[sales]=b.sales from #table1 a 
left outer join #table2 b on a.[month]=b.[month] 
select * from #table1 

Nov 9, 2015

Enable Cross-Origin Requests CORS in ASP.NET Web API

For enabling the CORS request in the ASP.NET Web API project, we have to download the cors package from the Nuget, i.e., Microsoft.AspNet.WebApi.Cors.

Open up the Nuget Package Manager console from the Visual Studio Tools Option —> Library Package Manager —> Package Manager Console.

nuget package
Type the following command to install Cors Package:

Install-Package Microsoft.AspNet.WebApi.Cors

The above CORS package installs, along with any dependencies, into the ASP.NET Web API WebService project. Now open the file App_Start/WebApiConfig.cs and add the following code to the WebApiConfig.Registermethod.

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


Next, add the [EnableCors] attribute to the Controller class, as follows:

Enable Cors Per Controller

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebAPI.Controllers
{
    [EnableCors(origins: "http://www.vamsi.com", headers: "*", methods: "*")]
    public class APIHomeController : ApiController
    {
       Public string Get(int id)
       {
           return "value";
       }
    }
}



If you set [EnableCors] attribute controller class, then it will apply action result methods.
For disabling the Cors, set the [DisableCors] attribute for the particular controller or action method.

Enable Cors Per Action


namespace WebAPI.Controllers
{
    public class APIHomeController : ApiController
    {
      [EnableCors]
      Public string Get(int id)
       {
           return "value";
       }
    } 
}

For Enable Cors for the Entire ASP.NET Web API Project


public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.vamsi.com", "*", "*");
        config.EnableCors(cors);
    }
}

Understanding Routing in ASP.NET MVC

Routing Engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller. We can find the following piece of code in Application_Start() method ofGlobal.asax file.

We can find RouteConfig.cs file under App_Start folder in ASP.NET MVC 5 application. If we follow this method inRouteConfig class, we will find one default configured route as follows. Line # 03 to #07 is configuring one default route.



protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

}

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 routes.MapRoute(
      name: "Default",
     url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
     );

}


Oct 27, 2015

There are several characteristics of C# are :

    There are several characteristics of C# are :
  • Simple
  • Type safe
  • Flexible
  • Object oriented
  • Compatible
  • Consistent
  • Interoperable
  • Modern

Give me the real time example of abstraction in c#.

A "Person" is the Example of OOPS. Skin hides the Heart methods, Body methods,........ as we donot need to know the implementation. we just know the body parts are working or not 

PERSON -- CLASS PART -- 

OBJECT TASK -- method 

ABSTRACTION -- donot want to know how parts work 

ENCAPSULATION - gives protection to our body with our clothes

 inheritence -- blood travels and inherits from one part to another 

POLYMORPHISM -- Brain function


 Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker's works. You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.

List down the commonly used types of exceptions in .Net?

ArgumentException,

 ArgumentNullException ,

 ArgumentOutOfRangeException, 

ArithmeticException, 

DivideByZeroException , 

OverflowException ,
 IndexOutOfRangeException , 

InvalidCastException,
 InvalidOperationException ,
 IOEndOfStreamException , 
NullReferenceException , 
OutOfMemoryException ,
 StackOverflowException etc

What are magic tables?

Magic tables are logical tables which are managed internally by SQL Server. In every DML operations first data move into these tables. "INSERTED" and "DELETED" are tables names for magic table. We can't access these tables except in trigger.


Magic tables are used by mostly triggers in SQL Server. DML Language uses these table to store data tempararey.


Often we need to know about the data which is inserted/deleted by the triggers in database. With the insertion and deletion of data, tables named “INSERTED” and “DELETED” automatically gets created in SQL Server which contains modified/deleted data. These “INSERTED” and “DELETED” tables are called magic tables.

What are http handlers in ASP.NET

HTTP handlers are the .NET components that implement the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface can act as a target for the incoming HTTP requests. HTTP handlers are somewhat similar to ISAPI extensions. One difference between HTTP handlers and ISAPI extensions is that HTTP handlers can be called directly by using their file name in the URL, similar to ISAPI extensions. HTTP handlers implement the following methods. Method Name Description ProcessRequest This method is actually the heart of all http handlers. This method is called to process http requests. IsReusable This property is called to determine whether this instance of http handler can be reused for fulfilling another requests of the same type. HTTP handlers can return either true or false in order to specify whether they can be reused



in the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler interface. ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. ASP.NET offers a few default HTTP handlers: Page Handler (.aspx): handles Web pages User Control Handler (.ascx): handles Web user control pages Web Service Handler (.asmx): handles Web service pages Trace Handler (trace.axd): handles trace functionality You can create your own custom HTTP handlers that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example delivery of dynamically created images (charts for example) or resized pictures. RSS feeds which emit RSS-formated XML You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property. The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.

IEnumerable Vs IQueryable?

IEnumerable: IEnumerable is best suitable for working with in-memory collection (or local queries). 

IEnumerable doesn't move between items, it is forward only collection.

 IQueryable: IQueryable best suits for remote data source, like a database or web service (or remote queries).
 IQueryable is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries). 

So when you have to simply iterate through the in-memory collection, use IEnumerable, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable


In case of IEnumerable, Return LINQ result list and thne execute condition But in IQuerable, which execute condition at the end and return the list

Ienumerable fetches the entire data from the database.It fetches the record one by one.It can Read , but cannot modify and update the data.It is the forward only data,we cannot insert the items at the middle. 

IQueryable : IQueryable fetches the Record based on filter wise. IQueryable is faster than IEnumerable.

When we are using the combination of Inheritance and interfaces, in what order we have to use them and what separator is used?

The base class always comes first followed by the interfaces (in any order) separated by commas. For example:


 class MyClass : MyBaseClass, IFace, IFace2 { // code }

What is the difference between HashTable and ArrayList?

1) HashTable is a collection of objects which store values based on key where as ArrayList is just a collection of objects stored based on index 

2) Retrieving value from HashTable is faster as it is linked with key whereas it is difficult in case of ArrayList value is fetched with index 

3) HastTable is used for maintaining huge data


An ArrayList is a dynamic array that grows as new items are added that go beyond the current capacity of the list. Items in ArrayList are accessed by index, much like an array. The Hashtable data structure is typically an array but instead of accessing via an index, you access via a key field which maps to a location in the hashtable by calling the key object's GetHashCode() method. In general, ArrayList and Hashtable are discouraged in .NET 2.0 and above in favor of List and Dictionary which are much better generic versions that perform better and don't have boxing costs for value types

How to return Data from 4 Different tables in Stored Procedure with out using joins?

For selecting columns without join just do like this.

 Select table1.FieldName,table2.FieldName from table1,table2. 

Or 
if you want to take only common fields from different tables without joins do like this.

 select table1.fieldname, table2.fieldname from table1, table2 where table1.commonfiledname = table2.commonfieldname

What the difference between get and post?


Get method can carry only text data get method is faster as compared to post Data is passed through URL that is Data is append to URL Data is append to the URL.Data is not secret GET request is SEO friendly. SEARCH will be the best example for GET request. Data is publicly available GET/POST/PUT methods both send and receive response/data. GET/POST/PUT methods all transmit at the same speed Caching is possible Hacking will be easy POst method can carry test as well as binary data post method is slower as compared to get Post we use to send data through body.Data is not append to the url.Data is secret. POST request has not. LOGIN will be the best example for POST request. No caching Hacking is difficult


get and post are the methods . they are used to transfer the data from front end form like html or aspx page to middle end i.e programming languages like c# java etc. in get methods we cannot send large data there is a limitation to 1024 characters . and is not suitable to transfer data like passwords . whatever we send data using get method it is visible in url. but if we use post method the data is encrypted and separate page is created and is append to it.

What is IOC and DI?

Inversion of control,
it is a container that holds the objects and 

DI is a dependencey injection whereas we can remove the one object dependency of others. we are creating a loosely couple with objects by the DI.we can implement through the Interfaces. 

DI can be inject on during Property creation and constructor creation.

What is Restful services? What is difference between SOAP and RestFul sevice?

Soap= lots of configuration + support only XML+ no cache Rest= get and post features of http + json or xml format + support cache


1-REST permits many different data formats whereas SOAP only permits XML. 

2-JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to its support for JSON. 

3-REST has better performance and scalability.

 4-REST reads can be cached, SOAP based reads cannot be cached.

 5-SOAP is a protocol its Simple Object Access Protocol and rest is an Architecture .REST stands for Representational State Transfer.

Where Session ID Stores in Asp.net?

Session Data is always stored in Server(May be store in sqlserver or Out of Proc depend upon your choice ) and Server always generate a Session Id for each session this id by default store in user's memory in form of Cookie.This Cookie is only set of Characters like 'lin8py55t21z5v65vlm25s55' . If cookie are disabled then session id will attach with Url. Url without Cookie: http://www.Indiaonline.com/page.aspx Url with Cookie : http://www.Indiaonline.com/(S(lin8py55t21z5v65vlm25s55))/page.aspx This Method is not good because some user can save this url as Bookmarks.Then it will generate problems

What is the difference between display:none and visibility:hidden style?

visibility: hidden

hides the element, but it still takes up space in the layout.

 display: none
 removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code.

What is the difference between Singleton and Static class

Singleton: 

1. Singleton class contains both static and non-static members 
2. You can create instance of Singleton class. 
3. You can implement inheritance. 
4. You can clone a singleton class object.
 5. Singleton class object creates in Heap memory.

 Static Class: 

1. Static class contains only static members. 
2. You can't create instance of Static class.
 3. Once you declare a class as static you can't implement inheritance. 
4. You can't clone static class object.
 5. Static class object creates in stack memory.


Singleton Class: 
you can create one instance of the object and reuse it. Singleton instance is created for the first time when the user requested. singleton class can have constructor. 

Static Class: 
You can not create the instance of static class. are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. Static Class class cannot have constructor.

how much types of serialization support wcf

Basically WCF supports three types of serialization :
 XMLSerializer
 NetDataContractSerializer
 DataContractSerializer


XMLSerializer

We can find XMLSerializer in the System.Xml.Serialization namespace. WCF supports this serialization from .Net 1.0. It is used by default with the ASP.Net webservices (ASMX).

Usage
  • We can use this serializer whenever we want to get backward compatibility with ASMX.
  • It can also be used when integrating with non WCF Services.
NetDataContractSerializer

NetDataContractSerializer is analogous to .Net Remoting Formatters. It implements IFormatter and it is compatible with [Serializable] types. It is not recommended for service oriented design.

Usage
  • It is used when we have WCF services at both sides.
  • It is easier when we want to migrate .Net remoting applications.
DataContractSerializer

DataContractSerializer is a default serializer for WCF. We need not to mention DataContractSerializer attribute above the service contract. 

Usage
  • Used by default unless we specify otherwise.
  • It is the best choice for code-first designs.

Why multiple inheritance is not possible in c#

Because when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override it), and B and C have overridden that method differently, then via which class does it inherit: B, or C? So., multiple inheritance is not possible in C#. that is called Diamond Problem. But., in C# we can solve the Diamond problem with the help of interfaces in some cases.


If multiple inheritance would have allowed in the C#, there would be a problem so called "Diamond Problem". Diamond problem occurs when same method exist in two or more base classes. Thus the child class would end up inheriting duplicate methods.


How to add a button dynamically to a grid view?

Button myButton = newButton();  
myButton.Text = "Hai";  
myGrid.Controls.Add(myButton);   

How to find a control inside a GridView?


Button btnTest = (Button) myGrid.Rows[0].Cells[1].Controls[1].FindControl("myButton "); 

Asp.net checkboxlist, select or deselect all list items

<asp:ListItem Text="Diploma" Selected="True" Value="1"></asp:ListItem> 

protected void buttonSelectAll_Click(object sender, EventArgs e)
{
    foreach (ListItem li in CheckBoxList1.Items)
    {
        li.Selected = true;
    }
}

protected void buttonDeselectAll_Click(object sender, EventArgs e)
{
    foreach (ListItem li in CheckBoxList1.Items)
    {
        li.Selected = false;
    }
} 



Binding an asp.net dropdownlist with an XML file

First add an XML file, to the web application project. To do this 
1. Right click on the web application project, and select Add => New Item.
2. In the Add New Item dialog box, select XML File.
3. Give the XML file a meaningful name. In our case let's name it Countries.xml and click Add.
4. In the Countries.xml file, copy and paste the following
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country>
    <CountryId>101</CountryId>
    <CountryName>India</CountryName>
  </Country>
  <Country>
    <CountryId>102</CountryId>
    <CountryName>US</CountryName>
  </Country>
  <Country>
    <CountryId>103</CountryId>
    <CountryName>Australia</CountryName>
  </Country>
  <Country>
    <CountryId>104</CountryId>
    <CountryName>UK</CountryName>
  </Country>
</Countries> 


Drag and drop a DropDownList on the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Create a new DataSet
        DataSet DS = new DataSet();
        //Read the xml data from the XML file using ReadXml() method
        DS.ReadXml(Server.MapPath("Countries.xml"));
        DropDownList1.DataTextField = "CountryName";
        DropDownList1.DataValueField = "CountryId";
        DropDownList1.DataSource = DS;
        DropDownList1.DataBind();
        ListItem li = new ListItem("Select""-1");
        DropDownList1.Items.Insert(0, li);
    }
}

The important thing to notice here is that, we are using ReadXml() method of the DataSet object, to read the data from the Countries.xml file into a DataSet.Server.MapPath() method returns the physical path of the file from the provided virtual path. We will discuss about this method in a later video session.

To insert a ListItem at a specific location use the Insert() method specifying the index of the location where you want to insert, and the listitem object.