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 =
              FormsAuthentication.Decrypt(authCookie.Value);
            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);
                        Response.Cookies.Add(faCookie);

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


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:



<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <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"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>


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

User.GetIdentity().DisplayName

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!

Color:

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.

Brightness:

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~~~~

Weight:

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 () {
   @Override
   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() { 
@Override
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:

@Override 
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:

http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

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
 }
 
 @Override
 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.