“Article of the day” @ ASP.NET Microsoft Website for Nov 10 , 2013

Hi All,

Happy to announce that my article entitled “Protecting a WCF Service Over Internet: Authenticating and Authorizing Users by Using the ASP.NET Membership Provider and Role Provider” has been selected as “Article of the day” @ASP.NET Microsoft Official Website for November 10, 2013.

You can check this out at : http://www.asp.net/community

Articleoftheday-10-Nov-2013

Thank you very much to all my readers and well wishers who has inspired me to write useful content on this blog. I will continue this going forward as well.

With Regards
Sandeep Ramani

Remove spaces of a string in SQL Server

Recently, I was facing one issue while trying to remove leading and trailing space using LTRIM and RTRIM SQL function.

Normally, When you want to remove leading and trailing spaces from column of a table, you just use below query:

Select LTRIM ( RTRIM ( ColumnName ) ) FROM TableName

But In my case I was not able to remove trailing spaces from column using above query. So I have investigated the issue and came to know that if my column contains Line feeds, carriage returns or tabs than TRIM functions can not able to remove it. So we need to use below query:

Select LTRIM ( RTRIM ( REPLACE ( REPLACE ( REPLACE ( ColumnName, CHAR(10), ''), CHAR(13), ''), CHAR(9), '') ) )  FROM TableName

There also some other characters which are not printable. Such characters needs to be replaced with Blank character before we use TRIM Functions. List of such characters are :

--NULL
Replace(ColumnName,CHAR(0),'');
--Horizontal Tab
Replace(ColumnName,CHAR(9),'');
--Line Feed
Replace(ColumnName,CHAR(10),'');
--Vertical Tab
Replace(ColumnName,CHAR(11),'');
--Form Feed
Replace(ColumnName,CHAR(12),'');
--Carriage Return
Replace(ColumnName,CHAR(13),'');
--Column Break
Replace(ColumnName,CHAR(14),'');
--Non-breaking space
Replace(ColumnName,CHAR(160),'');

Hope this will help !!!

Jay Ganesh

Interview Q&A Set – 2

1) Can we use this inside static method?

Ans : No

The keyword ‘this’ returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class.

2) Can we create property get/set with diff modifier? How can we achieve this if such sitaution arise? How to create readonly property?

Ans:

Yes, this is possible. It is called Asymmetric Accessor Accessibility. The code would look something like this:

public int Age
{
get
{
return _age;
}
protected set
{
_age = value;
}
}

However, there are a couple of important caveats to keep in mind:

Only one accessor can be modified.
Any restrictions placed on an individual accessor must be more restrictive than the accessibility level of the property itself, not less.
You cannot use accessor modifiers on an interface or an explicit implementation of an interface member.

more info : http://msdn.microsoft.com/en-us/library/75e8y5dd.aspx

3) Base class has virtual method with internal. can we overide that method in derived class with public access modifier?
   Same vise versa is posssible? Does it gives any warning/error?

Ans: No , Not Possible

4) Is there an attribute to turn off serialisation for fields in a custom object ?

Ans: IgnoreDataMemberAttribute is used to turn off serialisation for field.

5) How to return object in JSON format in WCF service method?

Ans: using the DataContractJsonSerializer class to serialise bjects to JSON.

6) How to restrict announoumous access to WCF service methods?

Ans:

Disabling anonymous access requires coordinating the settings in IIS and in your service configuration. To switch off anonymous access with HTTP, you need to set the security mode to TransportCredentialOnly.


<basicHttpBinding>
<binding>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>

To switch off anonymous access with HTTPS, you need to set the security mode to Transport.

<wsHttpBinding>
<binding>
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
</binding>
</wsHttpBinding>

7) How i can restrict specific users to access few web methods in webservice?

Ans :

This can be done in a couple of ways: certificates, username/password, windows credentials, … Authorization will decide what an (authenticated) user is allowed to execute. Implementing restricted access to a WCF service can be done in a couple of ways. A first option is to mark methods with the declarative PrincipalPermissionAttribute to restrict access to certain roles or users. An other option is to imperatively check the credentials of the current user.

Both of these methods have the drawback that they result in a lot of duplication when you have multiple service methods. Because duplication is the root of all evil, the creators of WCF have foreseen an extension point in WCF to implement authorization in a generic way: the ServiceAuthorizationManager.

Implementing a ServiceAuthorizationManager is straightforward; you need to extend the class “ServiceAuthorizationManager” and you need to override the method “CheckAccessCore”. In this small example, I will restrict access to my service to users of the windows group “Administrators”.

public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
try
{
ServiceSecurityContext securityContext = operationContext.ServiceSecurityContext;
WindowsIdentity callingIdentity = securityContext.WindowsIdentity;

WindowsPrincipal principal = new WindowsPrincipal(callingIdentity);
return principal.IsInRole("Administrators");
}
catch (Exception)
{
return false;
}
}
}

Now that our custom ServiceAuthorizationManager has been implemented, we need to hook it into the WCF pipeline. The most easy way to do is, by using the web.config or app.config file.

<system.serviceModel>
<!-- Define service and endpoints -->
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceAuthorization serviceAuthorizationManagerType="MyNamespace.MyServiceAuthorizationManager, MyAssembly" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Conclusion

When you test your service, you will notice that every method is secured by our custom ServiceAuthorizationManager implementation. I hope that you agree with me, that the ServiceAuthorizationManager is a clean way to implement authorization at the service level.

Hope this will Help !!!

Jay Ganesh

Interview Q&A Set – 1

This question set will be useful to the .Net Developer with fresher level or 1/2 years of experience. As it contain basic questions with little information.

1. Under what circumstances would you consider using a Code Generation Tool?

When we are writing repeating code or same code is reusable. Example Insert/Update/Delete/Search routine for database operation. For these we can create templates for each routine and use those template for code generation.

2. Explain the virtual function in c# with an example?


using System;
class A
{
public virtual void Test()
{
Console.WriteLine("A.Test");
}
}

class B : A
{
public override void Test()
{
Console.WriteLine("B.Test");
}
}

class Program
{
static void Main()
{
A ref1 = new A();
ref1.Test();

A ref2 = new B();
ref2.Test();
}
}

Output
--------
A.Test
B.Test

With virtual methods, the runtime type is always used to determine the best method implementation. In the main entry point, ref1 has a compile-time and runtime type of A. On the other hand, ref2 has a compile-time type of A but a runtime type of B.

With virtual methods, The runtime type is used in both invocations.

3. Explain how cookies work in ASP.NET? Also explain difference between session and persistent cookie.

Cookies are used to save user related preferences in browser & reuse those settings when user comes back on same website.

Session cookies are temporary cookies , when browser closes it loses data stored in it.
Persistent cookies are permanent cookies, saved in browser setting folder till you manually delete it or browser setting expiry date meets.

4. What is Ispostback method in ASP.Net? Why do we use that??

This is a read-only Boolean property that indicates if the page or control is being loaded for the first time, or if it is being loaded in response to a client postback.

5. Explain how the querystring is used to pass parameters between ASP.NET pages. Provide an example.

Target Page
—————

Page_Load(object sender, System.EventArgs e) {
string ID = Request.QueryString["ImageID"];
string Name = Request.QueryString["ImageName"];
Label1.Text = "ImageID: "+ ID;
Label2.Text = "Image name: "+ Name;
Image1.ImageUrl = "~/Images/"+Name+".jpg";
}

Calling Page
————–

String ImageID = "123";
String ImageName = "ProfilePic";
Response.Redirect("~/TargetPage.aspx?ImageID=" + ImageID + "&ImageName=" + ImageName);

6. Explain how a Single Sign-on login might be achieved across two separate ASP.NET applications which share the same database.

–>txtUserName is the text box ID that will carry the user name
–>txtPassword is the text box ID that will carry the password
–>Check and validate the user is exists with the right user and password or not


if (Membership.ValidateUser(_txtUserName.Text, _txtPassword.Text))
{

MembershipUser user = Membership.GetUser(_txtUserName.Text);
MembershipUser.IsApproved

if (_user != null)
{
if (_user.IsLockedOut)
{
//do something like display a message that this account is locked out
}
else
{
FormsAuthentication.SetAuthCookie(_txtUserName.Text, true);

string url=string.format(“http://SecondApplicationURL/authntication.aspx?username={0}&BackURL={1}”,_txtUserName.Text,”Http://FirstApplicationURL/deafult.aspx”);

Response.Redirect(url);
}
}

}

7.  What is difference between ExecuteReader, ExecuteNonQuery and Executescalar?

ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.
ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete.
ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value.

8. What is use of finally block? For what purpose you can use it?

Finally can be used to ensure that some logic is always executed before the method is exited.

 9. What is difference between truncate and delete?

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster.

DELETE is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent.

10. Explain modes of firing triggers.

AFTER INSERT Trigger : This trigger is fired after an INSERT on the table.
AFTER UPDATE Trigger : This trigger is fired after an update on the table.
AFTER DELETE Trigger : This trigger is fired after a delete on the table.

11. What is ViewState? Explain with example

ViewState allows the state of objects to be stored in a hidden field on the page.

<form id="form1" runat="server">
<asp:TextBox runat="server" id="NameField" />
<asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" />
<asp:Button runat="server" id="RefreshPage" text="Just submit" />
<br /><br />
Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" />
</form>

 


protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["NameOfUser"] != null)
NameLabel.Text = ViewState["NameOfUser"].ToString();
else
NameLabel.Text = "Not set yet...";
}

protected void SubmitForm_Click(object sender, EventArgs e)
{
ViewState["NameOfUser"] = NameField.Text;
NameLabel.Text = NameField.Text;
}

12. Please explain how javascript can be added to an ASP.NET application such that its content is created dynamically at run-time and can contain database content.

Here is the code which help is to add javascript dynamically :

ClientScriptManager CS = this.ClientScript;
StringBuilder SB = new StringBuilder();
SB.Append("window.alert(\"1111\");");
CS.RegisterClientScriptBlock(this.GetType(), "MyScript", SB.ToString(), true);

13. Please explain steps required to deploy an ASP.NET application & database in an automated manner.

Using Publish Profile we can automate deployment process of our application.

Hope this will Help !!!

Jay Ganesh

ASP.NET N-Layered Applications By Imar Spaanjaars

In this new article series you’ll see how to design and build an N-Layered ASP.NET application using ASP.NET MVC 4, ASP.NET 4.5 Web Forms and a number of other up-to-date technologies such as Entity Framework 5 and WCF.

In this series, I’ll build a sample application to manage contact people called the ContactManager v4.5 application, similar to the demo application demonstrated in the previous article series. Over the next 10 articles I’ll dissect the sample application (that you can download at the end of each article, starting with Part 2) and show you how I designed and built it.

Part 1 – Introduction
Part 2 – Setting up the Solution in Visual Studio
Part 3 – Making your Projects Unit Testable
Part 4 – Implementing a Model
Part 5 – Implementing a Repository using Entity Framework Code First
Part 6 – Implementing an ASP.NET MVC 4 Frontend
Part 7 – Implementing a Web Forms 4.5 Frontend
Part 8 – Implementing a WCF 4.5 Frontend
Part 9 – Importing Data Using the API
Part 10 – Extensions, Tools and Wrapping Up

More info click here.

Hope this will help !!!

Jay Ganesh