Saturday, August 8, 2015

AngularJS Project Template and Apache 2.2/2.4 setup

On my Github, I've created an AngularJS project template that sets up Grunt, LibSass, and HTML5Mode.

https://github.com/pbrizardo/grunt_libsass_angular_scaffold

Setting up Apache 2.2/2.4 to support Html5Mode

Use Apache's mod_rewrite to forward the index.html for any URL requests through the use of rewrite rules.

1) Put all rewrite rules in httpd.conf.
2) Edit httpd.conf and put rewrite rules in .htaccess

Method 1 will be more convenient since all changes are done in one file.
Method 2 might be convenient for those who want different rewrite behavior in different applications (Never tried this)

Method 1

1. Open httpd.conf
2. Find the Directory tag for the served documents.

Ex. <Directory "/apache2.2/htdocs"> or <Directory "var/www">

3. Add the following rules:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png)
    RewriteRule (.*) index.html [L]

4. Make sure AllowOverride None is set

That's it!

Method 2

1. Open httpd.conf
2. Inside the <Directory /> tag, make sure it has the follow options:

<Directory />
    Options All
    AllowOverride All
</Directory>


3. Change all instances of AllowOverride None to AllowOverride All
4. Open .htaccess file
5. Insert the following at the end of the file

<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png)
    RewriteRule (.*) index.html [L]
</ifModule>

6. If running Apache 2.4, go to the next step, otherwise, you're done!
7. Due to change in new directives access control modules, directives such as Order, Deny, and Satisfy have been replaced

http://httpd.apache.org/docs/2.4/upgrading.html

So you'll find the old directives under the tag  <FilesMatch "(^#.*#|\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|sw[op])|~)$">

Replace all directives with

Require all denied

Tuesday, June 16, 2015

AngularJS, Spring MVC, Tuckey URL Rewrite

I wanted to use html5Mode with an existing Spring MVC backend. This assumes that the front-end code will be deployed as part of the WAR file.
I did the following steps:

1. In Angular, I added the following html5Mode config:

$locationProvider.html5Mode(true).hashPrefix('!');

2. In Spring MVC, I added the Tuckey URL Rewrite Module in the Maven pom.xml:

<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>3.0.4</version>
</dependency>


3. Do a Maven Update 4. Open the web.xml and enter the following within the web-app tag (I left the debug line there)

<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>logLevel</param-name>
<param-value>DEBUG</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>


5. Create a urlrewrite.xml under the WEB-INF folder of the your Spring project and the contents should look like the following:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN"
"http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">

<!--

Configuration file for UrlRewriteFilter
http://www.tuckey.org/urlrewrite/

-->
<urlrewrite>

<rule>
<from>^/mypage$</from>
<to>/index.html</to>
</rule>

</urlrewrite>


And that is it! I had trouble before cause I was using 'index.html' in the 'to' tag instead of '/index.html'

Wednesday, March 25, 2015

[HTML/CSS] Bottom footer for reference

Yea! For once and for all, the bottom footer has been solved. I'm such a noob. Here is my reference to an example:


The only quirk I had once an extra spacing that was occurring at the bottom of the page. To help this, I added overflow:hidden to the wrapper container.

Cheers

Monday, March 9, 2015

NodeJS,SVN Problems

I'll try to spill out my frustrations at the top of my head.

Getting ECONNRESET when doing npm install

Getting this error flag showing up on your screen sucks. To fix, you need to edit the registry URL in the user config file by typing npm config edit and changing the https in the URL to http.

Getting Certificate Expiration date in Eclipse SVN or tortoise

In Windows, search for {User}/AppData/Roaming/Subversive/auth or something along those lines. Delete all the subfolders in the directory, then try to perform actions to the repository. It may ask for your credentials again, so prepare yourself.

Friday, July 25, 2014

[HTML/CSS/Javascript] Floating header/scrollable body

So you want to build something like this....

Header

Scrollable Body

When content vertically overflows, the expected outcome is this (red is the scrollbar):

Header

Scrollable Body

So in the early versions of Internet Explorer, it expresses evilness like so:

Header

Scrollable Body

So yea. The only way to make IE behave properly is to use conditional CSS properties and native javascript. I would use jQuery because I'm noob, but I got too lazy to find the CDN link.

Here is the code below:

<!DOCTYPE html>
<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if (gt IE 8)|!(IE)]><!-->
<html class="">
<!--<![endif]-->

<head>
    <title>Floating Header</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
        #container {
            width: 100%;
            height: 100%;
            position: relative;
        }
        #header {
            width: 100%;
            height: 120px;
            background: blue;
            position: absolute;
            top: 0;
            left: 0
        }
        #content-scroll-container {
            overflow: auto;
            overflow-x: hidden;
            background: black;
            width: 100%;
            height: 100%;
            padding: 0;
        }
        #content {
            margin-top: 120px;
            color: white;
        }
        .tbl-whole-span {
            width: 100%;
            margin: 0;
            padding: 0;
        }
        .tbl-whole-span td {
            background: gray;
        }
    </style>
</head>

<body>

    <div id="container">
        <div id="header"></div>
        <div id="content-scroll-container">
            <div id="content">
                First line of destruction
                <br/>
                <input id="btnAddLine" type="button" value="Add Line" onclick="addLine()" />
                <br/>
                <table class="tbl-whole-span">
                    <tr>
                        <td>
                            Some table contents here.
                            <span style="float:right">Text to the right</span>
                        </td>
                    </tr>
                </table>
                Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>Some content, some content
                <br/>
            </div>
        </div>
    </div>
    <script>
        ;
         // Adjust content width when vert scrollbar appears
        function adjustWidth() {
            var scrollDiv = document.getElementById("content-scroll-container");
            var contentDiv = document.getElementById("content");
            var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
            var newWidth = scrollDiv.offsetWidth - scrollbarWidth;
            var percentageWidth = newWidth * 100.00 / scrollDiv.offsetWidth;
            contentDiv.style.width = percentageWidth + "%";
        }

         // Function to add content. This function relies on calling
         // adjustWidth.
        function addLine() {
            var content = document.getElementById("content");
            content.innerHTML += "Line Added<br />";

            // Detect version of IE here. Modify if needed. 
            var html = document.getElementsByTagName("html")[0];
            if (html.className != "")
                adjustWidth(); // adjust width only if class is IE
        }
    </script>
</body>

</html>

Wednesday, July 16, 2014

[MySQL] Grouping Intervals and counting columns

Say you have table like this...

idcodedateactivity
12002014/06/04
22002014/05/04
35002014/04/04
45042014/05/28

...and now you want to get the past 7 days but count how many times 200 (success code) comes up and how many times a number other than 200 (failure code) comes up. So the idea is simple. Get total of success + failure codes, left outer join for success, left outer join for failure. The filter where the date is more the the current day minus 7 days. At the end, you should return a row that has the day, total count, success count, and failure count. the Got it? Yes you do. You're a trooper. Here is a sample:

select STR_TO_DATE(a.period, '%m-%d-%y') as period, ifnull(a.cnt,0) total, ifnull(b.cnt,0) success, ifnull(c.cnt,0) failure 
from
(
select
date_format(dateactivity , '%m-%d-%y') period,
count(*) cnt
from mytable
where dateactivity >= DATE_ADD(NOW(), INTERVAL -7 DAY)
group by date_format(dateactivity , '%m-%d-%y')
) a 
left outer join
(
select
date_format(dateactivity , '%m-%d-%y') period,
count(*) cnt
from mytable
where code = '200'
and dateactivity >= DATE_ADD(NOW(), INTERVAL -7 DAY)
group by date_format(dateactivity , '%m-%d-%y')
) b on a.period = b.period 
left outer join
(
select
date_format(dateactivity , '%m-%d-%y') period,
count(*) cnt
from mytable
where (code != '200' or code is null)
and dateactivity >= DATE_ADD(NOW(), INTERVAL -7 DAY)
group by date_format(dateactivity , '%m-%d-%y')
) c on a.period = c.period
;

I know that there are probably different ways of doing this. If you know how, please share. Sharing is caring. And I care for all.

Tuesday, July 15, 2014

[Java/Spring/Maven] Making JSTL work!!!!

Here are some settings to check to make sure JSTL works in your project. I'm using JSTL 1.1.2 and

Pom.xml dependencies ( Just dumping all dependencies including non-jstl related ones )

 <dependencies>
   <!-- Spring dependencies -->
 <dependency>
  <groupId>org.springframework</groupId>
 <artifactId>spring-aop</artifactId>
 <version>${spring.maven.artifact.version}</version>
 </dependency>
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>${spring.maven.artifact.version}</version>
 </dependency>
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.maven.artifact.version}</version>
 </dependency>
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${spring.maven.artifact.version}</version>
 </dependency>
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring.maven.artifact.version}</version>
 </dependency>
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${spring.maven.artifact.version}</version> 
    </dependency>       
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.maven.artifact.version}</version>
    </dependency>       
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.maven.artifact.version}</version>
    </dependency>       
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.maven.artifact.version}</version>
    </dependency>      
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.maven.artifact.version}</version>
    </dependency>               
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.maven.artifact.version}</version>
    </dependency> 
   <!-- JSP, Servlet, JSTL dependencies -->
 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>${version.javax.servlet}</version>
 </dependency>
 <dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>${version.javax.servlet.jsp}</version>
 </dependency>
 
 <dependency>
            <groupId>xmlbeans</groupId>
            <artifactId>xbean</artifactId>
            <version>2.2.0</version>
        </dependency>
 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>${version.javax.servlet.jstl}</version>
 </dependency>
 <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
      <scope>compile</scope>
    </dependency>
   <!--  Codehaus Jackson dependencies -->
   <dependency>
        <groupId>org.codehaus.jackson</groupId> 
        <artifactId>jackson-core-asl</artifactId> 
       <version>1.9.1</version>
    </dependency>    
    <dependency>
        <groupId>org.codehaus.jackson</groupId> 
        <artifactId>jackson-jaxrs</artifactId> 
        <version>1.9.1</version>
    </dependency>    
    <dependency>
        <groupId>org.codehaus.jackson</groupId> 
        <artifactId>jackson-mapper-asl</artifactId> 
        <version>1.9.1</version>
    </dependency>    
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-lgpl</artifactId>
        <version>1.9.1</version>
    </dependency>
    <!-- Jettison -->
    <dependency>
        <groupId>org.codehaus.jettison</groupId>
        <artifactId>jettison</artifactId>
        <version>1.3.1</version>
    </dependency>
    <!-- Apache Datasource -->
    <dependency>
  <groupId>commons-dbcp</groupId>
  <artifactId>commons-dbcp</artifactId>
  <version>1.2.2</version>
 </dependency>
    <!--  Oracle Driver -->
     <dependency> 
         <groupId>com.oracle</groupId>
         <artifactId>ojdbc14</artifactId>
         <version>10.2.0.4.0</version>
     </dependency>
    
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>myspringproject</finalName>
  </build>
  <properties>
   <spring.maven.artifact.version>2.5.6</spring.maven.artifact.version>
   <version.javax.servlet>2.4</version.javax.servlet>
   <version.javax.servlet.jstl>1.1.2</version.javax.servlet.jstl>
   <version.javax.servlet.jsp>2.1</version.javax.servlet.jsp>
  </properties>

JSP taglibs/charset (utf-8)


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %> 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Postman</title>
</head>
<body>

web.xml
The web-app attribute to configure the version might start giving you an error saying that the Dynamic Web Module cannot convert to <some version>. If you encounter this, right-click your project in the Project Explorer, go to the Project Facets, uncheck the Dynamic Web Module, Hit OK, and Update Maven Project. If you have the code below, it will set it as the assign version I believe.


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

Wednesday, March 19, 2014

[.NET] For reference, StructureMap basic setup

The StructureMap xml should look like this for several mappings:

<?xml version="1.0" encoding="utf-8" ?>
<StructureMap>
  <DefaultInstance
    PluginType="LoginExample.Domain.Interfaces.Repositories.IUserRepository,
        LoginExample.Domain.Interfaces"
    PluggedType="LoginExample.Infrastructure.TestDataAccess.TestUserRepository,
        LoginExample.Infrastructure.TestDataAccess" />
  <DefaultInstance
    PluginType="LoginExample.Domain.Interfaces.Services.ILoginService,
        LoginExample.Domain.Interfaces"
    PluggedType="LoginExample.Services.LoginService,
        LoginExample.Services" />
  <DefaultInstance
    PluginType="LoginExample.Domain.Interfaces.Services.IAuthenticationService, LoginExample.Domain.Interfaces"
    PluggedType="LoginExample.Services.AuthenticationService, LoginExample.Services" />
</StructureMap>

Below are contents of the Bootstrapper. Use the Run method in Global.asax.

// StructureMap ContollerFactory
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController
            GetControllerInstance(RequestContext requestContext,
            Type controllerType)
        {
            try
            {
                if ((requestContext == null) || (controllerType == null))
                    return null;

                return (Controller)ObjectFactory.GetInstance(controllerType);
            }
            catch (StructureMapException)
            {
                System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
                throw new Exception(ObjectFactory.WhatDoIHave());
            }
        }
    }

    public static class Bootstrapper
    {
        public static void Run()
        {
            ControllerBuilder.Current
                .SetControllerFactory(new StructureMapControllerFactory());

            ObjectFactory.Initialize(x =>
            {
                x.AddConfigurationFromXmlFile("StructureMap.xml");
            });
        }
    }

Monday, June 10, 2013

[Android] Clearing previous activities and opening a new one

So maybe you want to close the Welcome Screen as well as the Login Screen when you get to the screen after a successful login. Here are the flags to pass:

Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK

If you look around, people may suggest 

Intent.FLAG_ACTIVITY_CLEAR_TOP
but this didn't do the job.

Wednesday, April 17, 2013

[MySQL] Installing MySql on windows 7 no-installer


Getting the MySQL service to work
  • Extract the file contents to desired directory.
  • Create a 'my.ini' file in the root of the new directory.
  • Copy the following info into my.ini:
[mysqld]
 basedir = C:/mysql
datadir = C:/mysql/data
port = 3306
socket = /tmp/mysql.sock


  • In command line, run ' mysqld --install ' to add the MySQL service
  • Run MySQL service 
  • Then just run mysql to start mysqling. lol
Creating Users

  • Run mysql
  • Type in: create user 'username'@'localhost' identified by 'password'
  • Grant privileges by using the following as guidelines:
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' -> IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' -> IDENTIFIED BY 'some_pass' WITH GRANT OPTION; GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
GRANT USAGE ON *.* TO 'dummy'@'localhost';

Tuesday, April 16, 2013

[PHP] Installing PHP, Apache, Laravel locally on Windows 7

This guide is only for note taking purposes. Whenever I set up something for the first time, I feel like writing about it. I don't know why that is, but don't worry about it and let's begin.

Installing PHP 5.4 and Apache 2.4:
  • Download Apache 2.4 from apachelounge.com
  • Download PHP 5.4 from the php.net
  • Extract Php files into a directory. You can choose c:\php if you want.
  • I think Apache 2.4 comes in a zip. So just extract the contents into a directory of choice. I use c:\apache
Configuring PHP and Apache

  • In command line, install Apache as a service by running this in cmd: httpd -k install
  • Navigate to Apache's configuration directory and open httpd.conf in a text editor
  • Add the following lines

# PHP Stuff #####################################
#
LoadModule php5_module "c:/php/php5apache2_4.dll"
AddHandler application/x-httpd-php .php


# configure the path to php.ini
PHPIniDir "C:/php"


  • Change the listening port if necessary. You may want IIS to be on 80 and Apache on 8080. Or vice versa
  • Start apache!!!
Install Laravel
  • Download Laravel 4. Search on google. And follow the tutorial on the Tut+ site
  • If you're migrating and seeding the database, you need to add $this->call('TableNameTableSeeder') make the following class:


class TableNameTableSeeder extends Seeder {

    public function run()
    {
        DB::table('tablename')->delete();
        User::create(array(
                'id' => 1,
                'username' => 'firstuser',
                'password' => Hash::make('first_password'),
                'created_at' => new DateTime,
                'updated_at' => new DateTime
        ));   
    }
}


Monday, April 8, 2013

[.NET] Adding POCO Entities in the WCF mix

When you want to separate the domain model such that it is now housed a separate project for other layers/projects to use, you must remove proxy creation and assign the domain object and properties with DataContracts and DataMember attributes.

To remove proxy creation, simply put in the service implementation constructor

DBcontext.ContextOptions.ProxyCreationEnabled = false

Sunday, February 10, 2013

Asus G75VW Boot Recovery. Formatting is not an option!!!!!

Hey guys,
I just got a new Asus G75VW with Windows 7 Ultimate loaded (in place of Home Premium). I do not have an Ultimate disk nor the Home Premium (except for the CD key in the bottom of the laptop). The current Windows was booting by EFI so this was going to be a special solution.

I completely f'd up my Asus G75VW laptop by messing with EasyBCD. In detail, I messed up by using EasyBCD 1.6, since adding a new entry has the ability to choose Generic x86 as the boot type or whatever. I needed this option because lots of hackintosh tutorials used this. Turns out, EasyBCD 1.6 is not supported by Win7. I loaded some defaults with EasyBCD, saved it, and restarted my computer. NOW YOU CAN POUND ME INTO A PANCAKE!!!!!

So when I boot, windows boot manager loads into an error screen that says something is wrong with the BCD. The location was either of the error was either (forgot which displayed first):

/EFI/Microsoft/Boot/BCD

or

/Boot/BCD


So, what are my options? A. Fix the boot for Windows Ultimate. B. Format the drive with Windows Home Premium. I opted for A: So what worked and what didn't?

- When doing a search, I found a lot of people suggest using the Repair disk in the Windows Install DVD. This DID NOT WORK....yet. Something about being EFI bootable will show an incompatibility error no matter which Windows disk I used.

Then I downloaded the Hiren Boot CD 15.2!!!!

- Then I used DiskGenius, which was part of the CD. This may work for some, but it totally f'd up my BCD. Refer to here:

http://www.sevenforums.com/installation-setup/228504-missing-boot-manager-4.html

Using it pretty much just made the whole drive unallocated, although the partitions were still there, but lost.

- Then I used Partition Recovery Wizard, another utility in the CD. I basically used this to find partitions and repair it. It successfully did.

- Now when I restarted the computer, it would say BootMgt is missing.

- So I popped in a Windows 7 disk. At the installation screen, I pressed shift+f10 to go to the command line and I ran all the bootrec commands. It successfully did.This also assigned a drive to the BCD. So you when you run bcdedit in command line, you see "partition=c:" instead of {unknown}

- I believe it still didn't boot then. So now I booted up the Windows 7 Ultimate DVD and hit the repair disk option. Finally!!! It passed the incompatibility error. Now all I did was choose the option to fire up the Startup Recovery.

- When I booted, now there are 2 options for this drive. To boot off the Windows Boot Manager or the drive itself. The boot manager, I believe, boots off the EFI partition. This will obviously create an error since I did not fix this. So if I boot off the hard drive itself, it will FINALLY LOAD INTO WINDOWS! YA!

Conclusion:

I know this was not a clean fix, since I converted from EFI to MBR boot (or is it GPT or MBR boot?). Anyways, I am not a claimed IT, hardware expert either. But I'm just glad this thing is finally working.

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.

WUDDDAAAPPPAAAACCCKKERRRR

Alright, this was such a headache, but thanks to Matt Johnson in this stack overflow link:
http://stackoverflow.com/questions/3797248/update-function-import-not-displaying-in-context-file

...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)
                {
                    continue;
                }
#>

        ObjectParameter <#=parameter.LocalVariableName#>;

        if (<#=parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"#>)
        {
            <#=parameter.LocalVariableName#> = new ObjectParameter("<#=parameter.EsqlParameterName#>", <#=parameter.FunctionParameterName#>);
        }
        else
        {
            <#=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()))#>);
    }
<#
        }

        region.End();



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.

Index:
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);
                        db.SaveChanges();
                        return "Succesfully Updated!";
                    }
                    else
                        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);
                        db.SaveChanges();
                        return "Succesfully Updated!";
                    }
                    else
                    {

                        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.