My name is Johnny,I have being working as a developer, programmer for about 13 years now, and I think I will stay as a programmer for as long as I can. All these years I have used so many technologies , programming languages,but majority is using C++ and .net, there are ups and downs along the way, this blog is just to write down all the issues that I had been worked on, things that I learned. if someone else can also benefit a little bit from it , that's already a big bonus.
Thursday, November 3, 2011
Calling RESTful service under IOS5 failed with 401 error
Sunday, June 12, 2011
How to talk to Exchange Server using .net code.
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
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.
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.
- 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.
- Why IsLoggedIn function always return false, even right after login.
<system.web.extensions>
<scripting>
<webServices>
<authenticationService enabled="true"
requireSSL = "false"/>
</webServices>
</scripting>
</system.web.extensions>
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
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
<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>
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
}
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
Thursday, February 10, 2011
How to play steam video in Silverlight 4.0
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
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.
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
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
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
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
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;
}
}