Just in Chronicles

Life as a Voyage

How to Get URL Hash Programmatically with Javascript

leave a comment »

URL hash is not part of official URL fragments (RFC 2396), but is widely used for page navigation purposes. As this is not a part of web standards, even though most web browsers support this, there is no way to pass this value to server-side scripts, unless Javascript helps.

<script type="text/javascript">
	(function ($) {
		$(document).ready(function () {
			//	Appends the URL hash, if exists.
			var hash = window.location.hash;
			$("div.pagination a").each(function (i) {
				//var href = $(this).attr("href") + hash;
				$(this).attr("href", $(this).attr("href") + hash);
			});	//	$.each
		}); //	$.ready
	})(jQuery);
</script>

Let’s see the Javascript code above. The highlighted line is the key to get the hash URL. With this approach, we can easily get the hash URL and append it to any anchor tag programmatically.

Written by Justin

08/03/2012 at 17:06

Posted in For Web

Tagged with ,

How to Add External Error Log to Umbraco with Razor Macro Scripts

leave a comment »

Umbraco Razor macro script is very powerful and handy solution for developers to implement websites quite easily, while XSLT scripts are very hard to read and understand. However, using Razor macro scripts in Umbraco calls error log functions internally, which saves the logs to the database, rather than specific files.

That sometimes gets developers bothered as they have to append “umbDebutShotTrace=true” query string to its URL to debug an error when it occurs. Besides using the “umbDebugShowTrace=true” option, developers want to save that error details to a specific location other than the database. In order to achieve this, Umbraco core needs to be modified and recompiled. The key method is “umbraco.MacroEngines.RazorMacroEngine.Execute()” which is coded in “/umbraco.MacroEngines.Juno/RazorCore/RazorMacroEngine.cs“. Let’s see the code.

public string Execute(MacroModel macro, INode currentPage)
{
	try
	{
		Success = true;
		return ExecuteRazor(macro, currentPage);
	}
	catch (Exception exception)
	{
		Success = false;
		ResultException = exception;
		HttpContext.Current.Trace.Warn("umbracoMacro", string.Format("Error Loading Razor Script (file: {0}) {1} {2}", macro.Name, exception.Message, exception.StackTrace));
		var loading = string.Format("<div style=\"border: 1px solid #990000\">Error loading Razor Script {0}</br/>", macro.ScriptName);
		if (GlobalSettings.DebugMode)
			loading = loading + exception.Message;
		loading = loading + "</div>";

		// Adds the exception to the current HttpContext.Items.
		// Option #1: Using Dictionary<T>
		List<Dictionary<string, string>> logs = (List<Dictionary<string, string>>)HttpContext.Current.Items["umbracoErrorLogItems"];
		if (logs == null)
			logs = new List<Dictionary<string, string>>();
		logs.Add(new Dictionary<string, string>() { { "message", exception.Message }, { "source", exception.Source }, { "stackTrace", exception.StackTrace } });

		// Option #2: Using general Object
		List<object> logs = (List<object>)HttpContext.Current.Items["umbracoErrorLogItems"];
		if (logs == null)
			logs = new List<object>();
		logs.Add(new { Message = exception.Message, Source = exception.Source, StackTrace = exception.StackTrace });

		HttpContext.Current.Items["umbracoErrorLogItems"] = logs;
		return loading;
	}
}

The lines highlighted between 18 and 29 are newly added for the external log saving mechanism. When an exception occurs, HttpContext.Current.Items["umbracoErrorLogItems"] stores the error details. Option #1 uses Dictionary<T> while Option #2 uses general object.

Then, open the /default.aspx page of the website’s root directory and put the following code bits.

<script runat="server">
	protected void Page_Load(object sender, EventArgs e)
	{
		var logs = Context.Items["umbracoErrorLogItems"];
		if (logs != null)
		{
			foreach (var log in logs)
			YourLogHelper.SaveLog(log);
			Context.Items["umbracoErrorLogItems"] = null;
		}
	}
</script>

Once the page is loaded, if there is any error log details found from HttpContext.Current.Items["umbracoErrorLogItems"], the highlighted log saving method will be executed. Once all the error log details are saved, the Context.Items["umbracoErrorLogItems"] has to be cleared for further use.

That’s what I’ve found so far. I know modifying the core source code is not the ideal solution, but it this case might be excused.

Written by Justin

06/03/2012 at 18:01

Posted in For .NET

Tagged with , ,

How to Restore Data to MS-SQL Server 2008 from MS-SQL Server 2008 R2

Like other DBMS, MS-SQL Server doesn’t support backward compatibility, in regards to the database backup and restore function. So, it’s not possible to restore data to MS-SQL Server 2008 (SQL 2008) from the MS-SQL Server 2008 R2 (SQL 2008 R2) backup. Officially SQL 2008 has its version number as 10.0 and SQL 2008 R2 has 10.5. However, instead of using the backup and restore function, we can simply generate SQL script to handle the database schema and its data. This is how we make this possible.

Step #0. Open the MS SQL Server Management Studio (MS-SSMS).

Step #1. Select the database you’d like to create script and right mouse click, and you’ll see the menu below.

Step #2. Now, click the “Generate Scripts…”, and “Generate and Publish Scripts” wizard will be popped up. Click “Next”.

Step #3. Select appropriate option. Here, we’ll choose the first option, “Script entire database and all database objects”. Click “Next”

Step #4. Choose the output option. We can simply select to save the script to our local machine or screen. Click “Advanced”.

Step #5. This is the most important step. Select the red boxed options accordingly. For fresh restore, all objects must be dropped and re-created. Therefore,  choose “Script DROP and CREATE” option. Server version must be “SQL Server 2008″ as we’ll run this script on SQL 2008. Finally, “Schema and data” must be chosen as we’ll restore all objects and their data. Then click “OK”.

Step #6. Once the “Advanced” option is set, you’ll see the Step #4 screen again. Click “Next” and you’ll see the summary screen. Click “Next” again.

Step #7. The wizard creates the script we need. Click “Finish” and you’ll see the generated script on your screen or in your specific location.

That’s it! It’s not the perfect or desirable way to restore data to SQL 2008 from SQL 2008 R2, but useful workaround. If you get some error while you are running the generated script on SQL 2008, you might need to modify running order in the script.

Written by Justin

01/03/2012 at 11:05

Posted in For Database

Tagged with , , , ,

How to Connect MS-SQL Server from Virtual Machine

Let’s say there is a server environment up and running on a virtual machine – regardless that it is MS Virtual PC, VM Player or whatever. The server environment is only for web sites. Let’s say that a database development server is installed on a local machine, not on a virtual machine. The web server needs to have a connection to the database. However, sometimes the database won’t allow the VM’s access, even though “ping” is sent from VM to the local.

In this case, the following is worth checking.

  1. Run SQL Server Configuration Manager from Start > All Programs > Microsoft SQL Server 2008 R2 (or other versions) > Configuration Tools
  2. Find SQL Server Network Configuration > Protocols for MSSQLSERVER (or SQLEXPRESS, or another instance)
  3. Set the protocol – TCP/IP – to “Enabled”

That’s it! Now try to connect the database from your virtual machine. It should be working. All good, mate!

Written by Justin

04/07/2011 at 16:17

How to Save Log While Handling Error in ASP.NET MVC 2

leave a comment »

The built-in Error.aspx page provided by ASP.NET MVC 2 is pretty convenient as developers don’t need to worry about handling an error when it occurs. However, the page is just displaying “THERE IS AN ERROR!”, not anything else. Typically developers and their clients want to know why errors have occurred, but also don’t want to expose the error details to general public. In order to achieve this, error logging to a text file or database is commonly used.

The Error.aspx page has a model instance typed System.Web.Mvc.HandleErrorInfo. As soon as an error comes up while processing data in a controller, if the action gets the [HandleError] attribute set, the error object is immediately thrown to the model. So, error saving function should be implemented before the exception is thrown to the model.

First of all, we need to prepare a base controller class inherited from System.Web.Mvc.Controller.

[HandleError]
public abstract class BaseController : Controller
{
	protected string BaseUrl { get; private set; }
	protected string PublicUrl { get; private set; }

	public BaseController()
	{
	}

	[HandleError]
	protected override void OnException(ExceptionContext filterContext)
	{
		base.OnException(filterContext);

		this.SaveLog(filterContext.Exception);
	}

	[HandleError]
	private void SaveLog(Exception e)
	{
		using (StreamWriter sw = File.AppendText(System.Web.HttpContext.Current.Server.MapPath("~/logs/error/log-" + String.Format("{0:yyyy-MM-dd}", DateTime.Today) + ".txt")))
		{
			sw.WriteLine("--------- " + Convert.ToString(DateTime.Now) + " --------- --------- --------- --------- ---------");
			if (e != null)
			{
				sw.WriteLine("Message: " + e.Message);
				sw.WriteLine("Stack Trace: ");
				sw.WriteLine(e.StackTrace);
				sw.WriteLine("");
			}
			sw.Close();
		}
	}
}

Please note that the base controller overrides the OnException() method, which triggers when an exception is thrown. So, the overridden method will call the SaveLog() method. Within the SaveLog() method, you can whatever you want to do.

Written by Justin

30/06/2011 at 15:09

Posted in For .NET

Tagged with , , ,

In case of having troubled with Sony Ericsson MW600 Bluetooth Headset

leave a comment »

Reference: Sony ericsson MW600 bluetooth driver for Windows 7 ?

I bought a bluetooth headset from eBay a week ago for my iPhone. It was perfectly fit to my phone but not for my laptop running Windows 7 Professional (x64).

According to the post linked above, Windows 7 doesn’t provide a proper driver for this product and Sony doesn’t either. Even worse, both parties wouldn’t consider this product. What a shame! However, a good news is that the bluetooth driver for Lenovo laptops are also suitable for other vendors’ laptops to figure this issue.

Solution? So simple. Go to the post above or directly download the bluetooth driver from here (http://download.lenovo.com/ibmdl/pub/pc/pccbbs/mobiles/7zbv14ww.exe), install it and reboot your Windows 7. After your Windows 7 being rebooted, find or update your bluetooth driver to Broadcom. That’s it.

Written by Justin

28/11/2010 at 23:00

Posted in For Windows

Tagged with ,

Lentil Soup

leave a comment »

Well, let’s start being a master chef!

This is my – not a first time, though – recent cooking. :-)

Lentil Soup - Ingredients

Lentil Soup - Ingredients

Lentil Soup

Lentil Soup

Seems to be easy, doesn’t it? Here’s my crappy recipe.

  • Grab any veggies from a fridge.
  • Chop everything.
  • Stir and fry them. Good to stir/fry bacons and onion first then the others later.
  • Stir/fry even lentils.
  • Pour water and boil. Try small amount of chicken stock with preference.
  • Boil.
  • Keep boiling.
  • Keep boiling until enough.
  • Done.
  • Enjoy!!

Easy!!

Written by Justin

25/10/2010 at 18:47

To-do list for this week

leave a comment »

Obviously both WordPress and CodeIgniter are very popular framework for PHP developers. Both are quite different from each other, though, there must be a way to integrate. Well, let’s have a look.

  • To develop the integration tool between WordPress and CodeIgniter by web services
  • To separate the login for admin by WordPress from the site login for general users by CodeIgniter
  • To customise Twitter Tools, in terms of displaying date – should follow the WordPress setting
  • To fix the CSS for the Disqus comment box

What else? Too many? Let’s do this!

Written by Justin

20/10/2010 at 09:55

Posted in As Chronicles

Tagged with ,

Bypassing 404 Error Page on IIS

leave a comment »

References

If you are using a web hosting company to run your own web site, sometimes you are experiencing unwanted 404 error page that is provided by the hosting company, which is hardly customisable, especially in IIS environment.

However, web.config of IIS is possible for site owners to bypass the 404 error page and show their own 404 page or a solution-generated 404 page like what WordPress does. It’s super simple. Open web.config of your root directory and add the following line within <system.webServer>...</system.webServer>:

<httpErrors existingResponse="PassThrough"/>

That’s it!

Written by Justin

13/10/2010 at 15:02

Posted in For Windows

Tagged with ,

Moving into WordPress

leave a comment »

Welcome to AlienCube Networks. This is your first post. Edit or delete it, then start blogging!

So far, I’ve been thinking of moving my blog systems from Tistory to WordPress. Now, I got the backup file of Tistory and playing with this.

Coming sooooooooooooooooooooooooooooon~

Written by Justin

10/10/2010 at 20:44

Posted in As Chronicles

Tagged with

Follow

Get every new post delivered to your Inbox.

Join 669 other followers