Wednesday, November 02, 2011

C# Checking a File exists in Folder

How to get all files from a folder and compare a whether that file exists in that folder or not. Here is a sample code where you can loop through the code and check the file.

I have declared a variable to check there it exists or not.

private bool isFileExists = false;


Now I have this code to check whether file exists and based on it I’ll redirect in to that page.


string searchfolder = Server.MapPath("~") + "\\TestFolder";
DirectoryInfo Dir = new DirectoryInfo(searchfolder);
FileInfo[] FileList = Dir.GetFiles("*.aspx", SearchOption.AllDirectories);
foreach (FileInfo FI in FileList)
{
if (FI.Name == redirectPage)
{
isFileExists = true;
break;
}
}
if (isFileExists == true)
{
Response.Redirect("~/redirectPage");
}
else
{
Response.Redirect("
~/OtherRedirect.aspx");
}

Here I have search pattern as *.aspx as I need to check these files. This can be based on the files you want to check

Monday, October 24, 2011

Silverlight Integration Pack for Microsoft Enterprise Library 5.0

Silverlight Integration Pack for Enterprise Library is a collection of guidance and reusable application blocks designed to assist Silverlight application developers with common LOB development challenges. This release includes: Caching Application Block, Exception Handling Application Block, Logging Application Block, Policy Injection Application Block, Validation Application Block, and Unity Application Block. These blocks are designed to encapsulate recommended practices which facilitate consistency, ease of use, integration, and extensibility. The release also addresses the needs of those who would like to port their existing LOB applications, that already leverage Enterprise Library, to Silverlight

This release includes:

  • Caching Application Block with support for:
    • In-memory cache
    • Isolated storage cache
    • Expiration and scavenging policies
    • Notification of cache purging
  • Validation Application Block with support for:
    • Multi-level complex validation
    • Attribute-based specification of validation rules
    • Configuration-based specification of validation rules
    • Simple cross-field validation
    • Self-validation
    • Cross-tier validation (through WCF RIA Services integration)
    • Multiple rule-sets
    • Meta data type for updating entities with external classes in Silverlight
    • Rich set of built-in validators
  • Logging Application Block, including:
    • Notification trace listener
    • Isolated storage trace listener
    • Remote service trace listener with support of batch logging
    • Implementation of a WCF Remote logging service that integrates with the desktop version of the Logging Application Block
    • Logging filters
    • Tracing
    • Logging settings runtime change API
  • Exception Handling Application Block, including:
    • Simple configurable, policy-based mechanism for dealing with exceptions consistently
    • Wrap handler
    • Replace handler
    • Logging handler
  • Unity Application Block – a dependency injection container
  • Dependency injection container independence (Unity ships with the Enterprise Library, but can be replaced with a different container)
  • Unity Interception mechanism, with support for:
    • Virtual method interception
    • Interface interception
  • Policy Injection Application Block, including:
    • Validation handler
    • Exception Handling handler
    • Logging handler
  • Flexible configuration options, including:
    • XAML-based configuration support
    • Asynchronous configuration loading
    • Interactive configuration console supporting profiles (desktop vs. Silverlight)
    • Translation tool for XAML config (needed to convert conventional XML configuration files):
      • Standalone command-line tool
      • Config console wizard
      • MS Build task
    • Programmatic configuration support via a fluent interface
  • StockTrader V2 Reference Implementation
Download

Download the "Enterprise Library 5.0 Silverlight Integration Pack.msi" and install it. Alternatively, download specific application blocks from NuGet.
To get the optional configuration tool, install it separately from the Visual Studio gallery or download and install the Microsoft.Practices.EnterpriseLibrary.ConfigConsole.vsix package.

Microsoft Enterprise Library 5.0

Microsoft Enterprise Library is a collection of reusable application blocks designed to assist software developers with common enterprise development challenges. This release includes: Caching Application Block, Cryptography Application Block, Data Access Application Block, Exception Handling Application Block, Logging Application Block, Policy Injection Application Block, Security Application Block, Validation Application Block, and Unity Application Block.
This major release of Enterprise Library contains many compelling new features and updates that will make developers more productive. These include:

  • Major architectural refactoring that provides improved testability and maintainability through full support of the dependency injection style of development
  • Dependency injection container independence (Unity ships with Enterprise Library, but you can replace it with a container of your choice)
  • Programmatic configuration support, including a fluent configuration interface and an XSD schema to enable IntelliSense
  • Redesign of the configuration tool to provide:
    • A more usable and intuitive look and feel
    • Extensibility improvements through meta-data driven configuration visualizations that replace the requirement to write design time code
    • A wizard framework that can help to simplify complex configuration tasks
  • Data accessors for more intuitive processing of data query results
  • Asynchronous data access support
  • Honoring validation attributes between Validation Application Block and DataAnnotations
  • Integration with Windows Presentation Foundation (WPF) validation mechanisms
  • Support for complex configuration scenarios, including additive merge from multiple configuration sources and hierarchical merge
  • Optimized cache scavenging
  • Better performance when logging
  • A reduction of the number of assemblies
  • Support for the .NET 4.0 Framework and integration with Microsoft Visual Studio 2010
  • Improvements to Unity

Download the MSI and install

Wednesday, October 12, 2011

Understanding SOAP and REST

Which is better SOAP or REST? One of the most common discussions. Both REST and SOAP are different approaches in writing the service oriented applications. REST is an architectural style for building client-server applications. SOAP is a protocol for exchanging data between two endpoints.

It is more appropriate if you compare REST with RPC(remote procedure call). RPC is a style of building client-server applications. Compared to RPC there won’t be generated proxy for client which is less coupled to the service.

REST relies on HTTP, requests for data[Get requests] can be cached. RPC systems not having such infrastructure even when using SOAP over HTTP.

Both REST and SOAP can used to implement similar functionality but SOAP should be used when a particular feature of SOAP is needed.

Security

Is SOAP is more secured than REST? answer is no. It is easy to make REST based service secure as it is to make SOAP service.The security in REST  is in the form of HTTP-based authentication and Secure Sockets Layer(SSL).  Because of WS-* specifications SOAP supports the end-to-end message security.

Transactions

This is another feature that SOAP and WS-*  supports where REST has none.

WS-Atomic transactions supports distributed, two-phase commit transactional semantics over SOAP-based services. REST has no support for distributed transactions. To create something like transactions in REST you create a  resource called Transaction. When client wants to do some transaction and then he creates a resource that specifies all the correct resources.

Interoperability

SOAP services are less interoperable than REST Services. In terms of platforms, For REST all you need is HTTP stack. REST has widest interoperability like mobile devices,household devices, POS devices etc. The problem in SOAP and WS-* is the large number of standards to choose from.

Metadata

There is no direct way in REST to generating client from server-side-generated metadata. In SOAP with WSDL we can generate the client proxies. In REST we can achieve the same using WADL (Web Application Description Language). WSDL makes easier in generating the proxy than writing some code fro generating for REST service.

Protocol Support

Though REST is currently tied with HTTP but you still can implement the REST features on other protocols until vendors add support for this.

IS REST is for Internet-facing apps and SOAP for enterprise apps?

Answer is no. This question comes due to lack of distributed transaction support in REST vs explicit WS-atomic transactions in SOAP.

ASP.NET doesn’t have support for distributed transactions, but does that mean ASP.NET isn’t useful for enterprises?

Enterprise applications need scalability and speed. SOAP services are much harder to scale than RESTful services. Most of the scaling features can not be used with SOAP because SOAP uses POST only over HTTP.

Conclusion

“Which is better, REST or SOAP?” is “It depends”. Both REST and SOAP has advantages and disadvantages when it comes to building the services. When you need the features that are easy to implement using REST or SOAP choose it..

Saturday, September 10, 2011

Convert DateTime values to W3C DateTime format in C#

ConvertDateToW3CTime() function takes a C# DateTime value and converts it to a W3C formatted date/time value.
The function works by first converting the date/time parameter to a UTC (Coordinated Universal Time) value and formatting it. It then appends the UTC offset time to the previously formatted string.

The T placed between the date and time simply indicates that the numbers following it are Time values. The UTC offset can be one 3 states, zero e.g. there is not difference in time between the UTC value and the local value. A zero value is identified by simply appending the letter Z to the end of the formatted datetime value. If the offset time is greater than 0 then it is preceded with a + sign, e.g. 2 hours and 30 minutes over the UTC time would be written as +02:30. If the offset is less than the UTC value then it is preceded with a sign e.g. -01:00.

/// <summary>
/// Converts a datetime value to w3c format
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string ConvertDateToW3CTime(DateTime date)
{
//Get the utc offset from the date value
var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(date);
string w3CTime = date.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss");
//append the offset e.g. z=0, add 1 hour is +01:00
w3CTime += utcOffset == TimeSpan.Zero ? "Z" :
String.Format("{0}{1:00}:{2:00}", (utcOffset > TimeSpan.Zero ? "+" : "-")
, utcOffset.Hours, utcOffset.Minutes);

return w3CTime;
}



Here is an example, how to use it


ConvertDateToW3CTime(DateTime.Now);
//Output 2011-10-17T19:10:48+01:00