Friday 31 October 2014

Memory leak in CS

A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code. 

A memory leak can diminish the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down unacceptably due to thrashing.

There are many ways to avoid memory leak in C#; we can avoid memory leak while working with unmanaged resources with the help of the ‘using’ statement, which internally calls Dispose() method. The syntax for the ‘using’ statement is as follows:

using(var  objectName = new AnyDisposableType)
{
  //user code
}

There are two major causes for memory leak in C#:

  1. The first cause is having an unused object that is no longer required but still referenced by a variable that has its scope throughout the application’s lifetime. Since this object has a reference, it will not be destroyed by the garbage collector and will remain in the memory forever and can become a reason for a memory leak. An example of this situation can be an event that we have registered but is never unregistered.
  2. The second cause is allocating the memory for unmanaged resources and then not releasing it after use. Whenever we are working with objects that are not collected by the garbage collector, we need to be extra careful to dispose of them after use. Otherwise, these will cause a memory leak as they are not cleaned up by the GC.
Conclusion
When an application doesn’t release the memory that it has used during its execution, this memory will be blocked and cannot be used by any other process, resulting in a memory leak. The garbage collector can automatically dispose of managed objects but cannot dispose of unmanaged objects or resources.


Continue Reading →

Javascript Vs Jquery

JavaScript: A powerful language in web development
JavaScript is a scripting language that is used to add interactivity to our web pages. It is one of the three core technologies alongside HTML and CSS which are used to create web pages. 
JavaScript is supported by all the web browsers and the web browsers have a built-in JavaScript engine to identify JavaScript code and work with it. Thus, JavaScript is majorly a client-side language.

jQuery: A library developed from JavaScript
jQuery is a library of JavaScript which is built from it. It is the most popular JavaScript library. jQuery is free, an open-source library, licensed under the MIT License. This has a powerful feature of cross-browser compatibility. It can easily handle cross-browser issues that we can face with JavaScript. Thus many developers use jQuery to avoid cross-browser compatibility issues.

Why jQuery is created and what are the special capabilities of jQuery?
In JavaScript, we have to write a lot of code for basic operations while with jQuery the same operations can be done with a single line of code. Therefore developers find it easier to work with jQuery than with JavaScript.

DOM Traversal and Manipulation

In JavaScript:

We can select a DOM element in JavaScript using the document.getElementById() method or by using the document.querySelector() method.

var mydiv = document.querySelector(“#div1”);
//Or
document.getElementById(“#div1”);

In jQuery:

Here, we will have to only use the $ symbol with the selector in brackets.

$(selector)

$("#div1") – The selector is an id ‘div1
$(".div1") – The selector is a class ‘div1
$("#P") – The selector is the paragraph in the Html page

Adding styles in JavaScript:
document.getElementById ('myDiv').style.backgroundColor="#FFF"

Adding styles in jQuery:
$('#myDiv').css (‘background-color','#FFF');

Continue Reading →

Monday 27 October 2014

Abstract Class & Interface

What is an Abstract Class?
An abstract class is a special kind of class that has no implementation. It cannot be instantiated. Its implementation logic is provided by the classes that derive from it. It can have both abstract as well as non-abstract methods.  It is not compulsory to have only abstract methods in an abstract class. We can also have an abstract class with only non-abstract methods.

Why do we need an Abstract Class?
With an Abstract Class, we can provide some kind of default functionality for all derived classes to extend from. This is useful to avoid code duplication in many cases. 

Suppose we are defining an iPhone class for Apple and then inheriting it to iPhone13 and iPhone14 subclasses. Practically we don't want an object of an iPhone class since we first need to know the model of iPhone. So, the iPhone class should be an abstract class that contains some predefined functions like Call() and SMS() for all iPhone models to share . We can also add abstract methods like Model() and Color() into the iPhone class that must be implemented by all the subclasses inheriting iPhone. The main advantage of this approach is, whenever we inherit the iPhone class into a derived class, say iPhone5s, we need not define the Call() and SMS() methods again. We just need to implement the abstract methods and we are good to go. It helps to provide default functionality in all the derived classes and also avoids code duplication. 

  1. -If we don't provide the definition of the abstract method in the derived class, it throws an error:
  2. -An inheritance between abstract to abstract classes is possible. We don't need to implement abstract methods of the base abstract class into a derived abstract class. We can implement it later in concrete classes. 
  3. -An abstract class can never be sealed or static. 
  4. -An abstract class can have abstract as well as non abstract methods. 
  5. -The abstract keyword can be used with class, methods, properties, indexers and events.
  6. -Abstract members can only be declared inside an abstract class. 
  7. - An abstract member cannot be static or private. 
  8. - An abstract method cannot be marked virtual. 
  9. - A concrete class cannot inherit more than one abstract class, in other words multiple Inheritance is not   possible.

Reference:
http://www.c-sharpcorner.com/UploadFile/d0e913/abstract-class-interface-two-villains-of-every-interview/

What an interface is ?

In the real world, an interface means a medium to interact with something. To be precise, it's a point where two systems, subjects, organizations and so on meet and interact. Suppose you are going for an interview of Programmer Profile. The interview is only possible if the interviewer and you speak the same language.
Moreover, you and the interviewer have the same skill set of programming languages to discuss upon.
Similarly, in the programming world, an interface means a contract to interact with multiple code modules. If a class wants to communicate with an interface, it must implement it and define its members. Consider it like the interviewer's question and you need to answer it correctly, if you want the job.

The MSDN Library defines the interface like a pure abstract class. An interface contains only the signatures of methods, properties, events, or indexers. It has no implementation of its own and can only be implemented by a class or a struct. Any of the two that implement the interface must provide the definitions to members specified in the interface. It is like a contract for all the derived classes to follow.

An interface is declared using the interface keyword. interface members are implicitly public and abstract, so we cannot prefix any access modifiers to it. An interface cannot contain fields, constant members, constructors, destructors and static members.

Why we need an interface

An interface is not a class. It contains only method signatures. It has no implementation on its own and cannot be instantiated. Its implementation logic is provided by the classes that derived from it. An interface is mostly considered to be a pure abstract class. However, there is the advantage of using an interface over an abstract class; that is "Multiple Inheritance Support". In C#, two classes (either abstract or concrete) cannot be inherited by the same derived class. It causes ambiguity in the derived class if both have the same method signature. We can do multiple inheritance in C# using interfaces.

An interface plays a vital role in the Service Oriented Architecture (SOA). In WCF, we use interfaces to define Service Contracts. A single class can implement any number of Service Contract Interfaces. It is generally accepted as the best practice to do so. However, we can also use classes for Service Contracts.

How to define an interface

Suppose we need to define a class for a Smart Phone. The class can have members like OS, AppStore and Call. The Smartphone can be either Android based or iOS based and cannot be both. There is no common functionality between an Android and iOS Smartphone, so we don't need to provide any default functionality. One approach is to make the SmartPhone class abstract and also all its members abstract. This approach works fine and several concrete classes like Samsung, Apple, HTC can inherit from it.

Now, after a few days Apple wants to add a Touch ID feature to its Smartphone. You can add TouchID as an abstract method in your abstract base class SmartPhone. But what if HTC doesn't want that feature and neither does Samsung? So, the TouchID method cannot be placed inside the abstract class SmartPhone. An alternative is to define another abstract class Features and add the TouchID method to it. This is also a bad idea since C# doesn't support inheritance of multiple classes (abstract or concrete) into a derived class.

In this situation, an interface is useful and plays a vital role in solving the problem. An interface provides only the method definitions, just like an abstract class, but can be useful in multiple inheritances. You can make the Features class an interface and add the TouchID method to it. It provides only the method signature and whichever class inherits it can implement it in its own way. It is also completely valid for a class to inherit more than one interface in C#. Also, we can make the SmartPhone class an interface instead of an abstract class. It is better instead of making a pure abstract class, we can use interfaces. 
Let us consider the example discussed above and create a Console Application for it. Open Visual Studio and add a new console project as "InterfaceDemo".

Let's create an abstract class SmartPhone and define OS and AppStore abstract methods in it. We can create an abstract class by putting the keyword "abstract" before a class definition.

Now define the concrete classes Apple and Samsung that inherits from Smartphone and provides the definitions to the abstract methods OS and AppStore.

using System;  
namespace InterfaceDemo   
{   
      //Abstract Class SmartPhone with only abstract methods in it   
      abstract class SmartPhone   
      {  
         public abstract void OS();  
         public abstract void AppStore();   
      }  
      class Apple : SmartPhone   
      {  
          public override void OS()   
          {   
            //Some Implementation Here   
          }  
  
          public override void AppStore()   
          {  
             //Some Implementation Here   
          }   
       }   
  
       class Samsung: SmartPhone   
       {  
          public override void OS()   
          {   
              //Some Implementation Here   
          }  
  
          public override void AppStore()   
          {  
              //Some Implementation Here   
          }  
       }  
      
       class Program   
       {   
          static void Main(string[] args)   
          {   
          }   
       }   
}  

If we compile the code now, it works fine. Our SmartPhone class is implemented by two different concrete classes Apple and Samsung and defined depending on them. Now, let us suppose Apple wants to provide TouchID features to its Smartphone. We can add another abstract method TouchID in the SmartPhone class and let Apple inherit it and implement it. 

using System;    
namespace InterfaceDemo   
{   
    //Abstract Class SmartPhone  
    abstract class SmartPhone   
    {   
       public abstract void OS();   
       public abstract void AppStore();   
  
       //TouchID method meant only for Apple Class  
       public abstract void TouchID();   
    }   
  
    class Apple : SmartPhone   
    {   
         public override void OS()   
         {  
            //Some Implementation Here   
         }  
  
         public override void AppStore()   
         {   
             //Some Implementation Here   
         }  
  
         //Implementing the TouchID feature   
        public override void TouchID()   
        {   
            //Some Implementation Here   
        }    
    }   
  
    class Samsung: SmartPhone   
    {   
        public override void OS()   
        {   
             //Some Implementation Here   
        }  
  
        public override void AppStore()   
        {   
              //Some Implementation Here   
        }   
    }  
  
    class Program   
    {   
       static void Main(string[] args) { }   
    }  
}  

The Apple class inherits the TouchID method and provides a definition to it. Let's compile the code now and see what happens. 






It throws an error saying that the Samsung class doesn't implement the TouchID method. By the definition of abstract class, any class implements it must provide definitions to all its abstract members. The TouchID method is meant only for the Apple class and the Samsung class doesn't want to implement it. It clearly seems that our approach is wrong since the TouchID method cannot be placed in the SmartPhone abstract class. 

An alternative approach is to define another abstract class Features and define the TouchID method to it. This approach seems fine since whatever class inherits Features can implement the TouchID method. 

using System;   
namespace InterfaceDemo   
{   
      //Abstract Class SmartPhone   
      abstract class SmartPhone   
      {  
         public abstract void OS();  
         public abstract void AppStore();   
      }  
  
      //Abstract Class Features for TouchID method  
      abstract class Features   
      {  
         public abstract void TouchID();   
      }   
  
     //Apple Class inherits both SmartPhone and Features  
      class Apple : SmartPhone, Features   
      {  
         public override void OS()  
         {   
            //Some Implementation Here   
         }  
          
         public override void AppStore()   
         {  
             //Some Implementation Here   
         }  
  
         //Implementation of TouchID method in Apple Class   
         public override void TouchID()   
         {  
             //Some Implementation Here   
         }  
      }  
  
      class Samsung : SmartPhone   
      {  
         public override void OS()   
         {   
           //Some Implementation Here   
         }   
  
         public override void AppStore()  
         {  
            //Some Implementation Here   
         }   
       }  
  
       class Program   
      {  
          static void Main(string[] args)   
          {  
          }   
      }   
}

Let's compile the code and see what happens. 


It again throws an error saying we cannot have multiple base classes in a derived class. This is called Multiple Inheritance of classes and is not allowed in C#. So, our second approach also fails to implement the TouchID method. This is where an interface is useful and helps to solve the "Multiple Inheritance" issue in C#. We can define both the SmartPhone and Features as interfaces and let the classes implement them as they need to. We can also have more than one interface in a class. This is the only way to do multiple inheritance in C#. 

Let's re-create the same project using interfaces. We can create an interface using the keyword interface. It is considered a good practice to prefix "I" before the interface name, however the point is arguable and the choice is yours.
 

using System;   
namespace InterfaceDemo   
{  
     interface ISmartPhone       //Definition of Interface   
     {   
         public void OS();   
         public void AppStore();   
     }   
  
     class Program   
     {    
        static void Main(string[] args)   
        {   
        }   
     }   
}

We have defined the interface ISmartPhone with the method signatures OS and AppStore in it. If we compile the code now, it throws an error straightaway. 


It says we cannot prefix public modifiers with method signatures. In fact, no access modifier is allowed with interface methods. Interface methods are implicitly public in C# because an interface is a contract meant to be used by other classes. Moreover, we must declare these methods as public in derived classes, when we provide implementations to these methods. Also, we cannot declare these methods as static.
  1. - An important point that should be noted here is that whenever we implement interface members in derived classes, the access modifier must always be public otherwise it throws an error. If we write a protected modifier instead of public to the OS method, the compiler throws an error.
Now if the Apple class wants to implement TouchID features, it can easily be done by defining another interface IFeatures. The Apple class can simply inherit the interface and implement the TouchID functionality to its class. This is the case where an interface is useful instead of an abstract class.  

So, this way we can get multiple inheritance in C#. Let's create the objects of the concrete classes Apple and Samsung and build the project.

using System;    
namespace InterfaceDemo   
{   
     interface ISmartPhone    
     {   
         void OS();   
         void AppStore();   
     }   
  
     //New Interface meant only for Apple Class   
     interface IFeatures   
     {   
          void TouchID();  
     }  
  
     class AppleISmartPhoneIFeatures   
     {   
         //OS Method Implementation   
         public void OS()   
         {   
             Console.WriteLine("OS Method: The OS of this smartphone is iOS8");   
         }   
  
         //AppStore Method Implementation   
         public void AppStore()   
         {   
            Console.WriteLine("AppStore Method: The Application Store of this
smartphone is iTunes");   
         }  
  
         //TouchID Method Implementation   
         public void TouchID()   
         {  
            Console.WriteLine("TouchID Method: This method provides Touch/Gesture
Control features.");   
         }  
     }   
  
     class Samsung : ISmartPhone   
     {   
         //OS Method Implementation   
         public void OS()    
         {   
            Console.WriteLine("OS Method: The OS of this smartphone is Android");   
         }   
  
         //AppStore Method Implementation   
         public void AppStore()   
         {   
            Console.WriteLine("AppStore Method: The Application Store of this
smartphone is Google Play");   
         }   
      }   
  
      class Program   
      {   
          static void Main(string[] args)   
         {   
             Console.WriteLine("////// - Interface Demo -////// \n");                      
             Console.WriteLine("Apple SmartPhone:");   
             Apple apple = new Apple();   
             apple.OS();   
             apple.AppStore();   
             apple.TouchID();   
               
            Console.WriteLine("\n\n");   
            Console.WriteLine("Samsung SmartPhone:");   
            Samsung samsung = new Samsung();   
            samsung.OS();   
            samsung.AppStore();   
            Console.ReadKey(); }  
      }   
}


If we run the code now, it works perfectly.  



Continue Reading →

Saturday 18 October 2014

Self Joins in SQL Server

Self Joins in SQL Server- Find the Manager Name for each employee in the employee table
self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. To perform a self join, Oracle combines and returns rows of the table that satisfy the join condition.
For example the following query returns employee names and their manager names for whom they are working.
Create table Emp
(
empid int primary key,

name varchar(50),

mgrid 
int

)

Insert into Emp(empid,name,mgrid) values (1001,'Manish Agrahari',1001); 

Insert into Emp(empid,name,mgrid) values (1002,'Deepti',1001);
Insert into Emp(empid,name,mgrid) values (1003,'Amit',1001);
Insert into Emp(empid,name,mgrid) values (1004,'Sandy',1002);
Insert into Emp(empid,name,mgrid) values (1005,'Ankit',1003);
Insert into Emp(empid,name,mgrid) values (1006,'Kapil',1002);
Select * from Emp;



select e.empid,e.name,m.name as 'mgr name' from Emp e, Emp m where e.mgrid =m.empid
select e.empid,e.name,m.name as 'mgr name' from Emp e, Emp m where m.empid = e.mgrid



Fetch the Managers
SELECT DISTINCT e1.EmpId, e1.name FROM Emp e1, Emp e2 where e1.EmpId=e2.mgrid; 


Fetch the Employee who has Managers
SELECT DISTINCT e2.EmpId, e2.name FROM Emp e1, Emp e2 where e1.EmpId=e2.mgrid; 





Thanks
~ Suraj K.

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives