Tuesday, December 4, 2012

[.NET] I don't have time for this. POCO Generator, Function Imports, Returning None

1. Used POCO Generator to create Function Imports
2. Had a Function that returns none
3. POCO Generator does not generate Functions that return none.


Alright, this was such a headache, but thanks to Matt Johnson in this stack overflow link:

...problem was solved.

Here is the Function Import region of the .tt file:

region.Begin("Function Imports");

        foreach (EdmFunction edmFunction in container.FunctionImports)
            var parameters = FunctionImportParameter.Create(edmFunction.Parameters, code, ef);
            string paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
            string returnTypeElement = edmFunction.ReturnParameter == null
? null : code.Escape(ef.GetElementType(edmFunction.ReturnParameter.TypeUsage));

    <#=Accessibility.ForMethod(edmFunction)#> <#= returnTypeElement == null ? "int" : ("ObjectResult<" + returnTypeElement + ">") #>  <#=code.Escape(edmFunction)#>(<#=paramList#>)
            foreach (var parameter in parameters)
                if (!parameter.NeedsLocalVariable)

        ObjectParameter <#=parameter.LocalVariableName#>;

        if (<#=parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"#>)
            <#=parameter.LocalVariableName#> = new ObjectParameter("<#=parameter.EsqlParameterName#>", <#=parameter.FunctionParameterName#>);
            <#=parameter.LocalVariableName#> = new ObjectParameter("<#=parameter.EsqlParameterName#>", typeof(<#=parameter.RawClrTypeName#>));
        return base.ExecuteFunction<#= returnTypeElement == null ? "" : ("<" + returnTypeElement + ">")#>("<#=edmFunction.Name#>"<#=code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))#>);


Monday, November 19, 2012

[PHP/MySQL] Amazon EC2, Elastic Beanstalk, RDS setup

Basic setup of using these three services in.....haaaarrrmony. I'm using WinXP.

1. Setup EC2 instance
2. Setup Elastic Beanstalk with GIT (Tested with PHP projects)
3. Setup RDS to be used with MySQL Workbench

1. EC2 Instance
   Just follow the instructions and CREATE and DOWNLOAD your key/pair. Creating your instance is the only time you can assign a key/pair to it, let alone download it. Take note of the security group you are using for it. Also, go find your internet IP and add it to the selected security group.

2. Elastic Beanstalk
   This is basically your web host that you deploy to. Download GIT and the CLI Package (http://aws.amazon.com/code/6752709412171743). Find GIT on Google and the CLI Package in the Elastic Beanstalk documentation. Install GIT and run the CLI Package according to the instructions in the archive. 

Configuring Beanstalk for file uploading/deploying:
Go to your working folder in command line.
First, type eb init
Follow the instructions and you can find the your credentials here: https://aws-portal.amazon.com/gp/aws/securityCredentials
After you're done, enter the command: eb start

Now, you should be able to run git commands. Usually, this is the sequence I use:
1. git add .    (adds all files/folders/sub-folders)
2. git commit -m "<your message>"
3. git aws.push

3. RDS
1. Choose/create a database instance you would like to work with.
2. Go to the DB Security Groups section.
3. Add a new connection type of EC2 Security Group and choose the same one used in your EC2 Instance. You may also want to add a new CIDR/IP address using an IP finder.
-- MySQL Workbench
4. Setup a New Server Instance
5. Select Remote Host and input the address of your EC2 instance.
6. Select SSH type of connection
7. For SSH user, put ec2-user if using Amazon or ubuntu if using Linux
8. SSH password is not required.
9. Use the key/pair generated earlier
10. Enter the rest with the DB Instance info.

After all that, you should be good to go. Cheers

Monday, October 29, 2012

[.NET] Updating Detached Objects in Entity Framework

Here's the scenario.

An object is being passed like this

  1. Object gets pull from the database through the Business Logic layer and WCF, as well as getting converted into a detached object.
  2. Values are changed in the Business Logic Layer.
  3. Object gets passed back into the WCF for an update.
I've seen several ways of how a detached object could be updated. Previously in the data access layer, I was retrieving the original object from the database and getting the object again by the original's entity key. Then updated the values and applied the changes. It looks something like this:

using (MyDBContext db = new MyDBContext ())

                    My_Object obj =  db.GetObjectByKey(GetObjectFromDatabaseByID(id).EntityKey) as My_Object;

                    obj.Name = <newName>;

                    if (obj != null)
                        db.ApplyCurrentValues("My_Object_Table_Name", obj);
                        return "Succesfully Updated!";
                        return "Record Does Not Exist.";

So one thing, the method that surrounds this code is only passing an 'id'. There is no objects coming in. Therefore, the object would have to be retrieved again to use its Entity Key to grab the object again, except with an attached state. Another parameter that was passed into the method was the newName. So this newName variable has to be assigned to the new attached object. Only then, we can apply and save the changes. Yes, this is a crude way of doing it, but it works.

Recently, I found a new way of handling an update. So what if we pass in a whole object? Will we have to consider the change of all members of the object? What if the object has 50 members? Well, coding will definitely suck. This method was posted on MSDN, so I'm just going to take it as a valid strategy, and it goes something like this:

 EntityKey key = default(EntityKey);
                object originalObj = null;

                using (MESDataModel.e_MESEntities db = new MESDataModel.e_MESEntities())
                    key = db.CreateEntityKey("KIT_Part", ct);

                    if (db.TryGetObjectByKey(key, out originalObj))
                        db.ApplyCurrentValues(key.EntitySetName, ct);
                        return "Succesfully Updated!";

                        return "Record Does Not Exist.";


In this situation, we are creating an entity key out of the passed in object. If it already has a key, then it will return the original instead of creating a new one. Similar to the first method, we are using the key to retrieve an attached object. At this point, the attached object and the passed in object now has the same keys. Call ApplyCurrentValues and the data from the passed in object will write to the attached object within context. This is pretty much MSDN's definition of what ApplyCurrentValues does. Save changes and everything should work. Hope this kind of helps.

Hmm, Okay, what about using DetectChanges?
This method seems to be good, if you are pulling straight from the database, writing new values, and saving it back to the database. No detached objects involved here. If there is a way to use this method with cross platform in mind (Android, iPhone), please let me know.

Saturday, October 6, 2012

[SQL/MySQL/.NET] Setting databases for .NET usage

After setting up WCF services and having my android devices consuming it, I wanted my WCF to be the layer that communicates to a database resource. At first, I had a hard time with getting started with SQL Server, so I went with MySQL instead.

NOTE: In your IIS, make sure the ASP.NET 4.0 Application Pool "Identity" is set to Local System. This is the reason why SQL Server wouldn't go so smooth at first, but I will discuss details later.

MySQL setup:

1. Download MySQL server installer, MySQL OBDC connector, and MySQL Net connector. Optionally, download the Workbench, which provides a GUI solution for handling SQL functions. If you're lame like me, you would use this tool.

2. Set up your tables using Workbench or commandline.

3. In Visual Studio, add a new ADO.NET Entity Data Model and point to your MySQL Server when prompted. If you don't know the server name or IP Addy, you can always go to the Workbench and see the properties there. Mine was Follow through with creating the .edmx file.

4. Now you should see the newly created entities right in front of you. The name of the object is exactly what the header of the entity is. So you can instantiate it like:

User objUser = new User();

Of course, we don't want to instantiate like this, but rather grab the info from the database and create the object then. We will use LINQ to do so.

 Now look for Entity Container Name in the properties of your .edmx file. This is the object you use to connect to the database. So lets just put 2 and 2 together with the entity object included:

MyDBEntities db = new MyDBEntities();
List<User> users = ( from p in db.Users select p ).ToList();

This should select all users from a "Users" table and return it as a list of User objects.

Run the WCF Test Client and test if it works.

SQL Server setup:

Okay, if you installed SQL Server 2008, I believe that it should've created an instance of SQLEXPRESS. So we will just go with this default setup, although, you might have set up another instance, you'll just have to remember the server name for that one.

So by default, your instance of SQLEXPRESS should be your <computername>\SQLEXPRESS. (ex. KETTLEPOT-PC\SQLEXPRESS).

Create tables in SQL Management Studio (Free) by using the server name.

From now on, follow step 3 from the MySQL setup section to configure everything in VS2010.

 Now, if you're getting the "underlying provider" error when you run the WCF Test Client and invoke your method, check out the "NOTE" at the beginning of this post.

Hope that helps!!!!

[Andoird/.NET] Android and WCF template

I've been working a lot with setting up WCF locally. Now it is time to do the true test and connect my android with the sucka!

To set up the WCF, just follow this post:

Setting Up WCF in Virtual Directories

All you need is Android and Eclipse set up. Also, get the KSoap plug-in and add it to your library. Now just add this to your code:

 private static String SERVICE_URI = "";

 private static final String METHOD_NAME = "GetData";

 private static final String NAMESPACE = "http://tempuri.org/";

 private static final String URL = "";

 private static final String SOAP_ACTION = "http://tempuri.org/IService1/GetData";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);


 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

 envelope.dotNet = true;
 HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
 SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
 String resultData = result.toString();

EDIT: Btw, the request.addProperty method is a parameter of your method. And if you don't know your namespace, look at the wsdl of your service. This was done to target an Android 2.2 device. If you noticed, I was using the template VS2010 gives when you create a new Web Service.

Also, I tried using HttpResponse and HttpEntity, but I got no response when I tried to do something like I believe it has something to do with the binding. By default, WCF uses WSHttpBinding I think. I tried changing to BasicHttpBinding, but the configuration had issues finding MetaData. That is it for now.

Friday, October 5, 2012

[.NET] Setting up WCF in Virtual Directories of IIS

Alright, this one was an adventure for me. So this info will be here for the next time I need to set up WCF in a virtual directory. This tutorial will start from the beginning, which is installing IIS. This is assumed that Visual Studio 2010 is already installed. So let's get started with the list:

1. Install IIS through Programs and Features. If you're feeling lazy, just try to install as much of the IIS options you can check. Otherwise, you just need ASP.NET under World Wide Web Services. This will auto-check dependencies as well. And IIS Metabase under IIS 6 Management Compatibilty. Also, you will need to go under the Microsoft .NET Framework 3.5.1 section, which is separated from the IIS section btw, and check both boxes under that. They should have the description with Windows Communication Foundation within it.

2. Make a new wcf service project or open an existing one. Go to it's project properties. Under the Web tab, select he use local IIS option. When you save, it will create the virtual directory for you. There are other ways to deal with the virtual directory like publishing, or adding it directory in the IIS manager. It is up to you.

If you get an error when you try to save the project properties, check if you have all the IIS components installed. VS2010 does a good job telling you what you need anyways.

Hmmm, that seemed to be a short list. But here are some problems + fixes that you may have to encounter.

Errors you may have encountered:

1. "Something about having a duplicate handler in your web.config". What happened here was that I tried to add a handler myself before installing the WCF stuff under Microsoft .NET Framework 3.5.1 section. Therefore, IIS couldn't even populate it's integrated handlers, let alone, let me add any more handlers. So I had to edit the web.config manually by copying it outside it's original directory, removing the handler, and then moving it back into the original directory. It will not let you edit it if you open it within the original directory.

2. 404.17: The requested content appears to be script and will not be served by the static file handler.

Check if you installed all the necessary components for IIS and WCF. You may have to run aspnet_regiis.exe -i under the command line if you have ASP.NET 4.0. After doing this, WCF should run smooth and you should be able to see the .svc file in your browser as intended.  This solution may be different if you are running an older version of ASP.NET.

3. Make sure  the application pools between the website and your virtual directory are ASP.NET 4.0. I haven't thoroughly tested this one out yet. I changed the website to ASP.NET anyways just to be safe. 

Local Host Stuff 

 If you tried to access your IIS or .svc from another computer, you may find that it will not connect by timing out or what not. This may be caused by the firewall. If you are using Windows Firewall, find and enable the inbound rule for World Wide Web Services. The port should be 80.


When on another computer, you may not want to type in just to get to connect to your service. You may want to type in http://MySite instead. This will be controlled in a DNS Server. The DNS settings should be located in your router firmware.

Thursday, October 4, 2012

[.NET] Unexpected error occurred in the .NET Framework...blah blah

  • An unexpected error occurred in the .NET framework data provider for Microsoft SQL Server Compact 3.5. Please contact the provider vendor to resolve this problem.

    If you're getting the error above, while trying to view your connections or trying to generate a new entity data model, try this:

    Go to your registry.
    Navigate to:
    And delete anything that has .NET framework data provider for Microsoft SQL Server Compact

Wednesday, September 19, 2012

[.NET/IIS] Tired of opening up a web service just to run it? Use Virtual Directories!

Alright, so lately I've been working a lot with web services and one the major gripes is actually running the darn things. At first, I always had to open VS2010, open my project, and then right click the solution that contains the svc, and click view in model browser. Being that I'm currently on windows XP, this whole procedure was not pleasant. Then I found out how to activate it through a batch script. The batch script looked like this:

@echo off

set webserverpath="C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\WebDev.WebServer40.EXE"

set webservice="C:\Workspace\MyWebService"

start "" %webserverpath% /port:3934 /path:%webservice%

To add more web service solutions, I just had to new variables and commands under WEBSERVICE PATHS and COMMANDS. Although, this saved me A LOT of time compared to the first method, it was still a hassle just click the little bugger. Also, when a web project gets deployed on a server, there may be instances (maybe all instances) where the web services are needed to be running at all times. So if you configure your localhost to be the same way, then there shouldn't be any hassles when deploying code on the server (for example, the need to change the web.config).

So here's how to do it:

Go to your IIS. So under where you have Web Sites, and maybe Default Web Site, add a new virtual directory. Assign the path to where your .SVC file or web service project is located. Now go back to your web app in VS2010, and open up the web.config. You may need to add or edit the necessary endpoints. Right now, my endpoint address looks like, "http://localhost/MyWebService/WebService.svc". After that, you should be good to go and should never have to run or edit your webservice....hopefully...yea

Edit: If you're running .NET 4, make sure your application pool for your web service is also version 4 in the IIS and ASP.Net tab of your service.

Thursday, June 7, 2012

[HTML] Divs no wrap in Doctype 4.0 Transitional for IE7

So you're making a menu and you're forced to use Doctype 4.0 Transitional. This means that min-width will not work for you if you are doing this for IE7. So for fancy stuff like a menu bar, the elements will start stacking underneath each other as the window is resized. I believe min-width may work for Google Chrome, I'm not sure.

I won't put any code here in the mean time since I'm at a very special place, so I'll try to give an idea as best as I can.

My goal was to make a horizontal menu to look like this:

| ---------------------------- page width = 100% --------------------------------------------|

|  Home |  Links |  About Me |                                                                                              

Let's break it down (3 parts) and give them the needed CSS values.

1. Wrapper

border-top: whatever u want
border-bottom: whatever u want

2. Wrapper of the actual menu elements ( no visual representation here)
width:Choose a value that extends the width of the accumulated menu elements

3. Actual Menu Elements
| Home | Links | About Me |
float: left
border-left: whatever u want
border-right:whatever u want

That's ittt....

Next up is blocking a floating right div. So say you have a layout like this:

|                                                                                                                            float item |
|                                                                                                                                           |

So when you resize it, it will look like this, which is not desired

| at item|

So you want to block it the float at some point to keep it from moving left. I haven't figured that out yet so stay tuned.

Thursday, May 10, 2012

Gone Wireless! With the Logitech M510 and K270

Finally converted to the wireless input setup! Before, I was afraid of terrible input lag and bad range based on newegg/amazon reviews. I guess some people just didn't take care of their products or didn't have any luck. Anyways, lets go on with the brief review of these products.

 Before this mouse, I impulse bought the Marathon Mouse. I think the model was M705. So here's the list of features of the Marathon Mouse and things I'd like to point out:

+3 Hour battery life
+Ergonomic feel (when I tried it at best buy)
+ Frictionless scroll wheel

- Cramped my hand after some use. It's not like my IM Explorer where I can just lay my hand on the mouse. I had to sort of claw grip it since my hands are big.
 - Sensor was off-centered to the upper right of the mouse (facing down). This was the main reason I exchanged this product with the M510. Normal browsing was a hassle, even for just click programs on the taskbar and desktop. The mouse pointer goes along an unusual arc when the mouse is pivoted and translated. So in order to get accurate motion, you have to keep the mouse straight.

After getting the 510, here is what I noticed:

+Good battery life. I really don't mind changing the batteries at least every year.
+Better ergonomic feel. It's better for me to claw grip a mouse that is mostly symmetrical.
+Sensor is still off-centered, but only to the right (when mouse is facing down). There is still a slight arc when I pivot the mouse. It still throws off accuracy, but it is way more tolerable. For serious gameplay, I would just use a mouse with a centered sensor. But I use this mouse for messing around in games like LoL. I haven't tried it for FPS, but I imagine it wouldn't be the best experience.
+Range is awesome. Could be used from across the other end of my room and into the bathroom. Of course, there has to be nothing in the way. In my case, my desktop is in the way since I put the receiver in the back, but a wall will totally hinder the connection.

- Off- centered sensor


This keyboard has the basic layout, with basic keys (non-flat). The keys are a bit cramped together so that when I rest my fingers on ASDF, my pinky hangs on the left edge of the 'A' key as if it is about to fall off. This doesn't really hinder my typing though. Once I start stroking (lol), I'm still capable of hitting all the keys accurately.

A surprise was how responsive the keyboard is. I decided to give a Stepmania test and I was pinning down Flawless points as if I was on my wired keyboard. This was a major plus for me. Also, the range is just as far as the mouse.

The construction does feel a bit cheap though. When I hold it, it feels like it would break easily. For example, it would snap all the way through the internals if I step on it lightly. The good thing about this, is that the keyboard is super light and small. So it would be easier to carry around for LAN parties.


I'm completely happy with these purchases. Once I find a cheap wireless logitech mouse with a unifying receiver that has the mouse sensor in the middle, I will purchase it immediately. But for now, I'm pretty satisfied going wireless and I wish I would've done it sooner.

[C#] Visual Studio Database woes...

Site is on one domain and I need to remotely connect to an SQL Database.
- In the Server Explorer, connecting to the SQL Database uses Windows Authentication.
- With Windows Authentication on, produces untrusted zone error.
- With it off, produces failed login error.

The fix?
- Connection string format:
"Data Source=<source>;Persist Security Info=False;Initial Catalog=<initial_catalog>;Trusted_Connection=Yes"

- In Web.Config, add
       <identity impersonate="true"/>


Sql Db Type is numeric, but how to express it in C#?
- Use Decimal


How to express VarChar(MAX) in C#?
- SqlDbType.VarChar, -1


Wednesday, May 2, 2012

Sony Ericsson C901 vs W810 photo comparison

 I'm going to start posting random photos from the C901 in my new Flickr here:

Yea, I know that this is an unfair battle, but there may be people out there still living in the k750/w810 world. Below are samples ( First pic of set is w810).

When taking the pic of the jacket, I set the EV to about -1.7 on the C901. On the W810, I changed the EV, but it didn't have much effect. Also, the colors on the C901 were close to what I see with my eye. It's a little on the cool side. The real color is a bit more yellowish. You can take the C901 pic of the jacket and in Photoshop, enter the color balance mode and adjust the yellow to 80% to the left while the preserve luminosity option is unchecked.

In the pics with the guitar, it seems that the w810 showed better color. Notice how the wall in the background is a bit blue-ish on the C901 pic. I guess that is the "cool" trait that it has.

Samsung Attain 4G

[Samsung Attain 4G]
I put pics from this phone for fun. It did pretty well and is more tolerable than the W810. The C901 still has better color reproduction, and the guitar is a bit saturated in the Samsung phone. As far as sharpness, it is hard to tell at this point. As you can see on the little "grid circles" on the bed sheet, the C901 shows it more clearer. This probably means there were different focal points, which probably means that the C901 might have a focusing problem, since I know I didn't aim at the bed.

So the pics speak for themselves. What about the rest of the features? In the eyes of a daily user, both phones pretty much function the same, especially in navigation. I do notice a difference in sound quality, which the C901 wins.

The camera fps and quality is way more tolerable. The quality is probably not that friendly for the hardcore youtubers that require 720p and up.

Physical feel? Maybe the user before changed the C901 keypad or something cause the tactile pressure seems uneven. It seems to have a more "clicky" feel near the center of the pad, which loses that trait near the edges. Also, since the C901 is thin, adding a plastic case actually makes it feel a bit nicer for people with big hands. Adding one on a W810 just made it uncomfortably beefy.

Battery life? I can go 3 days without charging with my W810 with minimum activity. It beats going only half a day with Android. I haven't tested the battery life on the C901 yet, but I'll update this blog with it later.

Price? I can score the w810 for under 30 bucks which includes shipping. That's pretty good for cellphone, flashlight, decent camera, music player (which sucks a lot of battery juice btw, don't know if the C901 will), durability, and battery life. I scored the C901 for about a 100, which was an impulse buy when I saw that Buy It Now price. So was it worth it? Well, I'll just have to find out and update this blog....

...anyways, that's all for now!

Saturday, April 21, 2012

[.NET] Could not find System.EnterpriseService....more problems :(

I recently had to do a System Restore, which pretty much messed up the .NET assemblies by actually removing them from the C:\WINDOWS\assembly folder. So when I ran my projects, it would say that the System.EnterpriseService.dll could not be found. Now, I do not have admin in this particular system, so from what I read, I couldn't just drag and drop the System.EnterpriseService dlls into the C:\WINDOWS\assembly folder. So here is the other work-around.

For .NET 2.0 and below, go to C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\

The v7.0A might be another number, but all is good if you can access the bin folder and find 'gacutil.exe'.

If you find that run the command line and run:
gacutil.exe /i <path-to-System.EnterpriseService.dll>
For .NET 4.0, go beyond the bin directory and go to the NETFX 4.0 Tools directory. In the command line, run:
gacutil.exe /i <path-to-ASP.NET 4.0's System.EnterpriseService.dll>

Tuesday, April 17, 2012

[.NET] MVC 3.0, Razor, Custom Principal and Identity

The goal here is to render user info such as the full name instead of the user login name. I'm thinking that I could've used static classes or store info in the Global file, but I wanted to avoid doing those regardless. So lets get started.

You'll need to make a custom Principal and Identity classes, where the Identity contains additional info. These can be these class files anywhere you want. Or declare it some security class file and just make the classes in there.

Principal class:

public class CustomPrincipal : IPrincipal
        private CustomIdentity _Identity; 
        public IIdentity Identity 
            get { return _Identity; } 
        public CustomPrincipal(CustomIdentity identity) 
            _Identity = identity;
        public bool IsInRole(string role) 
            throw new NotImplementedException(); 

Identity class:

public class CustomIdentity : IIdentity
        private string _UserName;
        private string _DisplayName;
        private bool _IsAuthenticated;
        private Roles _Role;

        public CustomIdentity(string username)
                _UserName = username;
                _IsAuthenticated = true;
                _Role = Roles.Admin;

        public string AuthenticationType
            get { return "custom authentication"; }

        public bool IsAuthenticated
            get { return _IsAuthenticated; }

        public string Name
            get { return _UserName; }

        public string DisplayName
            get { return _DisplayName; }
            set { _DisplayName = value; }

        public Roles Role
            get { return _Role; }

    public enum Roles
        Admin = 1,
        User = 2,
        Guest = 3

If you noticed the Roles class, ignore that. I won't be going over it until a next update.

Now go to your Global.asax file and add this method:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
            // Get the authentication cookie
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];

            // If the cookie can't be found, don't issue the ticket
            if (authCookie == null) return;

            // Get the authentication ticket and rebuild the principal 
            // & identity
            FormsAuthenticationTicket authTicket =
            string[] roles = authTicket.UserData.Split(new Char[] { '|' });
            CustomIdentity userIdentity =  new CustomIdentity(authTicket.Name);
            userIdentity.DisplayName = authTicket.UserData;
            CustomPrincipal userPrincipal = new CustomPrincipal(userIdentity);
            Context.User = userPrincipal;

Being a stateless application, these classes get called when a page loads. So this method gets called to make sure the current user is authenticated. Also, notice where the userIdentity stuff is at. I used the FormsAuthenticationTicket UserData property to store a string of data. I guess if you have more than one data you want to store, you can separate the literal by commas and parse it later.

In the controller, lets say the AccountController that appears in the default templates, go to the LogOn method that has the HttpPost attribute. Here you want to do all your login comparisons, whether you are using a stored procedure of an external database or by other methods. In the end, you'll want to create your FormsAuthenticationTicket here. And here it is:

FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(15), false, "Phil Jackson");
                        string encTicket = FormsAuthentication.Encrypt(authTicket);
                        HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

                        string redirectUrl = FormsAuthentication.GetRedirectUrl(model.UserName, false);

The last parameter in the FormsAuthenticationTicket constructor is the user data string. So I hardcoded the name for this example, but you can retrieve strings of data from a database and use them here.

If you run it now, everything should work, but you still cannot render the name yet. So the idea is to create an Extensions class. These classes allow you to add more fields when using Razor. For example, we want to use User.DisplayFullName instead of User.Name. DisplayFullName is not a member originally so that is where extensions come in.

So you can create a new class, which can be stored anywhere as well:

public static class PrincipalExtensions
        public static CustomIdentity GetMyIdentity(this IPrincipal principal) 
            return principal.Identity as CustomIdentity; 

It's pretty obvious what this method does so no explaination is needed here. But we cannot use this yet. I guess, that we have to "reference" or "add the namespace" of the class in the View's Web.config. And here it is:

    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="IR_Project.Security"/>

Now we can use it!! Just do something like:


Sunday, April 15, 2012

Journey, From AMD to Intel

Finally suckered into going to the darkside. Micro Center just had a good deal for an i7 2600k for $200 bucks and it also knocked down $50 bucks for certain motherboards. So, I only bought the cpu and an Asus p8z68-LX mobo for $70. This came up to $290 for everything.

I hoped that it was going to be a quick install, but there came some huge problems. When I had everything attached and fired up, the mobo wouldn't post. A red light would just stay on by the RAM slots, which meant something was wrong up in this neighborhood. So it came down to using only ONE RAM slot, which caused the mobo to finally post, but running dual channel was a no go. I did every possible combination, so I'm sure the RAM slots were shot.

Being disappointed, I wasn't expecting more disappointing things to happen. When I took the CPU off, about 5 pins were bent like crazy. I looked up what can be done to solve this problem before I take a stab at it, and I only found that it's EXTREMELY difficult to get it returned/exchanged/RMA'd once the pins are bent. So I said, screw it and I actually got most of the pins straightened except for one pin that had a broken tip. Just for curiosity, I put back the CPU on, but it failed once again.

So being that I wanted the processor installed ASAP, I went back to Micro Center to attempt an exchange, which failed. The clerk quickly noticed the bent pins and sent me off. Being very disappointed, I might as well finish the build and by and new Mobo, which is a Gigabyte z68apd3.

This added $100 bucks to the bill. Making the whole deal pretty useless at a total of $360 spent. I dug deep into my optimism and told myself that I may still use the motherboard later if I get a cheap 1155 socket CPU, and I just have to use one RAM stick. But before that, I will try to RMA board.

Finally, I was able to successfully install the new board and CPU. My impression? I have yet to see major improvements in speed. This probably most likely due to the bottle necking by my 7200 rpm hard drive. Also, I haven't run any performance tests. So it's really hard to say why I bought this for besides saying that it was a good deal.  I guess later I'll have find out.

Sound quality is punchier and cleaning than my previous ASRock board.  It's a nice little bonus.

I will continue this later...

Wednesday, April 11, 2012

[.NET] IIS - Failed to access IIS metabase

In command line, go to the folder of your .NET Framework version that is specified in the error page. It should be the small text at the bottom. Now type aspnet_regiis -i and you should be good to go. If not, try aspnet_regiis -u and aspnet_regiis -i afterwards. If that doesn't work, then keep trying aspnet_regiis -i. It'll eventually work I guess.

This is for a WinXP SP3 system running IIS 5.1.

Wednesday, April 4, 2012

Monitors Comparisons: LCD and LED so far...

I deleted the old LG E2550 vs ASUS VH236H thread. Just thought it was unfair to judge only 2 very different monitors specifically. So this thread will be a continuous rant of what I notice within the monitors that I have. For right now, I ONLY have the LG E2550 and ASUS VH236H. In future, I shall obtain more!!! So lets get started!


LG E2550T: The colors are very natural, cool, and crisp. When looking at the monitor with just a full screen HD picture loaded, I don't feel like I'm looking into a monitor anymore, but I feel like I'm staring through a window of a different dimension where everything in life is in HD. IMO, this would be perfect for graphic/video artists. I would have to test this with another monitor to see if LG is doing things right, or this is just a property of LED monitors.

On the other hand, the colors do not get vibrant, even if it tried. So when there is a lot of ambient light, especially light hitting the screen, the colors start to go pale and doesn't feel exciting anymore. In majority of cases, this shouldn't happen though.

VH236H: The colors are very vibrant, but maybe too vibrant to the point where colors seem to bleed and come out at you....BRO. For someone that stares at the screen a lot, they probably don't need the eyestrain from vivid colors jumping all over the place. So my configuration is to make the colors as natural, calm looking as possible. I could not get it anywhere as spectacular as the LG E2550T, and I could only reproduce a more pale-ish/gray-ish look. It's still good enough for reducing eyestrain though.

Objects with a yellow-to-orange shading looks very unnatural. Comparing the haystack wallpaper that comes stock in the Windows 7 OS, I notice the orange shading has a strong reddish tone to it, like it seems to be leaking ketchup or something. But I didn't really buy this monitor for this purpose of seeing bleeding ketchup. I will mention its purpose later.

Unlike the LG E2550T, ambient light glare does phase the ASUS! Turn on the elite scenery mode and you get colors that are especially pleasant to the eye. It still bleeds ketchup and it is not natural looking, but the visuals won't be as boring.


LG E2550T: This thing has an extreme contrast ratio. For example, when viewing the image of the haystack that comes stock in the Windows 7 OS, there are no big blobs of bright spots. Now pull up a browser with a web page that has a white background, and you'll be like, "Whoahh, close the shutters!!!!" Now put on a HD picture with the sun, and it really feels like you're staring into the sun! This is with brightness half way!

 I usually have the monitor brightness set to 0 when I'm doing beginner coding, but after awhile, the brightness of a white background still hurts my eyes. I know, I know, just change my background to white, right? Yea, but I'm lazy.

VH236H: This is one of the top reasons why I bought an LCD monitor. I heard the brightness can go loww, loww, low. When I'm coding with low-mid light ambience, I have the brightness at 0. It's kind of like looking at the ink-technology thingie that the old kindle uses, and I can stare at that for hours. When there is lots of light around, I switch to scenery mode where brightness turns up to about 50 I think.

Input Lag:

Okay, I went to some site for this one where you display a stop watch on both monitors. Then take a picture with both monitors in view, and the one that has a higher number has less lag. Here's the site: http://tft.vanity.dk/

I was surprise to see that the LG E2550T kept winning by .01 ms against the ASUS VH236H. I really have nothing more to say about this. 

Monitor Controls:

LG E2550T: Smooth as eggs. Love it and I don't miss tactile buttons on monitors anymore.

ASUS VH236H: Let's just say using the force still causes problems in operating these buttons. I hate them! Luckily, there are savable presets so I can jump from one mode to another without adjust brightness. *CLICK CLICK CLICK CLICK* "YES! WENT FROM 95 to 91!!! 91 MORE CLICKS TO GO!!! SIGGGHHH~~~~


LED monitors only eat slim fast. THUMBS UP!
LCD monitors only eat tacos.
Just for fun.... CRT = http://www.youtube.com/watch?v=jSJQEl5vcAo

Friday, March 23, 2012

Java: A Practical use of Interfaces

On the last post, I used an interface to help call an overrided method when some event is triggered (such as the Back button).

So to jot things down, here is what an interface seems to me.

Button: Overriding onClick example

Okay, so you have an interface like this:

public interface IClass {
      public void methodOne();
      public String methodTwo ( int i );

This is some interface class, and if you haven't worked with interfaces much, then you'll probably be like, "This has no use to me." Anyways, lets try to make some module...hmmm...lets try a Button class.

public class MyButton {
   IClass listener;
   MyButton() {}
   public void onClick() { listener.methodOne(); }
   public void setOnClickListener(IClass listener) { this.listener = listener; }

Now, here's the situation. You created the MyButton in some bigger context class, but you can't override it. For example, in Android, you call in your components statically like this:

(MyButton) findViewById(R.id.mybutton);

This doesn't allow you to override methods like this:

new MyButton () {
   public void onClick() { //do something }

So in times like these, you ask how am I going to customize that onClick method? That's what setOnClickListener is for. You pass in a new Interface into the method like this:

setOnClickListener(new IClass() { 
methodOne() { // do stuff  }

Now since the onClick() function is defined to use the listener's method, it will now run the methodOne that you overrode. So in a way, it's like passing in a method as a parameter.
BUT!!! I just realized....couldn't I have done it with a normal class? Yes. I believe so. So next question is...What is the advantage of using an interface than a class in this situation? Or what is the advantage of implementing an interface that forces you to override all it's methods?

Uses of Interfaces

From what I read, if you app is constantly on update mode, use interfaces since you can implement interfaces as many times as you want like:

public class MyClass implements Interface1, Interface2, Interface3

Or you can extend an interface with multiple interfaces like:

public interface Interface1 extends Interface2, Interface3

Type Casting these babies

Another usage is to connect two different typed objects together by casting. Say you have two class that implements some interface:

public class Ball implements Relatable
public class Car implements Relatable

Where the interface Relatable coded like this:

public interface Relatable {
      public boolean isSofterThan(Relatable otherObject);

Now, if you wanted to make the method isSofterThan work with just the two classes (no interface), you'd have to make specific methods for each class like this:
(Reminder: For the following examples, interfaces is not implemented)
For Ball class:
public boolean isSofterThan(Car object);

For Car class:
public boolean isSofterThan(Ball object);

Now let's say that a class called Plushie comes along, then the Ball and Car class would have to add:
public boolean isSofterThan(Plushie object);

The point here is that you'd have to keep producing more of the same method with different signatures. Now this is where the interface comes in. Assume that each class has a variable called softness. So in each class that now implements Relatable, you can define the isSofterThan method like:

public boolean isSofterThan(Relatable otherObject) {
    return (this.softness > otherObject.softness) ? true : false;

Now that this method is defined in the Ball, Car and Plushie classes. Lets try to use this in actual code.

Ball ball = new Ball();
Car car = new Car();
Plushie plushie = new Plushie();

ball.softness = 5;
car.softness = 2;
plushie.softness =  99999999999999999999;

Relatable rBall = (Relatable)ball;
Relatable rCar = (Relatable)car;
Relatable rPlushie = (Relatable)plushie;

if (rBall.isSofterThan(rCar)) println("Ball is softer than car!"); 
else println("Car is softer than Ball");

if (rPlushie.isSofterThan(rCar) println("OVER 9000000!");

Okay so I will disclaim that I haven't really tested this out. But the main thing to look at is that I type casted two different objects into one similar object, which is displayed in hot, red text. I learned this thing from:


That's it for now... Remember, I'm a programming noob. So help me, don't bash me. :)

Android: Do something after Soft Keyboard closes

Heya, I got this method from one of the stack overflow threads, but forgot to save the link. But I'm just posting the code here for reference as usual.

So this involves making a custom EditText and listener interface.

Interface code:

public interface ImeBackListener {
 public abstract void onImeBack(SearchEditText ctrl, String text);

Now apply this when making your custom EditText:

public class SearchEditText extends EditText{

 private ImeBackListener mOnImeBack;
 public SearchEditText(Context context, AttributeSet attrs) {
  super(context, attrs);
  // TODO Auto-generated constructor stub
 public boolean onKeyPreIme(int keycode, KeyEvent event) {
  if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
   if (mOnImeBack != null) mOnImeBack.onImeBack(this,  this.getText().toString());
  return super.dispatchKeyEvent(event);
 public void setOnImeBackListener(ImeBackListener listener) {
  mOnImeBack = listener;


So when you call this in the code (statically or by creating a new object), just call setOnImeBackListener (new ImeBackListener() { // your code });

"your code" would be whatever you want to change in the activity.

Tuesday, March 20, 2012

Java: File Renaming

In a project, sometimes you get a bunch of files that need to be renamed. They either have same prefix/suffix and it would be a pain to rename them one by one. Being a beginner programmer, I felt obliged to build a quick "script" instead of download an app. So here's the code:

import java.io.File;
import java.util.*;
import java.io.IOException;

class Renamer {
 public static void main(String[] args) throws Exception {
  String path = ".";

  String files;
  File folder = new File(path);
  File[] listOfFiles = folder.listFiles();

  for (File f: listOfFiles) {
   f.renameTo(new File(f.getName().replaceAll("_mdpi","")));


Using Textpad's ctrl+1 and ctrl+2 shortcuts for run and compile, the task becomes easy., but I'm sure that using one liners in other script proggies are faster. I need get around to learning Python or something. Hmmmm....

Android: Timer/TimerTask/Hander/ stopping AsyncTask

Here's a common implementation that I used.

The Handler and TimerTask that is randomly within my activity class.

private Handler mHandler = new Handler();
 private class MyTimerTask extends TimerTask {
  public void run() {
   mHandler.post(new Runnable() {
    public void run() {
     Log.i("MyTimerTask", "Cancelling Search Task");
     if (!stask.isCancelled()) stask.cancel(true);
     toast = Toast.makeText(mContext,"Could not find any locations", Toast.LENGTH_LONG);

I have a Timer global variable in the AsyncTask class, so then I instantiate the timer and run it like this within the Async doInBackground method:

timer = new Timer();
timer.schedule(new MyTimerTask(), SEARCH_TIME_OUT);

In the post execute method, I cancelled the timer. Not sure if the timer will still be running after the AsyncTask is done, so I cancelled it just in case.

In the doInBackground, I could've handled all the code in one section without creating any classes in the activity. So it would've looked like this:

final Handler mHandler = new Handler();
TimerTask mTimerTask = new TimerTask() {
   public void run() {
      mHandler.post(new Runnable() {
          //handle cancelling here
mTimer = new Timer();
mTimer.schedule(mTimerTask, TIME_OUT);

Hmmm, this seems better to use. I'll switch that in my code later.

Sunday, March 18, 2012

Android: ListView, Checkable, ArrayAdapter.....FUN STUFF!!!

EDIT: I needed the list to resize based on the quanity of items. It's rather hard to do it with a ListView. So I actually skipped using the adapter and just went with building rows on a vertical LinearLayout. 

I starting to feel lazy again, so I just copy and pasted the CustomDropDown class and the necessary xml files at the bottom. But here are some notes about the code:

1. Create a CustomDropDown that extends Button. After all, the Spinner is just a button that opens a Dialog. You can copy the whole code at the bottom of this post.

- You might see something like isButtonAutoGen or something like that, setTextOnSelectedItems. These are basically related to showing the selected contents on the DropDown Button. If you look at the image below where the dropDown has text that says "Click to open dialog," then imagine that text is replaced by the values in the list. These values are separated by commas and ellipsizes if the content is too long.

- The method, createList, is where it populates the values into the drop down.

2. So now you just need the layouts for these rows and the dialog itself. I will post these at the bottom of the post as well. Animations and styles are included as well.

3. To use, make a new CustomDropDown. Populate data by passing in a text array or text resource into setAdapterFromResources. If you look at the image below, you will see a "Done" button. You may have to manual give it's clickListener the property to close the dialog.

Other things:  You can set the multichoice mode and singlechoice mode. Both modes will use the checkbox drawable, since I haven't gotten around to using a radio button for the singlechoice mode.

I hope that the code below works for you. I haven't really tested it out by copy and pasting. Anyways, farewell.

Here is what I was trying to do with these playful things:


Create a spinner that opens a dialog from the bottom and stops about half way. The picture shows a Single-Choice mode, but it should be able to convert to Multi-Choice mode where it shows check-boxes instead of radio buttons. Also, the contents inside the ListView must be capable of modification.

Things that need to be created:

- anim, layout, and style XMLs
- adapter, checkable, and button implementations

I'm pretty tired right now...I'll add more to this section. In the mean time, you can refer to this:

The link above helped me on implementing Checkable. This is what binds the View of a row in a ListView to have a checkable state.

Another thing if you use the Single-Choice mode for the list, using the AdapterView.OnItemSelectedListener does not work here. Instead, use AdapterView.OnItemClickListner. This means if you want another component to be affected by the dropdown at the beginning of the activity, you would have to manually set the state of the component. Then the listener will take care of the rest afterwards.

When access data in the ListView, such as the checkbox value, all ways use the "Item Checked" methods. The Item Selected just does not work at all. So use those methods for both Singe and Multi-modes.

Anyways, time to flee......

Full CustomDropDown code:
public class CustomDropDown extends Button {

 private Context context;
 private Dialog dialog;
 private boolean isButtonTextAutoGen;
 private CheckBox[] checkBox;
 private TextView[] textView;
 private int listSize;
 private ListLayout layout;
 private final int TEXT_SIZE = 16;

 public CustomDropDown(Context context, AttributeSet attrs) {
  super(context, attrs);
  this.context = context;
  this.isButtonTextAutoGen = true;
 // Adapter methods
 public void setAdapterFromResources(int array_res) {
  CharSequence[] txt = context.getResources().getTextArray(array_res);
 public void setAdapterFromTextArray(CharSequence[] txt) {
  // Initialize dialog
  this.dialog = new Dialog(context,R.style.Popup_Dialog) {
   public void onDetachedFromWindow() {
    if (isButtonTextAutoGen) setTextOnButtonToSelectedItems();
  this.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {

 private void createList(CharSequence[] text) {
  this.listSize = text.length;
  textView = new TextView[listSize];
  checkBox = new CheckBox[listSize];
  layout = (ListLayout) dialog.findViewById(R.id.listlayout);
  for (int i=0;i<listSize;i++) {
   View row = LayoutInflater.from(getContext()).inflate(R.layout.single_line_checkbox_item, null);
   textView[i] = (TextView) row.findViewById(R.id.text);
   checkBox[i] = (CheckBox) row.findViewById(R.id.checkbox);
   if (i < (listSize-1)) {
    LinearLayout divider = new LinearLayout(getContext());
    divider.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
    divider.setBackgroundColor(Color.argb(160, 160, 160, 160));
 // Getters/setters
 public Dialog getDialog()     { return this.dialog; }
 public void setBoolStringToCheckBoxes(String s) {
  if (s!=null) 
   for (int i=0;i<s.length();i++) {
    if (s.charAt(i)=='1') checkBox[i].setChecked(true);
    else checkBox[i].setChecked(false);
 public String getCheckBoxValuesToString() {
  StringBuilder sb = new StringBuilder(); 
  for (int i=0;i<listSize;i++) {
   if (checkBox[i].isChecked()) sb.append("1");
   else sb.append("0");
  return sb.toString();
 public boolean isNoneChecked() {
  for (int i=0;i<listSize;i++) 
   if (checkBox[i].isChecked()) return false;
  return true;
 public boolean isCheckedAt(int index) {
  return checkBox[index].isChecked();
 public int getSize() { return listSize; }
 public void setTextAt(int index, String text) {
 public String getTextAt(int index) { 
  return textView[index].getText().toString();
 public CheckBox[] getCheckBoxArray() { return checkBox; }
 public void singleChoiceListenerMethod(CheckBox chbx) {
  for (int i=0;i<listSize;i++) {
   final int current = i;
   for (CheckBox b: checkBox) {
    if (b==chbx) b.setChecked(true);
    else b.setChecked(false);
 public void setChoiceMode(int mode) {
 public void setChoiceMode(int mode, int startingPos) {
  if (mode==ListView.CHOICE_MODE_SINGLE) {
   ((TextView) dialog.findViewById(R.id.select_option_text)).setText("Select one");
   // set up listeners to act like single mode
   for (int i=0;i<listSize;i++) {
    final int current = i;
    checkBox[i].setOnClickListener(new View.OnClickListener() {     
     public void onClick(View v) {      
      for (CheckBox b: checkBox) {
       if (b==checkBox[current]) b.setChecked(true);
       else b.setChecked(false);
   // check if none is check at start, set the first value to true
//   for (int i=0;i<listSize;i++) {
//    if (checkBox[i].isChecked()) return;
//   }
//   checkBox[startingPos].setChecked(true);
 public int getSelectedItemPosition() {
  for (int i=0;i<listSize;i++) {
   if (checkBox[0].isChecked()) return i;
  return -1;
 public void setTextOnButtonToSelectedItems() {
  StringBuilder sb = new StringBuilder();
  for (int i=0;i<listSize;i++) {
   if (checkBox[i].isChecked()) sb.append(getTextAt(i)).append(", ");
  if (sb.length()!=0) {
   this.setText(sb.toString().substring(0, sb.length()-2));
  } else {
 public void setIsButtonTextAutoGen(boolean b) { this.isButtonTextAutoGen = b; }


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:text="Select one or more"
        android:text="  Done  " 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"


<style name="Popup_Dialog">
        <item name="android:windowNoTitle">true</item>  
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowContentOverlay">@null</item>  
        <item name="android:windowAnimationStyle">@style/Animations.PopupDialog</item>

<style name="Animations" parent="@android:Animation"/>  
     <style name="Animations.PopupDialog">
         <item name="android:windowEnterAnimation">@anim/slide_in_bottom</item>  
            <item name="android:windowExitAnimation">@anim/slide_out_down</item>

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
 <translate android:fromYDelta="100%" android:toYDelta="0"

<?xml version="1.0" encoding="utf-8"?>