Search

Showing posts with label Knowledge Base. Show all posts
Showing posts with label Knowledge Base. Show all posts

Jun 27, 2012

Deleting Parent and its child record without setting ON CASCADE DELETE

Hello All,

Very recent I found requirement for removing parent record which is having tons of relation as they have foreign key constrains; you can’t delete them unless you have ON CASCADE DELETE

I found solution on Stack Overflow and base main article from sqlteam. I have modified procedure to fix some minor issue and here is the procedure which take table name and a query to filter row which we need to delete from table along with its reference.

-- ================================================
-- Expects the name of a table, and a conditional for selecting rows
-- within that table that you want deleted.
-- Produces SQL that, when run, deletes all table rows referencing the ones
-- you initially selected, cascading into any number of tables,
-- without the need for "ON DELETE CASCADE".
-- Does not appear to work with self-referencing tables, but it will
-- delete everything beneath them.
-- To make it easy on the server, put a "GO" statement between each line.
-- ================================================
CREATE PROCEDURE DeleteCascade (
@BaseTableName VARCHAR(200)
,@BaseCriteria VARCHAR(1000)
)
AS BEGIN

DECLARE @ToDelete TABLE
(
Id INT IDENTITY(1, 1) PRIMARY KEY NOT NULL,
Criteria VARCHAR(5000) NOT NULL,
TableName VARCHAR(200) NOT NULL,
Processed BIT NOT NULL,
DeleteSql VARCHAR(5000)
)

SET NOCOUNT ON

INSERT INTO @ToDelete (Criteria,TableName , Processed)
VALUES (@BaseCriteria, @BaseTableName, 0)

DECLARE @Id INT
DECLARE @Criteria VARCHAR(5000)
DECLARE @TableName VARCHAR(5000)

WHILE EXISTS(SELECT 1 FROM @ToDelete WHERE Processed = 0)
BEGIN

SELECT TOP 1
@Id = Id
,@Criteria = Criteria
,@TableName = TableName
FROM @ToDelete
WHERE Processed = 0
ORDER BY Id DESC

INSERT INTO @ToDelete (Criteria, TableName, Processed)
SELECT
ReferencingColumn.name + ' IN (SELECT [' + ReferencedColumn.name + '] FROM ['
+ @TableName +'] WHERE ' + @Criteria + ')',
ReferencingTable.name,0
FROM sys.foreign_key_columns fk
INNER JOIN sys.columns ReferencingColumn
ON fk.parent_object_id = ReferencingColumn.object_id
AND fk.parent_column_id = ReferencingColumn.column_id
INNER JOIN sys.columns ReferencedColumn
ON fk.referenced_object_id = ReferencedColumn.object_id
AND fk.referenced_column_id = ReferencedColumn.column_id
INNER JOIN sys.objects ReferencingTable
ON fk.parent_object_id = ReferencingTable.object_id
INNER JOIN sys.objects ReferencedTable
ON fk.referenced_object_id = ReferencedTable.object_id
INNER JOIN sys.objects constraint_object
ON fk.constraint_object_id = constraint_object.object_id
WHERE ReferencedTable.name = @TableName
AND ReferencingTable.name != ReferencedTable.name

UPDATE @ToDelete
SET Processed = 1
WHERE Id = @Id

END

SELECT
'PRINT ''Deleting from ' + TableName + '...''; DELETE FROM [' + TableName + '] WHERE '
+ Criteria
FROM @ToDelete
ORDER BY Id DESC

END



When you execute this, you will see list of DELETE statement, which you need to run.

May 15, 2012

Enumeration Types as Bit Flags

An enum is best practice to give internal constants to readable string format, example

image

It’s very handy to use string rather to remember int value and it also helps to maintain code if down the road we need to change integer value it wont be difficult. I am sure developer knows very well about how to use enum in their code.

The post is all about answering few question comes while development or requirement, How you pass multiple value by using enum? or How to assign multiple enum values to variable? or How can I store combination of enum values using single enum variable?

All question have single answer, to use enum as bit flags. In order to achieve this, you have to add new attribute Flags to your enum declaration. As these values are bit you can use bitwise operation which are AND, OR, XOR and NOT.

Let’s see useful example of Flag enum using normal coding and then we will see same thing using Flags.

In normal coding if I want to calculate discount for four country and more then one at same time, I rather create for methods and call four individual functions

image

OR I can add bool into signature for calculating particular discount.

image

Drawback of first method is you have to keep adding new functions if you introduce new country and in second you have to pass false to country which you don’t want to do calculation, so signature will get increase in case we have more countries

Now lets use Flag enumeration to avoid mention drawbacks.

This will how your new enum will look like

image

A new attribute called Flags is added and we have assigned constants in power or TWO, that is 1,2,4,8 and so on, so when we use in combination no one get overlap.

Lets go ahead and create CalculateDiscount function and use into our program.

image

So single function CalculateDiscount is responsible to calculate discount for four different country at a time. If I want to calculate discount for German and Canada, you can do that by passing both in single argument using ‘|’ operator, its bitwise OR operator. You can use ‘&’ bitwise AND operator to determine whether a specific flag is set or not.

Jul 17, 2010

How to get multiple result set of procedure using LINQ to SQL

There always be case where one procedure returns more then one result set. Getting those data in DataSet is lazy way of coding, best way to do that is using DataReader. DataReader having method call NextResult which allows us to read next result set if any.

Read more from here.

Jun 24, 2010

OperationFormatter could not serialize error with WCF

I was working with calling WCF from iPhone, I have posted one post on “how can you call WCF from iPhone” you can find here. While I was working with this, I faced this issue and after doing some research I found solution! Here is what I did.

Following operation contract works fine.

[OperationContract]
public Dictionary<string, string> GetDictionary()

Note that I have only put operation contract not decoration which needed to work WCF with iPhone and Json.
But if we change this that operation contract to following...

[OperationContract]
public string GetDictionary()

After doing this I started getting follwoing error.

The OperationFormatter could not serialize any information from the Message because the Message is empty

I was wondering as it was issue with primitive type string! where it was working find with complex type. I searched a lot but did not get any solution for this. The service was retuning Serialized Json data; but not sure what was wrong there. I was searching for workaround to this but didn’t find any then I wrap that string into concert class and and return that class object, and you don’t believe it works fine! Error is gone I fixed The OperationFormatter could not serialize any information from the Message because the Message is empty error, wow!!!!!

I have modified operation and now it looks like following.

[DataContract]
public class Response
{
[DataMember]
public string Data { get; set; }
}

[OperationContract]
public Response GetDictionary()
{
return new Response() { Data = "success" };
}

It still open question why it was not working in only string, however it was working with Dictionary object and then with Abstract type! I assume that at the time of serializing request its not able to create object of string as its primitive type! Not sure its true but it works fine with wrapper.

Jun 22, 2010

wsdl-service-soap-address location having machine name not domain name

After fixing “Domain name replaced with machine name in WCF Service”, you can find solution in my previous post.

I found same issue but somewhere else, when you look into wsdl at the end where all services are listed there still machine name exists.

image

And hence any of the client will have following error.

There was no endpoint listening at http://domainname/ServiceName.svc that could accept the message. This is often caused by an incorrect address or SOAP action.

That is because it still uses computer name in soap address not domain name. Lets fix this issue too. We have to simply change endpoint address nothing more.

<services>
<service behaviorConfiguration="serviceBehaviour" name="Demo.Service.MultiEndPointsService">
<endpoint address="http://192.168.1.2/Demo.Service/MultiEndPointsService.svc/basic" binding="basicHttpBinding" bindingConfiguration="basicBinding"
contract="Demo.Service.MultiEndPointsService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.1.2/Demo.Service/MultiEndPointsService.svc/basic"/>
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>

Now let’s how wsdl looks like.

image

We are good to go!

Domain name replaced with Machine Name in WCF Service

I personally came across this issue WCF was taking machine name not IP address or domain name and also I got questions from forums about “how to replaced Machine Name with Domain name in WCF Service wsdl link?”. This occurs when we host WCF service on IIS then the links to wsdl is uses local machine name not the domain name or IP address.

image

You can see in browser [here I used IP address of my machine] in wsdl link its adding my computer name, this is same issue when I publish this service on production; the wsdl link is taking name of production machine not domain.

I found some solutions which changes the bindings on server but again that is not helpful for me on production server however it works well on local machine.

Then I was checking the configurations and found solution for how Domain name replaced with Machine Name in WCF Service without playing with IIS bindings. In service behavior we can change the behavior of serviceMetadata which will FIX our problem. We need to specify on what location metadata will resides httpGetUrl or httpsGetUrl. We can add url having domain rather machine name. So final configuration should look like following which is our solution.

<system.serviceModel>
<services>
<service name="Demo.Service.MultiEndPointsService" behaviorConfiguration="serviceBehaviour">
<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="Demo.Service.MultiEndPointsService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.3.61/Demo.Service/MultiEndPointsService.svc/basic" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None"></security>
<readerQuotas maxStringContentLength="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>

You can see value of httpGetUrl; I have specified IP address

image

Now let’s see again in browser.

image

There you goo!!!

Jun 21, 2010

Calling WCF service from iPhone

WCF changes way of communication between application-to-application and intra-application. This post will help you to call WCF from iPhone application. First we will see what we have to do on WCF to let iPhone application call service. And the sample code which call WCF from iPhone.

First let’s create simple WCF service.

[ServiceContract(Namespace = "")]
[DataContractFormat]
public class MultiEndPointsService
{
[OperationContract]
public string GetDictionary()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("IB", "Imran Bhadelia");
dict.Add("DO", "David Oliver");
dict.Add("NA", "Nick Althoff");
dict.Add("JJ", "Jay Joshi");
dict.Add("DL", "Dave Larson");
dict.Add("BA", "Brenda Ayong-Chee");
dict.Add("JP", "Jay Parikh");

StringBuilder sbJson = new StringBuilder();
new JavaScriptSerializer().Serialize(dict, sbJson);
return sbJson.ToString();

}
}

This is simple WCF Service. We need to add some decoration for enabling web script and handle POST method. We are going to send http post form iPhone application and send Json string as response. Doing so we also need to decorate our operation contract to set request and response format.

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehaviorAttribute(IncludeExceptionDetailInFaults = true)]
[DataContractFormat(Style = OperationFormatStyle.Document)]
public class MultiEndPointsService
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
public string GetDictionary()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("IB", "Imran Bhadelia");
dict.Add("DO", "David Oliver");
dict.Add("NA", "Nick Althoff");
dict.Add("JJ", "Jay Joshi");
dict.Add("DL", "Dave Larson");
dict.Add("BA", "Brenda Ayong-Chee");
dict.Add("JP", "Jay Parikh");

StringBuilder sbJson = new StringBuilder();
new JavaScriptSerializer().Serialize(dict, sbJson);
return sbJson.ToString();
}
}

And following are the configuration settings

<system.serviceModel>
<services>
<service name="Demo.Service.MultiEndPointsService" behaviorConfiguration="serviceBehaviour">
<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="Demo.Service.MultiEndPointsService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None"></security>
<readerQuotas maxStringContentLength="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>

We need to create basicHttpBinding so it get called form iPhone application, we haven’t sent security to call this method; and following is the Objective-C code which call WCF from iPhone.

NSString *soapMessage = [NSString stringWithFormat:@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><GetDictionary></GetDictionary></SOAP-ENV:Body></SOAP-ENV:Envelope>"];

NSURL *url = [NSURL URLWithString:@http://localhost/Demo.Service/MultiEndPointsService.svc/basic];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"urn:MultiEndPointsService/GetDictionary" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

Once you parse the response it will look like following.

wsdl

You can also call operation contract having parameters, for that need to create proper message and then add it in SOAP-BODY that will work.

Jun 20, 2010

WCF Service with webHttpBinding-basicHttpBinding-wsHttpBinding

WCF Services are designed to support distributed services where consumed client. Services are typically have WSDL interface which any of client can consumed regardless of platform on which WCF is hosted on.

WCF Services having three portions, Class having methods, host environment to host service, and one or more endpoints. Endpoints is place where WCF Client connects to WCF Service. In order to accommodate different communication scenario you just need to create more then one endpoints, for each endpoint you specify the address, a binding and a contract. Address is simple listener; contract specify the format of message which will arrive on specified address and binding is let you configure transport protocol, encoding and security. There are few built-in bindings represented by System.ServiceModel.Channels.Binding class to support HTTP, TCP and MSMQ protocols.

That was brief about WCF, now lets come to our business. We need to use wsHttpBinding + basicHttpBinding + webHttpBinding all together. That means we need to have multiple ends points to our service for different-different scenario. Here are the Service contract and operation contracts which we are going to use.

image

We will add one by one binding and check into WCF Test Client. First we will add basicHttpBinding which is designed for interoperability utmost important, its using SOAP 1.1.

image

You can see single endpoints having address and bindings, we have added binding configuration name basicBinding, which have property like security mode to None, readerQuotas having setting for client who is reading data from channel, also maxBufferSize which is parameter defined size which can be passed thru channel. We can see bindings in WCF Test Client it will show basic http bindings having one method. The value of maxBufferSize and maxReceivedMessgaeSize should be same for transfer mode is buffered. We have added behavior configuration for our service; serviceMetadata httpGetEnabled="true" allows simple HTTP Get request to succeed for metadata retrieval, by default WCF does not exposed metadata.

We can use WCF Test Client to check whether our setting are correct or not. So open WCF Test Client and add service url into service project.

image

It shows that we have exposed our service using basicHttpBinding. Now lets add wsHttpBinding binding, which is design for security, reliable messaging and transactions and its using SOAP 1.2 along with WS-Addressing 1.0 for message version which will carry additional protocol headers.

image

We have added binding configuration to set security and session reliability. The reliable session WCF provides ensures that messages sent between endpoints are transferred across SOAP or transport intermediaries and are delivered only once and, optionally, in the same order in which they were sent

Now let’s check on our WCF Test Client.

image

So, we can see two endpoints has been exposed, one is for basic binding and other is web script bindings. We already add basic and ws bindings lets add now web bindings.

image

One more endpoint, it’s now easy to expose more then one endpoint for single operation contract. If you need any security or additional settings then you can add binding configuration for this endpoint, but for now we don’t need any configurations. Let’s check our WCF Test Client.

image

We can see all these three binding for single operation contract! You can see wsdl file which will expose all these three bindings.

image

So we have exposed webHttpBinding + basicHttpBinding + wsHttpBinding endpoints in WCF service using same operation contract. We can use webHttpBinding for Silverlight application and also Json call.

Jun 14, 2010

RadComboBox dropdown issue in IE

Hello All, I was facing issue with RadComboBox dropdown, its adding scrollbar in IE if an item is longer then default size.

image

This is normal behavior, as we have item which get fits into dropdown, now consider following case where we items which are little longer then before.

image

Here you can see horizontal scrollbar is appear as our text is little bit longer then min-width property. Min-width property allow you to set minimum width of dropdown. But this looks weird.

Solution: You need to override following default style of RadComboBox.

<style>
.rcbSlide div
{
width: auto !important;
min-width: 150px !important;
max-width: 400px !important;
}
.rcbList
{
position: relative !important;
}
</style>

We can see after applying this style into page, RadComboBox will look like following.

image

Apr 17, 2010

HTTP Error 404.17 - Not Found with IIS7 and WCF

Hello All,

I was running to same issue when I have installed VS2010 on Windows 7 after installing .NET on IIS 7.5. My WCF service was retuning me the following error when I try to hit my wcf service it will giving me following error.

HTTP Error 404.17 - Not Found

I tried to change application pool and switch form 2.0 classic to 4.0 class, and then it gives me one more error!

HTTP Error 500.19 – Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Error Code 0×800700b7
Config Error There is a duplicate ’system.web.extensions/scripting/scriptResourceHandler’ section defined

After doing some search I found out the fix of this, we just need to register service model using following command, you should run command prompt in administrator mode and then go to following directory.

$WindowsDir$\Microsoft.NET\Framework\v3.0\Windows Communication Foundation

And run this command in favor to register service model.

servicemodelreg –i

It will install machine configuration sections, handlers, assemblies, modules, protocols and lots of other thing to work things properly.

Mar 16, 2010

Two WCF Sharing same a Data Contract - Ambiguous Error

[Problem: Ambiguous reference]

Hello All,

I came across one common issue while working with WCF services, Two WCF exposing same data contract with different namespace. Here are my two service contract with operation contracts.

namespace SVCDataContractTest.WCF
{
[ServiceContract]
public interface IService1
{
[OperationContract]
void DoWork(UserInfo userInfo);

[OperationContract]
void SaveContact(ContactInfo contactInfo);

}

public class Service1 : IService1
{
public void DoWork(UserInfo userInfo)
{
//Do some work
}

public void SaveContact(ContactInfo contactInfo)
{
//Do some work
}
}

[ServiceContract]
public interface IService2
{
[OperationContract]
UserInfo DoWork();
}

public class Service2 : IService2
{
public UserInfo DoWork()
{
//Do some work
return new UserInfo();
}
}
}

While adding them as reference it will generate two separate class having different namespace, we are good here as there won't be any compilation error if a requester don't import both namespace.



You can see there two UserInfo classes. Now problem comes when you imported both of the namespace, what happen to your class? it will start giving you following error.



It says that UserInfo is an ambiguous, as there are two set of classes resides in reference. The problem is when you add Service reference it's not treating UserInfo class as Shared class. Solution for this is to create Proxy with Type Sharing. We can use wsdl.exe to create proxy with shareType switch

wsdl.exe /out:ServiceProxies.cs /shareTypes http://localhost/SVCDataContractTest.WCF/Service1.svc?wsdl http://localhost/SVCDataContractTest.WCF/Service2.svc?wsdl

This will result in one class file called ServiceProxies, which contains the proxy implementation of both service but the implementation of UserInfo will be single.

ProxyCD1

Dec 10, 2009

Schema and Data Compare Scripts in MS SQL

Hello All,

I was searching for a tool which gives me the Schema and or data comparison for SQL Server, its really needed while we are updating staging or updating our live site. There may be lots of tool available on net but I found one tool which is part of Microsoft® Visual Studio Team System 2008 Database Edition GDR R2.

Team Edition provides lots of functionality, mainly we are using to write Test Case which is very useful for Test Driven Development.

On top of this if you have Database edition then you can do lots of things with it. One of the feature is Schema and Data Compare. This blog post will walk you thru steps to compare data and schema.

Schema Comparison

1. Go to New Schema Comparison form Data menu

2. Next select the two database, one is source and other is target

 

3. When press OK will give you the Schema Compare of all the objects including Tables, Views, Stored Procedures and many more.

Here you can see the list of Objects and the Object Definitions windows

4. In following image Table is expanded so you can see the changes in details on what table what action is held.

 

5. To see more in details select one of the updated row and you can see the definition in Object Definitions window; it will generate Create script and highlight the difference. There is also Schema Update Script which will have alter script of all the changes that is detected during Schema Compare.

6. You can either copy the script or export to file or editor by using Export To Edition command on tool box.

This was all about how to detect schema change, its very handy with lots of options.

Data Comparison

Now same way we have Data Comparison, which is use to compare data, it provides tons of details and script for insert/update and delete. The steps are pretty much starlight forward. I have listed the steps here.

1. Click on New Data Comparison from Data menu

2. It will ask for Source and Target tables

3. On click of Finish, it will provide you all the information that is differ in between two database tables

You can see here it shows 2 rows are only in source, means two rows are added to SB_mst_Group table. It also provides the what exact rows are added in middle section along with other options.

In third last section which is Data Update Script; provides you the script for the action, here we have addition, so its provide the insert statements which we can run in UAT to get the date.

I found it very useful and easy to generate required script in few mouse click!

Nov 25, 2009

Consuming WCF service out of box

Hello All,

I found one issue while consuming WCF service from out of box, There are lots of threads I found for 'The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.' error, CommunicationObjectFaultedException exception thrown and 'The caller was not authenticated by the service.'

I spent lots of time in search, got bunch of solutions, some worked some does not, after doing lots of troubleshooting I got solution for my problem.

My case was, a web application running on different box is trying to consume WCF service which is hosted on different box, but some how on production it was not working. It always throws 'CommunicationObjectFaultedException'. Usually we are putting such calls in using blog, as its taking care of disposing object. But in case of WCF it may not work as per expected, the reason is; A CommunicationObjectFaultedException has been throws so you, the object is not yet initialized and you are using is trying to dispose method which again throw exception.

 

This is because using implicitly call Dispose at the closing brace, which may throw an exception because your object is not yet initialized as its in the Faulted state. To over come this a simple solution, use try catch and call Abort. More reading on this click Avoiding Problems with the Using Statement, good article form Microsoft including Sample application. During my search I found one good code delegate make you fell like you are using clause, but internally its handling such exception.

private class Util
{
public static void UsingWcf<T>(T client, Action<T> action)
where T : System.ServiceModel.ICommunicationObject
{

try
{
action(client);
client.Close();
}
catch (Exception)
{
client.Abort();
throw;
}
}
}
class Program
{
static void Main(string[] args)
{

Util.UsingWcf(new WcfClient(), c =>
{

});

/*using (WcfClient wcfClient = new WcfClient())
{
....
}// This will throw an error
*/
}
}

So we have caught CommunicationObjectFaultedException, but still we are not able to make call to service method. Now you can see one new error 'The caller was not authenticated by the service'. Cool we reach the service but its missing some credentials, as we are consuming service out of box.

Typical configuration section looks like following



Form error 'The caller was not authenticated by the service' we can guess that we need some credentials to call method. You can see the configuration; it says clientCredentialsType="Windows" and security mode is Message, generally with wsHttpBinding these are the typical settings.



As we are using Windows as credential type, we need to provide credentials to use WCF serverice out of box. Once this done you just need to pass user and password in ClientCredentials just like bellow

Nov 21, 2009

Baroda Developers Conference

Hello All,

Event  Baroda Developer Conference was held on Saturday, November 21, 2009 at Dr. I.G. Patel Seminar Hall Vadodara.

Links: Baroda Mega Developers Conference; Baroda Developers Conference [Dev-Con]

I recently gave presentation at a session titled as "Features of C# 3.0" followed by Probjots session "Introducing LINQ" & "VS 2010 & .Net 4.0" and "MOSS 2007" by Bhavin Gajjar.

It was my first experience to give a presentation. There were students who were part of Microsoft Student Partner program with sound knowledge in Microsoft .Net Technology.

Here are few snaps from conference. 

 

[Attending one students' question on Partial Methods]

[Me with Probjot and students]

[Attendees]

I want to congratulate all the attendees for being part of such a knowledge sharing conference and taking active part in it.They came from different territories of all over India. I really appreciate their interest. Also I have demo project which I have used during my presentation to get this send me an email.

I am very much thankful of Jacob Sebastian who promoted me for this event and Prakher Mehta who was the organizer and inviter of BUG [Baroda User Group]

Oct 14, 2009

Rolebase page access and rulebase operation access

Hi Again,

This is typical scenario where programmer done want to allow specific user to visit specific page due to functionality which needs to be secure based on user types. The task like managing users should not accessed by a normal user. So we need security based on user types, more precisely we need Authorization. Once user passed thru authentication it is not Authorization who decide the access of current logged user to perform some task.

Before introductions of ASP.NET Rolebase providers, people used to check on each page for the role, and if it does not have that role then redirection process, here all data related to user role kept in session.

This functionality is much more simpler after introduction of Rolebase provider, we just need to define roles and access to that roles. We can restrict users based on either role or userid itself, its depend how the application needs the functionality. This is for particular page, now what if I need to restrict user at operation level? Mean I don't allow Account user to manage users personal details, he just need to play with user's account, he does not need to update personal details of user. Here we can use Rolebase provider to check whether logged in user have rights to perform that operation or not.

Rolebase page Access: After setting roles and mapping, you just need to add few settings into configuration file which rolebase provider will use to perform authorization. Typical example of such web.config is as following.

Authorization_Admin

Lets understand the setting.

  • location tag in which you have to specify path of resource. If path is directory then the authorization will consider on all the pages inside that directory.
  • authorization tag will contains the allow or deny user/roles listing.
  • allow tag contains the roles attribute, in which you have to put role name. So you are allowing user having SiteAdmin to access ManageUser page. In the same way if you write deny roles then it will deny that particular role to access ManageUser page.
  • deny tag contains roles or user. In typical setting we are putting selected roles/users in allow list and for rest we kept as deny, so in deny you may always find * which means all user or all roles.

Typically we have more then one configuration files kept in different-different directories to manage folder separately.

Now let's see how we can implement operation level security using Rulebase provider. Microsoft Enterprise Library Security Application Block helps developers implement common authorization-related functionality in their applications. We just need to set some configuration setting using which you can identify the operation level access. Following is the typical configuration to implement rulebase provider.

RuleBaseProvider

You can see the how rule has been added here along with expression. You can add new rule by adding name and expression, expression is simple string which contains set of Role name and expression. There are list of more expression you can find bellow. First lets try to understand EditPersonalInfo rule, it has two role SiteAdmin or Superuser or User, so all user having these roles can perform EditPersionInfo operation.

Rule Expression can contains I, R, AND, OR, NOT, (, ), ?, *.

  • I: It will authorize to identity which is supplied with I
    • expresson="I:Imran" will allow a user with identity Imran
  • R: It will authorize to role which is supplied with R
  • Rest will be operator you can use at any time
    • expression="((R:Superuser OR R:AccountAdmin) AND (NOT R:SiteAdmin))"

Now this is all about configuring rules. Will see how to apply these rules in our coding.

RoleProvider_Code

Just two lines of code to know weather user is authorize to do that action or not.

Oct 11, 2009

Core Service - Extensible Output Caching

Output caching is one of the major factor to load your page more faster. up to now ASP.NET allow developer to store generated output of page, control and HTTP request into memory to used further request.

ASP.NET 4.0 provides the mechanism to let developer handle output cache by creating your own custom output-cache provider and manage the persistency of HTML content. For doing this you just need to create class which derives from System.Web.Caching.OutputCacheProvider type and add it to your caching section of web.config. The default provider is AspNetInternalProvider.

ExtensibleOutputCaching 

In addition, you can choose different provider for different pages! There are two way to do this.

First you need to override one new method in Global.asax called GetOutputCacheProviderName which helps you to select output cache provider.

OutputCacheGlobal

Adding code at request level is like adding more work to do, the easiest way is to select output-cache provider is to set value of attribute providerName which is part of OutputCache page or control directive.

OutputCachePage

Topic: ASP.NET 4.0 and Visual Studio 2010 Web Development Beta 2 Overview

Oct 10, 2009

Core Service – Web.Config file Minification

The configuration file is very important for each web application, each web application will have one master web.config file which contains all the setting that a simple web application needs, on top of it we have machine.config, there always be single machine.config file.

Now typical web.conifg will have lots of section and sub-section which are common for all the application, like AJAX related stuff, IIS integration and many more, what 4.0 does is it moved common setting from web.config to machine.confg, this means now your web.config file in ASP.NET 4.0 either empty or contains following lines.

WebConfigMinification

Topic: ASP.NET 4.0 and Visual Studio 2010 Web Development Beta 2 Overview