Archive for the ‘.Net/C#’ Category

I am trying the IdentitySamples in my own helloworld MVC project. I have added the controller, model and view codes, but when I tried to edit the user, it gives me the exception in the below line

return View(new EditUserViewModel()
        {
            Id = user.Id,
            Email = user.Email,
            RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
            {
                Selected = userRoles.Contains(x.Name),
                Text = x.Name,
                Value = x.Name
            })
        });

When debugging, i found that RoleManager is null. To resolve it, I need add the below line in Startup.Auth.cs

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

I have this iOS app that uploading camera image to server and server will create a thumbnail from the uploaded image. The original image is in portrait, but the thumbnail generated is rotated as landscape.

After some search i found that it’s because of the EXIF orientation flag in digital camera images. For details on EXIF orientation, can be found here. http://www.impulseadventure.com/photo/exif-orientation.html

Below is the sample code to rotate the image in C#.

public static void rotateImageIfNecessary(Image image)
{
    if (image.PropertyIdList.Contains<int>(0x0112))
    {
         int rotationValue = image.GetPropertyItem(0x0112).Value[0];
         switch (rotationValue)
         {
              case 1: //landscape
                   break;
              case 3: //bottoms up
                   image.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone);
                   break;
              case 6: //rotated 90 left
                   image.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone);
                   break;
              case 8: //rotated 90 right
                   image.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone);
                   break;
          }
      }
}

Credit: http://stackoverflow.com/questions/17186568/upload-from-ios-picture-to-net-app-rotate

I received this error when opening a docx created by OpenXml 2.5 SDK.

The error is because that I created a few empty table cell. Paragraph must be created for each table cell in OpenXml.

To fix this is very easy, just create the empty table cell with an empty Paragraph.

TableCell cell = new TableCell(new Paragraph());

PS: Since docx is just a zip container, you can just extract it using any zip program. You will be able to see the document.xml in the word directory. You can compare the malformed xml with a correct one.

we are required to enable HttpOnly in all our servers because it presents a potential XSS vulnerability. For more information on httpOnly, please read https://www.owasp.org/index.php/HttpOnly.

It’s very easy to enable it globally in .Net and Apache/PHP.

.Net 2.0+

//add the following line to the web.config system.web section
<httpCookies httpOnlyCookies="true">

Apache

//add the following line to the http.conf. Make sure mod_headers is enabled
Header edit Set-Cookie ^(.*)$ $1;HttpOnly

 

The sad story is that, one of our legacy server is running classic ASP…

I googled a few days and cannot find a working solution. Microsoft has one example on how to set cookie to httponly through ISAPI Filter (http://msdn.microsoft.com/en-us/library/ms972826), but only works for one cookie situation, which means no cookie because there is already one by default: ASPSESSIONIDxxxx.

After reading some documentation, I modified the Microsoft example to make it work for multiple cookies.

First, you need create a new Win32 Dynamic-Link Library project in Visual C++ 6.0 and create two files: httponly.cpp and httponlydef. Below are the source code for both files.

httponly.cpp

#define STRSAFE_NO_DEPRECATE

#include <windows.h>
#include <httpfilt.h>
#include "tchar.h"
#include "strsafe.h"


BOOL WINAPI GetFilterVersion(HTTP_FILTER_VERSION *pVer)
{
    pVer->dwFlags =  SF_NOTIFY_PREPROC_HEADERS  | SF_NOTIFY_SEND_RESPONSE;

    pVer->dwFilterVersion = HTTP_FILTER_REVISION;

    strcpy(pVer->lpszFilterDesc, "HttpOnly Filter, Version 1.0"); 

    return TRUE;
}


// Portion of HttpOnly
DWORD WINAPI HttpFilterProc(
   PHTTP_FILTER_CONTEXT pfc,
   DWORD dwNotificationType,
   LPVOID pvNotification) {

   // Hard coded cookie length (2k bytes)
   CHAR szCookie[2048];
   DWORD cbCookieOriginal = sizeof(szCookie) / sizeof(szCookie[0]);
   DWORD cbCookie = cbCookieOriginal;
	
      HTTP_FILTER_SEND_RESPONSE *pResponse = 
         (HTTP_FILTER_SEND_RESPONSE*)pvNotification;

      CHAR *szHeader = "Set-Cookie:";
      CHAR *szHttpOnly = "; HttpOnly";
      if (pResponse->GetHeader(pfc,szHeader,szCookie,&cbCookie)) {
         /*if (SUCCEEDED(StringCchCat(szCookie,
                                    cbCookieOriginal,
                                    szHttpOnly))) {
            if (!pResponse->SetHeader(pfc,
                                      szHeader,
                                      szCookie)) {
                        // Fail securely - send no cookie!
                        pResponse->SetHeader(pfc,szHeader,"");
               }
            } else {
               pResponse->SetHeader(pfc,szHeader,"");
	 }*/
	 pResponse->SetHeader(pfc,szHeader,"");
	 CHAR outCookie[2048];
	 char * token;
	 // the last occurence of semicolon
	 char * semi; 
	 token = strtok (szCookie,",");
	 while (token != NULL)
	 {
		strcpy(outCookie, "");
		strcat (outCookie, token);

		semi = strrchr(token, ';');
		//if the last character is ;
		if(semi - token == strlen(token) - 1){
			strcat (outCookie, " HttpOnly");
		}
		else{
			strcat (outCookie, "; HttpOnly");
		}

		pResponse->AddHeader(pfc, szHeader, outCookie);
			
		memset(outCookie, 0, 2048);
		token = strtok (NULL, ",");
	 }
   }

   return SF_STATUS_REQ_NEXT_NOTIFICATION;
}

httponly.def

LIBRARY HttpOnly
EXPORTS
    GetFilterVersion
    HttpFilterProc

For information on how to create a ISAPI filter using Visual C++, you can refer to http://blogs.msdn.com/b/david.wang/archive/2005/12/19/howto-compile-and-use-my-isapi-code-samples.aspx.

When connecting to a https SOAP web service, you may receive the error

The provided URI scheme ‘https’ is invalid; expected ‘http’

To fix it, inside the app.config <binding> section, you need add

<binding ............>
	<readerQuotas .../>
	<security mode="Transport">
		<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
		<message clientCredentialType="UserName" algorithmSuite="Default"/>
	</security>
</binding>

The basic design is that system will have a database table to store all the dirty words and when IIS starts, it will load the list to an application variable.

The filter will keep the first and last letter of the dirty word. For example, the f word will become f****k. I didn’t preserve the text length.

/*
retrieve all dirty words, if not in application variable, populate it.
*/
public static List<string> retrieveDirtyWords()
{
     if (HttpContext.Current.Application["Dirty_Words"] == null)
     {
         HttpContext.Current.Application["Dirty_Words"] = your_function_to_retrieve_dirty_words();
     }

     return HttpContext.Current.Application["Dirty_Words"] as List<string>;
}

/*
replace those dirty words
*/
public static string cleanText(string text)
{
     string pattern = string.Format(@"\b(?<dirty>{0})\b", string.Join<string>("|", retrieveDirtyWords()));

     return System.Text.RegularExpressions.Regex.Replace(text, pattern, new System.Text.RegularExpressions.MatchEvaluator(WordScrambler), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
}

/*
keep the first and last character for each matched dirty words.
*/
public static string WordScrambler(System.Text.RegularExpressions.Match match)
{
      System.Text.RegularExpressions.Group g = match.Groups["dirty"];
      if (g != null)
      {
          return g.Value.Substring(0, 1) + "****" + g.Value.Substring(g.Value.Length - 1);
      }

      return string.Empty;
}

For regular expression named capturing group syntax, you can refer to http://www.regular-expressions.info/named.html

Background: one partner requests to login our portal using their ADFS username and password without maintaining two sets of passwords.

Credit: http://leandrob.com/2012/04/requesting-a-token-from-adfs-2-0-using-ws-trust-with-username-and-password/

Preparation: The remote ADFS server need add your site to the trusted relying party list.


using Microsoft.IdentityModel.Protocols.WSTrust;
using Microsoft.IdentityModel.Protocols.WSTrust.Bindings;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.IdentityModel.Tokens;

//you may need add a few references for the above

string stsEndpoint = "https://WIN-2013.win2008.marz.com/adfs/services/trust/13/usernamemixed";
string relyingPartyUri = "https://www.yourrelyingpartyuri.com";

WSTrustChannelFactory factory = new WSTrustChannelFactory(
new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
new EndpointAddress(stsEndpoint));

factory.TrustVersion = TrustVersion.WSTrust13;

// Username and Password here...
factory.Credentials.UserName.UserName = "remote_user01";
factory.Credentials.UserName.Password = "the_password";

RequestSecurityToken rst = new RequestSecurityToken
{
     RequestType = Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13Constants.RequestTypes.Issue,
     AppliesTo = new EndpointAddress(relyingPartyUri),
     KeyType = Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13Constants.KeyTypes.Bearer,
};

IWSTrustChannelContract channel = factory.CreateChannel();

SecurityToken token = channel.Issue(rst);

//if authentication is failed, exception will be thrown. Error is inside the innerexception.
//Console.WriteLine("Token Id: " + token.Id);

I was requesting for a security token from a remote ADFS server. The program has been working on other clients, except this one server returning the error ‘An error occurred when verifying security for the message’

To keep it short, the date time was set wrongly in this server.

Dotfuscator: Exclude property

Posted: May 23, 2013 in .Net/C#
Tags:

Dotfuscator will rename all the class, property or field, method by default. This will cause problem in some cases. For example, when using Combobox, you can set DisplayMember to a class property.

comboBox.DisplayMember = “Name”;

Because Dotfuscator renames all the property, the Combobox won’t be able to display the list correctly.

To resolve this, just add a custom rule to exclude the Name property

  1. Click Add Type
  2. Uncheck the Regular Expression and check Exclude Type checkbox, set the name to the class which the Name property belongs to
  3. Right click the rule you newly created and click Add Field
  4. Uncheck the Regular Expression checkbox, set the Name to the property name

* Check or uncheck the regular expression based on your rule pattern. In my case, I only apply the rule to an exact class property.

dotfuscator

.Net assembly can be easily deassembled using some free tools, such as ildasm.

Dotfuscator is a free tool included in Visual Studio and it provides a way to make your code more difficult to be read.

Below is my obfuscated assembly loaded from ildasm. You can see all the class name are renamed to some non-sense name. dot

To use Dotfuscator is quite straightforward.

  1. Select the input assemblies
  2. Exclude those resources, namespace and types that don’t need to be renamed. This is very important especially when you are using third party dlls.
  3. Set the destination directory
  4. Build

When i used Dotfuscator for the first time, i kept receiving this error: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure “XXXXX.Properties.Resources.resources” was correctly embedded or linked into assembly “XXXXX” at compile time, or that all the satellite assemblies required are loadable and fully signed.

To fix this error, just make sure you have checked the Resources to be excluded in the step 2.

exclude