Breaking change in asp.net mvc v2 (2.0.0.0) for MvcContrib.Castle's WindsorControllerFactory class

Posted by ercu

I could not find anything related to this anywhere, but if you know there is a simple but breaking change in asp.net mvc version 2.0.0.0's DefaultControllerFactory, so WindsorContainerFactory got broken.

Because it could not get the instance of controller from controller factory, I kept getting the following error everytime i loaded my fresh web project built with asp.net mvc v2.

 

No parameterless constructor defined for this object.

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: System.MissingMethodException: No parameterless constructor defined for this object.

 

While searching for a solution around the web, I found the following lines in the release notes of mvc version 2:

DefaultControllerFactory API changes will break custom controller factories that derive from it
This change affects custom controller factories that derive from DefaultControllerFactory . The DefaultControllerFactory class was fixed by removing the RequestContext property and instead passing the request context instance to the protected virtual methods GetControllerInstance and GetControllerType.


So I just fetched latest MvcContrib source, changed GetControllerInstance found in WindsorContainerFactory.cs to work with latest mvc library by taking RequestContext as parameter. I rewrote  the function as follows.

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if(controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or it does not implement IController.", requestContext.HttpContext.Request.Path));
            }

            return (IController)_container.Resolve(controllerType);
        }

[/code]



 

Then it worked as I expected. Hope this helps anyone.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Platform Builder 5.0 Download

Posted by ercu

I needed Platform Builder 5.0 last week. After days long googling sessions on Chinese blogs, I've found it in the Windows CE 5.0 Setup. It was a big suprise because nothing was written about PB 5.0's location by Microsoft anywhere on msdn. However I could not imagine I would find Windows Ce 5.0 setup too, as all the pages were updated for version 6.0.

 Here is the link for Platform Builder 5.0:

 http://www.microsoft.com/downloads/details.aspx?FamilyID=486E8250-D311-4F67-9FB3-23E8B8944F3E&displaylang=en

 

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Testing Request object in Asp.net MVC

Posted by ercu

Some time ago I needed to test my Controllers, but they were depending on Referrer Url so I had to mock it. While searching I found a similar solution in MVCContrib's TestHelper documentation. So I ended up suiting it to my needs. In the function below you just have to pass the Controller as parameter. 

Used NUnit and Rhinomocks

private string referrerstr="http://thisisreferrer/";   //Don't forget to put "/" at the end of the url while testing

 private void CreateMockHttpContext(Controller controller)
        {
            var httpContext = MockRepository.GenerateStub<HttpContextBase>();

            httpContext.Stub(x => x.Request).Return(MockRepository.GenerateStub<HttpRequestBase>());

            //stub or mock what you need here

           httpContext.Request.Stub(x => x.UrlReferrer).Return(new Uri(referrerstr));          

            var context = new ControllerContext(httpContext,
                              new RouteData(),
                              controller);


            controller.ControllerContext = context;
        }

 

Then in my Test Method I just control Referer if it's equal to refererstr:

 [Test]
        public void CanCreateInstitution() {
            Institution institutionFromForm = CreateTransientInstitution();
            RedirectResult redirectResult = controller.Create(institutionFromForm)
                .AssertRedirect().ToUrl(refererstr);
            Assert.That(controller.TempData["message"].ToString().Contains("was successfully created"));
        }

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

PGP File Encrypt & Decrypting in C#

Posted by ercu

Here is my post, introducing PGP Command Line Utility (free) and It's usage for cryptographic pgp operations in C#. You can find tremendous number of sources about string encryption with PGP in C# over the web, but file encryption is a bit different because it involves binary file types.
 

PGP Command Line utility is a small 950kb executable file, published for NT type operating systems that can easily be executed by code for this specific mission

Here are steps for less painful results.

 

1. First download the utility, then you should create your own key files or load from existing ones.

To Create your own keys run this command

pgp.exe -kg

 

To Add existing key file (This should of course be a public key file if it's not yours)

pgp.exe -ka [path to key file]

 

Note: Keys are kept seperate for each logged in user, so do this step with the same credentials as your application starts. If you don't, this may cause headaches for Windows Service type Apps.

Note 2: Don't add any of keys from other PGP programs, such as PGP Desktop,  directly if the keys have passphrases. First write down the passphrase of the key then remove it and add the key to PGP Command Line utility. At least, edit the key (See step 3) to set previous pass phrase you just wrote down.

 

2. Sign new public keys on your public key ring, if you don't, the utility will ask for your confirmation each time you run some command. And this would require you to handle additional drawbacks in code.

To sign public keys

pgp.exe -ks [User Name or Email of the key]

 

3. Don't bypass this, if you don't want to hit your head against to wall. Edit your own keys to make them Trusted. You can also set Pass Phrase by editing, which will make it more secure.

To edit your own keys

pgp.exe -ke [User Name or Email of the key]

Then it will ask you to make it ultimate trusted, you say yes!

  --------- UPDATE -----

People are frequently asking me about relation between this post and C# as the title implies. Actually I first wrote my implementation here, but it was a bit messy, I was frustrated so removed it. However, Until I write a well-designed wrapper, I'm adding it again for anyone who needs it.

First setting up some variables that will be passed to pgp.exe:

string PGPLocation = "C:\Some_Directory\pgp.exe"; 
string ToUserName = "ercu"; // username of public key for the other end. when you send an encrypted file, only this user can open it. When you send encrypted files to this user, files will be signed with his public key too.
string MyUserName = "eser"; //will be used for encrypting your files, and decrypting files sent to you.
string PassPhrase = "MyTopSecretPassphrase;

[/code]

  

Then you need to open a command line using C#:

proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "cmd";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;

[/code]

 

Then use pgp.exe's Encrypt/Decrypt command functions as follows:

[code:c#] 

public string Encrypt(string filename, bool isBinary, ref string outstr){

            string outputfilename = filename;
          

            //We use stringbuilder for performance considerations
            StringBuilder sb = new StringBuilder();
            sb.Append("/c ");
            sb.Append("");
            sb.Append(PGPLocation);
            sb.Append(" +force -es ");
            sb.Append("\"");
            sb.Append(filename);
            sb.Append("\" ");
            sb.Append(ToUserName);
            sb.Append(" -u ");
            sb.Append(MyUserName);
           
            sb.Append(" -z ");
            sb.Append(PassPhrase);
            sb.Append(" ");
           
            // Use binary indicator because PGP produces different outputs for binary and plain text files
            if (isBinary)
                sb.Append("-a");
     
            proc.StartInfo.Arguments = sb.ToString();
        

                
          
            proc.Start();
            if (WaitForInfinity)
                proc.WaitForExit();
            else
                proc.WaitForExit(WaitTime);
            //string res = proc.StandardOutput.ReadToEnd();

            outstr = proc.StartInfo.Arguments;
            if (proc.HasExited)
            {
                int ab = proc.ExitCode;
                if (ab != 0)
                {
                    FireError(ab.ToString() +" : "+proc.StandardOutput.ReadToEnd());
                    return null;
                }
                else
                    if (!isBinary)
                        return outputfilename+".pgp";
                return outputfilename + ".asc";
            }
           
            return null;
        }
        public string Decrypt(string filename)
        {
            bool isBinary = filename.EndsWith(".asc");
            string outputfilename = filename;

            StringBuilder sb = new StringBuilder();
            sb.Append("/c ");
            sb.Append("");
            sb.Append(PGPLocation);
            sb.Append(" +force \"");
            sb.Append(filename);
            sb.Append("\" ");
            sb.Append(" -z ");
            sb.Append(PassPhrase);

            proc.StartInfo.Arguments = sb.ToString();
            proc.Start();

            if (WaitForInfinity)
                proc.WaitForExit();
            else
                proc.WaitForExit(WaitTime);

            if (proc.HasExited)
            {
                int ab = proc.ExitCode;
                if (ab != 0)
                {
                    FireError(ab.ToString() +" : "+proc.StandardOutput.ReadToEnd());
                    return null;
                }
                else
                    return outputfilename;
            }

            return null;

        }

[/code]

 

PGP.rar (373,24 kb)

Currently rated 4.7 by 3 people

  • Currently 4.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5