Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Mar 21, 2018

Where is Unity Log Files?

Log Files

There might be times during development when you need to obtain information from the logs of the standalone player you’ve built, the target device, or the Editor. Usually you need to see these files when you have experienced a problem, to find out exactly where the problem occurred.
On macOS, the player and Editor logs can be accessed uniformly through the standard Console.app utility.
On Windows, the Editor logs are placed in folders which are not shown in the Windows Explorer by default. See below.

Editor

To view the Editor log, select Open Editor Log in Unity’s Console window.









On macOS, all the logs can be accessed uniformly through the standard Console.app utility.
On Windows, the Editor log file is stored in the local application data folder \Unity\Editor\Editor.log, where is defined by CSIDL_LOCAL_APPDATA.

Player


Note that on Windows and Linux standalones, the location of the log file can be changed (or logging suppressed). See documenttion on Command line arguments for further details.

iOS

Access the device log in XCode via the GDB console or the Organizer Console. The latter is useful for getting crashlogs when your application was not running through the XCode debugger.
The Troubleshooting and Reporting crash bugs guides may be useful for you.

Android

Access the device log using the logcat console. Use the adb application found in Android SDK/platform-tools directory with a trailing logcat parameter:

$ adb logcat

Another way to inspect the LogCat is to use the Dalvik Debug Monitor Server (DDMS). DDMS can be started either from Eclipse or from inside the Android SDK/tools. DDMS also provides a number of other debug related tools.

Universal Windows Platform

 


WebGL

On WebGL, log output is written to the browser’s JavaScript console.

Accessing log files on Windows

On Windows, the log files are stored in locations that are hidden by default. In Windows XP, make hidden folders visible in Windows Explorer using Tools > Folder Options… > View (tab).
On Windows Vista/7, make the AppData folder visible in Windows Explorer using Tools > Folder Options… > View (tab). The Tools menu is hidden by default; press the Alt key once to display it.

Reference:  https://docs.unity3d.com/Manual/LogFiles.html

How to Save and Load a Game in Unity

Games are getting longer and longer, with some having over 100 hours of content. It would be impossible to expect players be able to complete all of what a game has to offer in just one sitting. That’s why letting the player save their game is one of the most essential features your game should have — even if it’s just to keep track of their high scores.
But how does one create a save file and what should be in it? Do you need to use a save file to keep track of player settings too? What about submitting saves to the web so they can be downloaded later on a different device?
In this tutorial you will learn:
  • What serialization and deserialization are.
  • What PlayerPrefs is and how to use it to save player settings.
  • How to create a save game file and save it to disk.
  • How to load a save game file.
  • What JSON is and how you would use it.
It is assumed that you have some basic working knowledge of how Unity works (such as being able to create and open scripts), but other than that everything has been prepared so this tutorial will be very easy to follow. Even if you are new to C#, you should have no trouble keeping up except for a few concepts that might require further reading.
Note: If you are new to Unity or looking to pick up more Unity skills, you should checkout out our other Unity tutorials where you can learn about lots of Unity topics from C# to how the UI works.

Getting Started

Download the starter project here. You will be implementing the code for saving and loading the game, as well as the logic for saving the players settings.

Important Save Concepts

There are four key concepts to saving in Unity:
PlayerPrefs: This is a special caching system to keep track of simple settings for the player between game sessions. Many new programmers make the mistake of thinking they can use this as a save game system as well, but it is bad practice to do so. This should only be used for keeping track of simple things like graphics, sound settings, login info, or other basic user-related data.
Serialization: This is the magic that makes Unity work. Serialization is the conversion of an object into a stream of bytes. That might seem vague but take a quick look at this graphic:
Serialization illustration
What is an “object”? In this case an “object” is any script or file in Unity. In fact, whenever you create a MonoBehaviour script, Unity uses serialization & deserialization to convert that file down to C++ code and then back to the C# code that you see in the inspector window. If you’ve ever added [SerializeField] to get something to appear in the inspector, you now have an idea of what’s going on.
Note: If you’re a Java or web developer, you might be familiar with a concept known as marshalling. Serialization and marshalling are loosely synonymous, but in case you’re wondering what a strict difference would be, serialization is about converting an object from one form to another (e.g. an object into bytes), whereas marshalling is about getting parameters from one place to another.
Deserialization: This is exactly what it sounds like. It’s the opposite of serialization, namely the conversion of a stream of bytes into an object.
JSON: This stands for JavaScript Object Notation, which is a convenient format for sending and receiving data that is language agnostic. For example, you might have a web server running in Java or PHP. You couldn’t just send a C# object over, but you could send a JSON representation of that object and let the server recreate a localized version of it there. You’ll learn more about this format in the last section but for now just know that this simply a way of formatting data to make it multi-platform readable (like XML). When dealing with converting to and from JSON, the terms are JSON serialization and JSON deserialization respectively.

Player Prefs

This project has been set up so that all you will focus on is the logic for saving and loading games. However, if you are curious how it all works, don’t be afraid to open all the scripts and see whats going on, and feel free to ask a question here or in the forums if you need help.
Open the project, then open the Scene named Game and then click play.
Start menu
To start a game, click the New Game button. To play the game, you simply move your mouse, and the gun will follow your movement. Click the left mouse button to fire a bullet and hit the targets (which flip up and down at various time intervals) to get points. Try it out and see how high a score you can get in 30 seconds. To bring up the menu at any time, press the escape key.
game in progress
As fun as that game was, it might have been a little dry without music. You may have noticed that there is a music toggle, but it was switched off. Click play to start a new game, but this time click the Music toggle so it’s set to “On”, and you will hear music when you start your game. Make sure your speakers are on!
music toggle
Changing the music setting was simple, but click the play button again and you’ll notice a problem: the music is no longer checked. While you did change the music setting earlier, there was nothing keeping track of that change. This is the kind of thing that PlayerPrefs excels at.
Create a new script named PlayerSettings in the Scripts folder. Since you’ll be using some UI elements, add the following line at the top of the file with the other namespaces:
using UnityEngine.UI;
Next, add the following variables:
[SerializeField]
private Toggle toggle;
[SerializeField]
private AudioSource myAudio;
These will keep track of the Toggle and AudioSource objects.
Next add the following function:
  public void Awake ()
  {
    // 1
    if (!PlayerPrefs.HasKey("music"))
    {
      PlayerPrefs.SetInt("music", 1);
      toggle.isOn = true;
      myAudio.enabled = true;
      PlayerPrefs.Save ();
    }
    // 2
    else
    {
      if (PlayerPrefs.GetInt ("music") == 0)
      {
        myAudio.enabled = false;
        toggle.isOn = false;
      }
      else
      {
        myAudio.enabled = true;
        toggle.isOn = true;
      }
    }
  }
When set up, this will:
  1. Check if the PlayerPrefs has a cached setting for the “music” key. If there is no value there, it creates a key-value pair for the music key with a value of 1. It also sets the toggle to on and enables the AudioSource. This will be run the first time the player runs the game. The value of 1 is used because you cannot store a Boolean (but you can use 0 as false and 1 as true).
  2. This checks the “music” key saved in the PlayerPrefs. If the value is set to 1, the player had music on, so it enables the music and sets the toggle to on. Otherwise, it sets the music to off and disables the toggle.
Now Save the changes to your script and return to Unity.
Add the PlayerSettings script to the Game GameObject. Then expand the UI GameObject, followed by the Menu GameObject to reveal its children. Then drag the Music GameObject on to the Toggle field of the PlayerSettings script. Next, select the Game GameObject and drag the AudioSource over to the MyAudio field.
<Connect PlayerSettings script
The music is set up to work when the game runs (since there is code in the Awake function), but you still need to add the code if the player changes the setting during gameplay. Open the PlayerSettings script and add the following function:
  public void ToggleMusic()
  {
    if (toggle.isOn)
    {
      PlayerPrefs.SetInt ("music", 1);
      myAudio.enabled = true;
    }
    else
    {
      PlayerPrefs.SetInt ("music", 0);
      myAudio.enabled = false;
    }
    PlayerPrefs.Save ();
  }
This does almost the same as the code you wrote earlier, except it has one important difference. It checks the state of the music toggle and then updates the saved setting accordingly. In order for this method to be called, and thus for it to be able to do its work, you need to set the callback method on the Toggle GameObject. Select the Music GameObject and drag the Game GameObject over the object field in the OnValueChanged section:
Connecting the callback method
Select the dropdown which currently says No Function, and select PlayerSettings -> ToggleMusic(). When the toggle button in the menu is pressed, it will call the ToggleMusic function.
Selecting the right method
Now you’ve got things set up to keep track of the music setting. Click Play and try it out by setting the music toggle to on or off, then ending the play session and starting a new play session.
The game menu
The music setting is now properly saved! Great job — but you’re only getting started with the power of serialization.

Saving The Game

Using PlayerPrefs was pretty simple wasn’t it? With it, you will be able to easily store other settings in there such as the player’s graphic settings, or login info (perhaps Facebook or Twitter tokens), and whatever other configuration settings make sense to keep track of for the player. However, PlayerPrefs is not designed to keep track of game saves. For that, you will want to use serialization.
The first step to creating a save game file is creating the save file class. Create a script named Save and remove the MonoBehaviour inheritance. Remove the default Start() and Update() methods as well.
Next, add the following variables:
public List<int> livingTargetPositions = new List<int>();
public List<int> livingTargetsTypes = new List<int>();

public int hits = 0;
public int shots = 0;
In order to save the game you will need to keep track of where existing robots are and what types they are. The two lists accomplish this. For the number of hits and shots you are just going to store those as ints.
There is one more very important bit of code you need to add. Above the class declaration, add the following line:
[System.Serializable]
This is known as an attribute and it is metadata for your code. This tells Unity that this class can be serialized, which means you can turn it into a stream of bytes and save it to a file on disk.
Note: Attributes have a wide range of uses and let you attach data to a class, method, or variable (this data is known as metadata). You can even define your own attributes to use in your code. Serialization makes use of the [SerializeField] and [System.Serializable] attributes so that it knows what to write when serializing the object. Other uses for attributes include settings for unit tests and dependency injection, which are way beyond the scope of this tutorial but well worth investigating.
The entire Save script should look like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Save
{
  public List<int> livingTargetPositions = new List<int>();
  public List<int> livingTargetsTypes = new List<int>();

  public int hits = 0;
  public int shots = 0;
}
Next, open the Game script and add the following method:
private Save CreateSaveGameObject()
{
  Save save = new Save();
  int i = 0;
  foreach (GameObject targetGameObject in targets)
  {
    Target target = targetGameObject.GetComponent();
    if (target.activeRobot != null)
    {
      save.livingTargetPositions.Add(target.position);
      save.livingTargetsTypes.Add((int)target.activeRobot.GetComponent().type);
      i++;
    }
  }

  save.hits = hits;
  save.shots = shots;

  return save;
}
This code creates an instance of the Save class you made earlier and then sets the values from the existing robots. It also saves the players shots and hits.
The Save button has been hooked up to the SaveGame method in the Game script, but there is no code in SaveGame yet. Replace the SaveGame function with the following code:
public void SaveGame()
{
  // 1
  Save save = CreateSaveGameObject();

  // 2
  BinaryFormatter bf = new BinaryFormatter();
  FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
  bf.Serialize(file, save);
  file.Close();

  // 3
  hits = 0;
  shots = 0;
  shotsText.text = "Shots: " + shots;
  hitsText.text = "Hits: " + hits;

  ClearRobots();
  ClearBullets();
  Debug.Log("Game Saved");
}
Taking it comment-by-comment:
  1. Create a Save instance with all the data for the current session saved into it.
  2. Create a BinaryFormatter and a FileStream by passing a path for the Save instance to be saved to. It serializes the data (into bytes) and writes it to disk and closes the FileStream. There will now be a file named gamesave.save on your computer. The .save was just used as an example, and you could use any extension for the file save name.
  3. This just resets the game so that after the player saves, everything is in a default state.
To save the game, press Escape at any time during play and click the Save button. You should notice everything resets and the console output displays a note that the game has been saved.
Console output
LoadGame in the Game script is connected to the Load button. Open the Game script and locate the LoadGame function. Replace it with the following:
public void LoadGame()
{ 
  // 1
  if (File.Exists(Application.persistentDataPath + "/gamesave.save"))
  {
    ClearBullets();
    ClearRobots();
    RefreshRobots();

    // 2
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Open(Application.persistentDataPath + "/gamesave.save", FileMode.Open);
    Save save = (Save)bf.Deserialize(file);
    file.Close();

    // 3
    for (int i = 0; i < save.livingTargetPositions.Count; i++)
    {
      int position = save.livingTargetPositions[i];
      Target target = targets[position].GetComponent();
      target.ActivateRobot((RobotTypes)save.livingTargetsTypes[i]);
      target.GetComponent().ResetDeathTimer();
    }

    // 4
    shotsText.text = "Shots: " + save.shots;
    hitsText.text = "Hits: " + save.hits;
    shots = save.shots;
    hits = save.hits;

    Debug.Log("Game Loaded");

    Unpause();
  }
  else
  {
    Debug.Log("No game saved!");
  }
}
Looking at this in detail:
  1. Checks to see that the save file exists. If it does, it clears the robots and the score. Otherwise it logs to the console that there is no saved game.
  2. Similar to what you did when saving the game, you again create a BinaryFormatter, only this time you are providing it with a stream of bytes to read instead of write. So you simply pass it the path to the save file. It creates the Save object and closes the FileStream.
  3. Even though you have the save information, you still need to convert that into the game state. This code loops through the saved robot positions (for living robots) and adds a robot at that position. It also sets it to the right type. For simplicity, the timers are reset, but you can remove this if you prefer. This prevents the robots from disappearing right away and gives the player a few seconds to get oriented in the world. Also, for simplicity, the animation of the robot moving up is set to finished, which is why robots partly moving up when you saved will be shown as fully up when a game is loaded.
  4. This updates the UI to have the right hits and shots set, and it sets the local variables so that when the player fires or hits a target it continues to count up on the value that was previously. If you didn’t do this step, the next time the player fires or hits a target the displayed values would get set to 1.
Click Play, play the game for a bit then save. Click the Load button and you will see it load the enemies as they were set up before when you saved the game. It also properly sets your score and the shots you’ve fired.
Game in progress

Saving Data With JSON

There’s one more trick you can use when you want to save data — and that is JSON. You could create a local JSON representation of your game save, send it to a server, then get that JSON (as a String) to another device and convert it from a string back to JSON. This tutorial won’t cover sending/receiving from the web, but it is very helpful to know how to use JSON — and it’s incredibly simple.
The format of JSON can be a little different than what you might be used from C# code, but it’s pretty straightforward. Here is a simple JSON example:
{
  "message":"hi",
  "age":22
  "items":
  [
    "Broadsword",
    "Bow"
  ]
}
The outer brackets represent the parent entity that is the JSON. If you are familiar with a Dictionary data structure, then JSON is similar. A JSON file is a mapping of key and value pairs. So the above example has 3 key-value pairs. With JSON, the keys are always strings, but the values can be objects (i.e. children JSON objects), arrays, numbers, or strings. The value set to the “message” key is “hi”, the value of the “age” key is the number 22, and the value of the “items” key is an array with two strings in it.
The JSON object itself is represented by a String type. By passing this data as a String, any language can easily re-create JSON object from the string as a constructor argument. Very convenient and very simple.
Each language has its own way of creating an object from this format. Since Unity 5.3, there exists a native method to create a JSON object from a JSON string. You will create a JSON representation of the high score of the player and then print it to the console. But you extend this logic by sending the JSON to a server.
The Game script has a method named SaveAsJSON that is hooked up to the Save As JSON button. Replace SaveAsJSON with the following code:
public void SaveAsJSON()
{
  Save save = CreateSaveGameObject();
  string json = JsonUtility.ToJson(save);

  Debug.Log("Saving as JSON: " + json);
}
This creates the Save instance like you did earlier. Then it creates a JSON string using the ToJSON method on the JsonUtility class. It then prints the output to console.
Start a game, hit a few targets, then press Escape to bring up the menu. Click the Save As JSON button, and you will see the JSON string you created:
Console output
If you want convert that JSON into a Save instance you would simply use:
Save save = JsonUtility.FromJson(json);
That is what you would do if you wanted to download a save file from the web and then load it into your game. But setting up a web server is a whole other process! For now, pat yourself on the back because you just learned a few techniques that will… save you some trouble in your next game (groan)!

Reference:  https://www.raywenderlich.com/160815/save-load-game-unity

Feb 10, 2018

Resolving harmless binding errors in WPF

While developing WPF applications, you will notice a lot of binding errors being displayed in output window; like this
System.Windows.Data Error: 4 : Cannot find source for binding with reference 
'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', 
AncestorLevel='1''. BindingExpression:Path=CellsPanelHorizontalOffset; DataItem=null; 
target element is 'Button' (Name=''); target property is 'Width' (type 'Double')

System.Windows.Data Error: 4 : Cannot find source for binding with reference 
'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', 
AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; 
target element is 'ComboBoxItem' (Name=''); target property is 
'HorizontalContentAlignment' (type 'HorizontalAlignment')

System.Windows.Data Error: 4 : Cannot find source for binding with reference 
'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', 
AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; 
target element is 'ComboBoxItem' (Name=''); target property is 
'VerticalContentAlignment' (type 'VerticalAlignment')
I also faced this problem and tried a lot of things to get to the root cause of the problem. It was very frustrating as AncestorLevel is not used anywhere in code! and I was not able to find the place in code which is responsible for these errors.
Even after searching the various forums and articles there was no solution for this problem; but this was a very common issue and cause of this problem as mentioned on various forums:
This is a "known" issue, and happens to all controls that contain dynamically created lists (all item controls i.e. ComboBox, menu, ListBox etc.).
ControlTemplate of items in these controls (specifically MenuItem, ComboBoxItem etc.)
try to find the nearest ItemsControl and bind to the VerticalAlignment and HorizonalAlignment properties and raises this error on not finding the source.
Microsoft guys mention here and here that “This error has already been handled internally, so you can just leave it alone.” But, still I wanted some sort of solution so as not to have so many irritating error messages in my output window;
Solution 1:
So, I tried one of the workaround provided for this problem i.e. to explicitly set the properties which cause problems like this -
<ComboBox
    Name="control">
    <ComboBox.ItemContainerStyle>
        <Style
            TargetType="ComboBoxItem">
            <Setter
                Property="HorizontalContentAlignment"
                Value="Left" />
            <Setter
                Property="VerticalContentAlignment"
                Value="Center" />
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>
This works but it’s very hard task to set these properties across the whole solution for each problematic control(i.e. ListBox, Menu, ContextMenus etc.).
Have a look at this SO question for some other workarounds for this problem - ListBox with Grid as ItemsPanelTemplate produces weird binding errors
Solution 2:
Another workaround is to suppress these errors (actually, it seems more appropriate to call them warnings) by setting the data binding source switch level as critical in constructor of the class or a top level window -
#if DEBUG 
System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level = System.Diagnostics.SourceLevels.Critical;
#endif
I find this one line workaround more appropriate as it works for all such controls (like Menus, ListBox etc.) and that too across the whole project  -

REFERENCE : https://weblogs.asp.net/akjoshi/resolving-un-harmful-binding-errors-in-wpf

Jan 4, 2018

WPF Error 40 BindingExpression path error: property not found on 'object'

On XAML, I created a datatemplate with binding for an object called Skills.
And I set the datatemplate in my C# program on a ListViewItem like this:

DataTemplate template = (DataTemplate)this.FindResource("SkillListItem");
ListViewItem litem = new ListViewItem();
litem.ContentTemplate = template; 

And on visual studio I got this error:
WPF Error 40 BindingExpression path error: 'Name 'property not found on 'object' Skill

It is a strange error that can solve by changing
public string Name;
 
to this
public string Name{ get; set; }


 

Dec 17, 2017

A Better Way to Data Bind Enums in WPF

Have you needed to data bind enums in WPF? Well, if you write WPF applications, you bet your ass you have! In this post, I would like to show you how I like to deal with enums in WPF. Fo this post, I will be using the following enum to bind to.

public enum Status
{
    Horrible,
    Bad,
    SoSo,
    Good,
    Better,
    Best
}

The WPF Way

Normally if you were going to data bind a control to your enum you would need to go through a number of steps.  First you need to add a XAML namespace for your local enum type and to System in MSCorLib.

xmlns:local="clr-namespace:BindingEnums"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Then you would to create an ObjectDataProvider as a resource.  Give it an x:Key so you can use it in your code, set the MethodName to “GetValues” which exists on the enum data type, and then set the ObjectType to that of the enum type.  But wait, you’re not done yet.  Next you need to set the ObjectDataProvider.MethodParameters to that of your enum type.  So you will end up with something like this.

<Window.Resources>
    <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                        ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:Status"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>
Now, you you have something you can data bind to.  For example, if I wanted to data bind a ComboBox to this enum, I would have to set it’s ItemsSource to a new Binding, and set the source to that of our enum ObjectDataProvider we created above.  Like so:

<Grid>
    <ComboBox HorizontalAlignment="Center" VerticalAlignment="Center" MinWidth="150"
              ItemsSource="{Binding Source={StaticResource dataFromEnum}}"/>
</Grid>
And viola! Our enum is data bound.

This isn’t bad.  It works just fine, but it requires a lot more code than I would like to have to write over and over.  I would rather write the code once, and just change the enum type so I can reuse all that logic all over my application.  With the above approach we have to create a new ObjectDataProvider for each enum we have, which just means more code to maintain, and more chances of writing broken XAML.  Especially since you are more likely to copy and paste a previous ObjectDataProvider you created and just change some parameters.  Hence, it’s more error prone.

The Better Way

Let’s look at how we can use features of WPF to improve the usage and readability of our code when data binding to enums.  First, I want to encapsulate all that logic for creating a bindable list of enum values without the need of an ObjectDataProvider.  I also want to eliminate the need to create a Resource that must be defined in order to be used in my XAML.  Ideally I would just do everything inline like I would with a normal object binding.  To accomplish this, I am going to enlist the help of a custom MarkupExtension.  This extension will simply take an enum Type and then create a bindable list of enum values for my control.  It’s actually quite simple.  Take a look:

public class EnumBindingSourceExtension : MarkupExtension
{
    private Type _enumType;
    public Type EnumType
    {
        get { return this._enumType; }
        set
        {
            if (value != this._enumType)
            {
                if (null != value)
                {
                    Type enumType = Nullable.GetUnderlyingType(value) ?? value;                     if (!enumType.IsEnum)
                        throw new ArgumentException("Type must be for an Enum.");
                }
                this._enumType = value;
            }
        }
    }
    public EnumBindingSourceExtension() { }
    public EnumBindingSourceExtension(Type enumType)
    {
        this.EnumType = enumType;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (null == this._enumType)
            throw new InvalidOperationException("The EnumType must be specified.");
        Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
        Array enumValues = Enum.GetValues(actualEnumType);
        if (actualEnumType == this._enumType)
            return enumValues;
        Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
        enumValues.CopyTo(tempArray, 1);
        return tempArray;
    }
}

Now we can simplify our XAML and simply create an enum binding like this:
<Grid>
    <ComboBox HorizontalAlignment="Center" VerticalAlignment="Center" MinWidth="150"
              ItemsSource="{Binding Source={local:EnumBindingSource {x:Type local:Status}}}"/>
</Grid>
Same result, but without the need for an ObjectDataProvider.

Adding Description Support

Now that we have our enum binding working perfectly without the need for that silly ObjectDataProvider, we can improve our enum experience.  It is very common to have a enum to represent the values, while at the same time, give the enum value a description so that it is more readable to your user.  For example; let’s say you have an enum will all the state abbreviations (ID, TX, AZ, etc.), but you would much rather display the full state name (Texas, Idaho, Arizona, etc.).  Wouldn’t it be nice to have this ability?  Well, luckily for us, this is easy to.  We will just need to use a simple TypeConverter that we can attribute our enum with.  Check it out:

public class EnumDescriptionTypeConverter : EnumConverter
{
    public EnumDescriptionTypeConverter(Type type)
        : base(type)
    {
    }     public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            if (value != null)
            {
                FieldInfo fi = value.GetType().GetField(value.ToString());
                if (fi != null)
                {
                    var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    return ((attributes.Length > 0) && (!String.IsNullOrEmpty(attributes[0].Description))) ? attributes[0].Description : value.ToString();
                }
            }
            return string.Empty;
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

Now add the attribute and add some descriptions to our enum:
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum Status
{
    [Description("This is horrible")]
    Horrible,
    [Description("This is bad")]
    Bad,
    [Description("This is so so")]
    SoSo,
    [Description("This is good")]
    Good,
    [Description("This is better")]
    Better,
    [Description("This is best")]
    Best
}
BAM!  We now have our descriptions display to our users, but the actual values remain intact.

That does it for this post.  Hopefully you will find this useful, and maybe even use this approach in your WPF applications.  Be sure to check out the source code, and start playing with it.  As always, feel free contact me on my blog, connect with me on Twitter (@brianlagunas), or leave a comment below for any questions or comments you may have.

REFERENCE: http://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
 

Oct 10, 2017

Happy Ada Lovelace Day!


British mathematician Augusta Ada Byron, who after marriage became Countess of Lovelace and was better known simply as Ada Lovelace, was born in London on December 10, 1815. Check out 10 surprising facts about the pioneering woman often cited as the world’s first computer programmer.

1. Lord Byron was her father.

Although Ada Lovelace was English poet Lord George Gordon Byron’s only legitimate child, he was hardly an exemplary father. The first words he spoke to his newly born daughter were, “Oh! What an implement of torture have I acquired in you!” The marriage between the erratic, abusive and womanizing poet and Lovelace’s mother, Lady Anne Isabella Milbanke Byron, was brief and unhappy. According to the new book “Lady Byron and Her Daughters” by Julia Markus, less than a month after the birth of their daughter, Lord Byron informed his wife of his intention to continue an affair with a stage actress and three days later wrote Lady Byron telling her to find a convenient day to leave their home. “The child will of course accompany you,” he added. Soon after, the poet left England and never saw his daughter again. He died when Lovelace was 8.

2. Fearing Lovelace would follow in her father’s footsteps, Lady Byron immersed her in mathematic.s

Lady Byron, herself a mathematical wiz called “Princess of Parallelograms” by Lord Byron, believed a rigorous course of study rooted in logic and reason would enable her daughter to avoid the romantic ideals and moody nature of her father. From the age of 4, Lovelace was tutored in mathematics and science, an unusual course of study for a woman in 19th-century England.

3. At the age of 12, Lovelace conceptualized a flying machine.

After studying the anatomy of birds and the suitability of various materials, the young girl illustrated plans to construct a winged flying apparatus before moving on to think about powered flight. “I have got a scheme,” she wrote to her mother, “to make a thing in the form of a horse with a steamengine in the inside so contrived as to move an immense pair of wings, fixed on the outside of the horse, in such a manner as to carry it up into the air while a person sits on its back.”

4. The “father of the computer” was her mentor.

At the age of 17, Lovelace met inventor and mathematician Charles Babbage and watched him demonstrate a model portion of his difference engine, an enormous mathematical calculating machine that has led to his being dubbed the “father of the computer.” After becoming Babbage’s protégé, she translated into English an article written by military engineer—and future Italian prime minister—Luigi Menabrea about Babbage’s theoretical analytical engine. Lovelace augmented the translation with her own notes about the analytical engine that were three times as long as the original paper and published in an English journal in 1843 with only her initials, “A.A.L.” In Note G of her elaborate paper, Lovelace wrote of how the machine could be programmed with a code to calculate Bernoulli numbers, which some consider to be the first algorithm to be carried out by a machine and thus the first computer program.

5. She was a visionary who predicted that computers could do more than just crunch numbers.

Lovelace foresaw the multi-purpose functionality of the modern computer. Although Babbage believed the use of his machines was confined to numerical calculations, she mused that any piece of content—including music, text, pictures and sounds—could be translated to digital form and manipulated by machine. Lovelace wrote that the analytical engine “might act upon other things besides number, were objects found whose mutual fundamental relations could be expressed by those of the abstract science of operations… Supposing, for instance, that the fundamental relations of pitched sounds in the science of harmony and of musical composition were susceptible of [mathematical] expression and adaptations, the engine might compose elaborate and scientific pieces of music of any degree of complexity or extent.”

6. She was a compulsive gambler.

Beginning in the 1840s, Lovelace began a gambling habit that contributed to her dwindling finances and forced her to secretly pawn the Lovelace family’s diamonds. According to “Lady Byron and Her Daughters,” Lovelace once lost £3,200 betting on the wrong horse at the Epsom Derby. “Ada, encouraged by con men, would turn her prodigious talents toward gambling and programming the outcomes of horse races,” wrote Markus, who added that a mysterious “book” that passed between Lovelace and Babbage once a week probably contained a program designed to predict horse-race results.

7. Charles Dickens read a passage from one of his novels to Lovelace on her deathbed.

Dickens and Lovelace likely met through Babbage in the 1830s, and the mathematician occasionally attended dinners at the writer’s London home. As Lovelace suffered from uterine cancer in August 1852, the famed British novelist visited his bed-ridden friend and, at her request, read a well-known scene from his popular 1848 novel “Dombey and Son” in which 6-year-old boy Paul Dombey dies. Three months later, Lovelace passed away on November 27, 1852.

8. Lovelace was buried next to the father she never knew.

Although Lovelace didn’t know Lord Byron, she maintained a life-long fascination with him and his works. After her death, she was buried at her request in the Byron family vault inside the Church of St. Mary Magdalene in the small English town of Hucknall. Her coffin was placed side-by-side with that of her father, who also passed away at the age of 36.

9. Her contributions to computing weren’t recognized until a century after her death.

Lovelace’s ideas about computing were so far ahead of their time that it took nearly a century for technology to catch up. While Lovelace’s notes on Babbage’s analytical engine gained little attention at the time they were originally published in 1843, they found a much wider audience when republished in B.V. Bowden’s 1953 book “Faster Than Thought: A Symposium on Digital Computing Machines.” As the field of computer science dawned in the 1950s, Lovelace gained a new following in the digital age.

10. A computer programming language is named in Lovelace’s honor.

During the 1970s, the U.S. Department of Defense developed a high-order computer programming language to supersede the hundreds of different ones then in use by the military. When U.S. Navy Commander Jack Cooper suggested naming the new language “Ada” in honor of Lovelace in 1979, the proposal was unanimously approved. Ada is still used around the world today in the operation of real-time systems in the aviation, health care, transportation, financial, infrastructure and space industries.

Reference:  http://www.history.com/news/10-things-you-may-not-know-about-ada-lovelace

Sep 13, 2017

Best-websites-a-programmer-should-visit

Some useful websites for programmers.

When learning CS there are some useful sites you must know to get always informed in order to do your technologies eve and learn new things. Here is a non exhaustive list of some sites you should visit, this list will get updated as soon as I can get another link, but you can also contribute by adding those you know 😉

Index

When you get stuck

  • Codementor : A mentorship community to learn from fellow developers via live 1:1 help and more.
  • devRant : Community where you can rant and release your stress
  • Learn Anything : Community curated knowledge graph of best paths for learning anything
  • Quora : A place to share knowledge and better understand the world
  • Stack Overflow : subscribe to their weekly newsletter and any other topic which you find interesting

News

  • ACM TechNews : TechNews
  • Stratechery : Stratechery by Ben Thompson
  • AlternativeTo : Crowdsourced software recommendations
  • Ars Technica : posts unique quality articles
  • Better Dev Links : Weekly links to help you become a better developer
  • DevOpsLinks : An online community of thousands of developers and IT experts interested in DevOps
  • GSMArena.com : news related to latest mobile phones and android.
  • Hacker News Digest : curated automatically, delivered as frequently as you want
  • Hacker News : news aggregator for programmers where civility is king, try a newsletter to get top news to your inbox:
  • Hacker Newsletter : curated by hand, delivered weekly
  • High Scalability : Success stories of various companies on their apps, infra scaling.
  • Lobsters : Lobsters is a technology-focused community centered around link aggregation and discussion.
  • product hunt : Discover your next favorite thing
  • Recode : Tech news that focuses on the business of Silicon Valley
  • Reddit.com/r/programming : Subreddit with aggregated tech news and articles
  • Slashdot : News, Social news (Originally "News for Nerds. Stuff that Matters")
  • Stack Share : Technical stack sharing site for various companies
  • TechCrunch : dedicated to obsessively profiling startups, reviewing new Internet products, and breaking tech news
  • The Verge : More product oriented tech news
  • XDA : Android Developers News

Magazines

  • MIT Technology Review : MIT's tech review magazine.
  • Nautilus : NewYorker for tech.
  • LWN : Weekly news coverage of opensource technologies, programming, etc. ( Originally Linux Weekly News).

Coding practice for beginners

  • Cave of programming : Learn to program, Upgrade your skills.
  • Codeacademy : Learn to code interactively, for free.
  • CodeAbbey - a place where everyone can master programming : Best place to begin with problems that start at the easiest and gradually increase difficulty with each problem.
  • Exercism.io : download and solve practice problems in over 30 different languages, and share your solution with others.
  • freeCodeCamp : Learn to code and build projects for nonprofits. Build your full stack web development portfolio today
  • karan/Projects-Solutions : Solutions to most of the problems in the link above
  • Lod - Cloud : The Linking Open Data cloud diagram
  • Programming by Doing : very good site for those who want to start with absolute basics
  • Reddit.com/r/dailyprogrammer : interesting programming challenges where you can learn from looking at other's code , even if you are not able to solve code you can look at how others solved.
  • People Can Program : The most user-friendly code learning application on the internet.
  • Programming Tasks : large collection of small programs
  • Vim adventures : Learn VIM by playing
  • Pramp : It's your turn to be the interviewer. when done, click on the swap roles button on the left
  • Paqmind : Guides and challenges to learn programming

For those who want to start a small project but can't find the ideas

General Coding advice

Coding Style

General Tools

  • CodePad : Quickly Conduct Coding Interviews and Phone Screen Interviews.
  • CodePen : Front End Developer Playground & Code Editor in the Browser
  • Devicons : Cheatsheet for devs icons
  • regex101 : Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript
  • regexr : Another online tool to learn, build & test Regular Expressions
  • Wit AI : Natural Language for Developers

Bash and Shell scripting

Interview Preparation

Documentaries

MOOCs for learning something new

Sites related to your preferred programming language (For me Java)

Learn AI

Seminar , research writing , talks etc

Everything in one place

YouTube Channels

Good Articles

Podcasts

  • Coding Blocks : A podcast covering topics such as best programming practices, design patterns, coding for performance, object oriented coding, database design and implementation, tips, tricks and a whole lot of other things.
  • Developer On Fire : A podcast that shares the humanity of developers and tells stories of some of the amazing people in software, hosted by Dave Rael.
  • Developer Tea : A podcast for developers designed to fit inside your tea break.
  • Front End Happy Hour : A podcast featuring a panel of Software Engineers from Netflix, Evernote, Atlassian & LinkedIn talking over drinks about all things Front End development.
  • Full Stack Radio : Everything from product design and user experience to unit testing and system administration.
  • Groovy Podcast : A podcast dedicated to the Groovy programming language and its ecosystem.
  • IPhreaks : A weekly group discussion about iOS development and related technology by development veterans. We discuss Apple, tools, practices, and code.
  • JavaScript Jabber : A weekly discussion about JavaScript, front-end development, community, careers, and frameworks.
  • MS Dev Show : Jason Young and Carl Schweitzer talk about the latest in developer news covering topics such as the Azure cloud, Windows, Windows Phone, Visual Studio, and cross-platform development using the Microsoft platform.
  • React Native Radio : A weekly discussion of the tools, techniques, and technologies used to build mobile applications with JavaScript and React.
  • Software Engineering Daily : A daily technical interview about software topics.
  • Software Engineering Radio : A podcast targeted at the professional software developer. The goal is to be a lasting educational resource, not a newscast.
  • Syntax : A Tasty Treats Podcast for Web Developers by Wes Bos & Scott Tolinski.
  • The Bike Shed : Guests discuss their development experience and challenges with Ruby, Rails, JavaScript, and others.
  • The Changelog : A weekly conversation that gets to the heart of open source technologies and the people who create them.
  • The Cynical Developer : A podcast that aims to help you to improve your development knowledge and career, through explaining the latest and greatest in development technology and providing you with what you need to succeed as a developer. Covering Desktop, web and mobile development, mainly around the .Net Stack but often looking into other software and frameworks.

Building a Simple Compiler/Interpreter

Tutorials

Watch others code

  • LiveEdu.tv : screencast of people building application, websites, games, etc.
  • Twitch.tv : The programming community of twitch.

What should a programmer know

Competitive programming

Computer Books

Video Tutorials

Online Compiler and Sharing Code snippets

  • CodePad : Code editor to try, test and run 25+ languages
  • Codesandbox.io : CodeSandbox makes it easier to create, share and reuse React projects with others.
  • Godbolt.org : Excellent tool for exploring the assembly output of different compilers with and without optimization.
  • Ideone.com : online compiler and debugging tool for more than 60 programming languages
  • JSFiddle : Test your JavaScript, CSS, HTML or CoffeeScript with online code editor
  • Pastebin.com
  • C9.io : Your development environment, in the cloud
  • Github Gist : Instantly share code, notes, and snippets.

Blogs of Developers

For improving your English

When you get bored from CS related stuff

Open Source Websites

  • Open Hatch : OpenHatch is a non-profit dedicated to matching prospective free software contributors with communities, tools, and education.
  • Source Forge : SourceForge hosts nearly 280,000 projects (at last count). It serves more than 2 million downloads a day and includes apps and tools in a wide variety of categories.
  • Google Code : Google offers free hosting for open source projects using the Subversion or Mercurial version control systems. It offers 2 GB of storage, integrated code review tools, a wiki, and an issue tracker. The Google Code site also provides links to Google's many publicly available APIs and other developer tools.
  • Launch Pad : Maintained by Canonical, LaunchPad is particularly targeted at projects that run on Ubuntu. It provides hosting for more than 21,000 projects that use the Bazaar version control system.
  • Google Open Source : Google Open Source
  • Red Hat Developer : The world's leading provider of open source solutions
  • Open Source : Open Source
  • Google Summer of Code : Google Summer of Code is a global program focused on bringing more student developers into open source software development. Students work with an open source organization on a 3 month programming project during their break from school.
  • Open Source Web Design : Open Source Web Design is a platform for sharing standards-compliant free web design templates. We give web publishers a voice through good design.
  • Mozilla Winter of Security : The Winter of Security (MWOS) is a program organized by Mozilla's Security teams to involve students with Security projects. Students who have to perform a semester project as part of their university curriculum can apply to one of the MWOS project.
  • Eclipse Lab : Eclipse Labs is a community of open source projects that build technology based on the Eclipse platform. It provides the infrastructure services typically required by open source projects, such as code repositories, bug tracking, project web sites/wiki. Eclipse Labs is hosted by Google Code Project Hosting, so it will be very familiar to developers already using Google Code Project Hosting.
  • Bit Bucket : Like GitHub, BitBucket hosts both public and private projects. On this site, open source projects and private projects with fewer than five users are free. It hosts more than 48,000 repositories, many of which are searchable on the site.
  • Media Wiki : MediaWiki is a free software open source wiki package written in PHP, originally for use on Wikipedia. It is now also used by several other projects of the non-profit Wikimedia Foundation and by many other wikis, including this website, the home of MediaWiki.

Visual Studio Keyboard Shortcuts

Playing with keyboard shortcuts is very interesting and reduce the headache of using the mouse again and again while programming with visu...