A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Archive for March, 2008

Service XXX.ABCService is not available in the current context.+WCSF

Posted by kiranpatils on March 31, 2008

Problem:

if you have changed your solution structure to one level down means first your page opens up like this: /Employee/Employee.aspx and now you
moved Employee Folder to EMI folder. So now page URL should look like this when it s open: EMI//Employee/Employee.aspx

and it is dependent on its Module named as Employee and now when you run the application the page says:

Service XXX.ABCService is not available in the current context.

Stack Trace:
Service XXX.ABCService is not available in the current context.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Microsoft.Practices.CompositeWeb.ServiceMissingException: Service IEmployeeService is not available in the current context.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ServiceMissingException: Service IEmployeeService is not available in the current context.]
Microsoft.Practices.CompositeWeb.Collections.ServiceCollection.Get(Type serviceType, Boolean ensureExists) +291
Microsoft.Practices.CompositeWeb.Collections.ServiceCollection.Get(Type serviceType, Boolean ensureExists) +237
Microsoft.Practices.CompositeWeb.ServiceDependencyParameter.GetValue(IBuilderContext context) +142
Microsoft.Practices.ObjectBuilder.ConstructorPolicy.GetParameters(IBuilderContext context, Type type, String id, ConstructorInfo constructor) +102
Microsoft.Practices.ObjectBuilder.WCSFExtensions.CreationStrategy.InitializeObject(IBuilderContext context, Object existing, String id, ICreationPolicy policy) +117
Microsoft.Practices.ObjectBuilder.WCSFExtensions.CreationStrategy.BuildUpNewObject(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +208
Microsoft.Practices.ObjectBuilder.WCSFExtensions.CreationStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +51
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.SingletonStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +171
Microsoft.Practices.ObjectBuilder.TypeMappingStrategy.BuildUp(IBuilderContext context, Type t, Object existing, String id) +322
Microsoft.Practices.ObjectBuilder.CreationParameter.GetValue(IBuilderContext context) +31
Microsoft.Practices.ObjectBuilder.ConstructorPolicy.GetParameters(IBuilderContext context, Type type, String id, ConstructorInfo constructor) +102
Microsoft.Practices.ObjectBuilder.WCSFExtensions.CreationStrategy.InitializeObject(IBuilderContext context, Object existing, String id, ICreationPolicy policy) +117
Microsoft.Practices.ObjectBuilder.WCSFExtensions.CreationStrategy.BuildUpNewObject(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +208
Microsoft.Practices.ObjectBuilder.WCSFExtensions.CreationStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +51
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.SingletonStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +171
Microsoft.Practices.ObjectBuilder.TypeMappingStrategy.BuildUp(IBuilderContext context, Type t, Object existing, String id) +322
Microsoft.Practices.ObjectBuilder.CreationParameter.GetValue(IBuilderContext context) +31
Microsoft.Practices.ObjectBuilder.PropertySetterInfo.GetValue(IBuilderContext context, Type type, String id, PropertyInfo propInfo) +10
Microsoft.Practices.ObjectBuilder.PropertySetterStrategy.InjectProperties(IBuilderContext context, Object obj, String id) +259
Microsoft.Practices.ObjectBuilder.PropertySetterStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +29
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.CreationStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +68
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.BuilderStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +38
Microsoft.Practices.ObjectBuilder.WCSFExtensions.ReflectionStrategy`1.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +322
Microsoft.Practices.ObjectBuilder.SingletonStrategy.BuildUp(IBuilderContext context, Type typeToBuild, Object existing, String idToBuild) +171
Microsoft.Practices.ObjectBuilder.TypeMappingStrategy.BuildUp(IBuilderContext context, Type t, Object existing, String id) +322
Microsoft.Practices.ObjectBuilder.WCSFExtensions.WCSFBuilderBase`1.BuildUp(IReadWriteLocator locator, Type typeToBuild, String idToBuild, Object existing, PolicyList[] transientPolicies) +151
Microsoft.Practices.CompositeWeb.CompositionContainer.BuildItem(IBuilder`1 builder, IReadWriteLocator locator, Object item) +256
Microsoft.Practices.CompositeWeb.WebClientApplication.InnerPreRequestHandlerExecute(IHttpContext context) +92
Microsoft.Practices.CompositeWeb.WebClientApplication.Application_PreRequestHandlerExecute(Object sender, EventArgs e) +79
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64

Solution:
In web. config under that folder means /DevelopmentWebsite/EMI/Employee/Web.config
and locate modules section under it
you will have like this:
<module name=”Employee” assemblyName=”Employee” virtualPath=”~/Employee”> //old configuration

change it to like this
<module name=”Employee” assemblyName=”Employee” virtualPath=”~/EMI/Employee”> //new configuration


That’s it!!
Why it happened?


for it you should understand Web.config file.
Web.config file. This is an ASP.NET configuration file that contains the module definition. The module definition is a <module> entry inside the <modules> configuration section of the Composite Web Application Block. A module definition has the following elements:
name attribute. This is the name of the module. for example Employee
assemblyName attribute. This is the name of the module assembly.for example Employee
virtualPath attribute. This is the relative path where the Web pages of the module are located within the Web site. Business modules must always declare the attribute. Foundational modules must not declare the attribute. for example ~/EMI/Employee
<dependencies> element. This defines inter-module dependencies. A module can express dependencies on other modules by adding <dependency> entries inside the <dependencies> element. All modules listed as dependencies will be loaded before the current module is loaded.

This may be occur for others too..main problem is modules section and in web.config.

UPDATED 23-APR-2008

I had faced the same error before few days.. and found one more cause for this error.

If you have not register your service under XYZModuleInitializer.cs file’s method

protected virtual void AddModuleServices(IServiceCollection moduleServices)

{

//REGISTER YOUR SERVICE HERE.

}

Then it will also give you same error..so register your service first and kill that error.

Posted in Web Client Software Factory | Tagged: | 1 Comment »

Use Predicate for complex Conditional Block[if..else]

Posted by kiranpatils on March 29, 2008

yesterday i had completed coding of my block which has too may if..else blocks….which goes too approx. 20-30 lines… it does simple logic as under:

1. Gets Value from Querystring

2.and based on value redirect my page to appropriate page..

for doing the above thing i had written following code[looks like garbage]..

———————————————————————————————————

private void CacheAndTransfertoNext(){

string EntryPoint = Request.QueryString["EntryPoint"];

if (!String.IsNullOrEmpty(EntryPoint)){

if (_emppresnter.SaveEmployee()){

//Redirect on Next Page Based on EntryPoint Value

if (EntryPoint == “1″){

Response.Redirect(“Page1.asp”);}

else if (EntryPoint == “2″){

Response.Redirect(“page2.asp”);}

else if (EntryPoint == “3″){

Response.Redirect(“page3.asp”);}

else if (EntryPoint == “4″){

Response.Redirect(“page4.asp”);}

else if (EntryPoint == “5″){

Response.Redirect(“page5.asp”);}

else if (EntryPoint == “6″){

Response.Redirect(“page6.asp”);}

else if (EntryPoint == “7″){

Response.Redirect(“page7.asp”);}

}

else

{

Response.Redirect(“Default.aspx”);}

———————————————————————————————————

 i thought that can’t i make it smaller..i got it using predicate..i had accompilished the task in four lines…:)

Here it is:

1. I need to create some classes[which are self explanatory].

URLList.cs

using System;

using System.Collections.Generic;

using System.Text;

using System.Configuration;

public class URLList{

private List<MyUrls> _bookerurl = new List<MyUrls>();public List<MyUrls> BookerUrlList{

get { return _bookerurl; }

set { _bookerurl = value; }}

public URLList(){

_bookerurl.Add(new BookerURL(“1″,“page1.asp”));_bookerurl.Add(new BookerURL(“2″,“page2.asp”));__bookerurl.Add(

new BookerURL(“3″,“page3.asp”));__bookerurl.Add(new BookerURL(“4″,“page4.asp”));__bookerurl.Add(

new BookerURL(“5″,“page5.asp”));__bookerurl.Add(new BookerURL(“6″,“page6.asp”));}

}

using System;

using System.Collections.Generic;

using System.Text;

public class MyUrls

{

public MyUrls(){

}

public MyUrls(string key, string value){

_key = key;

_value = value;

}

private string _key;public string Key{

get { return _key; }

set { _key = value; }}

private string _value;public string Value{

get { return _value; }

set { _value = value; }}

}

——————- Now Lets see my Function now..

private void CacheAndTransfertoNext()

{

string EntryPoint = Request.QueryString["EntryPoint"];if (!String.IsNullOrEmpty(EntryPoint)){

if (_emppresnter.SaveEmployee()){

 URLList urlist = new URLList();
 MyUrls _nexturl = urlist.BookerUrlList.Find(delegate(MyUrls url) { return url.Key == EntryPoint; });                                        
string nextpageurl = (_nexturl != null) ? _nexturl.Value :  ”Default.aspx”;

Response.Redirect(nextpageurl);

}

}

Posted in .NET | Tagged: | Leave a Comment »

ExpectationViolationException+Rhino Mocks

Posted by kiranpatils on March 24, 2008

Why ExpectationViolationException?

Error:

HelloRhino.MyRhinoImplementationTest.HelloRhinoMock_Test : Rhino.Mocks.Exceptions.ExpectationViolationException : IMyRhinoImplementation.HelloRhinoMocks(“ABC”); Expected #1, Actual #0.

Rhino Mock supports following three types of Mock Objects:
    * Mock Objects – Strict replay semantics. – Created by calling CreateMock(): WE ARE GOING TO USE THIS ONE
    * Dynamic Mock – Loose replay semantics. – Created by calling DynamicMock()
    * Partial Mock – Mock only requested methods. – Created by calling PartialMock()

Strict replay semantics: only the methods that were explicitly recorded are accepted as valid. This mean that any call that is not expected would cause an exception and fail the test. All the expected methods must be called if the object is to pass verification.

Loose replay semantics: any method call during the replay state is accepted and if there is no special handling setup for this method a null or zero is returned. All the expected methods must be called if the object is to pass verification.

Mocking only requested methods: this is available for classes only. It basically means that any non abstract method call will use the original method (no mocking) instead of relying on Rhino Mocks’ expectations. You can selectively decide which methods should be mocked.

Mock object code
[TestFixture]
    public class MyRhinoImplementationTest
    {
        MyRhinoImplementation myimple;
        IMyRhinoImplementation mockMyRhinoImplementation;
        MockRepository mockrepository;
        [SetUp]
        public void DoSetup()
        {
            //Mock
            myimple = new MyRhinoImplementation();
            mockrepository = new MockRepository();
            mockMyRhinoImplementation = mockrepository.CreateMock<IMyRhinoImplementation>();
            RhinoMocks.Logger = new TextWriterExpectationLogger(Console.Out);
           
        }
        [TearDown]
        public void DoCleanup()
        {
            myimple = null;
            mockrepository = null;
            mockMyRhinoImplementation = null;           
        }

        [Test]
        public void HelloRhinoMock_Test()
        {
            //Record our Expectations
            using (mockrepository.Record())
            {
                                Expect.Call(mockMyRhinoImplementation.HelloRhinoMocks(“ABC”)).Return(“Hi!! from Rhino Mocks to:ABC”);
            }           
            // Tell Rhino Mocks We’re Done Setting Expectations
            mockrepository.ReplayAll(); // it replay all mocks from reopository

            //We played a Expectation now lets check that our Recorded song is playing as per
            //our expectation or not? 
  //THIS LINE WILL THROW AN EXCEPTION BECAUSE WE Must needs to call Method which we have expcted to call for this
  //Example:mockMyRhinoImplementation.HelloRhinoMocks(“ABC”)          
  mockrepository.VerifyAll(); //Verifies all the mocks from the repository

            //Aboves VerifyAll block throws an Error
            //HelloRhino.MyRhinoImplementationTest.HelloRhinoMock_Test : Rhino.Mocks.Exceptions.ExpectationViolationException :
            //IMyRhinoImplementation.HelloRhinoMocks(“ABC”); Expected #1, Actual #0.
           
            //This exception is thrown when there is a an expectation violation.
        }
    }

Mock objects are useful when you want complete control over what happens to the mocked object.

Solution:
in HelloRhinoMock_Test() Method do the changes:
    //-*****
            mockMyRhinoImplementation.HelloRhinoMocks(“ABC”); //Line added–For solving ExepcationviolationException
            //-*****
            mockrepository.VerifyAll(); //Verifies all the mocks from the repository

Conclusion:
So for using Rhino Mocks just follow the steps as under with Mock Object:
1.Create mock by: mockrepository.CreateMock<IMyRhinoImplementation>();
2.Record your expactations: in Record Block.
3.call ReplayAll to tell rhino Mocks that you are done with recording
4.MOST IMP. STEP:Call expected method here for example: mockMyRhinoImplementation.HelloRhinoMocks(“ABC”)
 NOTE: Must need to pass the same arguments what you have recorded else it will again throw ExpectationViolationException.
5.Call VerifyAll();          

Reference:
http://www.ayende.com/Wiki/(S(wp4edvbnsrsr2reccscyaq2w))/Default.aspx?Page=Rhino+Mocks+Introduction

Posted in Unit testing | Tagged: | Leave a Comment »

DateTime formatting with C#.NET

Posted by kiranpatils on March 19, 2008

Whenever you want to format any DateTime in C#.NET and want to return it with specific type then you should use overloaded function of ToString(“<Pattern to get>”).

Some of it is here:

http://www.codeproject.com/KB/cs/DateTime_Patterns.aspx

Enjoy!!

Posted in Uncategorized | Tagged: | Leave a Comment »

Changing bgcolor of Page/Master Page dynamically+ASP.NET

Posted by kiranpatils on March 19, 2008

Hi, one of my colleague was struggling that how to set  value of Page’s background color in ASP.NET Code??

Problem:

Actually we want to set a page’s background color on Page_Load. and value changes everytime..how can i achieve it?

Solution: 

Nothing magic in it just two lines will do the same:

HtmlGenericControl bodytag = (HtmlGenericControl)Page.Master.FindControl(“body”);
bodytag.Style.Add(“background-color”,”#000999″);

for it my Master Page has body tag declared like this:

 <body ID=”body” runat=”server”/>

That’s it..

Posted in ASP.NET | Tagged: , | Leave a Comment »

Generating guid(Globally Unique Identifier) with .NET

Posted by kiranpatils on March 19, 2008

I was playing with guid..initially i was getting same guid it was generating same Guid(000-000….)for all time…i was wondering about its strange behaviour..the code what i had written for it is as under:

//Not working

 public static Guid GetGuid()
{
return new Guid()

  }

at last i  found it’s solution:

 public static Guid GetGuid()
{
return Guid.NewGuid();
}

it will give new Guid everytime you call this function..Looks good na??Magic of NewGuid()!!!!

312a12b4-9853-45d2-8ccf-6d59ec940b41

NOTE: you can copy[if you can do try cut ] paste to you class call it.It will give you proper value means GUID

Happy guid!!!

Posted in .NET | Tagged: , | 1 Comment »

IF…else with Eval is not supported+GridView+ASP.NET

Posted by kiranpatils on March 19, 2008

Yesterday i was struggling with GridView I need to check some if..else logic and based on it have to show values in Grid..I am checking it in Eval if else but can’t get succeeded because if..else is not supprted with Eval..then how i have achieved it..its concept of “Binding Grid with functions”. Let us see..

Problem:

On binding of Grid i want to check that if entityCount>1 then have to show that value in grid with HyperLink which points to some page else show Plain Text in grid..

I was trying this one[Which won't work]

<asp:TemplateField HeaderText=”Def Price”>
<ItemTemplate>
<%# if Eval(“entityPriceCountField”) > 1%>
<asp:HyperLink ID=”lnkentityPrice” Text=’<%# Eval(“entityPriceField”) %>’ runat=”Server”   Target=”_blank” NavigateUrl=”#”/>
<%# else  %>
<asp:Label ID=”lblentityPrice” Text=’<%# Eval(“entityPriceField”) %>’ CssClass=”SearchBookingsLabelStyle” runat=”Server” />
  
                               

</ItemTemplate>
</asp:TemplateField>

NOTE: You can’t write like this.

Solution:

I had its solution:

1. Binded my grid with function in my .aspx.cs file.

this function check count if count>1 then text will be in hyper link else show plain text.

2.  Called it witin my Grid.

Here it is:

.aspx page 

<asp:TemplateField HeaderText=”Def Price”>
<ItemTemplate>
<asp:Label ID=”entityPrice” Text=’<%# GetEntityPriceText((double)Eval(“entityPriceField”),(int)Eval(“entityPriceCountField”))%>’ CssClass=”SearchBookingsLabelStyle” runat=”Server” />
</ItemTemplate>
</asp:TemplateField>

 .aspx.cs code

 protected string GetEntityPriceText(Nullable<double> entityprice,Nullable<int> entityPriceCount)
{
//If count>1 then show text in HyperLink
string labelText = string.Empty;
if (entityPriceCount > 1)
labelText = “<a href=MyPage.aspx’>” + entityprice.ToString() + “</a>”;
else
labelText = entityprice.ToString();
r
eturn labelText;
}

It worked like a chram!!!

Posted in ASP.NET | Tagged: , , , | 2 Comments »

CS1502+Eval+GridView+invalid arguments

Posted by kiranpatils on March 19, 2008

Yesterday was binding my grid with function.. But it is showing me some errors which is as under

Server Error in ‘/DevelopmentWebsite’ Application.
——————————————————————————–

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1502: The best overloaded method match for ‘SellBooking_EventSearch.GetEntityPriceText(double?, int?)’ has some invalid arguments

Source Error:

Line 133:
Line 134:
Line 135:                                       <asp:Label ID=”entityPrice” Text=’<%# GetEntityPriceText(Eval(“entityPriceField”),Eval(“entityPriceCountField”))%>’ CssClass=”SearchBookingsLabelStyle” runat=”Server” />          

ASP.NET FUNCTION:

protected string GetEntityPriceText(Nullable<double> entityprice,Nullable<int> entityPriceCount)
{
//If count>1 then show text in HyperLink
string labelText = string.Empty;
if (entityPriceCount > 1)
//To-DO Change it to appropriate ASP Page
labelText = “<a href=’Booker.aspx’>” + entityprice.ToString() + “</a>”;
else
labelText = entityprice.ToString();
return labelText;
}

Solution and Cause of Error:

Cause of Error: Eval function returns object and my function expects double/int so it throws invalid arguments.

So just need to cast my Evals to appropriate type for my example double/int..so now it looks like this:

<asp:Label ID=”entityPrice” Text=’<%# GetEntityPriceText((double)Eval(“entityPriceField”),(int)Eval(“entityPriceCountField”))%>’ CssClass=”SearchBookingsLabelStyle” runat=”Server” />      

It ran like a charm.

Hope it will help…

Posted in ASP.NET | Tagged: , , | Leave a Comment »

How to set a icon for web application?+ASP.NET

Posted by kiranpatils on March 13, 2008

icon.jpg

Have you ever thought that how can i set icon for my Web application developed in ASP.NET. so it can show a custom icon in IE7,Mozilla[as shown above for Google]

Solution:

On any page for which you want to show a custom icon follow the stpes:

1. [One time] put any icon on root of your application folder/at any images folder.

2.add the following tag under <head> tag [i had added on default.aspx]

<link REL=”icon” href=”myicon.ico”/>  //give path of a icon

That’s it

Posted in Uncategorized | Leave a Comment »

Encryption/Decryption Helper Class using RijndaelManaged

Posted by kiranpatils on March 13, 2008

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace RfcDemoPwdGenerator
{
class Helper
{
private static string password = “ABCDE”; //give strong password
private static int iterations = 1024;
private static byte[] salt = Encoding.ASCII.GetBytes(“This is My Salt value”);
/// <summary>
/// this function will take a plaintext as an arg and
/// returns ciphertext as an O/P
/// </summary>
/// <param name=”plaintext”></param>
/// <returns></returns>
public static string Encrypt(string plaintext)
{
Rfc2898DeriveBytes KeyBytes = new Rfc2898DeriveBytes(password, salt, iterations);
//The deafault iteration count is 1000
RijndaelManaged alg = new RijndaelManaged();
alg.Key = KeyBytes.GetBytes(32);
alg.IV = KeyBytes.GetBytes(16);
MemoryStream encryptStream = new MemoryStream();
//Stream to write
CryptoStream encrypt = new CryptoStream(encryptStream, alg.CreateEncryptor(), CryptoStreamMode.Write);
//convert plain text to byte array
byte[] data = Encoding.UTF8.GetBytes(plaintext);
encrypt.Write(data, 0, data.Length); //data to encrypt,start,stop
encrypt.FlushFinalBlock();//Clear buffer
encrypt.Close();
return Convert.ToBase64String(encryptStream.ToArray());//return encrypted data
}

/// <summary>
/// this function will take a ciphertext as an arg and
/// returns plaintext as an O/P
/// </summary>
/// <param name=”plaintext”></param>
/// <returns></returns>
public static string Decrypt(string ciphertext)
{
Rfc2898DeriveBytes KeyBytes = new Rfc2898DeriveBytes(password, salt, iterations);
//The deafault iteration count is 1000
RijndaelManaged alg = new RijndaelManaged();
alg.Key = KeyBytes.GetBytes(32);
alg.IV = KeyBytes.GetBytes(16);
MemoryStream decryptStream = new MemoryStream();
//Stream to read
CryptoStream decrypt = new CryptoStream(decryptStream, alg.CreateDecryptor(), CryptoStreamMode.Write);
//convert  ciphertext to byte array
byte[] data = Convert.FromBase64String(ciphertext); //IF using for WEB APPLICATION and getting ciphertext via Querystring change code to : Convert.FromBase64String(ciphertext.Replace(” “,”+”));

decrypt.Write(data, 0, data.Length); //data to encrypt,start,stop
decrypt.Flush();
decrypt.Close();
return Encoding.UTF8.GetString(decryptStream.ToArray());//return PlainText
}
}
}

Use it and Enjoy!!!!

Posted in Uncategorized | Leave a Comment »