Using Data Annotations to validate models

You can validate action results too and MVC methods by passing in the model which has the data annotations as part of the parameter list

Coding Wise

The .NET Framework provides us a set of attributes that we can use to validate objects. By using the namespace System.ComponentModel.DataAnnotations we can annotate our model’s properties with validation attributes.

View original post 181 more words


OWIN Classes with Access-Control-Allow-Origin Header: *

XMLHttpRequest cannot load http://localhost:7802/token. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘http://localhost:7812’ is therefore not allowed access

This error means that there is an attempt to access a resource from a different domain by a web app, and the requested resource does not have any policies that would allow the apps from the origin domain to consume it. This error can be reproduced by loading a web app on a different domain (or port) and making an AJAX call to an API. The code would be
something similar to the following:
Client App
type: “POST”,
contentType: ‘application/json’,
data: JSON.stringify(contact),
headers: {
‘Authorization’: ‘Bearer ‘ + tokenProvider.token,
success: function (res) {

error: function (req, status, error) {

public IHttpActionResult PostContact
        ([FromBody]Contact contact)
    IHttpActionResult result = null;
    if (!ModelState.IsValid)
          //handle request
     return result;

When making a CORS request, we need to understand that for every request that we send to a different domain, there may be two requests made to the server, preflight and actual requests. For each of these requests, the server must respond with the Access-Control-Allow-Origin header set with the name of the origin domain.

Preflight Request
A preflight or OPTIONS (HTTP verb) request is created by the
browser before the actual request (PUT,POST) is sent for a resource in
another domain. The goal is to have the browser and server validate that the other
domain has access to that particular resource. This is done by setting the Access-Control-Allow-Origin
header with the host or origin domain.
Actual Request
Once the preflight request has a response with the
corresponding headers, the browser sends the actual request. For this request,
the server also checks the CORS policies and adds the Access-Control-Allow-Origin
header with the host domain.
The way to implement CORS using OWIN and MVC Web API is by first configuring the oAuth server options with an implementation of OAuthAtuhorizationServerProvider on the Startup class.
[assembly: OwinStartup(typeof(ozkary.Startup))]
namespace ozkary
    public class Startup
        public void Configuration(IAppBuilder app)

        private void ConfigureAuth(IAppBuilder app)
            // Configure the application for OAuth based flow
            var oAuthOptions = new OAuthAuthorizationServerOptions
                Provider =
new AuthorizationServerProvider(),
            // Enable the application to use bearer tokens to authenticate

The OwinStartup directive allows OWIN to run the StartUp class and inject the AppBuilder instance in the Configuration method. This is what we need in order to configure the custom provider that can handle our token management, user validation and CORS headers. (token and user validation is not in the scope of this article). The implementation of
AuthorizationServerProvider is listed below: (listing only the areas that are relevant to support CORS)
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
        /// <summary>
        /// match endpoint is called before Validate
Client Authentication. we need
        /// to allow the clients based on
domain to enable requests
        /// the header
        /// </summary>
        /// <param
        /// <returns></returns>
        public override Task MatchEndpoint(OAuthMatchEndpointContext context)

            if (context.Request.Method == “OPTIONS”)   

                return Task.FromResult(0);
            return base.MatchEndpoint(context);
        /// <summary>
        /// add the allow-origin header only
if the origin domain is found on the     
        /// allowedOrigin
        /// </summary>
        /// <param
        private void SetCORSPolicy(IOwinContext context)
            string allowedUrls = ConfigurationManager.AppSettings[“allowedOrigins”];
            if (!String.IsNullOrWhiteSpace(allowedUrls))
                var list = allowedUrls.Split(‘,’);
                if (list.Length > 0)
                    string origin =
                    var found = list.Where(item =>
item == origin).Any();
                    if (found){


new string[] { origin });

                                   new string[] {“Authorization”, “Content-Type” });

                                   new string[] {“OPTIONS”, “POST” });
The code above overrides the MatchEndpoint handler. This area of the code is called for every request including the preflight request (OPTIONS). Note that this handler is called before a call is made to Validate Client Authentication. This is where we need to manage the logic of adding the headers using OWIN.  We do this by calling
the SetCORSPolicy method.
The SetCORSPolicy method looks for a configuration setting (allowedOrigins) that contains the whitelist of domains that can consume the resources from our API. It then reads the Origin header to get the domain name (including scheme and port i.e. If the origin domain is found in the configuration, the Access-Control-Allow-Origin response header is set to the origin domain value.
This is what helps us resolve the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”.
The SetCORSPolicy method is also a good place to add other response headers that may be required for accessing our API. For example, we may need to add the Access-Control-Allow-(Header and Methods) for additional access. (Not CORS related)
We can use the browser developer tools to take a look at the network request and response headers. When CORS is configured properly, the response headers should look similar to this:
What to Avoid
When using the OWIN middleware to handle our CORS calls, we want to stay away from adding these headers in other areas of the application as this causes a duplicate header exception. Some of the things to avoid include:
  • Do not add these headers on the web.config file
  • Do not use app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll) as this allows all origin domains to have access. We could use this option for public APIs with no restrictions.
  • Do not use the config.EnableCors from WebApiConfig (HttpConfiguration) as we are already using a middleware to handle this concern. This option can be used when OWIN is not being used and we need to allow CORS
  • When configuring the whitelist for CORS, we need to make sure to include the scheme, domain and port number  (especially when testing with Visual Studio).   http://localhost is not the same as http://localhost:5733 and  http://www.ozkary .com is not the same as We need to match the Origin header value




We need to keep in mind that once we start using OWIN, we are essentially passing the CORS concern to the middleware. We do not want to start making changes in different areas of the application as that just makes thing confusing. We just need to focus on the AuthorizationServerProvider and add the necessary implementation to enable CORS in our apps.

A lottery industry insider installs undetectable software giving him advance knowledge of winning numbers, then enlists accomplices to play those numbers and collect the jackpots.

Eddie Tipton, the former security director of the Multi-State Lottery Association, reportedly installed software code to be able to know winning numbers. 390-lottery-0415Eddie was convicted of rigging the $16.5m jackpot in Iowa in 2015. At the moment, he is awaiting trial in four other states. The lottery security director was charged after being identified on the surveillance footage of a person buying the winning ticket for a $16.5m jackpot in 2010. Tipton, who had unparalleled access to lottery software, was identified on the footage by his colleagues.

Prosecutors say Tipton installed software known as a root kit that enabled him to manipulate numbers without a trace. What tripped him up, investigators say, was his decision to buy the winning ticket himself at a service station near the headquarters of the association, whose workers are prohibited from trying their luck.

Continue reading “A lottery industry insider installs undetectable software giving him advance knowledge of winning numbers, then enlists accomplices to play those numbers and collect the jackpots.”

Technology Bites Man Again


If entrepreneurs didn’t know by now that Technology was taking over the business world, now it’s encroaching on the gambling casinos.  We can’t even escape it on our trips to Las Vegas.

RADIO-FREQUENCY IDENTIFICATION is headed for Vegas.  Casino chips  embedded with RFID tags and are being tested at the Hard Rock Hotel & Casino and will be displayed this month at the new $2.7 billion Wynn Las Vegas hotel and casino.

The chips will each be given a unique player code to track behavior and possibly get more revenue out of high rollers.  It’s estimated that this could be a $100 million business by the year 2010.

There are two Vegas based companies that own the casino-RFID game: Progressive Gaming International and Shuffle Master.

Progressive’s TableLink, which reads RFID chips using table-embedded antennas and records the wagers on a dealer’s PC, is the system of choice at the two casinos.  Progressive and Shuffle Master have also developed optical card shoes, which holds decks and scan cards as they’re dealt.  Shuffle Master’s Intelligent Shoe is already getting rave reviews in Australia and Asia.

The cost of outfitting a table with the chips and antennas costs a casino about $8,000, but analysts predict that Progressive will score bigger bucks from the $6 per day per table it charges for its system.

One RFID chip costs a casino 40 cents more than a standard chip, but that margin will drop to about 10 cents in the coming months. This is certainly a “technology leap” from the “eye in the sky” that we all knew about in the casinos, but I don’t think that even George Orwell would have thought of these chips.

Those of us who used the games in Vegas casinos to escape our computers and software programs, seem destined to be followed by technology no matter where we go. Somehow Radio-Frequency Identification in poker/gaming chips just doesn’t seem to be what a good poker player expects.  Oh well, technology marches on…and on….and on.

You’re really getting tired of the 9 to 5 “rat race” and are thinking about chucking it for your own business.   All your friends keep telling you that you could do for yourself just what you’re doing now for your boss. Why shouldn’t you profit from your ideas instead of him?

You keep thinking about it because you know that you’ll never be financially where you want to be with a weekly paycheck, but what business would you start?

Before you pack in that weekly paycheck, this is the time to evaluate yourself and your future and it takes some real, down to heart honesty.  You want to change your life for the better, so let’s start. Did you know that you have the potential to do and be anything you want?  People have different perceptions of the ideal life, and it ranges from obtaining financial freedom to as simple as owning a new pair of sneakers. Unfortunately, many fail to reach their aspirations because they can’t get a solid, clear picture in their mind of what they want.

Take the next few days and embark on a fact-finding journey that will be a life-changing experience.  Get a pad and pencil and start with this first step:

STEP 1 – KNOW EXACTLY WHAT YOU WANT – Be specific in your passions, then focus all your efforts on that particular desire.

Those who always change their minds and those who give up easily when the going gets tough will never get anywhere.  If you’re a bit confused and aren’t sure what you really want in life answer these questions:

  1. What makes your heart beat with excitement?
  2. What makes you happy?
  3. What are you constantly thinking of day and night?
  4. What do you want to do with the rest of your life?
  5. What do you enjoy doing?
  6. What are your obsessions?
  7. What things make you jump for joy?


Write down all your possible answers to the above questions.  Write down everything, no matter how silly or unimportant it seems. Put all your desires on paper that answers any of the above questions.

When that’s done, go back and circle five to seven items that interest you the most.  Then evaluate and choose with your heart, not your mind, the one and only thing worthy to spend all your time and resources on and that brings out the best in you.

Now you may wind up with something like, “I want to play quarterback for the RAMS.”  If you’re over 20 I’d say that isn’t too viable a choice, but you could do something related to football or sports.  How about starting a sports publication?  Or perhaps a sporting goods retail business, sports memorabilia business, or even a gym could be the answer.  You can always read books and surf the net to help you in your search.

The most important thing to remember, no matter how “pie in the sky” it seems, is to USE YOUR HEART.  Others may disagree with you, but you should be firm with what you really want.  Others may offer comments or advice, but the final decision is always yours to make.  You should concentrate on what you want, not what others want.

Remember you only get one shot at living your life.   There are no replays and you don’t get to do it over.  You may not do it right, but at least you’re doing it.  Too many lives have been lived in quiet desperation waiting until – until they had saved a nest egg, until the children are out of school, until I retire, and they depart this life before “until” ever arrives.

Don’t go to sleep tonight without making a decision on WHAT YOU REALLY WANT IN LIFE MORE THAN ANYTHING ELSE.

Then spend a few days evaluating how to make it possible and make a living at it.  Begin living every day as if it were the last day you had – never leaving anything to be done next week, next month, or next year.  There will always be bills, things will always break down eventually and need replacing, there may be storms and earthquakes and repairs – but there will only be one life for you to live. It can’t be put on “hold”!

The final outcome of your efforts may be in the future, but you’re living each day by taking steps toward that outcome.

Safe Way to Start Your Own Business

Hopefully, you took my advice last week and you have a handy-dandy list now of what you want to do.  We know you want to start your own business; hopefully you now know what it will be.

Being used to a steady paycheck from a regular job, with a family or other financial obligations, makes stepping out of your comfort zone a little risky.  It doesn’t seem to matter how miserable you are in that job, the alternative scares the pants off many of us.  There is a safer way of jumping off that cliff and it entails your current boss.

Your employer could be your ticket to a successful freelance business, if his business doesn’t conflict with your dreams.  If you were thinking of starting a freelance copywriting business, you could negotiate a contract with your current employer for 50% of your time for the first year after you leave.  This would give you a springboard for finding other clients while still covering your monthly expenses.

You’re probably wondering about now, why your employer would agree to sign a contract for half of your time?  There are a number of reasons, and they can result in a “win-win” situation for both of you.

If you’re on good terms with your employer, chances are he doesn’t want to lose you.  It takes time to train someone to fill your job and train them to the company’s way of being productive.

Even if he decides to replace you, it can take months to gather resumes, interview candidates, and hire the right person.  During that time you can be performing job functions from your home office, perhaps even training your replacement and providing your boss with a smoother transition by minimizing the disruption to his business.

If you’re not on good terms with your boss and the company is downsizing, merging, or being bought out, you can help them avoid the unpleasantness and cost of firing you.  You are actually doing them a favor by restructuring this in the form of a contract for services that can be “stretched out” for a period of time if needed.

Frankly, if an employer has to choose between letting you go and paying severance and benefits versus signing a contract for a time period, which do you think they’d prefer?  Signing and getting tangible work and services in return without the costs associated with terminating you is a much better deal for him.  The contract may even be allocated from a different budget category, making it more affordable for the company.

There’s another reason your boss may opt for a contract, and that is your knowledge.  You are already familiar with the company, its clients and services.  You’re able to provide the services they need and you understand what has to be done. Many creative people have used this logic in approaching their bosses to negotiate their first contract and go out on their own.

If you’re interested in starting your own business your current job can provide the security you need in your first year.  What better way to get started on your dream?

Getting In On The Ground Floor

Tractors that steer themselves, property that knows it’s been stolen, airplanes that land without pilots – that sounds like science fiction.  It’s all a result of the global positioning system which is mind-boggling.   The industry is set to skyrocket and opportunities for the entrepreneur are there.

This spring the U.S. government will launch its first next generation GPS satellite to complement the 30 older models already in use.  The aim is to create stronger signals, increased bandwidth, and lots of potential for smart entrepreneurs.

Though startups are springing up all over the place, plenty of technologies remain untapped.  One of the untapped areas are automated navigation systems in family cars that keep drivers a safe distance from other vehicles.

Huge companies such as UPS plan to outfit 75,000 drivers with GPS-enabled handhelds this year to help them reach destinations more efficiently.  Some savvy entrepreneur who offered similar navigation and tracking services could also make out nicely.

There are companies that are using this technology to guide and navigate giant trucks around cliffs and mine shafts.  The maritime industry is predicted to invest hundreds of millions in coming years to outfit cargo containers and ships with GPS receivers.

Chipmakers already cashing in are charging about $13 per device to put GPS chipsets in phones, electronics, and car navigation systems.  And with a new federal regulation that is forcing wireless operators to include GPS in their phones and networking equipment, chip demand is sure to explode.

Remember the day when we said that expecting to buy drinking water in bottles was something the American consumer would never do.  Pay for water that comes out of the kitchen sink faucet?  How silly!  Look at the industry that’s grown up in that area!

Entrepreneurs – the GPS opportunity is out there, if only you know where to look.  Remember, you heard it here first!



Life is a sales job from beginning to end

Strange as it may seem, our life is made up of a series of “sales presentations”.  Sales may not be your gig, but if you’re the boss you’re making presentations everyday.  Be it a pitch to your Board, announcing a policy change to employees, selling an idea to your spouse, or just trying to win others over to your point of view – you need to punch up your people skills for winning pitches.

Like it or not we are all salesmen.  Our lives are made up of a series of “sales presentations”, otherwise known as presenting one’s self in the best light possible. Whether we’re out for a job interview, trying for a raise, or just convincing our employees that a job must be accomplished – you are making a presentation.

To become masterful at it can be summed up in the acronym IPRESENT!   Continue reading “Life is a sales job from beginning to end”

Prepare Crisis Control

A personal crisis doesn’t have to spell disaster for your business if you’re prepared.  Every business occasionally endures a crisis, but what happens when your dilemma isn’t falling profits but personal.

Because we have no idea what type of personal crisis may await us – an ugly divorce, debilitating disease, or ailing parent/child/spouse, we must be prepared. Just as you plan for advertising and promotions, you must plan for life’s surprises.

Paul Krasinski, founder of Lion Strategy Advisors, New York, suggests finding somebody NOW who can take over your responsibility and carry on for at least 20 days.  He/she needs to be someone who can communicate well with staff and command respect, and may or may not be the person you feel closest to in the company.

Once a personal crisis hits, Krasinski recommends “full disclosure” to your employees. This avoids the feeling of being hit by a bomb, and that business will go on as usual.  In case you think this doesn’t work, let me give you a case history. Continue reading “Prepare Crisis Control”