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


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.

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
              case 3: //bottoms up
                   image.RotateFlip(rotateFlipType: RotateFlipType.Rotate180FlipNone);
              case 6: //rotated 90 left
                   image.RotateFlip(rotateFlipType: RotateFlipType.Rotate90FlipNone);
              case 8: //rotated 90 right
                   image.RotateFlip(rotateFlipType: RotateFlipType.Rotate270FlipNone);


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

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">


//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 (, 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.



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


    pVer->dwFilterVersion = HTTP_FILTER_REVISION;

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

    return TRUE;

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

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

      CHAR *szHeader = "Set-Cookie:";
      CHAR *szHttpOnly = "; HttpOnly";
      if (pResponse->GetHeader(pfc,szHeader,szCookie,&cbCookie)) {
         /*if (SUCCEEDED(StringCchCat(szCookie,
                                    szHttpOnly))) {
            if (!pResponse->SetHeader(pfc,
                                      szCookie)) {
                        // Fail securely - send no cookie!
            } else {
	 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");
			strcat (outCookie, "; HttpOnly");

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




For information on how to create a ISAPI filter using Visual C++, you can refer to

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"/>

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

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


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 = "";
string relyingPartyUri = "";

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);