Pages

Monday, April 5, 2021

How to return multiple models in a single view in MVC?

Recently I got this question in one of my interviews. Although I have a single answer for this, but interviewers want more ways to return the multiple models in a single view. So I googled this after my interview and found the following ways to do it:

  1. Creating a new view model that consists of all these model classes
  2. Using Partial Classes
  3. Using ViewBag
  4. Using ViewData
  5. Using Dynamic Model
  6. Using Tuple

I will create small-small code snippets for these and will publish them soon here only.

Thursday, June 14, 2012

WCF Security Best Practices

From OWASP(https://www.owasp.org/index.php/WCF_Security_Best_Practices)
From WCF 3.5 Security Guidelines
(@Codeplex by J.D. Meier , Jason Taylor , Prashant Bansode , Carlos Farre, Madhu Sundararajan, Steve Gregersen.)

Design Considerations
  • Design your service as a wrapper
  • If you are coming from ASMX then use basicHttpBinding to support your existing clients
  • If you are coming from DCOM then, use netTcpBinding
  • If your clients are deployed within intranet then choose transport security
  • If your clients are deployed over the internet then choose message security
  • Know your Authentication options
  • Know your binding options
  • If you need to Interop with non MS clients, use basicHttpBinding or wsHttpBinding
  • If your non-MS clients understand WS stack, use wsHttpBinding

Auditing and Logging
  • Use WCF auditing to audit your service
  • If non-repudiation is important, consider setting SuppressAuditFailure property to false
  • Use message logging to log operations on your service
  • Instrument for user management events
  • Instrument for significant business operations
  • Protect log files from unauthorized access
  • Do not log sensitive information

Authentication
  • Know your authentication options
  • Use Windows Authentication when you can
  • If you support non-WCF clients using windows authentication and message security, consider using the Kerberos direct option
  • If your users are in AD, but you can’t use windows authentication, consider using username authentication
  • If you are using username authentication, use Membership Provider instead of custom authentication
  • If your users are in a SQL membership store, use the SQL Membership Provider
  • If your users are in a custom store, consider using username authentication with a custom validator
  • If your clients have certificates, consider using client certificate authentication
  • If your partner applications need to be authenticated when calling WCF services, use client certificate authentication.
  • If you are using username authentication, validate user login information
  • Do not store passwords directly in the user store
  • Enforce strong passwords
  • Protect access to your credential store
  • If you are using Windows Forms to connect to WCF, do not cache credentials

Authorization
  • If you store role information in Windows Groups, consider using the WCF PrincipalPermissionAttribute class for roles authorization
  • If you use ASP.NET roles, use the ASP.NET Role Provider
  • If you use windows groups for authorization, use ASP.NET Role Provider with AspNetWindowsTokenRoleProvider
  • If you store role information in SQL, consider using the SQL Server Role Provider for roles authorization
  • If you store role information in ADAM, use the Authorization Store Role Provider for roles authorization
  • If you need to authorize access to WCF operations, use declarative authorization
  • If you need to perform fine-grained authorization based on business logic, use imperative authorization

Binding
  • If you need to support clients over the internet, consider using wsHttpBinding.
  • If you need to expose your WCF service to legacy clients as an ASMX web service, use basicHttpBinding
  • If you need to support remote WCF clients within an intranet, consider using netTcpBinding.
  • If you need to support local WCF clients, consider using netNamedPipeBinding.
  • If you need to support disconnected queued calls, use netMsmqBinding.
  • If you need to support bidirectional communication between WCF Client and WCF service, use wsDualHttpBinding.

Configuration Management
  • Use Replay detection to protect against message replay attacks
  • If you host your service in a Windows service, expose a metadata exchange (mex) binding
  • If you don’t want to expose your WSDL, turn off HttpGetEnabled and metadata exchange (mex)
  • Manage bindings and endpoints in config not code
  • Associate names with the service configuration when you create service behavior, endpoint behavior, and binding configuration
  • Encrypt configuration sections that contain sensitive data

Exception Management
  • Use structured exception handling
  • Do not divulge exception details to clients in production
  • Use a fault contract to return error information to clients
  • Use a global exception handler to catch unhandled exceptions

Hosting
  • If you are hosting your service in a Windows Service, use a least privileged custom domain account
  • If you are hosting your service in IIS, use a least privileged service account
  • Use IIS to host your service unless you need to use a transport that IIS does not support

Impersonation and Delegation
  • Know the impersonation options
  • If you have to flow the original caller, use constrained delegation
  • Consider LogonUser when you need to impersonate but you don’t have trusted delegation
  • Consider S4U when you need a Windows token and you don’t have the original caller’s credentials
  • Use programmatic impersonation to impersonate based on business logic
  • When impersonating programmatically be sure to revert to original context
  • Only impersonate on operations that require it
  • Use OperationBehavior to impersonate declaratively

Input/Data Validation
  • If you need to validate parameters, use parameter inspectors
  • If your service has operations that accept message or data contracts, use schemas to validate your messages
  • If you need to do schema validation, use message inspectors
  • Validate operation parameters for length, range, format and type
  • Validate parameter input on the server
  • Validate service responses on the client
  • Do not rely on client-side validation
  • Avoid user-supplied file name and path input
  • Do not echo untrusted input

Proxy Considerations
  • Publish your metadata over HTTPS to protect your clients from proxy spoofing
  • If you turn off mutual authentication, be aware of service spoofing

Deployment considerations
  • Do not use temporary certificates in production
  • If you are using a custom domain account in the identity pool for your WCF application, create an SPN for Kerberos to authenticate the client.
  • If you are using a custom service account and need to use trusted for delegation, create an SPN
  • If you are hosting your service in a Windows Service, using a custom domain identity, and ASP.NET needs to use constrained trusted for delegation when calling the service, create an SPN
  • Use IIS to host your service unless you need to use a transport that IIS does not support
  • Use a least privileged account to run your WCF service
  • Protect sensitive data in your configuration files 

Tuesday, June 5, 2012

Properties and Indexers in C#

Abstract
Properties are known as smart fields and enable access to the fields of a class. Indexers are also called smart arrays in C# and can be used to use an object as an array. This article discusses both of these concepts with simple code examples.


Property
A property is like a "virtual field" that contains get and set accessors and provides an interface to the members of a class. They can be used to get and set values to and from the class members. Properties can be static or instance members of a class. The get accessor does not accept any parameter; rather it returns the value of the member that it is associated with. The set accessor contains an implicit parameter called 'value'. The following code example illustrates a simple property.

Listing 1 - Implementing properties

using System;
namespace ConsoleApplication
{
  class Test
  {
    private int number;
    public int MyProperty
    {
      get { return number; }
      set { number = value; }
    }
    [STAThread]static void Main(string[]args)
    {
      Test test = new Test();
      test.MyProperty = 100;
      Console.WriteLine(test.MyProperty);
      Console.ReadLine();
    }
  }
}
The following code shows a static property. The static property MyProperty can be accessed without instantiating the class. A static property can access static members of a class only.

Listing 2 - Implementing a static property
using System;
namespace ConsoleApplication
{
  class Test
  {
    private static int number;
    public static int MyProperty
    {
      get { return number; }
      set { number = value; }
    }
    [STAThread]static void Main(string[]args)
    {
      Test.MyProperty = 100;
      Console.WriteLine(Test.MyProperty);
      Console.ReadLine();
    }
  }
}
The following code shows how the visibility of the get and the set accessors has been restricted to the current assembly only by using the keyword "internal".

Listing 3 - Restricting the visibility
public class Employee
{
  private int empID;
  private string empName;
 
  internal int ID
  {
    get { return empID; }
    set { empID = value; }
  }
  internal string Name
  {
    get { return empName; }
    set { empName = value; }
  }
}
 
public class Test
{
  public static void Main(string[]args)
  {
    Employee emp = new Employee();
    emp.Name = "Joydip";
    emp.ID = 259;
    System.Console.WriteLine("The id is:" + emp.ID);
    System.Console.WriteLine("The name is:" + emp.Name);
  }
}
The keyword “internal” implies that the property's ID and Name can be accessed from the current assembly only as they are “internal” to the assembly in which they have been declared.
----------------------------------------------------------------------------------------------------
Indexer
Indexers are also called smart arrays in C# and can be used to treat an object as an array. An indexer allows an instance of a class or a struct to be indexed as an array, which is useful for looping or iterating or data binding operations.
The following is the syntax of an indexer declaration.
<Modifier> <Return type> this[arguments]
{
  get { }
  Set { }
}
The modifier can be one of the following
·         private
·         public
·         protected
·         internal
All indexers should accept at least one parameter. Indexers cannot be static. This is because static methods do not have access to ‘this’. The ‘this’ keyword indicates an instance of the current class. Look at the code given below.

Listing 4 - A simple indexer
namespace ConsoleApplication
{
  using System;
  class Employee
  {
    private string[]name = new string[10];
    public string this[int index]
    {
      get { return name[index]; }
      set { name[index] = value; }
    }
  }
 
  class Test
  {
    public static void Main()
    {
      Employee emp = new Employee();
      emp[0] = "Joydip";
      emp[1] = "Manashi";
      emp[2] = "Jini";
      Console.WriteLine("The namesare:--");
      for (int i = 0; i < 3;Console.WriteLine(emp[i++]))
        ;
      Console.ReadLine();
    }
  }
}
The output of the program is
The names are:--
Joydip
Manashi
Jini

Indexers in inheritance
The indexers of the base class are inherited to its derived classes. This is illustrated in the code shown below.

Listing 5 - Indexers in inheritance
using System;
class Base
{
  public int number;
  public int this[int index]
  {
    get
    {
      Console.Write("Get of the baseclass.");
      return number;
    }
    set
    {
      Console.Write("Set of the baseclass.");
      number = value;
    }
  }
}
 
class Derived: Base{}
class Test
{
  public static void Main()
  {
    Derived d = new Derived();
    d[0] = 500;
    Console.WriteLine("The value is: "+ d[0]);
  }
}
The program displays the string “Set of the base class. Get of the base class. The value is: 500”.
Indexers can be polymorphic. We can have the same indexer in the base and the derived classes. Such indexers are ‘overridden indexers’ and require the keyword virtual to be stated in their declaration in the base class. The following program illustrates this.

Listing 6 - Indexers can be polymorphic
using System;
class Base
{
  protected int number;
 
  public virtual int this[int index]
  {
    get
    {
      Console.Write("Get of the baseclass.");
      return number;
    }
    set
    {
      Console.Write("Set of the baseclass.");
      number = value;
    }
  }
}
 
class Derived: Base
{
  public override int this[int index]
  {
    get
    {
      Console.Write("Get of the derivedclass.");
      return base.number;
    }
    set
    {
      Console.Write("Set of the derivedclass.");
      base.number = value;
    }
  }
}
 
class Test
{
  public static void Main()
  {
    Base obj = new Derived();
    obj[0] = 500;
    Console.WriteLine("The value is: "+ obj[0]);
  }
}
The output of the program is “Set of the derived class. Get of the derived class. The value is: 500”.

Abstract indexers
Indexers can be abstract. We can have abstract indexers in a base class that need to be implemented by the class subclassing (inheriting from) it. The abstract indexer like an abstract method does not contain any code in its get or set. This is shown in the example below.

Listing 7 - Indexers can be abstract
using System;
abstract class Base
{
  protected int number;
 
  public abstract int this[int index]
  {
    get;
    set;
  }
}
 
class Derived: Base
{
  public override int this[int index]
  {
    get { return number; }
    set { number = value; }
  }
}
 
class Test
{
  public static void Main()
  {
    Derived obj = new Derived();
    obj[0] = 500;
    Console.WriteLine("The value is: "+ obj[0]);
  }
}
The output of the program is "The value is: 500".

Comparison between properties and indexers
Properties are accessed by names but indexers are accessed using indexes. Properties can be static but we cannot have static indexers. Indexers should always be instance members of the class. The get accessor of a property does not accept any parameter but the same of the indexer accepts the same formal parameters as the indexer. The set accessor of a property contains an implicit parameter called "value". The set accessor of an indexer contains the same formal parameters as that of the indexer and also the "value" as an implicit parameter.

Conclusion
Properties and indexers are two of the most important concepts in C#. This article has discussed both these concepts with code examples. I would highly appreciate any comments and or suggestions from the readers related to this article. Please post your comments and or suggestions if you have any. Happy reading!

Wednesday, May 23, 2012

Scenario for Self Join


Scenario for Self Join :-
Suppose you're tasked with writing a SQL query to retrieve a list of employees and their managers. You can't write a basic SQL SELECT statement to retrieve this information, as you need to cross reference information contained in other records within the same table. Fortunately, you can use a self-join to solve this dilemma by joining the table to itself.

Self join in sql means joining the single table to itself. It creates the partial view of the single table and retrieves the related records. You can use aliases for the same table to set a self join between the single table and retrieve the records satisfying the condition in where clause.

For self join in sql you can try the following example:
Create table employees:
emp_id emp_name emp_manager_id
1 John Null
2 Tom 1
3 Smith 1
4 Albert 2
5 David 2
6 Murphy 5
7 Petra 5

Now to get the names of managers from the above single table you can use sub queries or simply the self join.

Self Join SQL Query to get the names of manager and employees:
select e1.emp_name 'manager',e2.emp_name 'employee'
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id

Result:
manager employee
John Tom
John Smith
Tom Albert
Tom David
David Murphy
David Petra

Understanding the Self Join Example
In the above self join query, employees table is joined with itself using table aliases e1 and e2. This creates the two views of a single table.

from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id

Here e.emp_manager_id passes the manager id from the 2nd view to the first aliased e1 table to get the names of managers.

Tuesday, May 22, 2012

Add an icon to your URL


To add an icon to your URL:

You need an icon. There are plenty of icons on your pc to pick from. Use windows search and look for *.ico Or you can create one go here 
Upload the icon to your directory on line the same location of the index.html
Rename the icon on line to favicon.ico
Add both lines below to the head of your index.html page
<link rel="icon" type="image/ico" href="favicon.ico"></link> 
<link rel="shortcut icon" href="favicon.ico"></link> 

Also you can add an animated icon, just create an animated gif 16 x 16 and upload it to the root directory and add this code. It works only with Firefox browser.
<link rel="shortcut icon" type="image/gif" href="animated_favicon.gif"></link> 

They all will look like this
<link rel="shortcut icon" type="image/ico"favicon.ico"></link>
<link rel="shortcut icon" type="image/gif" href="animated_favicon.gif"></link>
<link rel="shortcut icon" href="favicon.ico"></link>


Also just upload the favicon.ico to the root directory of the site all new browsers will find it.
It works with and Netscape7,  IE5 and up and Firefox

Tuesday, May 15, 2012

Magic tables in SQL Server

 
Magic Tables are invisible tables, created on MS SQLServer, during INSERT/UPDATE/DELETE operations on any table. These tables temporarily persists values before completing the DML statements.
Inserted Table and Updated Table are two Magic tables available in SQLServer.

“Inserted Table” usage in “Trigger on Insert action”:

When a record is inserted into any table, then that record will be added temporarily inserted into Inserted table, before inserting into the appropriate table. Following Trigger on INSERT action explains the usage of Inserted Table,

CREATE TRIGGER PaymentLogger
ON Payment
FOR INSERT
DECLARE @UserID int
DECLARE @PaymentStatus varchar(50)
SELECT @PaymentStatus = PaymentStatus, @UserID = UserID FROM INSERTED
INSERT INTO PaymentLog(UserID, PaymentStatus, Message) VALUES (@UserID, @PaymentStatus, ‘Inserted into Payment table’)

“Deleted Table” usage in “Trigger on Delete action”:

When a record is deleted from any table, then that record will be inserted temporarily into the Deleted table. Following Trigger on DELETE action explains the usage of Deleted Table.

CREATE TRIGGER PaymentLogger
ON Payment
FOR DELETE
DECLARE @UserID int
DECLARE @PaymentStatus varchar(50)
SELECT @PaymentStatus = PaymentStatus, @UserID = UserID FROM DELETED
INSERT INTO PaymentLog(UserID, PaymentStatus, Message) VALUES (@UserID, @PaymentStatus, ‘Deleted from Payment table’)

Inserted and Deleted Table usage in “Trigger on Update action”:

When a record is updated from any table, then,
  1. New record updated will be added into the Inserted table, and
  2. Old record will be added into Deleted table.
Following Trigger on UPDATE action explains the usage of Inserted and Deleted Tables,

CREATE TRIGGER PaymentLogger
ON Payment
FOR UPDATE
DECLARE @UserID int
DECLARE @OldPaymentStatus,  @NewPaymentStatus varchar(50)
SELECT @NewPaymentStatus = PaymentStatus, @UserID = UserID FROM INSERTED
SELECT @OldPaymentStatus = PaymentStatus FROM DELETED
INSERT INTO PaymentLog(UserID, PaymentStatus, Message) VALUES   (@UserID, @NewPaymentStatus , ‘Updated from Payment table – old payment   status’ + @OldPaymentStatus )

Thursday, October 6, 2011

Error : WCF Service Host cannot find any service metadata.

Error : WCF Service Host cannot find any service metadata. This may cause the client application to run improperly. Please check if metadata is enabled. Do you want to exit?

Ans :-I got this error and in my case the problem was the value in the service name field did not actually match the namespace of the class actually implementing the operation contract in app.config file see the underlined text below. ist is the namespace and after dot is the actula name of the class which implements it. Just check the namespace for the name and the contract.

<services>
service name="WCFHelloWorld.HelloWorldService" behaviorConfiguration="WCFHelloWorld.Service1Behavior">