Fighting 4 Sanity

You Don't Have To Be Crazy But It Helps!!!

24. June 2014 10:06
by XavierShades
0 Comments

10 Things I learned about life by playing Fable

24. June 2014 10:06 by XavierShades | 0 Comments

10. Get married! (Great perks and it's less work than being a playa.)

9. Clothes really do make the man.

8. Ultimately, "the problem is choice!”

7. Bragging is best reserved for the pub.  (Bring proof!)

6. Regardless of the time period, bringing a knife to a “gun” fight will get you killed.

5. "Balancing the system" or "stacking the deck" does work.

4. The definition of good protection is dealing with problems before they occur, NOT as they happen.

3. F##k gambling... Real estate!

2. A good weapon will solve half your problems.

1. Being fast is just as good, if not better, than being stronger than your opponent.

13. May 2014 11:39
by Aaron Knipe
0 Comments

Entity Framework and Generic Repositories

13. May 2014 11:39 by Aaron Knipe | 0 Comments

We have started working on a psuedo skunk works project at work in order to try out some of the new technology available.  One of the big things on my list is Entity Framework.  I have worked with it heavily in the past how ever my new teammates havent used as much.  We are currently using a product called CodeSmith to generate most of the database connectivity as well as the proxy classes for database objects.  While this approach has worked well in the past, there is new stuff that I hope to bring to the table.  One of my goals is to present Entity in a way that is easy to transition to, as well as has all the functionality that we are getting from CodeSmith without needing the extra tool.  In order to get to this I began thinking about factories and repositories.  I have had very little experience with either and hit google for some code to sink my teeth into.  I came across a very helpful article by Tugberk Ugurlu(here) that went over some come repository patterns that I had seen elsewhere and presented a best approach which I have found to be superb in practice.  

First up is the interface.  This sets up the framework/common functionality that the generic repository is going to use.

public interface IGenericRepository<T> where T : class {
        IQueryable<T> GetAll();
        IQueryable<T> GetBy(Expression<Func<T, bool>> predicate);
        T GetSingle(Expression<Func<T, bool>> predicate);
        void Add(T entity);
        void Delete(T entity);
        void Update(T entity);
        void Save();
    }

 

Next is the generic repository class.  In Tugberk's example this is an abstract class, and you would instantiate concrete classes that inherit from this class.  For my environment concrete classes will not be used frequently and the functionality that the generic repository provides allows us to get at the typical RUDI(thanks Gareth) functionality.

public class GenericRepository<C, T> : IGenericRepository<T>, IDisposable where T : class where C : DbContext, new() {
        private C _entities = new C();
        private bool disposed = false;

        
        public C Context {
            get { return _entities;  }
            set { _entities = value; }
        }

        /// <summary>
        /// Returns all records in the table
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll() {
            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        /// <summary>
        /// Gets a filtered set based on the predicate
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public IQueryable<T> GetBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate) {
            IQueryable<T> query = _entities.Set<T>().Where(predicate);
            return query;
        }

        /// <summary>
        /// Gets a single records based on the predicate.  Returns null if more than 1 record is found.
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public T GetSingle(System.Linq.Expressions.Expression<Func<T, bool>> predicate) {
            T query = _entities.Set<T>().Where(predicate).SingleOrDefault();
            return query;
        }

        /// <summary>
        /// Adds the specified entity to the dbcontext
        /// </summary>
        /// <param name="entity"></param>
        public void Add(T entity) {
            _entities.Set<T>().Add(entity);
        }

        /// <summary>
        /// deletes the specified entity object from the dbcontext
        /// </summary>
        /// <param name="entity"></param>
        public void Delete(T entity) {
            _entities.Set<T>().Remove(entity);
        }

        /// <summary>
        /// updates the specified entity object
        /// </summary>
        /// <param name="entity"></param>
        public void Update(T entity) {
            _entities.Entry(entity).State = EntityState.Modified;
        }

        /// <summary>
        /// Saves the changes
        /// </summary>
        public void Save() {
            _entities.SaveChanges();
        }

        protected virtual void Dispose(bool displosing) {
            if (!this.disposed) {
                if (displosing) {
                    _entities.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

 

Since this kind of repository was new to me I needed to try it out myself to see how easy it was to query vs making the calls to entity directly.  I threw together a quick console application to test it out and was happy to see that all the entity calls worked as I expected.  The where predicates are as straight forward as with an entity query and I can make a call to any of my entity objects without much fuss.

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            //GenericRepository<PlayEntities, GeoLocateTest> t;
            //using (test.test t = new test.test()) {
            using(GenericRepository<PlayEntities, person> t = new GenericRepository<PlayEntities,person>()){
                var location1 = t.GetSingle(w => w.GeoLocateTest.locationId == 7);
                var location2 = t.GetSingle(w => w.GeoLocateTest.locationId == 8);

                var distance = (double)location1.GeoLocateTest.location.Distance(location2.GeoLocateTest.location) / 1609.344;

                Console.WriteLine(distance.ToString());
                Console.ReadKey();

            }
        }
    }
}

 

 

You can find the code on github(here)

7. June 2012 21:06
by Admin
0 Comments

Write Something Every Day Challenge: Day 9

7. June 2012 21:06 by Admin | 0 Comments

Not much to write about today.  I did write a lot of code... or rather rewrote but I guess that doesnt count.  We watch John Carter tonight.  It was a pretty good movie, the effects were pretty good, a nice story.  Leaves you wondering what happened in the 10 years he was gone.  I know my morbid mind says the chick was assassinated and a war started between the 4

6. June 2012 22:06
by Aaron Knipe
0 Comments

Write Something Every Day Challenge: Day 8

6. June 2012 22:06 by Aaron Knipe | 0 Comments

OK, so I missed day 7, bad me. I will get the hang of this yet. I guess technically I did write yesterday, as I have to write as part of my job. Its not writing in this sense however. I dont think there are many people out there that enjoy reading stuff like:

Create table access.users( 
  userId uniqueidentifier not null, 
  userName varchar(25) not null, 
  addDate datetime not null,
  constraint pk_users_01 primary key nonclustered(userId) 
)

or

using(DropBuryEntities dbe = new DropBuryEntities()){ 
     Role[] userRoles = dbe.vUserRoleMap.Where(w => w.user.userName == username).Select(s => new Role(){ Area = s.area, Role = s.roleName}).ToArray<>(); 
     foreach(Role role in userRoles){ //do something } 
}

 Any way, onto what I am writing tonight. Shara stood with her hands behind her head trying not to look at the scruffy man holding the photon pistol a few inches from her head. She fought down her natural instincts, she had to keep her cover. She spent a lot of time and energy making herself a common face in this town and she didnt want to blow it now. She took a second to glance at her roommate. Jessara had taken her in, believing she had was trying to escape an abusive relationship. She was holding her son close, obviously scared. Shara looked back at the man holding the gun. He was taller than her, and had brown eyes and smelled like he hadnt bathed in a week. His face was almost as dirty as the duster he was wearing and sweat was beading on his forehead despite the relative coolness in the apartment. Two other men were behind her looking through the cabinets and draws. "Hey Cli I think we have something here!" one of the men said as he waived a rusted metal box in the air. "No not that, its all we have, you can take anything else, but not that" jessara shrieked dropping to her knees sobbing. The tin contained all their savings. Without it they wouldnt be able to pay rent or buy food for some time. Shara couldnt let them take it without a fight. She uncoiled like watch spring wound too tight. Her right had shot across her body striking the inside of the mans wrist, she heard a faint crack as she twisted into his body grabbing and twisting the wrist holding the gun straight up as she drove her left elbow into his temple. He went limp releasing the gun into her hand. She leveled the fire arm on the man with the tin and fired a shot. The shot penetrated through his eye and out the back of his skull sending a fine mist of blood and brain matter into the air. Cli turned in time to catch another round between the eyes and dropped without making a sound. Shara lowered the weapon and looked to Jessara. "Are you ok?" Jessara just stared at her. Her face had gone ghost white and Billy was holding his hands to his ears openly crying. Shara knew it was too late to do anything about it now. She went to her room and packed her things, carefully rolling the pistol in some clothes and putting it at the bottom of her bag. Jessara was still on her knees, staring at the dead men in shock. Shara checked the unconscious man for additional rounds and bolted for the door. The hallway was full of their neighbors. They all had concerned looks on their faces. Some were puzzled to see Shara leaving after hearing gun fire. Shara headed down the stairs. The lawmen would be be here any minute, she went down the extra flight towards the back door. As she was gently closing the door behind her, she heard the front door bang open and heavy foot steps running up the stairs to her former home. She would have to send Jessara some Marks and an apology once her job was done; this wasnt any way to repay her for taking her in. She couldnt worry on that now. She had to make her self scarce and come up with another way to complete her mission. It was unlikely that she would be able to get close to the Kalvin now. It would only take a few hours for Kalvin to hear about the woman who fled town after some gun fire. All the lawmen would want to question her. No she was going to have to go about this differently. She needed some place safe to hideout and think. She headed towards the desert.

4. June 2012 22:06
by Admin
0 Comments

Write Something Every Day Challenge: Day 6

4. June 2012 22:06 by Admin | 0 Comments

So I have already broken the streak. Between DND on saturday(which was awesome), and yard work on Sunday I didnt write anything last weekend. That's ok, you learn from working at it, and next weekend will be better(hopefully). Tonight was a karate night for the kids and I. We all piled into the car and drove down to Dover. We stopped at the McDonalds in Smyrna to get food on the way. Typically I drop Athena off at mom and dads house while Chase, Xavier and I do karate, but I got a call from dad about 10 minutes from the house letting me know that he wasnt there. So I took Athena to karate and dad came and picked her up. As we were pulling into the dojo parking lot, it dawned on me that I had left Xavier Gi sitting on the couch, nearly an hour away. Thankfully the dojo had one that was close to his size that he could borrow. When I say close to his size, I mean to say it was too big. We had to tie the waist band really tight so it didnt fall off of him, and roll his pant legs up so he wasnt tripping on them. He made it through class with out too much difficulty. He is doing really well in class, though he does get distracted very easily. I happen to believe that its because one of the other boys in the class plays around, but who knows. I hope he doesnt act like that in school... After Xaviers class, Chase and I have our class. During our class, Xavier plays quietly with his toys. We had a really good class tonight. After stretching we did some bag work. It was nice, I havent done bag work in a long time and I missed it. After some more shadow sparing we broke down and did kata. We worked from seisan through shinto, both by the numbers and all the way through. We stopped several times mid kata so the instructor could correct people stances or hands. This left us holding in a position for several minutes. By the time it was done my legs were burning and I welcomed the end of class. Then it was off to get Athena from mom and dads house then the nice hour long drive home. As usual the kids fell asleep in the car. I carried them both up stairs to bed despite the protest I got from my legs. Tomorrow I hope to write a small scene from a story. I have an idea rolling around in my head which should be interesting, we shall see.

31. May 2012 21:05
by Admin
0 Comments

Write Something Every Day Challenge:Day 3

31. May 2012 21:05 by Admin | 0 Comments

Joral stepped back blocking and redirecting his brothers attacks, waiting for an opening. His brother loved to be on the offensive, almost to a fault. Ducking a high kick Joral shot forward attempting to drive his palm into his brothers chest and was met with cross block. To the untrained eye it would appear that the brothers were dancing. Each step match and answered. Punches dodged and redirected, followed by kicks that barely missed. Redirected blows turned into a block or a new attack. Around the ring the brothers ebbed and flowed, neither seeming to gain the upper hand. Hannel's eyes saw much more. Focused energy was pushed or absorbed with each attack and block. Joral's kicks contained enough focus to render most men uncontentious but Kansu absorbed it and pushed it back towards his brother with equally powerful punches. Their focal aura's sent sparks into the air when they touched. Their battle was truly one that never seemed to end. Every day the brothers would battle neither ever winning or losing. Sometimes the fight would last hours, other times minutes, every match ended with the Master stopping the fight. Hannel tried to watch every match. He could match neither one in technique or power but he hoped he would learn something in watching. When the brothers first started their battles most of the school would watch. Now few watched, and all expected the same outcome, a draw.

30. May 2012 22:05
by Admin
0 Comments

Write Something Every Day Challenge: Day 2

30. May 2012 22:05 by Admin | 0 Comments

So, I had planned to write a short story, or an intro to a story today but the idea isnt thought out enough in my head so I am going to do that tomorrow... maybe. In stead I am going to write about Xaviers Spring concert. At 11:10am I double checked my camera gear and headed out the door. I was on my way to Wilbur Elementary School for Xaviers Spring Concert. As I havent been to one of Xaviers concerts before I was unsure what to expect so I left myself plenty of time and arrived early. When I pulled into the parking lot I was surprised to see a lot of cars, though I hoped it was the school faculty and not eager parents. I made my way to the Multi purpose room and found the room fairly empty. There were a lot of chairs arranged around the room, all facing a small stage, but none were too close. there was a large open area in the middle of the room, with a small column of chairs in the middle of the room. I chose a seat in the front row on the left side of the room, hoping Xavier wouldnt be on the other side of the room. As people started to show up, I prepared my camera, check the setting, did a quick exposure check, and waited. The room quickly began to fill up and I was glad I arrived early. My seat wasnt exactly prime, but the remaining seats were worse. Soon the kindergarteners started to arrive. I had assumed that that would all be singing together but I quickly realized that wasnt the case. The first class that came in sat on the floor in the open area in the middle of the room. In hind site this made perfect sense, the center column of chairs was for the teachers so they could keep an eye on their class. The next class that came in began arranging themselves on the stage, and the remaining classes took their places on the floor. Xaviers class was one of the last classes in the room and I was able to get a couple of pictures of him hamming it up as he came in.  The classes each took turns singing a song, and doing a little dance or hand motions with the song. Xaviers class was one of the last groups to go, and I was surprised that their song was the shortest of the group.

 

After all the classes finished singing their songs, the teachers took their kids back to their classes. In the end the performances were cute and I was glad I was able to go.

 

 

29. May 2012 10:05
by Admin
0 Comments

Write Something Every Day Challenge: Day 1

29. May 2012 10:05 by Admin | 0 Comments

In order to prepare for this years NaNoWriMo I am going to try to write every day. There are a couple of reasons for this. First, in order to be successful at NaNoWriMo you need to write every day in order to hit the target word count for the challenge. This is where I have stumbled in the past. Writing a little over 1000 words a day doesnt seem like a lot until you are 10,000 words in. It is a true challenge and one I intend to be successful at this year. Second, I read an article that hypothisised that in general people have not problem talking because we do it all the time. Most people rarely write however so when they need to write something its difficult and not very good. The article went on to suggest that if we wrote every day that we would naturally become better writers as we are practicing every day. This makes sense to me so I am going to give it a go. I am not sure what I am going to write about on a daily basis. I am sure on some days its going to be pretty horrible(probably most days), but I am going to try to write something daily, perhaps I will write more than once a day, I suppose thats a meaningful goal. Well here is to the challenge. Wish me luck!

28. October 2011 23:10
by Admin
0 Comments

Project: Rocket Launch Box Part 3

28. October 2011 23:10 by Admin | 0 Comments

Tonight I had some time to add the 2nd shift register. At first I wasn't sure how to pass values to each one. Turns out its as simple a processing another shift out. I also added 2 buttons. The first is a toggle that is used to arm the box. This switch will also function as a kill switch. I have gotten a missile switch cover for the switch. When the cover is closed it will throw the switch back into the off position. The 2nd button is the launch button that will trigger the count down. 

 

 

 

Below is the updated source code:

Insert code here...#define Buzzer 13 
#define latch 8
#define clock 12 
#define data 11 
#define armButton 4 
#define launchButton 5
#define armedIndicator 3 
#define launchIndicator 2 
 
const byte numbers[11] = {0b11000000,0b11111001,0b10100100,0b10110000 ,0b10011001,0b10010010,0b10000010,0b11111000 ,0b10000000,0b10011000,0b11111111}; 
int count = 25; 
int tens = 0; 
int ones = 0; 
boolean launched = false;
boolean armed = false; 
int iterations = 0; 

void setup(){ 
 pinMode(latch,OUTPUT); 
 pinMode(data,OUTPUT); 
 pinMode(clock,OUTPUT); 
 pinMode(Buzzer,OUTPUT); 
 pinMode(armButton,INPUT); 
 pinMode(launchButton,INPUT); 
 pinMode(armedIndicator,OUTPUT); 
 pinMode(launchIndicator,OUTPUT); 
 Serial.begin(9600);
}

void loop(){ 
 if(digitalRead(armButton) == HIGH){
 digitalWrite(armedIndicator,LOW); 
 if(digitalRead(launchButton) == HIGH){ 
 launched = true;
 }
 } 
 else{ 
 digitalWrite(armedIndicator,HIGH); 
 digitalWrite(launchIndicator,HIGH); 
 launched = false; 
 tens = getTens(count); 
 ones = getOnes(count); 
 lightSegments(numbers[tens],numbers[ones]); 
 }
 if(launched){ 
 digitalWrite(launchIndicator,LOW); 
 tens = getTens(count); 
 ones = getOnes(count); 
 if(count == -1){ 
 blinkZero(); 
 delay(1000); 
 } 
 if(count >= 0){ 
 lightSegments(numbers[tens], numbers[ones]); 
 if(count > 0){ 
 beep(500,500); 
 } 
 else{ 
 beep(1000,1000); 
 } 
 } count--; 
 } 
} 

void lightSegments(byte tens, byte ones) { 
 Serial.print("Set Lights"); 
 digitalWrite(latch,LOW); 
 shiftOut(data,clock,MSBFIRST,tens); 
 shiftOut(data,clock,MSBFIRST,ones); 
 digitalWrite(latch,HIGH); 
} 

void blinkZero(){ 
 lightSegments(numbers[0], numbers[0]); 
 delay(1000); 
 lightSegments(numbers[10], numbers[10]); 
} 

void beep(int fDelay, int lDelay){ 
 analogWrite(Buzzer,128); 
 delay(fDelay); 
 digitalWrite(Buzzer,LOW); 
 delay(lDelay); 
} 

int getOnes(int count){ 
 return count % 10; 
} 

int getTens(int count){ 
 return count / 10; 
}