Skip Ribbon Commands
Skip to main content
Home
The personal web log (blog) site of Alex Tjahjana is called 1sweetlove because this web site will be the place that contains all of the things he love sweetly as well as the place to store the scribles of his thoughts. The one and only place.
August 31
Creating a Code Snippet using Visual Studio 2010

After attending TechEd and Code Camp 2011, I receive a code from Jeremy Boyd which potentially I will use quite often. My first instinct is to copy-and-paste those lines of codes into a text file. However, I quickly change my mind because in the future, at least it would be quite a feat to remember where I store those codes in the first place. Then I remember about snippet. Sounds like a good idea; especially I'm also don't have a clue on how to use snippet in Visual Studio. So, I got 2 good reasons to find out how to create and to use snippet.

So, first of all, how to use snippet. You can use snippet in 2 ways:

  1. Right-click > Insert Snippet... > [Choose your snippet]
  2. Ctrl-K + Ctrl-X > [Choose your snippet]

That simple, and now I felt stupid that I was struggling upon how to use snippet especially during the Hands-on-lab time. This would have save me lots of time from typing the lab codes. :D

Now, how to create a snippet. The easiest way is to follow these steps:

  1. File > New File > XML File
  2. Ctrl-A
  3. Insert a snippet called "Snippet" (Ctrl-K + Ctrl-X > Snippets > Snippet)

This will you the snippet template, and you'll only have to update some part of it. Handy. The template will look like the following image:
Snippet Template

Next is the steps to customised the snippet:

  1. First of all, you have to change the Language part at line 19, into the language of your code. The options are:
    • VB
    • CSharp
    • VJSharp
    • XML

    You should change the language into the language of the code that you will put as the snippet.

    The language also have to match the location of your snippet, e.g. if you will store it in the XML folder, the language should be XML, and if it will be in the Visual C# folder then the language will have to be CSharp, if the code is for a snippet for web.config, then the language should be XML, and should be stored in the XML folder.

    Failure to do so, will give you the "Missing or unspecified Language attribute" error message (in the Output window).

  2. You should change the title of the snippet
  3. Change the author of the snippet
  4. Assign shortcut to the snippet. However, please note that the shortcut only available for codes that support intellisense; hence, the shortcut won't work for XML pages such as web.config.
  5. Update the description of your snippet, as this will help to remind you what your snippet is all about sometime in the future.
  6. Place your code in between the square brackets.
  7. And if you got some dynamic content such as file location, variable name, class name, etc you can use the <Literal> (or <Object> for object name) to make it easier to customise the code. In my case, I add:

    <Literal>
    <ID>filename</ID>
    <Default>logfilename.log</Default>
    </Literal>

    and in my code, I use %filename% at the location where I should place the location of the log file.

  8. Save the code using .snippet extension.

That's all. If you want to learn further, MSDN got an excellent set of articles.

June 19
Showing detailed error messages on WCF Data Services

In the past few days, I was troubled by some issues ​with my code. Unfortunately, the error messages that I got is just like the following snapshot:

Default WCF error message

Just saying "The server encountered an error processing the request. See server logs for more details." is not very helpful isn't it? So, I dig my eyes and head into every server logs that I know and can think of, but to no avail. Out of desperation, I stumbled upon So Special - InitializeService in ADO.NET Data Services, a blog post by Marcelo Lopez Ruiz. Following his suggestion, I add the following single line of code

[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults=true)]

so my code now look like the following:

namespace publicationLibrary
{
 [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults=true)]
 public class ListOfPublications : DataService
 {

When I check the error message, I finally got the detailed one like the following snapshot:

Detailed WCF error message

I can see the detailed error message! Yay! Problem solved.

One very important thing to do before I enabled the service into the production is to take that line of code; to minimize the security attack surface. I understand that this activity is easily forgotten. Therefore, I explore further and found out that I can use web.config to enable or disabled this feature.

What I did next is to remove that 1 line of code from my program. Then I modify my web.config files. By default, web.config disabled the includeExceptionDetailInFaults. Thus, assuming that you're using the default web.config files, if you change the default web.config.debug into the following:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
 <system.servicemodel>
  <behaviors>
   <servicebehaviors>
    <behavior>
     <servicedebug xdt:transform="Replace" includeexceptiondetailinfaults="true" />
    </behavior>
   </servicebehaviors>
  </behaviors>
 </system.servicemodel>
</configuration>

you will automatically achieve the same effect without even have to change your code. It will automatically display the detailed error message if you compile the code in Debug mode, however, if you compile your code in Release mode, it will automatically display the concise 1 line default error message, as in my first screen snapshot. Perfect!

June 08
Changing Office365 email from @<mydomain>.onmicrosoft.com into @<mydomain>

Last night when I search through the co​mmunity forum regarding how to change the main account email address from for example john.doe@mydomain.onmicrosoft.com into john.doe@mydomain, I found at least 6 threads, and all of then recommends that I have to create a new account for john.doe@mydomain and then delete the old john.doe@mydomain.onmicrosoft.com account. It works, but you have to do it at the very begining, before you created anything, receive/send any emails, or even joining the community. In my opinion, eventhough it works, it's not a good solutions. The following steps is, in my opinion, a much better solution.

  1. Start with loging in to por​tal.microsoftonline.com using your onmicrosoft account, e.g. john.doe@mydomain.onmicrosoft.com
  2. Then go to your 'Admin' site, and then to 'Domains'. The status of your domain should be 'Active'. At this point, it doesn't matter whether you've change your NS entries of your domain or not. However, to ensure smooth email transitions, I personally prefers not to change it yet.
  3. Then go to 'Users'.
  4. Select john.doe@mydomain.onmicrosoft.com's name, and then click 'More', followed by 'Change mailbox settings.'
  5. On the popped up window, go to 'E-mail Options.'
  6. Click 'Add' and enter john.doe on the text box and select mydomain from the dropdown list. Then click 'OK.' If John Doe have other email aliases, then you should add them too.
  7. Click 'Save' once you're done, and the popped up window will close.
  8. Click 'Save' on John Doe's page. This will take you back to the 'Users' page.
  9. Click 'New' > 'User'.
  10. Create a temporary user, e.g. temp@mydomain. Don't forget to give this user administrator permissions.
  11. Once temp@mydomain has been created, log out from your current user, then login using temp@mydomain. You'll have to assign new password before you can continue.

     

  12. Go to 'Admin' site, then go to 'Users,' and followed by repeating step 4.
  13. Click on 'Properties', and then change John Doe's username into: john.doe@mydomain.
  14. Click 'Save.'
  15. Log out, and relogin using John Doe's new username.
  16. You'll find that John Doe's primary email is now john.doe@mydomain, and all of your existing email, contact list, community access, SharePoint site(s), etc. are all still intact with your account.

The best thing with this solution is that you can do this whenever you want, don't have to be the very first thing that you have to do.

Another few steps that I would like to recommend you to do are:

  • Immediately delete temp@mydomain account. It's dangerous to leave unused account accessible, plus this unused account might cost you once the beta period had lapse.
  • You can now change the NS entries of your domain, and you won't loose any incoming emails. Although, for the next few days (usually around up to 72 hours), some of your emails might still go to your old email provider/account.

And now, I can say happy emailing with Office 365.

June 07
Moving my blog to a new host and new system

Finally, today I move my blog to a new sytem, as well as to a new host. It's no longer being hosted in a mock server that sits under my desk, and prone to service disruptions whenever my ADSL modem feel like dying on me, or when my internet provider feel like disrupting my internet connection.

Since my new host is running different blog engine, and I don't have control over what I can install into the host server, then I have to use a new system to run and manage my blog.

And this all began about 1 week ago, when I finally able to get my hands dirty with Office 365, and also getting a new Windows Phone 7. My excitement level at that time was stellar. Unfortunately, today I can't say the same.

There are disappointments upon disappointement came to me in the past week, starting from: (1) the SharePoint under Office 365 Small Business Plan is not accessible from Windows Phone 7 (Microsoft says that this will be fixed when "Mango" ship), (2) I accidentally delete my whole website when I actually just wanted to delete one of its sub-site, (3) Difficulties to customise/hide the "ribbon" on top of the blog site, (4) No support for tagging the blog post, and (5) Cannot install custom WebParts, such as the Cloug Tagging. Those are just some of issues I encountered that are either worth mentioning, or I still remember.

However, my move to Office 365 system isn't just a-bag-full-of-pain. It got happy memories too, such as: (1) How easy it is to transfer my contacts from my Outlook, (2) Better calendaring system that allows me to sync multiple calendars without messing each other up, and (3) Seamless transitions from my old email and web system to Office 365. To name a few.

It's true that there are challenges, but, I believe that this is my opportunity to finally learn about, and how to use SharePoint. Hopefully, at the end of the tunnel I'll master SharePoint once I'm done with this; and also because I have to administer SharePoint at work, soon.

June 06
Creating a Server-Control which will automatically add JavaScript

My previous post talks about how to create server-control shown in the Toolbox and click-and-drag enabled, and also about creating a server-control shown in toolbox with own icon but what if you want to automatically add/inject javascript? This post will talk about exactly that.

There's two approach for this:

  1. to dump the JavaScript code directly into the page
  2. to put the JavaScript code into a file and link that file

Although the first approach is straight forward, I personally prefers the 2nd approach as it's more efficient and allow the browser to cache the code, hence reduce the bandwidth usage and time to download.

Now, let's assume that we have a JavaScript file called Funky.js with the following code in it:

function TestFunction(ctrl) {
 alert("Test");
}

First of all, we need to add Funky.js into the project, and afterwards your Solution Explorer will look like the following:

ServerControlEmbed

Then, just like with adding the BMP as custom icon in creating a server-control shown in toolbox with own icon, we will have to set its Build Action property into Embedded Resource like the following image:

ServerControlJavaScript

Afterwards, we have to modified the code, from:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdvSolutions.MyControlLibrary
{
 [ToolboxData(@"<{0}:LogoControl runat=""server"" CompanyName="" "" LogoUrl="" "" />")]
 public class LogoControl : WebControl
 {
  public LogoControl() { }
  public String CompanyName { get; set; }
  public String LogoUrl { get; set; }
  protected override void Render(HtmlTextWriter writer)
  {
   writer.RenderBeginTag("div");
   writer.Write("<img src=\"{0}\" /><br />", this.LogoUrl);
   writer.Write(this.CompanyName + "<br />");
   writer.RenderEndTag();
  }
 }
}

into the following:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdvSolutions.MyControlLibrary
{
 [ToolboxData(@"<{0}:LogoControl runat=""server"" CompanyName="" "" LogoUrl="" "" />")]
 public class LogoControl : WebControl
 {
  public LogoControl() { }
  public String CompanyName { get; set; }
  public String LogoUrl { get; set; }
  protected override void OnPreRender(EventArgs e)
  {
   Page.ClientScript.RegisterClientScriptInclude("LogoUrl", Page.ClientScript.GetWebResourceUrl(this.GetType(),_
"AdvSolutions.MyControlLibrary.Funky.js")); base.OnPreRender(e); } protected override void Render(HtmlTextWriter writer) { writer.AddAttribute("onclick", "TestFunction(this);"); writer.RenderBeginTag("div"); writer.Write("<img src=\"{0}\" /><br />", this.LogoUrl); writer.Write(this.CompanyName + "<br />"); writer.RenderEndTag(); } } }

You'll see that we have to override OnPreRender as well, otherwise, it will be too late for us to tell ASP.NET that we want to link Funky.js.

Now, many tutorial stops here. However, I found that you have to perform another crucial step. Which is to add the following code:

[assembly: WebResource("AdvSolutions.MyControlLibrary.Funky.js", "text/javascript")]

at the end of your AssemblyInfo.cs file.

If you observe carefully, that line is composed from the Namespace and the filename. Now, if for instance you move Funky.js from the root folder of your project to a subfolder called Scripts for example, then you will have to change that line into:

[assembly: WebResource("AdvSolutions.MyControlLibrary.Scripts.Funky.js", "text/javascript")]

and we also have to modified the line in the OnPreRender from AdvSolutions.MyControlLibrary.Funky.js into AdvSolutions.MyControlLibrary.Scripts.Funky.js.

When you use this control, whenever you click on the logo the javascript will pops out a message. I know that the functionality is trivial, but I believe this will teach you the fundamentals to do more exciting things.

Have fun.

June 05
Creating a Server-Control shown in ToolBox with own Icon

My previous post talks about how to create server-control shown in the Toolbox and click-and-drag enabled, but it is shown in the Toolbox with the generic icon. It's ok if you have a few custom controls, but when you got a bunch of them displayed using the same icon, then it will take you a while to find the one that you're looking for.

To make your custom control displayed with your custom icon, then we will have to modified our code into the following:

using System;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdvSolutions.MyControlLibrary
{
 [ToolboxData(@"<{0}:LogoControl runat=""server"" CompanyName="" "" LogoUrl="" "" />"),
  ToolboxBitmap(typeof(LogoControl), "AdvSolutions.MyControlLibrary.LogoControl.bmp")]
 public class LogoControl : WebControl
 {
  public LogoControl() { }
  public String CompanyName { get; set; }
  public String LogoUrl { get; set; }
  protected override void Render(HtmlTextWriter writer)
  {
   writer.RenderBeginTag("div");
   writer.Write("<img src="\"{0}\"" /><br />", this.LogoUrl);
   writer.Write(this.CompanyName + "<br />");
   writer.RenderEndTag();
  }
 }
}

PS: You can find the original code in how to create server-control shown in the Toolbox and click-and-drag enabled.

After we modified the code, the next step is to add your icon (BMP) file into the project. Afterwards, your Solution Explorer will look like following:

ServerControlEmbed

The image file that you want to use as the icon will have to meet the following criteria:

  • It has to be 16x16 pixels BMP image/icon file.
  • It should have the same name with the class name you want it to represent. In our example it should be named LogoControl.bmp
  • You have to set its Build Action property into Embedded Resource like the following image:
    ServerControlImage
June 04
How to create Server-Control shown in the Toolbox and click-and-drag enabled

I was assigned to develop a server control using .NET, and altough it's quite easy to create a server control; making it drag-and-drop capable is a bit of a challenge. Although there are some tutorials out there, all that I've read have pitfalls that make me scratch my head.

Now, lets assume that we have the following code:

using System;

public class LogoControl{
 public LogoControl(){ }
 public String CompanyName {get; set;}
 public String LogoUrl {get; set;}
}

And let's assume that this server control inherits directly from the WebControl class. hence, the code will be like:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdvSolutions.MyControlLibrary
{
 public class LogoControl : WebControl
 {
  public LogoControl() { }
  public String CompanyName { get; set; }
  public String LogoUrl { get; set; }
  protected override void Render(HtmlTextWriter writer)
  {
   writer.RenderBeginTag("div");
   writer.Write("<img src="\"{0}\"" /><br />", this.LogoUrl);
   writer.Write(this.CompanyName + "<br />");
   writer.RenderEndTag();
  }
 }
}

Now, the web server-control is done. However, you can only use it from the source view of your Visual Studio. To give click-and-drag capability to this control, you have to modified the code into:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdvSolutions.MyControlLibrary
{
 [ToolboxData(@"<{0}:LogoControl runat=""server"" CompanyName="" "" LogoUrl="" "" />")]
 public class LogoControl : WebControl
 {
  public LogoControl() { }
  public String CompanyName { get; set; }
  public String LogoUrl { get; set; }
  protected override void Render(HtmlTextWriter writer)
  {
   writer.RenderBeginTag("div");
   writer.Write("<img src="\"{0}\"" /><br />", this.LogoUrl);
   writer.Write(this.CompanyName + "<br />");
   writer.RenderEndTag();
  }
 }
}

Although most people says that this is enough, it actually not. There's another step that you have to do, which is to modify the AssemblyInfo.cs file. Add the following line into it:

[assembly: TagPrefix("AdvSolutions.MyControlLibrary", "acl")]

Oh, you might also need to add

using System.Web.UI;

too.

Why? Because, if you look at the code again at line 7, you will find ... @"<{0}:LogoControl .... By adding that single line into AssemblyInfo.cs file, when you click-and-drag this control, it will automatically register the assembly and create the tag prefix, therefore, when you click-and-drag this control into the consuming project the line 7 on the code above will be automatically translated into:

<acl:LogoControl ID="LogoControl1" runat="server" CompanyName=" " LogoUrl=" " />

Now, if you look carefully at the code and AssemblyInfo.cs file again, you'll see that the namespace for this project is AdvSolution.MyControlLibrary. If we change the namespace into something like RandomNameSpace then we have to replace every AdvSolution.MyControlLibrary with RandomNameSpace.

I hope this help.

March 14
Outlook 2010 and Outlook Social Connector

When I tried Outlook 2010 Beta, the first things that I noticed are:

  • Outlook now starts so much faster even if I got a rather big outlook file
  • Can automatically open the online map of contact's address
  • The Outlook Social Connector, at the bottom of an email or contact's detail

contact

As you can see on the image above, it listed all of the email, attachments, meetings, and other stuff that I've received or I've sent to that contact; and also his/her status updates. I personally think that this is a good addition, and bring outlook up to speed with its main competitor.

Unfortunately, the standard Social Connector that comes with Outlook 2010 beta can only connects to Microsoft SharePoint. A big disappointment for such of a nice feature. However, there are now updates for this feature, and at present, you can connect to:

  • LinkedIn
  • MySpace

with connections for Facebook and Windows Live coming.

To enable these new connections, you have to:

  1. Download the Outlook Social Connector 32 bit (February 2010 Beta)
  2. If you're using Outlook 2010 Beta, then you have to uninstall current Outlook Social Connector. If you are using Outlook 2003 or 2007, then you can skip this step.
  3. Run the Outlook Social Connector that you have downloaded in Step 1, and follow the instructions on the screen
  4. restart Outlook
  5. Download the connector for LinkedIn or MySpace
  6. Install the downloaded connector
  7. Restart Outlook
  8. Provide the credentials for each of the social network that you want to connect to

You can then see the additional feeds on your Outlook Social Connections area.

March 05
Back from death

​After a few months battling issues with networking and server settings at my place, I finally manage to sort things out and bring most of my servers back to life. And one for sure, is to bring my blog back from death. Although I am very disappointed with this incident, however, I tons of material for my blog posts. Hopefully I can manage to spare some time to put them all on. For now, I'm just glad that I've manage to put this blog online, and kindly ask you to look forward for more postings in the near future to share my battle experiences. :)

October 21
How to properly use ReadOuterXml and ReadInnerXml

When I try to look for an example on how to properly use ReadOuterXml and ReadInnerXml, my search results returns lots of thread about people having issues when using any of those, but no real answers were given. Hence, the following is my contribution.

When we want to read XML documents, we usually use the lightweight readers derived from System.Xml.XmlReader, and most likely it will be XmLTextReader. For this example, let’s assume that we want to read the following XML file:

<?xml version="1.0" encoding="utf-8" ?>
<books>
<book title="Book1">
<author name="Author1"></author>
<publisher name="Publisher1"></publisher>
</book>
<book title="Book2">
<author name="Author2"></author>
<publisher name="Publisher2"></publisher>
</book>
<book title="Book3">
<author name="Author3"></author>
<publisher name="Publisher3"></publisher>
</book>
</books>

And we usually write our code as follows:

XmlTextReader xtr = new XmlTextReader(XMLFile);
while (xtr.Read()){
switch (xtr.Name.ToLower()){
case "book":
result += "<br />" + xtr.GetAttribute("title");
break;
case "author":
result += xtr.GetAttribute("name");
break;
case "publisher":
result += xtr.GetAttribute("name");
break;
default:
break;
}
}
if (xtr != null)
xtr.Close();

And when whe want to use ReadOuterXml or ReadInnerXml, we’ll most likely will modify the code above into the following:

XmlTextReader xtr = new XmlTextReader(XMLFile);
while (xtr.Read()){
if (xtr.Name.ToLower().Equals("book") && xtr.NodeType.Equals(XmlNodeType.Element)){
result += xtr.ReadOuterXml();
}
}
if (xtr != null)
xtr.Close();

And that’s when the problem starts. Most of the issue encountered is the reader only read every other record. This is caused by the fact that both ReadOuterXml and ReadInnerXml actually behaves like Read. Hence, after ReadOuterXml or ReadInnerXml is executed, it will move the cursor to the next Element/EndElement. Hence, our modified code actually shift the cursor twice which then explains why it only reads every other record. Once we know the reason, we can then re-modified our code into the following:

XmlTextReader xtr = new XmlTextReader(XMLFile);
while (!xtr.EOF){
if (xtr.Name.ToLower().Equals("book") && xtr.NodeType.Equals(XmlNodeType.Element))
result += xtr.ReadOuterXml();
else
xtr.ReadToFollowing("book");
}
if (xtr != null)
xtr.Close();

When this code is executed, it will correctly read every records in the XML file.

Just incase you’re wondering about the if statement within the while loop, that if means that if the cursor is at the right element, then reads its inner or outer XML; otherwise, go to the next correct element. If you forgot to put the cursor advancement statement, you’ll end up with infinite loop. And that's, my friend… something that you want to avoid.

1 - 10Next
 

 About this blog

 
About this blog

I'm a web development manager specialising in secure enterprise solution in Auckland, NZ. I work with ASP.NET, MVC, WCF, C#.NET, Windows Server, SQL Server, Windows 7, Windows Phone, Windows Azure, as well as Microsoft Kinect.

View Alex  Tjahjana's profile on LinkedIn