Thursday, November 3, 2011

Calling RESTful service under IOS5 failed with 401 error

Recently, we upgrade our iPad to IOS5, and xCode to 4.2 version,  after we done that I came across an issue. 

In our iPad application, we are calling the RESTful service on our server side, and we are using SSL and basic authentication, for most of the service call, it works fine, only two of the web services, the calls made from iPad application failed with 401 authentication error. 

The strange thing is , under IOS4.3.5 it works fine, only IOS 5 failed. 

after some investigation, I find out the RESTful service on our server, these two service that failed with 401, the url template is like /xxx/aaa/. while on the iPad application we are calling it as /xxx/aaa.

When I open Chrome and monitor the network request, I can actually see if we call it as /xxx/aaa, it get and HTTP 307 first, and redirect to /xxx/aaa/.

For some reason , IOS4 it works cause the basic authentication will be carry over to the next redirect request. while on IOS5, basic authentication will be dropped on the coming redirect request. that's why my service call fail, I change the code to call service like /xxx/aaa/ , then it all works. 

write down this just in case some other people also experiencing the same issue, so they can save a little bit time. 

Sunday, June 12, 2011

How to talk to Exchange Server using .net code.

Recently, I took a task to develop a tool , which will be required to access a mailbox, and pull email from there automatically and periodically. the situation is , one of our customer, which is using our financial service, when consumer go to their website or store, and want to buy their product using finance , they will ask consumer to fill in a form, and then send the information to us by email.

In the mean time, a team had been setup in house to specifically to handle those email, as you know, this is not a good solution, thus, we would develop a series of web service and try to avoid sending email, but as a matter of fact, there is a lot problem with the security setting, firewall stuff, which apparently block the web service.  In order to test the web service, they decide to send us the xml request through email as well.

Thus my tool will be required to pull those email  from a mailbox, which email body is the xml request, and then send route the xml to our web service, in this way, we can test our web service before the infrastructure issue is resolved.

Originally I was thinking, it is quite easy, I can use POP3 to access my mailbox, but it is quite frustrating , cause we are using Exchange server 2010, and POP3 had been turned off.  but after some investigation , I found out , that in Exchange Server 2010, it provide web service, as well as some SDK, thus application can use these SDK to access the mailbox.

If you also need to interactive with your Exchange mailbox, you can think about to use this as well, it is pretty easy.

The SDK is available at the following location.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c3342fb3-fbcc-4127-becf-872c746840e1

I just want to show you how easy to access your email box using C# code.
Connect to the mail server:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials("johnny.luo", "password", "domain");
service.AutodiscoverUrl("johnny.luo@*******.com.au");
go through emails

ItemView iv = new ItemView(200);
FindItemsResults<Item> result = service.FindItems(fi, iv);

send email:

EmailMessage msg = new EmailMessage(service);
                            msg.Subject = string.Format("Content {0}", ex.Message);
                         
                            msg.ToRecipients.Add("johnny.luo@******.com.au");
               
                            var att = msg.Attachments.AddItemAttachment<Item>();
                            att.Name = "XML email";
                            att.Item.MimeContent = xmlItem.EmailItem.MimeContent;
                            var att1 = msg.Attachments.AddItemAttachment<Item>();
                            att1.Name = "Plain Text email";
                            att1.Item.MimeContent = query.EmailItem.MimeContent;
                            msg.SendAndSaveCopy();

Monday, April 4, 2011

WPF DataGrid GotChas

I am intensively using WPF recently, this post explain quite a lot the issues I came across in the past two weeks.

http://blogs.msdn.com/b/vinsibal/archive/2009/04/07/5-random-gotchas-with-the-wpf-datagrid.aspx

If you want to use DataGrid in WPF , recommend you to read it.

Sunday, March 27, 2011

In GDI+ how to draw a text vertically.

Two weeks ago , I moved to a new company, and become very busy, to be honest, at Ninemsn, the culture is quite relax, not too much pressure, while in my new company, cause the team is small, I need to do most of the design and development, so quite busy, that's why I didn't get time to update my blog. 

As my first assignment in this company is to develop a chart control, which need to support line chart, pie chart, stack bar chart etc.  At this point , some people might ask , why not just find one from the market?  well, that's a very good question, I ask them as well, but the answer is , their chart requirement is quite unique ,   for example, they need a kind of stack bar chart.  all the others are standard, while the width of the stack bar should represent the production, that means , if a company, their production is high,  the width of the bar should represent it.  to be honest, I can't find a control from the market can meet this requirement without any funky customization.  furthermore, their want the chart can be export to word natively, when I say natively  means, the chart can be edit in word, cause most chart control currently, they can be export to word as an image, that means the chart can't be editable in word.  based on these two reason , we decide to implement one chart control of our own. 

Technically, it is not difficult, but I do came across a few issues, and I resolve that. 
1. In GDI+ how to draw a text vertically. 
In GDI+ , the way to do it is rotate the axis, for example, if you want to rotate it 90 degree, then you can use RotateTransform function. 
Assume, you want to draw a text at point(100,100) vertically,here is how you gona to do that. 
e.Graphics.TranslateTransform(100,100);
e.Graphics.RotateTransform(-90);
e.Graphics.DrawString("Hello", new Font("Arial", 10f, FontStyle.Regular), Brushes.Red, 0, 0);
e.Graphics.ResetTransform();
The reason why I mention this is , most post missed one point, that you need to translate your axis first, before you do the rotate. cause by default, rotate transform is roate the axis base on Point(0,0), if you don't translate your axis to the position where you want to draw your string, then most of the time, you will not be able to find the string you just drew, cause it is out of range. 

2.In my case, the other challenge is how to draw on multiple platform(WPF, GDI+ and Word), I use an interface to abstract the underlying drawing functionality. 


Sunday, March 13, 2011

How to setup Form Authentication Service through WCF

These few days, I am trying to implement something based on my own interest. And I would like to host my business logic on my server. So Obviously WCF is a good choice.  but I was thinking how can I make sure that my service can be only accessed by legitimate users instead of everyone, then I thought of Form Authentication, and it turns out Microsoft already provide a solution for this.

http://msdn.microsoft.com/en-us/library/bb386582.aspx

Given the fact that there are already pretty much articles about this topic on internet, I just want to write what I had been through.

  1. When you invoke the authentication service, if you get an error message say that the service is disabled. Make sure that the following few lines exist in your web.config file, and enabled has been set to true.
  2. <system.web.extensions>
       <scripting>
         <webServices>
           <authenticationService enabled="true"
            requireSSL = "false"/>
         </webServices>
       </scripting>
    </system.web.extensions>

  3. Why IsLoggedIn function always return false, even right after login. 

Check your local config file, to make sure that allowCookies option had been turned on.

    3.  For all the service that protected by form authentication, when you call those services, make sure you had passed in the form cookie. otherwise , you will be kicked out.

Monday, March 7, 2011

An interesting interview question, How to store an grid of which each dimension has more than 1m elements

One of my friend , he went to an interview, during the interview he was asked, if we have a grid , both x and y dimension have 1 million elements,  what kind of data structure you will use? Given the left top position of a view port , we also know the width and height of the view port, how we can quickly figure out those nodes in the viewport?

I was thinking this these few days, assume each node in the grid, we need to persist it's x axis and y axis,
public struct Node
{
     int x;
     int y;
}
each node need at least 8 bytes in memory, put the memory alignment aside , don't worry about it at this moment, for an 1million * 1million grid, if we store all the nodes in memory, how big it will be,
Total =  1million * 1million * 8 /1024/1024/1024 GB
         =  7450.58GB
so, obviously , it is not possible to store the whole grid in memory, we have to break down the grid to small grids.Assume the size of the view port is 1024 * 768, I will say each small grid, the size is 1024 * 768, a view port.

Based on this , we can break down the big grid to a small one, I will call it page grid, but each cell in the grid, pointing to another grid, which is exactly the size of one view port, I call it a page, sorry, I borrow this idea from database .

x:0-1024
y:0-768

x:1024-2048
y:0-768

x:2048-3072
y:0-768

x:3072 - 4096
y:0-768

......

x:0-1024
y:768-1536

x:1024-2048
y:768-1536

x:2048-3072
y:768-1536

x:3072 - 4096
y:768-1536

......

....

....

....

....

......

The width of this new grid is 1million / 1024 = 977
The height of this grid is 1million / 768 = 1303

The data of each cell on above grid will be store on hard disk, based on the left top position of the view port, we can easily identify data in which cell we need to access.  the formula is quite simple
maximum we will need to load in four cells of data.  think about it.

In this way, the is not too big anymore, so we don't need to bother whether to use linked list or binary tree,  or whatever,  for linked list, it is not design for fast search, it is for easy expandable. while binary tree, it good for search, but maintenance cost is very high. obviously we need to balance

while in this case , I will say , use an array or a hash map to persist the page grid, which is easy to search and maintain.

Monday, February 28, 2011

Highlight the column header and the first few cells in the DataGrid

In my application, I have a requirement, SelectionMode of the DataGrid has been set to Extend, and SelectionUnit is Cell, thus user can select each cell int the DataGrid, the first 4 or 5 columns in the data grid is used for display some information about the row,  so when user select a cell in the Grid, both the columnheader and the related information cell should be highlight , thus make it easier for user to understand what they are editing. like excel.
Originally I was thinking to hook up a function with the CurrentCellChanged event, and then when the cell is changed, I manually to find the columns that need to be highlighted, and apply a style to it. but it is ugly. so I am keep searching whether there is a better way to do that, finally I get it. 

In terms of select the column header,  First of all, we should create a style and bind it to the column header, put the following xaml expression to your style, trigger part.
<DataTrigger Value="True">
                                <DataTrigger.Binding>
                                    <MultiBinding Converter="{StaticResource IsHeaderCurrentConverter}">
                                        <Binding RelativeSource="{RelativeSource Self}" />
                                        <Binding Path="CurrentColumn" RelativeSource="{RelativeSource FindAncestor,AncestorType={x:Type DataGrid}}" />
                                    </MultiBinding>

                                </DataTrigger.Binding>
                                <Setter  TargetName="headerBorder" Property="Background"
                                Value="Red" />
                            </DataTrigger>

After that, create a convertor. 
public class IsHeaderCurrentConverter : IMultiValueConverter
    {

       
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool bResult = false;
            if (values[1] != null)
            {
                DataGridColumnHeader dgch = values[0] as DataGridColumnHeader;
                System.Windows.Controls.DataGridTextColumn dgtc =
                    values[1] as System.Windows.Controls.DataGridTextColumn;
                if(dgtc.Header.ToString().CompareTo(dgch.Column.Header.ToString()) == 0)
                {
                    bResult = true;
                }
            }

            return bResult;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

In the converter, if we return true, then the column header will be highlight with red.

Use the same theory , you can create a style to highlight the cells that you need to change when cell is selected.

Sunday, February 27, 2011

DataGrid, Create and load datatemplate on the fly.

Recently , I was investigating how to port a winform application to use WPF.  the winform application is intensively using DataGrid. But it is using a lot of code to handle the style and appearance. 

In WPF, we have data binding which is very flexible. Here is what I learned recently.

1.How to bind columns on the fly using code behind.

Assume you have a model class, which can return you a DataTable object, while the columns in the DataTable varies by the input parameter which you passed in when you invoke the function.  The data in the table cell is a custom data type(SiteData),base on the DataType property of MyCellData object, we should use different style to differentiate it,Base on the column name we should decide hide or show the column,How to bind the DataTable to a DataGrid?

To be clear, I post a function to generated the data here, so based on the code, you know What I mean.

   1:   public DataTable ToDataTable()
   2:          {
   3:              DataTable dt = new DataTable();
   4:              this.CreateDummyData();
   5:              dt.Columns.Add("Row1", typeof(RowHeadInfo));
   6:              dt.Columns.Add("Row2", typeof(RowHeadInfo));
   7:              for (var i = 2000; i <= 2020; i++)
   8:              {
   9:                  for (var j = 0; j <= 4; j++)
  10:                  {
  11:                      if(j == 0)
  12:                          dt.Columns.Add(string.Format("Y{0}", i, j), typeof(SiteData));
  13:                      else
  14:                          dt.Columns.Add(string.Format("Y{0}Q{1}", i, j), typeof(SiteData));
  15:                  }
  16:              }
  17:              foreach (var item in this._listRows)
  18:              {
  19:                  item.ToDataTable(dt);
  20:              }
  21:              return dt;
  22:          }



You might say just set the itemssource to the datatable, yeah, we should do that anyway, but it is not that easy, cause the data in the table is a custom data type, so you have to specify a binding to tell the grid which property to display, and we need trigger to change the style of display.


Eventually, we can’t write the DataGridColumns definition in xaml file. there are two solutions.


a)You can use a loop to go through the columns in the DataTable and then use code to add column to the DataGrid.  use this method, you have to set the AutoGeneratedColumns to false.


b)You can set the AutoGenerateColumn to true, while write a function to handle the AutoGeneratingColumn event. in this function , you can create and load data template use code.


   1:  private void dataGrid1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
   2:          {
   3:              if (e.PropertyType == typeof(RowHeadInfo))
   4:              {
   5:                  DataGridTextColumn dgtc = new DataGridTextColumn();
   6:                  dgtc.IsReadOnly = true;
   7:                  dgtc.Binding = new Binding(e.PropertyName + ".RowName");
   8:                  dgtc.CellStyle = this.FindResource("RowHeaderSelectedStyle") as Style;
   9:                  dgtc.HeaderStyle = this.FindResource("NormalHeaderStyle") as Style;
  10:                  e.Column = dgtc;
  11:              }
  12:              else if (e.PropertyType == typeof(SiteData))
  13:              {
  14:                  DataGridTextColumn dgtc = new DataGridTextColumn();
  15:                  dgtc.Width = 50;
  16:                  dgtc.Binding = new Binding(e.PropertyName)
  17:                  {
  18:                      
  19:                      Converter = new DataCellConverter(),
  20:                      Mode = BindingMode.TwoWay
  21:                  };
  22:                  
  23:                  if (e.PropertyName.Contains("Q"))
  24:                  {
  25:                      dgtc.Visibility = Visibility.Hidden;
  26:                      dgtc.HeaderStyle = this.FindResource("NormalHeaderStyle") as Style;
  27:                  }
  28:                  else
  29:                  {
  30:                      dgtc.HeaderStyle = this.FindResource("NormalHeaderStyleWithCheckBox") as Style;
  31:                  }
  32:                  
  33:                  dgtc.CanUserSort = false;
  34:                  dgtc.Header = e.PropertyName;
  35:                  
  36:                  string strStyle = Properties.Resources.NormalDataCellStyle;
  37:                  string strValue = strStyle.Replace("{0}", e.PropertyName);
  38:                  XmlReader xr = XmlReader.Create(new StringReader(strValue));
  39:                  Style st = (Style)XamlReader.Load(xr);
  40:                  dgtc.CellStyle = st;
  41:                  e.Column = dgtc;
  42:              }
  43:          }





   1:  <Style  TargetType="{x:Type DataGridCell}"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   2:              <Setter Property="Background" Value="Green" />
   3:              <Setter Property="Foreground" Value="White" />
   4:              <Setter Property="HorizontalAlignment" Value="Stretch" />
   5:              <Setter Property="VerticalAlignment" Value="Center" />
   6:              <Style.Triggers>
   7:                  <DataTrigger Binding="{Binding Path={0}.SiteDataType}">
   8:                      <DataTrigger.Value>
   9:                          REPORT
  10:                      </DataTrigger.Value>
  11:                      <Setter Property="Background" Value="Red" />
  12:                  </DataTrigger>
  13:                  <DataTrigger Binding="{Binding Path={0}.SiteDataType}">
  14:                      <DataTrigger.Value>
  15:                          ESTIMATE
  16:                      </DataTrigger.Value>
  17:                      <Setter Property="Background" Value="Yellow" />
  18:                  </DataTrigger>
  19:                  <Trigger Property="IsSelected" Value="True">
  20:                      <Setter Property="Background" Value="Green" />
  21:                  </Trigger>
  22:              </Style.Triggers>
  23:          </Style>

Saturday, February 12, 2011

How to do DB load test

For a portal which with very high traffic, Database is the one the will directly affect the performance of your website, so every time, when you need to deploy some store procedure or database changes, you will always think that whether you stuff will greatly affect the sites. 

Recently In order to reproduce one db issue we came across, we are trying to reproduce it on our dev environment. but after quite a lot try, we don't have any luck. so we are thinking whether we can do some load test on our database.  fortunately , with VS2008 we can actually do that easily. You might ask ,a lot people are already on VS2010, but unfortunately , this feature had been turned off in VS2010, but it still there, if you want to use it , you have to buy it... so you know why Microsoft is rich...

I had done some search via internet, but didn't find too much articles introducing how to do it, so I write this post, hopefully it will help someone later on, knowledge should be shared. 

Step 1 , you should use your VS2008 to create a test project, it is easy
Step 2,In the solution explorer, right click your project name , on the coming out context menu, click add a unit test, then select database unit test, refer to the following snapshot.
Step 3, in the coming out dialog, it will ask you to select a database, if your database connection is already there, you can just select one, or create a new one.

step4, create the test, on the following snapshot reflect screen, you can just click the "click here to create" link to create a database unit test case. basically once you hit the link , it will go to code mode, and allow you to type in a SQL statement, which you used for test.
 
Code window
Step 5, add a load test, in your test project , go to solution explorer, and right click your project, on the coming out context menu


Follow the load test wizard, usually, for Database test, we select step load, which means we will increase user load steady until it reach the maximum.
In the test mix, you can select the database test , which you just created.
Then your database load test is ready. run it , and check the performance counters....





Thursday, February 10, 2011

How to play steam video in Silverlight 4.0

Today , I am investigating how to play video in Silverlight 4.0 ,  using MediaElement, it is quite easy to play a video in local disk , or hold in a server that can be accessed through http.  but unfortunately , our server is in a seperate server, and exposed as mms stream.  

it is quite headache , I was plan to use telerik's media play control, but it can't support mms stream as well. it takes me a few hours to look around, but no luck , finally I was thinking whether I can change the mms protocol to using http to see what will happen,  the interesting thing is , I change the mms to http at the video url, and paste to chrome, and I found I can access it and play it successfully in a browser.

so I use MediaElement, and change the video url protocol to http and set to the source property of MediaElement, it works smoothly....

Is that mean mms is based on http? need to figure this out.

Tuesday, February 8, 2011

Silverlight 4.0 drag and drop -- continue

In a previous post, I mentioned the drag and drop in Silverlight 4, cause we upgrade to SL 4 recently, we were using the Silverlight Toolkit, ListBoxDragDropTarget, but in Silverlight 4, the performance of drag and drop control is deteriorative , even the issue that sometimes it lost mouse key up can be fixed, but still can't meet user's expectation.

So these few days, I tried to use telerik's silverlight controls, basically the performance is much better, and user experience is much better.  drag and drop much more smooth than silverlight toolkit, of course it will be better cause you gonna to pay it.

To be honest the silverlight toolkit drag and drop is quite automatic, you don't need to write too much code to make the drag and drop to work.  in this way, you also don't have too much control over it. while the drag and drop control of telerik on the contract , it gives you more control and require you to implement more logic and code to make it work.

Secondly, toolkit drag and drop can show some very good indicator when you drag over your drop target. such as insert indicator, etc.. while telerik control doesn't have that.

BTW. before I move to third party controls, I also looked into the toolkit source code, and find there are intensively use LINQ , which complex the who logic, and finally make me give up fixing the issues.

Just for the reference of those who also come across the same issue and considering some third party controls.

Monday, February 7, 2011

avoid checking parameters at where clause.

Recently , we came across an issue, when massive traffic come in, one of our store procedure will trigger very very high CPU usage,  at some point, it trigger the CPU usage spike to 90% percent, which greatly increase the database response time, and our service is timing out, also it slow down the other websites which are also connecting this database.  In our dev environment , when we look at the store procedure, it looks totally fine, we check the execution plan, it is good as well, we are using index seek , nothing is expensive at all.
Today we create a load test using Visual Studio 2010, which can simulate 1000 or 2000 concurrent online user and be able to reproduce the issue, and we have an interesting finding.

We are doing parameter check at where clause.

assume In SQL Server, if you have store procedure, which can pass in an @UserID INT, when @UserID is 0, you would like to skip this parameter, only use it when @UserID is not zero.  so the SQL Statement you can write like this.

SELECT ID,REALNAME,USERNAME FROM USERS where (@UserID=0 OR ID=@UserID)

When you looked at this statement it is fine, and when you try it , it works as well but it is problematic.
a)When you have a lot of traffic on a store procedure that is implemented in this way, you will find this statement use far more CPU resource than others.  in our case, the store procedure cause the SQL Server CPU to spike , and it reach 90% , and keep high.  after we take this statement out, CPU usage goes down to around 50 percent.
b)if you write SQL Statement this way, SQL Server will not be able to pick up appropriate index.

So be careful, if you are writing some SQL statement which will be executed on a database with high traffic, please avoid it.

Saturday, February 5, 2011

Caculate how many one in a bit format of int value

Everyone knows that in computer, no matter what type you are using, finally it will be represent with bits , 0 and 1 .   For example
INT value    Bit
1                  0001
2                  0010
3                  0011
4                  0100
and so on....

A couple days ago, I was asked, given an int value, can you print out it in bit format, and caculate how many 1 in the bit level.

First of all, it is quite easy to get the bit string of the int value, just use convert function.
Secondly , caculate how many one in the bit string, you can use & operator and >> operator


   1:  class MainClass
   2:      {
   3:          static readonly int LENOFBIT = 8;
   4:          public static void Main (string[] args)
   5:          {
   6:              int iValueToTest = 12345;
   7:              string strBit = Convert.ToString(iValueToTest,2);
   8:              Console.WriteLine("int value {0} in bit format is {1}",iValueToTest,strBit);
   9:              Console.WriteLine("there are {0} one in bit format",CaculateOne(iValueToTest));
  10:                          
  11:          }
  12:          
  13:          static int CaculateOne(int iValue)
  14:          {
  15:              int iResult = 0;
  16:              int iLen = sizeof(int);
  17:              for(int i=0;i<iLen * LENOFBIT;i++)
  18:              {
  19:                  if((iValue & 1) == 1)
  20:                  {
  21:                      iResult ++;
  22:                  }
  23:                  iValue = iValue >> 1;
  24:              }
  25:              return iResult;
  26:          }
  27:          
  28:      }

You may ask , what the hell this is used for? assume you are implementing a user permission system,  you can use each bit to represent a permission, thus an int value can represent 32 permissions.

Saturday, January 29, 2011

How to detect a loop in a single linked list

Continue my topic regarding linked list, I couple days ago , after I create the linked list class, I was thinking , in a single list, if one node point to a node prior to itself in the list, then it create a loop.  Then when you traverse the linked list, Ooops! you get into a dead loop.
So I was thinking How to detect this loop situation, then I did some research over internet, I do find quite a lot good articles.  here is one,  http://ostermiller.org/find_loop_singly_linked_list.html it explain good solutions and bad solutions.
this is another one explain how to address the culprit which cause the loop http://crackinterviewtoday.wordpress.com/2010/03/16/calculate-node-that-causes-loop-in-a-linked-list/

Today,I get some time , so I implement the function , here is the code.
Not only this function can address the loop, but also , it can address the exact node that cause it.


public bool hasLoop()
        {
            bool bReturn = false;
            
            if(_root != null && _root.next != null)
            {
                Node slow = _root;
                Node fast1 = Root;
                Node fast2 = Root;
                while(slow != null)
                {
                    fast1 = fast2.next;
                    if(fast1 != null)
                    {
                        fast2 = fast1.next;
                        if(fast1 == slow || fast2 == slow) //we have a loop
                        {
                            bReturn = true;
                            break;
                        }
                        else if(fast2 == null)//fast2 reach the end of linked list.
                        {
                            break;
                        }
                    }
                    else //fast1 is null means we reach the end of the linked list.
                    { 
                        break;
                    }
                    slow = slow.next;
                }
                slow = slow.next;
                Console.WriteLine(string.Format("Node:{0} cause a loop...",slow.Name));
            }
            
            return bReturn;
        }

Silverlight drag and drop issue

This week , I upgrade our project to silverlight 4, you know silverlight 4 is on the market for a long time, but unfortunately , we are still using silverlight 3.0, constrained by the infrastructure. cause it is not easy to change our build server.  finally now it is silverlight 4.

Once I finish up the upgrade, I came across a drag and drop issue. In silverlight 4, when I move mouse on the top of a ListBoxDragDropTarget, even me mouse left key is not down, but sometimes, it just start to drag....Which might cause a lot problem.  after some search , it turns out it is a bug of silverlight 4 toolkit, and I found a solution here  http://silverlight.codeplex.com/workitem/5930 , this solution works for me.

Wednesday, January 26, 2011

How to reverse a linked list

If you go for an interview and the position which you are interviewing for is r&d focus, then most likely they will ask you some very basic technologies,data structures.  Which you might learned from your uni, but after so many years of working, you almost forget about it.

Recently I came across a question: how to reverse a linked list?

Linked list is quite easy ,  if you don't know about it , you can go to http://en.wikipedia.org/wiki/Linked_list to read more.

From the question you can know , that the linked list which require you to reverse is single linked list.  cause double linked list, there is no point to reverse.

They give me a marker , and ask me to write down the function on a white board. I spend around 10 minutes and didn't get it right, then they lost patience.   the problem for me , is  I am not used to write any code on a board....

So today I create a function to reverse a linked list. Include build the linked list, traverse , and reverse , it totally take me around half an hour in front of my PC.

First of all , we need to define a class which can be used to represent a linked list.

internal class Node
{
public Node(string strName)
{
this._name = strName;
}

private string _name = string.Empty;
public string Name
{
get{return this._name;}
set{this.Name = value;}
}

private Node _next = null;
public Node next
{
get{return this._next;}
set{this._next = value;}
}

public void setNext(Node node)
{

this.next = node;

}
}