Quantcast
Channel: Corrado's Blog 2.0
Viewing all 46 articles
Browse latest View live

Beware of generated XAML in UWP

$
0
0

I admit, this is s strange blog post title but that’s what this post is going to talk about.

I’m working on a UWP app that has different min and target runtimes:

image

After doing some UI work with Visual Studio & Blend I’ve discovered that the app was crashing on machines without Anniversary edition installed. At the end of a debuggin session I’ve found the reason: The XAML template generated by the tools contains incompatible elements (resources mainly, but also new properties) that are not present on previous builds.

To give you an example, this is an extract from a ComboBox default template, generated by Blend when you use the Template->Edit copy feature:

10586

<Setter Property="Foreground"

Value="{ThemeResource SystemControlForegroundBaseHighBrush}" />

14393 (Anniversary)

<Setter Property="Foreground"

Value="{ThemeResource ComboBoxForeground}" />

The reason of this is because the tools generate the template from the Target version SDK and not the Min version SDK that might even not be present.

The team said that they’re going to give you some warnings in the future when situations like this happen, but in the meantime, at least when you’re doing design work, be sure to selected, the min target version SDK otherwise you might end up in troubles.


Genymotion and VirtualBox install issue

$
0
0

I use Genymotion as Android emulator for my Xamarin work, I know that there are better alternatives like Microsoft’s Android emulator but since can’t turn on Hyper-V on my machine this is the solution that works best for me.

Haven’t done any Android development recently so since I need to prepare some demos for my forthcoming session at Future Decoded I checked my system and discovered that Android emulator wasn’t working anymore as happened in the past. Checked the logs but nothing evident was listed apart some in influent login error, I then tried to run VirtualBox alone and noted that it was not starting at all, no error nor messages, just nothing was happening.

Ok, let’s reinstall Genymotion to latest version, maybe recent Windows 10 Anniversay update broke something, did that, no errors but, nothing changed, ok, let’s try installing VirtualBox alone from Oracle site and BOOM! got a weird error message about an adapter not being created because it was not possible to rename it (WHAAAT?)

Fired up a search engine looking for solutions and found thousands of thread starting from 2010, some of them even suggesting to repave the entire machine, luckily among this tons of documentation my attention got catched by a guy that claimed to have solved using this steps:

  1. 1-Go to 
  2. C:\Program Files\Oracle\VirtualBox\drivers\network
    2-Go into each directory contained into network and install the drivers by tight clicking every .inf file and selection Install from popup menu

    image

    3-Go to Network Connections, right click the Ethernet adapter associated with VirtualBox and select Properties

    image

    4-On the network properties panel, click Install and select Services

    image

    5-Now select the Oracle’s VirtualBox driver and select OK

    image

    6-Be sure that VirtualBox NDIS driver is selected.

    image

    7-Complete Genymotion install, if not already done, otherwise, just download a device and runt it, if it is your lucky day, it should work.

    You can read the original answer here, it also worked for me of course.

    …and after this annoying procedure you can go back coding in relax. Smile

    HTH

    UWP: Read German text from a file

    $
    0
    0

    I had some hard times figuring out how to properly read a file that contains typical German characters (e.g umlauts) so I want to share my solution in case are in the same situation.

    The magic trick is to register a new provider named “windows-1254” using Encoding.RegisterProvider

    Change x:Bind default binding mode

    $
    0
    0

    Recent release of Windows 10 introduced Complied Bindings, an type safe alternative to {Binding} syntax that add compile time checking and better performances, it can also be used in place of ElementName to bind to a UI element property.
    In order to squeeze performances the default binding mode of compiled bindings is OneTime, this means that any further change of bound property after initial one won’t get propagated to bound UI property, and this, personally, is one of the most annoying things because i often use properties whose value changes and everytime i spend time figuring why they don’t before remembering of this different behavior.

    To give you an example, let’s take this simple ViewModel

    Page code behind

    and page markup

    if you try this code you will see that value doesn’t change when you click the button, this is because of default OneTime binding.

    While you can change the behavior by adding Mode=OneWay to the Count binding, if you have many bindings and you’re targeting Fall Creators Update you can use the new attibute DefaultBindingMode

    The plus of using this attribute is that it changes the default binding mode to all compiled bindings contained in the element where it is applied (and all childrens) saving a lot of time.

    Nice! waited a long for this Smile

    Fix “No Internet Connection” issue

    $
    0
    0

    A couple of days ago, some applications like Skype, Skype for Business, Outlook stopped working due to a “can’t connect” problem, the only way to make them work was to enable corporate VPN, since I was busy didn’t take care of it and just used the VPN.
    This morning, same problem, and so I went to the “VPN trick” to get over it but this time it wasn’t working and after a few minutes I lost the entire interner connectivity on my main machine.
    Think you know that no internet connectivity at these days is more or less like a boot disk failure so i started trying nearly everything from reboot, to driver updates, going through wired connection, using tethering etc but got no luck.
    I then decided to compare what ipconfig was telling me on two different machines and i discovered a “little difference”, my wifi card was having the Autoconfiguration Ipv4 address set to a weird “169.254.X,Y” no idea of where that address was coming from but I thought that it could be the origin of my problem.

    I the started looking for a solution and, voilà, two magic commands solved my headache…

    1) Open command prompt as admin
    2) type netsh int ip reset +enter
    3) type netsh winsock reset + enter
    4) reboot your machine

    In my case it worked, hope it will be the same for you that you’ve reached this post probably because you have the same problem as me.

    Good luck!

    Fix Xamarin Form compilation errors

    $
    0
    0

    I’ve recentily repaved my development machine and installed Visual Studio 2017 adding nearly all features including, of course, Xamarin and all subsequent updates.
    Today I’ve tried to create a blank new Xamarin Forms project targeting .Net Standard for the common part but as soon as I tried to compile it I got a strange sequence of errors on Android project:

    error APT0000: 1: error: Error retrieving parent for item: No resource found that matches the given name ‘Theme.AppCompat.Light.Dark
    error APT0000: 2: error: Error: No resource found that matches the given name: attr ‘colorAccent’.
    error APT0000: 1: error: Error: No resource found that matches the given name: attr ‘colorPrimary’.
    error APT0000: 1: error: Error: No resource found that matches the given name: attr ‘colorPrimaryDark’.
    error APT0000: 1: error: Error: No resource found that matches the given name: attr ‘windowActionBar’.
    error APT0000: 3: error: Error: No resource found that matches the given name: attr ‘windowActionModeOverlay’.
    error APT0000: 1: error: Error: No resource found that matches the given name: attr ‘windowNoTitle’.
    error APT0000: 3: error: Error retrieving parent for item: No resource found that matches the given name ‘Theme.AppCompat.Light.Dial
    error APT0000: 3: error: Error: No resource found that matches the given name: attr ‘colorAccent’.

    Totally nonsense for me.
    After a chat with my friend Laurent we’ve discovered that problem depends on missing installation of Android SDK 24 (Nugat 7.0) after installing it using the new SDK Manager (via Tools->Android->Android SDK manager) problem was gone.

    Cause probably depends on referenced packaged used in default templates that no longer support Android Marshmallow (6.0) the version that gets installed by default by Visual Studio.

    Save Win2D CanvasControl content

    $
    0
    0

    Win2D is an easy-to-use Windows Runtime API for immediate mode 2D graphics rendering with GPU acceleration that is very helpful in some situations like real time or layered rendering.
    This post is about how to save dynamically rendered content to a file for further external processing.

    To give you an idea, let’s build a quick Win2D sample.

    Create a blank new UWP project and add a NuGet reference to Win2D package

    image

    on MainPage.Xaml add following XAML

    and this code on relative codebehind

    if you now run the sample and change the value of the slider you will see the rectangle moving this way

    cb

    From the code is evident that each time the value of the slider changes we invalidate the CanvasControl so that OnDraw method gets called and content is redrawn with the new rectangle position.

    To save CanvasControl content we basically need to draw actual content into an offscreen render target and use the SaveAsync method to get the stream content.
    Here’s the code:

    code just draws the same content into a CanvasRenderTarget representing the offscreen renderer and then gets that stream, the remaining code just saves it into a StorageFile.
    Off course what’s drawn into offscreen renderer is up to you (as example you might add a watermark) and output format can be changed via CanvasFormatBitmap parameter.

    HTH

    Playing with ParallaxView

    $
    0
    0

    Those of you who have some Windows Phone development experience will remember the Panorama control for sure.
    Control had a nice effect where background content was moving slowly below foreground, this effects is named Parallax and you’ll be glad to know that, starting from Fall Creators Update you can have this effects easily back into your own UWP applications, thanks to ParallaxView parte of the new Fluid Design System.

    Let’s see it in action:

    Create a new UWP application targeting Fall Creators Update (unfortunately ParallaxView is not available on older platforms)

    image_thumb1

    let’s now add the ParallaxView to MainPage.Xaml

    ParallaxView has a Child property that is used to represent the content that is scrolled slowly, in this case I defined it directly inside the ParallaxView.
    The key property is Source that you can bind to an element that can be a ScrollViewer or an element that contains a ScrollViewer like a ListView or a RichTextBox. (Note: I tried to nest ListView definition directly inside ParallaxView but seems not to work)
    Nothing special to mention about ListBox apart tha:

    1. -I used the ‘new’ PersonPicture control
    2. -The ListView must be placed after the ParallaxView definition, otherwise it wont work

    Codebehind is quite straighforward:

    The control supports both Verticaland and Horizontal scrolling and the most important property is probably Vertical/HorizontalShift that govers ‘how fast’ background scrolls, chose the one the best fits for you.
    Using Vertical/HorizontalStartOffset it is possible to fine tune background scrolling behavior (play with them…)

    Here’s final result, what do you think? Smile

    parallax


    Get unique Device Id and Application Id in UWP applications

    $
    0
    0

    Sometime you need to get a unique application identifier for your app together with a unique device id for internal processing.

    Here’s the code you need:

    A note regarding device identifier

    As you might see from the involved API name SystemIdentification.GetSystemIdForPublisher() the returned value is unique for the same app publisher, if publisher changes the value changes as well.

    Here are the Device Id characteristics

    • -Unique for each system
    • -On any particular system, all apps by the same publisher will get the same value for this ID (for all users). Conversely, apps by different publishers on the same system will obtain different IDs.
    • -Can be created offline
    • -Persists across restarts, reinstalls and upgrades of Windows, including clean installs (please see below for exceptions)
    • -Persists across most hardware modifications
    • -Available in OneCore

    How to get Skype ‘classic’ on Windows 10

    $
    0
    0

    skype_PNG31

    If you navigate to Skype website from a Windows 10 machine look like there’s not way to download the so called “classic” version, you are redirected to the Windows Store.
    I still prefer the classic one so I’ve found the direct link to the ‘classic’ version http://bit.ly/skypeclassic but if then you the run the installer you will get this sad message:

    image

    To, solve it, right click the installer file and select Properties, navigate to Compatibility tab, select Windows 8 and click Apply

    image

    And you’re done Smile

    image

    Happy ‘classic’ Skyping Winking smile

    Lottie animations in UWP

    $
    0
    0

    Lottie is a library created by Airbnb team that parses animation created using Adobe’s After Effects and exported as json file using Bodymovin plugin.
    The library was targeting iOS ,Android and React native initially, but thanks to the hard work of community developers a version for Xamarin and UWP is now also available.

    If you don’t have any ready-made animation you can get some (and contribute as well) from LottieFiles large repository.

    Note: LottieUWP supports Windows Build 10586+ (November Update) and above

    Showing a ‘Lottie’ animation in a UWP application is fairly easy.

    -Create a blank UWP application

    -Include LottieUWP nuget package (don’t forget to check Include prerelease flag to see it) 

    Capture1

    -Include one or more .json file (your own or one downloaded from LottieFiles) representing the animations you want to play and, important, change Build Action to Content

    Capture

    -Add a LottieAnimationView control where you want the animation to appear, as example inside MainPage.Xaml

    If you run the app you will see your animation playing endlessly Smile

    lottie1

    You can load an animation programmatically using different options, the most common one is probably via the SetAnimationAsync method that also allows you to provide a caching strategy optimization parameter that allows parsed and loaded animation to be cached for reuse.

    Adding these lines into MainPage.xaml.cs constructor generates this output

    lottie2

    If you want to have even more control, you can subscribe AnimatorUpdated event and inside event handler control the entire animation, in this example I make the animation play faster in the seconf half.

    lottie3

    Cool isn’t it? Winking smile

    There’s not to much interesting to say about it, if you want more details you can check these links:

    -LottieUWP github repository

    -#ifDef LottieUWP video on channel 9

    Go animating!

    Consume Google API from UWP

    $
    0
    0

    I’m writing this post so that you don’t have to spend too much time as I did to figure how to authenticate and invoke Google APIs from a UWP application.
    I found several solutions, mostly outdated, and tons of quite articulated documentation, including the official one from Google, all discussing about the same few APIs, but i got no chance to have it working, until I got to this solution.

    So, Lets’s go!

    As initial step we need to register our app into Google developer portal, registration will return us a couple of fundamentals info: Client Key and Client Secret.
    Navigate to console.developer.google.com , login and select Credentials under APIs and Services on the left side of the portal.

    image

    click on Create credentials and select the oAuthClientID, you will be promped with a similar screen

    image

    Required information are, Application Type, Name and Redirect (you can use whatever Uri you want here), when done click Create, this will generate the mandatory Client ID and Client secret info.

    image

    Download the code from https://github.com/corradocavalli/GoogleLogin2/ the sample shows you how to reried logged user informations like name, email, picture…

    If you analyze the code you’ll note that we use Xamarin Auth library for all oAuth2 stuff…

    image

    and basically the procedure is divided onto three main steps:

    1) Get the Google auth token

    2) Get oAuth2 token

    3) Call Google API passing the oAuth2 token, in our case we retrieve user info, but you can use any API you prefer

    There’s not too much to add but the fact that I’ve lost many hours trying to figure out how to make this basic sample working and I agree that using a library, maybe the official one from Google, would be better, but despite several attempts I was not able to make it working on UWP since looks like that some core parts related to authorization are not there yet.

    Hope this saved you some headaches Smile

    Trace application flow easily

    $
    0
    0

    UWP applications are compiled using .NET Native compiler as detailed here.
    This process gives many advantages over JIT compilation:

    • -Up to 60% performance improvement on cold startup times
    • -Up to 40% performance improvement on warm startup times
    • -Less memory consumption of your app when compiled natively
    • -No dependencies on the desktop .NET Runtime installed on the system
    • -Since your app is compiled natively, you get the performance benefits associated with native code (think C++ performance)
    • -You can still take advantage of the industry-leading C# or VB programming languages, and the tools associated with them
    • -You can continue to use the comprehensive and consistent programming model available with .NET– with extensive APIs to write business logic, built-in memory management, and exception handling.

    This brings a side effect:  Since app is compiled natively and logged StackTrace information is lost resulting in a series of meaningless series of entries like:

    SharedLibrary!<BaseAddress>+0x38449f at
    SharedLibrary!<BaseAddress>+0x3842cd Exception_EndOfInnerExceptionStack at
    SharedLibrary!<BaseAddress>+0×384405 at
    SharedLibrary!<BaseAddress>+0x3bd80d at
    SharedLibrary!<BaseAddress>+0x3c1f45 at

    that tells you nothing about what happened until reported exception, so the only real solution is to keep track of your workflow using custom made logging like:

    but this is absolutely tedious and repetitive, so we can simplify it using a good old C# trip based on coupling using keyword and IDisposable.

    Let’s create a TraceSession class this way

    With this class we can log any part of our code this way:

    Much more easier and readable since all you have to do is essentially to write your code inside using block,  if you paired this with a Visual Studio code snippet that generates initial code skeleton implementation becomes nearly invisible.

    UWP Share target and COM Exception 0×80004002

    $
    0
    0

    Goal was very simple initially: Implement a share target inside a UWP application that, when activated, just adds a new entry inside a pre-populated ObservableCollection.
    Sound easy right? It doesn’t, and I spent the entire morning fighting against this exception

    image

    Let’s see how I solved it.
    Download Share Source and Target solution from here I won’t go into code detail because if you need to learn how implement both share source and target you can find a detailed description from Microsoft documentation here:

    -Share Source
    -Share Target

    Let’s dig into critical part of the code:

    What shared target does is to load an item into an observable collection:

    and this is the code that gets invoked when share operation is invoked

    In line 9 we add a new item into shared observable collection and the code fails with an InvalidCastException.
    I’m used that when those crazy exception raise most of the times they come from threading issues, in fact share operation is invoked on a secondary thread so my next take has been to marshal the operation this way:

    but in this case the dispatched action it doesn’t even get invoked, probably because the main message pump is blocked, nice…

    So I tried another way, using Windows.Current’s dispatcher

    and in this case action is invoked, but… same error Sad smile probably because the dispatcher is the same as the one used to create the main application window.
    I was totally lost now since, while I’ve found many other developers struggling with this, no one posted a working solution (and this lead to the reason of this post) but, don’t know how, I remembered that there’s another way to access a dispatcher and is via CoreApplication class

    And… YES, It works! Smile
    I honestly don’t know what happens behind the scenes, but frankly, didn’t expected this apparently easy task to turn into a semi nightmare, but glad, with some luck honestly, I won over it.

    Learning Git with Visual Studio #1

    $
    0
    0

    As the vast majority of you i use Git as source control management, and, as many of you, I use it everyday but I feel that I’m just a basic user, so when something goes wrong or I just need to do something more ‘advanced’ i get lost very easily.
    Another thing that differentiates me from those geeky developers is that I don’t like using command line to interact with Git, but I prefer to use the same tool I use everyday: Visual Studio.
    This series of post are nothing more that my tentative to take some basic notes of my daily Git use as basic user.
    There is a lot of documentation around Git, in case you need more detailed info, at this link you will find a comprehensive guide.
    The core concept I want to point out here are:

    -Git is more than a simple source control system.
    -Git is a decentralized and serverless.

    Regarding 2nd point: It means that Git doesen’t require you to have a steady connection to a server, in fact you might even decide to not have a server at all and, in case of more developers working on the same code, they work with a local copy of the code and, when they decide to, they can sync their copies and this sync operation might lead to conflicts in case two or more developers changed the same parts of code.
    When this happen, fixing all conflicts must be done manually with great attention to prevent that some code modifications got lost (more on this in following episodes)

    When we create a new solution with Visual Studio, if we want to use source control with it we need to ‘add it’ to a source management system, Git in this case, since Visual Studio won’t do that automatically for us.
    Before creating our first project and connect it to Git we need to install the Git plugin into Visual Studio since this won’t be installed by default, we can do this in different ways:

    -At installation time
    -Modifying Visual Studio Installation via Visual Studio installer

    image

    -Add it via Extensions and Updates menu in Visual Studio

    image

    Done this let’s create a new UWP application (but you can use any project type you like) and note the “Create new Git repository” checkbox

    image

    If we check it, the new project will be associated with Git and we can use all related functionalities, confirmed by the presence of file status icons behind each file that is part of our solution.

    image

    All infos related to Git are stored inside hidden .git folder at the root of our solution on disk

    image

    If we now close the solution, delete the .git folder and reload it, we’ll see that solution is no longer associated with a source control because icons behind the files are gone

    image 

    How do we connect (or reconnect) a solution to source control? easy, just right click the solution and select Add solution to source control to go back to a connected solution

    image

    When we associate a project to git source control Visual Studio performs several operations behind the scenes, the most evident one are the inclusion of a couples of files:

    -.gitignore that contains a common list of files that don’t have to be considered by source control (e.g. binary files, log files etc)

    -.gitattributes configure some git behaviors (like line endings)

    We now have our brand new project and we know we can use Git source management system with it directly from Visual Studio, in the next episodes we’ll see how.


    Learning Git with Visual Studio #2

    $
    0
    0

    In the previous post we learned how to connect a solution to Git source control, we’ll now pay attention to the status of each file inside the solution.
    Git defines several status for the files it tracks, they can be:

    -Untracked
    Git knows nothing about that file, it totally ignores it
    -Tracked
    Git knows about that files and keep the history of it
    -Modified
    Git knows that that file has been modified compared to tracked version
    -Committed
    The file in the solution matches the one in the source control

    Note: This is my personal definition, git uses a different terminology, but you got the point.

    Take a look at following picture

    image

    In this case the .pfx file is untracked (ignored) because of the .gitignore file exclusion, if we want to include it we can right click it and select Add Ignored file to Source Control…

    image

    Turning it into a Tracked (or staged) file (equivalent to Git Add command)

    image

    Both Class1 and .pfx file are now tracked, meaning that git knows about that but it hasn’t started recoding changes because we have not commited them yet.
    To Commit them we can go to  Team Explorer inside Visual Studio and select Changes where we will see something like this

    image

    Where we see two different sets of files ready to be Committed, let’s add the mandatory comment and then we will be able to commit staged changes

    image

    Stages changes are a way to control what files are part of a specific commit, and are an alternative to a “general” commit where we commit everything that has changed.
    After clicking Commit Staged here’s what we see

    image

    And if we select View History under Action buttons we’ll see this

    image

    Ok, let’s now add another class (Class2) to our project, let go to Team Explorer window and let’s add a commit comment, we’ll se that button has a Commit all text where we can commit everything that has changed in one shot.

    image

    Ok, but what if i want to split committing of Class1 to commit of Class2 for better separation? Just right click the Class1 file and select Stage, add a comment and click Commit Stages, only Class1 addition will be tracked into history.

    image

    History

    image

    But what if i changed my mind and want to correct my last commit, maybe including Class2 as well? Just stage Class2 and use Amend Last Commit option under Actions (don’t use Commit staged that will generates a new commit entry)

    image

    and the previous commit will be updated with both Class1 and Class2 changes.

    image

    Most of the times I don’t do such granular commits, but since you can revert to a specific commit entry having using this option can help you track precisely the evolution of your app.

    Learning Git with Visual Studio #3

    $
    0
    0

    In this post we’re going to talk about History.
    In the previous post we saw how to commit changes so that git can track them, but without an history browser this list of changes wouldn’t be available and we couldn’t do anything regarding commit history.
    Git of course let you see all commits history and so the Visual Studio Plugin of course.
    From Team Explorer, inside the Changes Tab, select the Actions button and click View History

    image

    and the list of commits will open

    image

    Let’s now add a new Class1.cs file to our project, commit the change, then let’s add a property named P1 to the same class and commit the change again.
    If we now refresh the list using leftmost button we will see two new entries

    image

    One of the interesting features of history is that we can see what has changed in each commit, just select a commit entry, right click it and select View Commit Details, the Team Explorer tab will change to Commit Details and will show all files involved, in our case just Class1.cs.

    image

    Double click the Class1.cs and a diff viewer window will open showing what has changed compared with latest commit in our case we’ll see that property P1 has been added.

    image

    If you want to compare two specific commits instead just select them and click View Commit Details.

    Another interesting feature is Reset, with this option you can delete a series of commits and rollback to a specific point in history.
    Right click the commit you want to reset to, select Reset and select Delete Changes, this will remove all changes committed after that point resetting your project to that exact moment.
    Reset will remove all changes, including any file added that commit, so use it with care because your job will be definitely lost.
    In my case the Reset Hard operation deleted the Class1,cs file from both the project and the disk.

    image

    under Reset menu there’s another option: Reset (Keep Changes).
    After last Reset Hard I’ve re-added Class1.cs, committed, then added P1 property again and committed, putting the git history in the same status as it was before the Reset operation.

    image

    If I now right click commit with Id 0206669f and select Reset (Keep Changes) it looks like that nothing has changed since both Class1 and P1 are already there and if i add a new P2 property and I commit I see history changing appropriately and Class1 contains both P1 and P2.
    Still not totally clear to me honestly, comments welcome.

    If you want to delete a specific commit your can right click it and use Revert.
    To understand how it works, let’s add P3 and P4 properties to Class1 committing each addition, thus generating following history

    image

    Let’s now say that we want to delete commit with ID a5aa04f5, right click it and select Revert, we’ll now see Team Explorer tab to prompt something like this

    image

    and if we click Merge will see that merge tool will try to remove P3 from Class1

    image

    Click Accept Merge in the upper left corner and P3 property will be no longer present in Class1.

    What if you want to undo some modification did to a file returning it to last commit state? Just go to Changes tab, right click changed file, select Undo Changes… and you’re done.

    image

    Learning Git with Visual Studio #4

    $
    0
    0

    When you’re in a team and start working on a new implementation or when you just want to do some experiments with your code without worrying about introducing regression with actual code, the best thing to do is to create a git feature called Branching.
    Branching can be considered a total independent copy of the last commit, so, since we’re on a copy, the original source remains safe and untouched.
    While considered a copy, technically is not, because copying all files making up a solution would be not only slow, but also a total waste of disk space, so git handles all this internally, taking care of deltas, giving us the impression that we’re working on a physical copy.

    To create a new local branch (we’re still working locally exclusively) let’s select Branches inside Team Explorer, right click the only branch we have now master, and select New Local Branch From…

    image

    name it dev and select Create Branch

    image

    This will create a new “copy” named dev and it will make it the default project we will work on, you can see what’s current branch and even switch quickly by looking at Visual Studio lower right corner

    image

    Let’s now add a new Class2.cs file and commit the change as usual.
    If we have a quick look at the history we will see now a new Tag on the right indicating that that commit refers to dev banch

    image

    If we now, right click master branch and select Commit we will see that Class2 is not there, even on disk.
    Let move back to dev branch and let’s add a property P1 to Class2.cs without committing and let’s try to switch back to Master branch.
    We’ll see an error message stating that switching is not possible otherwise some changes will be lost, something that git tries to avoid anytime.

    image

    Let’s commit the change.
    Let’s say we’re done with changes on dev branch and we want to bring them into master branch, together with any changes that might have taken place since we created the dev branch.
    We can do that using Merge feature.
    Right click the branch were we want to push the changes of the actual branch (master in our case) select checkout to switch to that branch, right click it again and select Merge From…

    image

    Leave the Commit changes option to commit the changes after the merge automatically.
    Let’s have a look at Master branch history now

    image

    As you see you can’t see from the history there’s no trace that a merge operation occurred.
    Let Reset the merge and let’s do it again but this time unchecking the Commit Changes flag.
    This time we have a warning informing us that we have to commit changes to apply the merge

    image

    Let’s do it, giving a meaningful comment and let’s see how the history has changed

    image

    In this case the branch is evident including the additional comment we added after the merge.
    If you like this option, as I personally, do, make it permanently unchecking it on plugin settings tab.

    image

    Learning Git with Visual Studio #5

    $
    0
    0

    In previous article I showed how to take changes from a branch into parent branch, visually we could imagine this operation like “copying” some files from a directory into his parent, but what if, while acting on a branch a colleague working on another branch fixes a bug or add a feature we need to get asap? What if we need to “copy” some changes from parent folder into the one we’re working on at the moment?
    This operation is called Rebasing

    Starting from the sample solution we’re using in this series of post, let’s move to Master branch and let’s add an empty MustHave.cs class, solution now looks like in following picture

    image

    Let’s commit this change and checkout the dev branch created in the past article, we’ll see that MustHave.cs class is not present, how can we have it, together with any related change happened on Master branch since we initially created the dev branch?
    Checkout Master branch (or in general, the branch that contains the change you want to “merge” into your branch) go to Team Explorer, Branches tab, right click Master branch and select Rebase Onto… menu

    image

    You will be now prompted to indicated the destination branch where the changes will be merged, in our case the dev branch

    image

    Click Rebase and you’ll now see MustHave.cs class being listed into the project, so basically we can think Rebase being a sort of reverse Merge, a really nice to have feature especially when multiple people are working on different branches.

    Cool but: We have included ALL changes, including maybe some that could conflict or break the branch we’re working on. What if I need to take just one or more commits, maybe from different branches, because very critical for what I’m working on and ignore the others?
    Cherry-Pick is the git feature we need.

    Let’s imagine, that while on dev branch, someone did a series of commits adding a NewFeature1.cs file, then a P1 property and suddenly a P2 property (of course in real world the changes would be more articulated)
    The history for master branch now is:

    image

    While on dev branch, let’s now take single commits 193d63b4 by right clicking and selecting Cherry-Pick

    image

    You will get this confirmation message on Team Explorer

    image

    Let’s do the same with commit b46c2419, we will get a similar confirmation message, and the history of dev branch will now include both cherry-picked commits.

    image

    As you see, git offers several option for mixing and matching code residing in different branches, of course all have to be treated with care since the risk of overwriting changes is always around the corner.

    Learning Git with Visual Studio #6

    $
    0
    0

    In previous post we talked a lot about branches and all the stuff involved (merge, rebasing, cherry-pick) but we didn’t covered a quite simple scenario: You’re working on a branch, and while in the middle of an important refactoring you’ve to urgently move to a different branch to fix a bug.
    Answer is easy, commit changes and then checkout the other branch, but in this case we committed something that maybe doesn’t even compile, adding a sort of “ok, need to commit, sorry” entry into project history.
    Git covers this need with a feature called Stashing, that is the option to ‘save’ your work without involving commit and retrieve it later.
    Unfortunately this feature is not yet available into Git plugin for Visual Studio 2017, but with a little help from a 3rd party extensions we can stash changes without resorting to command line.
    First of all, install this extension from Visual Studio Gallery.
    The extension adds a new entry Stashes into Team Explorer home tab.

    image

    While on dev branch, let’s add a new property to Class2.cs and click Stashes, a new tab will open where we can add a comment and save current work.

    image

    Let’s click Create stash to confirm, we will see our change disappear and code revert back to last commit, don’t worry, nothing is lost.
    If we have a look at Changes tab we’ll also note that there are no changes pending.
    We can now checkout another branch, work on that and then go back to dev branch and click Stashes again.

    image

    Let’s now right click the Stash entry we want to load and select Apply stash option, this will get our changes back and we can continue working and, at the end, commit to history something that worth it and not clutter the history with meaningless commits.
    Here’s the history after committing all changes, no trace of the temporary switch of branch,

    image

    When you’re no longer interested on a specific stash, just right click it and select Delete stash.

    The extension sometime causes some Visual Studio slowness during stash/unstash operation but apart this small issue it works pretty well.

    Viewing all 46 articles
    Browse latest View live




    Latest Images