Nothing to see...

A simple blog about all things in the world that is ridikulouse.

Technological steps, are man kinds greatest achievements

Not a Fighter, but a lover of Tech.

Love of the internet

The Internet is the final frontier for open connected networks, it promotes speech and advances knowledge for any mere person. The internet is fast becoming a need rather a want, and it is recognised by the UN as a necessity for the modern person.

Photography

Photography is more than just Art and expression, it is the manipulation of the light and provokes emotion and memories.

Have a look around

The articles on this blog represent my thoughts and views at the time of writing, I can always change my views through further education...please don't hold me against my views. Some of the articles have been written to assist anyone else with similar issues - it also helps me to remember. Hope you get something out of this.

Monday, July 20, 2015

String Interpolation

String Interpolation is an interesting method of being able to access properties directly within a string. Once upon a time in order to include properties into a string you would have to do something like this :

int age = 16;
string mystr = "My age is" + age.ToString();

Essentially a string concatenation and then returning other types as a string.

Then we had string.Format which I thought it was fantastic with the autoconversion of types to string - so we had something like this:

string.Format("My age is {0}", age);


Now, this was very handy and made string concatenation simple and easy to read (have you ever encountered someone else's string concatenation and wondered wtf)?


One of the downfalls of string.Format was that you had to remember the order to add the variable. Since string.Format uses a format as {0}, {1}, {2}, etc... means that your arguements will need to be in the exact order. If you have alter your code delete a string block in the middle then you have to re-sequence everything.

String Interpolation aims solve some of these issues by allowing you to use name properties in your string. The code will look something like this :

int age = 16;
string mystr = $"My age {age}";

Notice, the "$" in front of the string, and also note that the property is surrounded by parenthesis.

Null Conditional Operators

I cannot count the number of times that I've faced exception caused by running into a null. This then leads to code using the if{} blocks or using the short hand "?" on almost all of your variables.

In C# 6.0 specification a null conditional operator. The null conditional operator allows you to check for the instance of a null and replace a returned value or to return a value.

For example :

If you have a simple class such as a Person :

public class person
{

public string Name {get;set;}

public int Age {get; set;}

}

and you instantiate the class :

person me = new person();


then if you do something like

Console.Writeline(me.Name);


you'll get a null exception since the Name has not been instantiated. Often to overcome this specific problem we use constructors :

public class person
{

public string Name {get;set;}

public int Age {get; set;}

public person()
{
Name = "";
Age = 0;
}

}

The Null Conditional Operator now allows you to check for the null based on a shorthand, and this is how it would look in use:

Console.Writeline(me?.Name ?? "Empty Name");

So lets look at what this is doing, the first item to look at is "me?.Name" which is essentially checking the object me to see if it is null, if it is not null it will look at the Name property. The second part is '?? "Empty Name"' which is basically stating that if any part of the expression is null then use the string "Empty Name".

This shorthand example is very important and useful in order to make your program less verbose. For example in order to the above single line you would have had to do multiple if{} blocks (first to check that me is not null, and then the Name property is not null.





Tuesday, June 9, 2015

Xamarin.Auth Sample How to

Introduction


I wanted to try out Xamarin.Auth and specifically have authentication for my App with Facebook. I downloaded the Xamarin.Auth from https://github.com/xamarin/Xamarin.Auth and I thought that this would be a simple build and run to check it out. However, it became slightly long winded process than the simple build and run. In this post I'll go through the steps that I went through.

1. Downloading the Sample

To get the sample application go to https://github.com/xamarin/Xamarin.Auth and download the a copy of the master. A button on the right hand side "Download Zip" will download a copy of the master.

Once this is downloaded, unzip the file to your preferred location. This will extract the contents, within the contents navigate to Xamarin.Auth-master\samples\Xamarin.Auth.Sample.Android and you'll find a solution file (.sln). Double click on the solution file to open it in your IDE (either Visual Studio or Xamarin Studio, in this post I'll be using Visual Studio 2013).

2. Doing the initial Setup

Once the solution file is open try and build and run the project, if you receive an error with the SDK version then follow these steps :


  1. Right click the project "Xamarin.Auth Sample(Android)
  2. Make sure that the Application tab is selected
  3. Update the values for Compile using Android version, Minimum Android to target, Target Android version.
For me I have the API Level 21 installed which is Lollipop (version 5.0x).


Once you have done this you may run into a problem stating "The Debugger Cannot Continue Running the Process. Unable to Start Debugging". If you do see my post on how to resolve this. 

Now, build and run your application. 





You'll be presented with two buttons within the app. If you click either of them you'll receive an error in the authentication. This is all good, since you have set up the authentication with your IDs...

3. Setting Up the Authentication

Now, to set up the authentication you need to register the application with Facebook to get an Application ID. In this step we will primarily focus on the facebook registeration, this is also assuming that you have an existing facebook account (e.g business or personal). In the following example I'll be using my personal account. 

When you examine the code in MainActivity.cs you'll notice the places where you will need to enter values from facebook. 



For example the line that states clientId: "App ID from https://developers.facebook.com/apps",  is your first hint. 

So, head over to developers.facebook.com/apps to start to create your application ID. If you have created an ID before then you can probably skip this step. If you haven't created a facebook application ID specifically for Android then you should read this through.

Click on the + Add a New App button, currently this is green in color in the top right. 

You'll be presented with an in-window dialog requesting for the type of application, in our case since we are trialing out the Xamarin.Auth for Android we'll need to select Android.

Once you click on the Android button, you'll be presented with the following window. 


At this point you can set up a proper application ID, with all the hash keys etc... however, since this is a sample we can skip all of this. Click on the button on the top right called "Skip and Create App ID". This will do a quick create, and present the following dialog: 

 What you will need to enter is the Name, Namespace, and you will need to choose the category. You can enter a dummy information to get you started, please note that the category is mandatory to be completed. Once you have entered all the information click on Create App ID

Once you have done this, you will be taken to a page for your application. Here you will find the application ID. Copy the application ID from the page and paste it in the MainActivity.cs so that the code reads as follows clientId: "1682369x1198632x",  (please note that I removed a character and replaced it with x).

Once you have updated this field, build the solution and run it. When you click on the button to login you'll be presented with another error:


Now that you've got this far, you'll need to head back to facebook. If you haven't closed down the window where you got the App ID, then simply click on the Settings tab on the right hand side. This will take you to the settings page, now you may need to scroll down to the bottom and you'll notice a button called + Add Platform.

You'll be presented with a dialog, select Android again. Now, click on the Quick Start button, because this will guide you through the process. 

Once you have clicked on Quick Start button you'll be presented with the following page:

This will guide you through implementing the facebook sdk to your project etc... but for our use we can skip all of these steps and head over to App Info. You can click directly on the progress breadcrumbs or scroll all the way down. 

From here you will need to enter the package name and the activity name. For the package name, go to your solution and right click > Properties > Application (tab if it is not already selected). Either copy the Assembly/Namespace or update it to whatever you want. 

Paste the copied namespace/assembly, in the packagename. 

For the activity name, use your package name and then add .MainActivity  so that it reads something like com.xamsamples.auth.MainActivity

Once you click on Next, the package name will be checked against google and a warning message will be displayed. This is to try and minimise errors of incorrect package names, since we are only looking to try out a sample we can ignore this, click on Use this package name.

4. Generating Hash Keys




You will now be taken to generate hashkeys, you will only need to generate the development hashkey. 

To generate the hashkey, you will need to download openssl - you will need to download the correct version according to your OS :
  • 32 bit version (https://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_WIN32.zip)
  • 64 bit version (https://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8e_X64.zip&can=2&q=)
The above links for Windows, extract the requried zip file to something such as c:\openssl

Once this is done, open up command.exe ( Windows + R, then type cmd and press enter). 

You'll need to detect the debug.keystore file path. To do this, type the following commands to search for it :

cd \
dir debug.keystore /s

You may get results for two files, one in .android directory and one within Xamarin\Mono for Android. The full path may be something like this C:\Users\username\AppData\Local\Xamarin\Mono for Android 

Next you need to locate the keytool location. Similar to the above step search for it using the following command:

dir keytool.exe /s

You'll get a number of hits depending on the java versions you have installed. Get the latest versions keytool.exe for me it is located at C:\Program Files (x86)\Java\jre7\bin 

Now navigate to the keytool directory just to make things easier. 

cd C:\Program Files (x86)\Java\jre7\bin

Now you will need to execute the keytool.exe using the debug.keystore and openssl to generate the hashkey. To do this execute the following, you must first update this with the paths relevant for you:


C:\Program Files (x86)\Java\jre7\bin>keytool -exportcert -alias androiddebugkey
-keystore "C:\Users\username\.android\debug.keystore" | "C:\openssl\bin\openssl" sha
1 -binary |"C:\openssl\bin\openssl" base64


The main area you will need to update is the path to the debug.keystore, if you installed openssl in c:\openssl then you don't need to change anything else. Once you execute this command you will receive a prompt requesting for a password. This is a password used to generate a hash key, so enter what you would want. 

A hashkey will be generated, simply copy this key (if you are using the command window then right click and select Mark and then highlight the key, then press enter). Now, go to the facebook page where it requested for a hashkey and paste the copied key in to the field called Development Key Hashes.

When you click Next, you've now completed everything. Facebook will provide additional information on the facebook.sdk which you can ignore for now. 

Think you are done ? well build and run the application now that you have the App ID in your application. You'll soon be presented with the following error:


This is the same error as before, nothing has changed (?). Ok, you need to do one more step to get this to work. Go to facebook into your application > setting and you may notice at the top there are three tabs. One of which is Advanced. Click on Advanced and scroll down to OAuth Settings and then paste in http://www.facebook.com/connect/login_success.html into the Valid OAuth Redirect Uris this should be the same as the redirectUri in your code. If it is anything different, copy and paste whatever you have in your code in to the   Valid OAuth Redirect Uris. 

While you are in the dashboard, double check the Hashkey to make sure that it has saved. If it has, then everything is all good - and you should be good to go.

Now, Rebuild your app and run it. 



There you have it, you now have Xamarin.Auth sample application running (as you can see I have edited the last image protect privacy, it essentially displayed your facebook name).

Final

This has been a long post, and almost all of it had to do with facebook registration, once you have the app id and facebook setup you simple need to replace app id in your code and execute the application. Unfortunately the documentation on Xamarin and also on github didn't indicate what you had to do, or provide documentation on setting up facebook. 

I hope this has helped someone. 









The Debugger Cannot Continue Running the Process. Unable to Start Debugging

While I've been working with Xamarin I have noticed some frustrating errors from Xamarin Studio and now with Visual Studio.

I was looking into Facebook Authentication and downloaded the master of Xamarin.Auth and tried to run the sample apps included and ran into a strange error:



Looking at the error it was hard to work out what went wrong, so I reverted to a friend to help with this.

The Fix


The solution contained two projects :

  1. Xamarin.Auth Sample (Android)
  2. Xamarin.Auth.Android
If you have the incorrect project setup as the startup project, in this case it is Xamarin.Auth.Android then you will get the error message. To fix this follow these steps:
  1. Right click on the Solution and goto Properties (it should be the last option or press Alt+Enter)
  2. Update the startup project to the project that should be starting up


I hope this helped. 

Saturday, May 30, 2015

VisualStudio 2013 - Xamarin - How to use Intellisense

When I installed Xamarin Business License, I noticed that intellisense was not working with the xml and axml files.

To get this to work you need to manually add two XSD files, once you have added them you will get Instellisense.

First open any random XML file, once you have opened it you will notice that the menu bar will have a new menu item called XML.

Next navigate to XML > Schemas > Add

Next enter the path in the filename box C:\Program Files (x86)\MSBuild\Xamarin\Android and hit enter

You should see two XSD files, select them both by holding shift and clicking on each.

Click on Open and you should see the files have been added in the XML Schemas dialog

Click OK in the Schema Dialog

and then close the XML file and reopen an XML or AXML and you should get intellisense as soon as you type <.

Hope this helps someone.

Tuesday, March 17, 2015

Intellisense in Razor View - Visual Studio 2013

Intellisense in VisualStudio is a god's gift to developers, its one of the things that make Visual Studio unbeatable for development. But on occasions Intellisense stops working for some reason, and I find that this normally happens while editing a view in an MVC application.

I tried a number of things, from building the project, to deleting the bin folder and re-doing the webconfig file, right through to re-creating the project again. That's how much it annoys me when Intellisense stops working.

I recently realized that this occurs when I edit the model backing the view. So when I'm editing the view and think that this would be better as a method in the model as opposed to doing calculations or think I actually need a another piece of data in the view, if I have the model available I quickly do an edit and then go back to the View and BAM! N.O M.O.R.E I.N.T.E.L.L.I.S.E.N.S.E.

So I closed the View, and then re-opened the view and there it was again - Intellisense was back again. I tried a couple of tests around this and this seems to be working.

So if you run in to a similar issue, before going through all of the work of re-creating the project try simple task of closing the View and re-opening it. It will save you a tonne of heartache and frustration.


Hope you find this helpful.

Wednesday, February 18, 2015

Building your own coils

Personal Vaporizers have suddenly become popular, so popular in fact that in my last trip to Europe and America I noticed that 50% of smokers were vaping. When you first start getting into vaping you will probably start off with a standard kit, as your curioisity grows you'll slowly move up and up in to more technical areas.

The minimum equipment you will need will be :
  1. Rebuildable Atmoizer 
  2. A small screwdriver or drill bit or anything that you can wrap a coil around
  3. Wicking Material
  4. Wire
  5. A blow torch (Butane)
  6. Tweezers 
  7. A cutting tool

This is assuming that you have a battery unit. 

Rebuildable Atomizer

A Rebuildable Atomizer is an Atomizer where you can build and install your own coils. In normal Kanger or Aspire tanks you would normally buy a units with built in coils installed and wicks installed - this is quite handy for most people since it is easy to replace the coils by unscrewing the old unit and replacing it with a new unit. 

Some people prefer to build the coils to their own specification, or you may want to build your own coil to dramatically decrease the costs of vaping. 

A Rebuildable Atomizer can be as cheap as $10USD right through to several hundred USD. If you are just getting into it, you may want to get something cheap to get you started and to make sure you are comfortable with all the fiddling around - please note that this is not for everyone. 

To get cheap "knock-off" rebuildables, head over to www.fasttech.com where you will find duplicates of some of the higher end brands. There is a tonne to choose from, and the duplicates vary in prices as well and they also vary in quality. 

Small Screwdriver

You will also need something that you can wrap the wire around to make the coil. Alot of people use small screw drivers or drill bits, but you can use just about anything you only need someone small enough for your preferred coil size that you can wrap the wire around 

You can also buy equipment that will also help you twist the wire around to make a coil.

You will also need a small screwdriver, usually a phillips head screwdriver, to attach the coil to the atomizer. 

Wicking Material

As I mentioned earlier, when you buy coils from Kanger and Aspire you will have a unit with wicking material. The wicking material is what sucks the juice and passes through the coil, the coil heats up and vaporises the juice in the wicking material. 

There is a lot of material that can be used as wicking material, for example you can use:
  • Silica Material
  • Cotton Balls
  • Cellucotton Rayon Fibers
  • Japanese Organic Cotton (Ken Doh Gen)
  • Ekowool
  • Stainless Steel Mesh
  • Ceramic Wick
Silica is what is commonly used by Kanger and Aspire, but a lot of people who build their own will tend to use Japanese Organic Cotton or Stainless Steel Mesh. It is generally by personal preference. You can purchase these at vape sites or on www.ebay.com.au.

Wire

The wire that you would generally be Kanthal A1 200 wire. There are different wires and different quality of wires. Some wires are advertised with a certain gauge but due to their quality they wont always produce the right ohm level that you would expect. 

Kanthal wires come in 22Gauge right through to 32 Gauge (commonly). Depending on the Gauge and the number of coils (Dual or single Coils) and the size of the coil will determine Ohm. 

For example 32 Gauge with 4 wraps to make the coil would generally give you about 2.2ohms. 
A 30 Gauge wire with 4 wraps will give you about 1.4 Ohm. If you have an electrical battery you probably want to get 30 Gauge wire, if you have a mechanical device you can go lower if you want it to. 

A Blow Torch

A blow torch or an open flame is required to prepare the wire. You generally need to run the blow torch up and down the wire to make it easier to work with (i.e it is more pliable).

Again you can get a butane device from www.fasttech.com or at a hardware store. 

Tweezers

You will need a pair of tweezers to hold the wire while you torch it, or squeezing down the coil to compress it or to space it while it is still hot. 

A Cutting Tool

You are going to cut the wire to the preferred size, and also trim excess wire after you attach the coil to the atomizer. A small scissors, a wire cutter, or even Nail Clippers will do the job. 

Personally I use nail clippers to trim the wick and the wires. 

I'll post pictures of my equipment soon. 


Tuesday, February 17, 2015

Entity Framework and Many to Many Relationship - Simple Example

If you want to do Many to Many relationship in Entity Framework the work is quite simple:

  1. Create two classes say Order and Product
  2. Establish a navigational property between the two classes 
  3. You're done. 
So lets take a look at this, the following, as in the example above is Order class

Public Class Order
{
    public int ID {get; set;}
    public string Description {get; set;}
    public virtual ICollection<Product> Products {get; set;}

    public Order()
    {
         this.Products = new List<Product>();
    }

}

The class is a basic class with an ID that is an integer, another property called Description which is of type string, and finally there is a collection of Products. The collection of products is what starts the relationship to Product entity or class. The collection is then instantiated in the constructor as a List. 

The following is the Product class

Public Class Product
{
    public int ID {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Order> Orders {get; set;}



 public Order()
 {
     this.Orders = new List<Order>();
  }

}


The product class is also quite simple in this example, it contains an ID of type integer, a Name of type string, and another collection - this time it is a collection of Orders. This then completes, for this example the many to many relationship. 

Therefore in reading the two entities you would say an Order has collection of Products (or many products) and Products has a collection of Orders (or many orders).

What is Virtual

You may have noticed that there is a virtual keyword before ICollection. The virtual keyword is to establish Lazy Loading. This means that when you retrieve the entity the collection is not loaded immediately, instead it is loaded when you start using it. 

Lets Continue

So to use the many to many relationship in the code you simply need to use the List functions to add/remove. For example to add a product to an instance of a order you would do something like this:


Order _order = New Order(){Description = "My Description"};
Product _product = new Product(){Name = "My Product"};
_order.Products.Add(_product);

In the above code, what we are doing is creating a new instance of Order and note that I'm assigning the value to the Description at the same time as creating the new object. I then create an instance of a Product, otherwise retrieve a product. I then add the product to the collection of Products in the Order object.

If you were using this in a database context you would need to add the Order to the Database, and then save the changes.  




Saturday, February 7, 2015

[Solved - I think ] Visual Studio High CPU usage

Out of nowhere I started Visual Studio to get some coding happening, and it was almost unusable.

I was editing a CSHTML file, and the CPU usage was through the roof. At one point the CPU usage was over 40% and my Surface Pro 3 started heating up and the only thing I could do was to shutdown Visual Studio.

I don't know why this is happening I was working on the same file last night without a hitch. Here is a screenshot of task manager:




























I'm suspecting that this is has something to do with JS and editing CSHTML files. When I edit a normal class everything is hunky dory.

Just an update: 

I tried closing some of the files, and restarted it. When I open one particular CSHTML file in my solution the CPU idles at 40%. I cannot share the code since it is part of a project. When I close the file it drops back 0% or 1%.




Another Update - I think I've worked it out.


I did some testing as to what was happening, I have a file I was doing some tests on called uploadFiles.cshtml. This was html to manage a ajax file upload. I was looking to integrate this functionality into my overall project.


  1. I opened uploadFiles.cshtml - The CPU usage hit 40% and bounced around from 30+% to 40%. I copied all the code and created a new CSHTML file (newupload.cshtml), pasted all the code without modifications. Once I closed  uploadFiles.cshtml and only newupload.cshtml was open the CPU usage went back down. Strange. I initially thought that it was because I had comments using the razor syntax with references to stackoverflow questions and answers and blog posts while I conducted my tests. 
  2. I closed VS and opened newupload.cshtml and everything was normal. I closed VS again, and reopened VS and this time I opened uploadFiles.cshtml. The CPU hit 40%. So now I realised that it wasn't the code in the uploadFiles.cshtml. Just to make sure I deleted all the code in uploadFiles.cshtml and replaced it with some normal markup. The CPU was still bouncing around from 30% to 40%. The only conclusion i could make is that there is something odd with the file. 
  3. I checked the file permissions and folder locations to make sure that there isn't something odd (like the file is located on another network share or USB etc...). But nothing was out of the ordinary. 
  4. I then checked the Solution, and then I noticed something. The uploadFiles.cshtml was excluded from the project. I then included the file into the project and the CPU was 0%-1% and everything was fine. I repeated this by excluding the file from the solution and re-opened the file and the CPU went to about 40%.  


My Conclusion


My conclusion at this stage is that there is something odd happening with opening excluded files in your solution. If you have this issue then try the following:

  1. Close the open file
  2. Right click on the file in your solution explorer and go to Include In Project. 
  3. Open file 

see if this works, it seems to be working for me. 




Thursday, February 5, 2015

Surface Pro Function Keys

If you are an owner of Surface Pro you may have noticed that you don't have quick access to the function keys. For the general consumer the settings of the function keys are less useful and the standard media and other options are far more convenient.

However, if you are a developer you tend to always try and reach for the function keys (e.g build, run etc...).

What you can do is press the    Fn    key +   Caps   key to lock the function key. Then you no longer need to press the Fn key to access the Function keys.

This may be a Windows feature or not and may work with other Laptops etc...

Tuesday, February 3, 2015

Create your own Android Character

There's a new site out that allows you to create your own Android Character. You can choose from a range body shapes, outfits, and accessories to try and mimic an Android that looks just like you, your friend, or your family member.

Or maybe make character of who you think you are, to check it out click here : https://androidify.com/en/#/

Samsung Galaxy S5 - What I want

I'll soon be in the market for a new smart phone, and I'm eagerly looking forward to what Samsung has been working on under the covers. The last set of rumours indicated that the Galaxy line up is being re-designed from the ground up. This is welcome news, since I didn't get a new phone this year because S5 just didn't cut it enough for me to move from my HTC One M7.

So if Samsung is looking to re-design this from the ground up, then here is my wish list:

TouchWiz

The only Samsung Phone that I have liked to date is the Samsung Galaxy Nexus and this was purely because it ran stock Android. It was snappy, had a slight curve and it just worked. Every time I looked at the Galaxy lineup I'm always greeted by TouchWiz, and it always turns we off.
I know there are people out there who think that TouchWiz is great, and I know that Samsung must do focus groups and the people who like them are attending those focus groups. But Samsung, you need to get out a bit more - A lot of people do not like TouchWiz and compared to Android 5 TouchWiz just looks awful and slow.


If you could get an option say - for technical minded people to download and install pure Android it wouldn't be so bad.

Home Button

I feel like the Home button is holding Samsung back. Android phones in general have embraced on-screen or Capacitive buttons for a while. But Samsung has held on to the home button, and then increased the use of the home button by adding a finger-print reader. I really think that Samsung's design could look a whole lot better if the Home Button disappears.

Loose the Gimmicks

With a lot of Android phones, Samsung and HTC included, in an attempt to stand out from the crowd they've tried to add features. In Samsung's case a lot of features. However, a lot of these features tend to be gimmicks - they look good or ok today and in a couple of months you are not using any of the features. There is so much packed into a Samsung phone, it'd be good if Samsung concentrated on a few features that people would actually want.

More Edge

Last year we saw an Alternative to the Galaxy Note which was the Galaxy Note Edge. This was sold along side Galaxy Note, probably not to disrupt the Galaxy Note Sales. However, I personally thought that this was interesting and I would definitively like to see more. Maybe something along the top or the bottom - something like showing the music controls so that it you can see it peeking out of your pocket.

Overall I just want to see what they can do with curved displays. LG G Flex 2 managed to showcase somewhat of a curved display and now its time for Samsung.

Build Quality

Some people are sick of the plastic build quality, and personally I don't really mind the plasticity of Samsung phones. I would much rather have a phone like the Samsung phones if I had to compromise with removable storage and removable battery.

However, there are a number of manufacturers who have dramatically improved their build quality - namely HTC, Moto,  and Apple, that I believe Samsung cannot ignore this any more and has to seriously think about build quality for their phones.



Visual Studio Code Snippets

I've been working with Visual Studio for years, and all this time I have not come across this feature till now.

Visual Studio has built in code snippets, in order to access them you need to first place your cursor where you want some code to be pasted and then you need to press


CTRL + K + CTRL X

I haven't been able to take a screenshot of this, but what will happen is a dialog box will appear with a set of folders. Simply use your cursor keys to navigate to a folder (in my case it is Visual C#) and then press enter, this will reveal the snippets. Browse through the snippet and then hit enter to when you find the one that you want.


Stuck trying to modify the ApplicationUser and Multiple DbContexts

When you are trying to update the AccountController in ASP.NET MVC - to enhance the ApplicationUser or another related entity during Registration you may quickly realise that the AccountController doesn't have a DbContext for you to use.

So like anyone, and looking at the other sample controllers you'll probably define something like this:

ApplicationDbContext db = new ApplicationDbContext();
You then write your code, everything compiles and you run a quick test. Suddenly you are left with a strange error... your applications dumps with Entity Framework complaining that about contexts. What's go ?

Well, what happens is within the AccountController there is no mention of a DBContext, instead the DBContext is being brought in using OWIN.

Have a look in Sartup.Auth.cs, in there there is a definition of the ApplicationDbContext:
app.CreatePerOwinContext(ApplicationDbContext.Create);
The UserManager then utilises OWIN to get the instance of the ApplicationDbContext, so when you define your own context the entities that you use to either retrieve or save using your own context will be tracked only within your defined context.

If you want to use the same DbContext as what the UserManager uses then it is as simple as using OWIN to get the context.

var db = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
This gets the DbContext from OWIN and it will be consistent with the DbContext that the UserManager uses.

Please note, if you want to use this method in any other controller other than the AccountController then make sure that you use the using statements:

using Microsoft.AspNet.Identity.Owin;

I hope this helps. I spent hours hunting this one down - hopefully you will find this page and save some time.

Monday, February 2, 2015

Get the Current Logged in user

In ASP.NET MVC if you are using Asp.Net Identities, you will need to at times get the current logged in user. You may need to do this to determine whether the current logged in user has access to view, create, modify records etc...

First of all this can be only completed in the Controller. If you need the user inside of another class, you will need to pass this through to the class method/function etc...

In the controller, header set the following properties:
   protected ApplicationDbContext Db { get; set; }
   protected UserManager<ApplicationUser> UM { get; set; }
Then in the class Constructor add the following lines:
this.Db = new ApplicationDbContext();
    this.UM = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.Db));

Once you have done this, you can then get the user within the controller using the following :
var user = UM.FindById(User.Identity.GetUserId());

The user will be of type ApplicationUser.

Saturday, January 24, 2015

MVC - Unable to Attach DB

If you are working in Visual Studio, sometimes you want to try and start again with the database. Often this is when you make drastic model changes. I have on a number of occasions have deleted the .mdf file in the App_Data folder.

This is not a recommended approach, since it will cause inconsistencies with the connected database. To resolve this, open up the Package Manager Console and type in the following commands:

sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
Add-Migration MyMigration
Update-Database


When you do Update-Database, you may need to create a migration using Add-Migration <name>.

I've updated it to include this with the migration, please note that MyMigration can be anything that you want to call it.

Hope this helps.

Tuesday, January 20, 2015

Lost Bitcoins

In the world of Crytocurrency Bitcoins is considered the Gold standard. One of the features that make Bitcoins and Cryptocurrency in general ahead of the normal Fiat currency is the fact that you transact anonymously around the world. This means that who ever owns the wallet is unknown,  which is why it was being used at underground sites such as SilkRoad.

There's a total limit of the number of Bitcoins that will ever be available, once this is completely mined and available to the public there is nothing further Bitcoins. The total number of Bitcoins is 21 Million. However, at the time of when the last Bitcoin is produced the total number in actual circulation will be far less than the 21 Million.

Why?

When Bitcoins were first introduced it was far less than a Niche product. It was being mined by people who were interested in it. It probably didn't have a lot of value at that time, and over the years some of the early Bitcoins that have been mined are now probably lost. For example, I mined Bitcoins in the early years, it had no value, I grew up changed computers and didn't think of backing anything up. I can't even recall how many I had - but I did have a handful. I'm sure I'm not the only that did this, so this leaves a hole in the total number of Bitcoins.

So what happens to them? 

 This also happens to cash, you leave it in your pocket, you drop it in a river, or you simply misplace it - or it is sitting under your couch. However, with normal currency additional currency is printed and produced - this is not the case with Bitcoins. It needs to be reclaimed from the original wallet - if the person that had the wallet no longer remembers their password, then the only option is to hack the wallet, if you can successfully crack the wallets then the whole Bitcoin security will come crumbling down.

The reality is Bitcoin has a lot of appeal on how currency can be digitised, however, it is going up against financial institutions and governments who have a lot of vested interest in their ecosystems. For the time being the total price of Bitcoin is purely speculations, it may one day be worth $100,000 or it may just fall off the cliff.

Surface Pro 3 - Fantastic


I think the last time I posted something about the Microsoft Surface it was a couple of years ago. Although Surface Pro 3 didn't deliver everything I wanted, I bit the bullet and bought one any way. That was over 6 months ago.

There are a number of reviews out there about Surface Pro 3, so I didn't want to something about the surface that has already been covered. 



After using the Surface Pro 3 this is how I feel about it : 

  • The product itself and overall is pretty impressive, I worried about performance etc... but I haven't had any problems to date. I did have a problem one night when it became really hot - I mean really hot. The temerature control came on and shut the system down - the fans could be heard fired up and whirring away. 
  • The Type Cover is fantastic, and it is almost as pleasurable to type on the Type cover as the macbook pro keyboard. The trackpad is a bit of a dud, I feel like I was spoilt with the trackpad of the macs - which is probably the best trackpad by a mile. There's been times when I'm scrolling a webpage and it just doesn't scroll and I had to use the touch screen. I also have issues with the left click, it feels that it is getting stuck and the tactile feedback is just not there sometimes (I have to bend the cover slightly to try and pop it up).
  • The screen is beautiful, absolutely gorgeous.
  • The Pen placement is still a problem. It is probably better the previous surface pro magnetic attachment but when you try and place it in a bag it sometimes gets caught - its just an annoyance. 
  • Pen implementation with one note is FANTASTIC I'm someone that writes, and draws pictures alot when I speak to people. I tend to use the back of what ever is around. With one note + surface + surface pen, I no longer need to do that I just use One Note. 
  • I haven't found any issues with windows 8,  I have to confess I do like the start screen in windows 8 compared to the previous versions. But I am in the desktop  mode quite alot. I also like the idea of being able to tap the Windows key and typing the name of the application and Enter (Perfect).
  • I like the swiping from the left to rotate the application, but I haven't had the need to put them side-by-side since I'm in the normal applications (not metro). 
  • I haven't had the need to use the camera at all yet. 
  • Sound is great for me - obviously this isn't something that provides the best quality sound possible through those tiny speakers. 
  • One major problem that I'm facing is the wireless - I have intermitent problems with the wireless. This ranges from poor performance, to dropped connections, to being unable find and/or connect to my home network. 
  • I am still disappointed that I don't wireless ac and mobile broadband. I'm waiting for the new Wireless AC routers before moving to Wireless Ac. 

I would consider getting the next version if it had mobile broadband wireless ac. 

Working with the Paypal Classic API Samples

When I started the the Classic API Samples I had to do the following operations for Visual Studio 2013:

  1. Open the solution by double clicking on the .sln file via Exporer (or open it directly from Visual Studio)
  2. Visual Studio will prompt you about one way migration, accept it and continue
  3. Set the .NET Framework to 4.5.2 as it suggests

When you run the application it will work to a point - I noticed that the order that the main() executes the calls is not in the right order. Also, I noticed that there was a number of items that was hardcoded.

For example, the SetExpressCheckoutSamplewas further down, and CreateRecurringPaymentsProfileSample and DoCaptureSample were ahead of it. In terms of the order of operations this doesn't really make any sense since the Customer has not authorised anything they would have clicked submit on your page. 

The tokens that are used were also hardcoded, this is ok for the initial test - but Paypal really should have paid more attention to this. Since this will get Newbie (such as myself unstuck). 

To resolve this, I had to store the token once SetExpressCheckoutSample.SetExpressCheckoutAPIOperation() is executed. I then had to pass the token into where ever the token was being referred to. 

For example, in GetExpressCheckoutDetailsSample I overloaded the constructor to take in a string:

public string tk {get; set;}


public GetExpressCheckoutDetailsSample(string tk)
    {
        this.token = tk;
    }

Please note that this is to try and get the samples to actually work only. 

Then, I replaced GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType("EC-11U13522TP7143059"); with 

GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(this.token);

As you can see above the Token was hardcoded, by passing the this.token instead of the hardcoded value I could use what I had set previously in SetExpressCheckoutSample.

Unfortunately the Classic API sample is a console application, after making these changes I was expecting the PayerID to be printed. When I found that this didn't actually print out anything and debugging and checking google. I noticed that there was a comment above the Console.WriteLn stating:

"
// Unique PayPal Customer Account identification number. This
                    // value will be null unless you authorize the payment by
                    // redirecting to PayPal after `SetExpressCheckout` call.

"

Good work Paypal, why would you provide a sample without actually providing a working sample? This sample should have been a asp.net sample, with the appropriate redirection routine. 

I'm positing this as I progress - however, I may need to alter posts as I learn more.

Thanks