Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
NodeJS, Quick tips

How to delete node_modules folder on Windows machine?

Due to its folder nesting Windows can’t delete the folder as its name is too long. To solve this, install RimRaf:

npm install rimraf -g

and delete the node_modules folder easily with:

rimraf node_modules

 

edit: If you happen to get an “error” like this:

C:\Users\Nikola\Desktop>npm install -g rimraf
C:\Users\Nikola\AppData\Roaming\npm\rimraf -> C:\Users\Nikola\AppData\Roaming\npm\node_modules\rimraf\bin.js
npm WARN unmet dependency C:\Users\Nikola\AppData\Roaming\npm\node_modules\generator-ionic requires cordova@'^4.2.0' but will load
npm WARN unmet dependency C:\Users\Nikola\AppData\Roaming\npm\node_modules\cordova,
npm WARN unmet dependency which is version 5.1.1
npm WARN unmet dependency C:\Users\Nikola\AppData\Roaming\npm\node_modules\bower\node_modules\bower-registry-client requires request@'~2.51.0' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency C:\Users\Nikola\AppData\Roaming\npm\node_modules\bower\node_modules\fstream-ignore requires fstream@'^1.0.0' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm ERR! peerinvalid The package node-inspector does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants node-inspector@~0.7.0

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\NodeJS\\\\node.exe" "C:\\NodeJS\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "rimraf"
npm ERR! cwd C:\Users\Nikola\Desktop
npm ERR! node -v v0.10.36
npm ERR! npm -v 1.4.28
npm ERR! code EPEERINVALID
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Users\Nikola\Desktop\npm-debug.log
npm ERR! not ok code 0

Don’t panic :), just try to run rimraf instead, as noted above. In most cases, all will be okay and you’ll be able to use it without a problem. If not, head to the comments, and we’ll take care of it together! For those who don’t care much about comments, here’s the post in which I address this node-inspector issue.

How to delete node_modules folder on Windows machine? http://t.co/0pV4OSTG1L #nodejs #windows #node_modules

— Nikola Brežnjak (@HitmanHR) July 28, 2015

Stack Overflow

How to add three dots in a multiline span

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was that I actually found the solution to this in another StackOverflow question, and that the solution is pretty simple. The link to the jsFiddle for the example is here, and also copied here for reference. HTML code:

<span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen look</span>​

CSS code:

span{
    display:inline-block;
    width:180px;
    white-space: nowrap;
    overflow:hidden !important;
    text-overflow: ellipsis;
}

And it works like expected, it prints: Lorem Ipsum is simply du…

However, when I tried this in another example. JsFiddle is here. HTML code:

<div class="textContainer">                
    <img src="#" class="image" alt="the_image">
    <span class="text">"The quick brown fox jumps over the lazy dog" is an english-language pangram, that is, a phrase that contains all of the letters of the English alphabet. It has been used to test typewriters and computer keyboards, and in other applications involving all of the letters in the English alphabet. Owing to its brevity and coherence, it has become widely known.</span>
</div>

CSS code:

.textContainer{
    width: 430px;
    float: left;
    margin-top: 10px;
    border: 1px solid black;                
}

.text {
    font-size: 24px;
    line-height: 24px;
    font-weight: bold;
    color: #047F04;
    display: block;
    white-space: normal;
    overflow: hidden !important;
    text-overflow: ellipsis;
    height: 99px;
}

.image {
    float: right;
    position: absolute;
    top: 85px;
    right: 10px;
    width: 108px;
    height: 42px;
}

So my question was how could I achieve to put … on the end of the string in my example?

The answer, by user devundef, was:

The specification for the text-overflow property says that this is not possible for multiline text:

This property specifies rendering when inline content overflows its block container element (“the block”) in its inline progression direction that has ‘overflow’ other than ‘visible’. Text can overflow for example when it is prevented from wrapping (e.g. due to ‘white-space:nowrap’ or a single word is too long to fit).

In other words, only works on single line text blocks.

source: http://dev.w3.org/csswg/css3-ui/#text-overflow

EDIT This fiddle has a workaround using jquery: http://jsfiddle.net/k5VET/ (source: Cross browsers mult-lines text overflow with ellipsis appended within a width&height fixed div?)

Stack Overflow

Serialize form not working in jQuery

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was if, for example, we have this HTML form code:

<form action="#" id="gamesForm">
    <p>                                                        
        <input id="gName" type="text" class="medium" />
        <span class="notification information">Game name</span>
    </p>

    <p>                            
        <span class="notification information">Enabled:</span>
        <input id="gEnabled" type="checkbox" />              
    </p>


    <br />
    <!--Additional data for extra type-->
    <div id="extraAdditionalData" class="hidden">                            
        <p>
            <input id="rRacers" type="text" class="medium" />
            <span class="notification information">Racers</span>
        </p>

        <p>
            <input id="rVideoSet" type="text" class="medium" />
            <span class="notification information">Video set</span>
        </p>                                                         
     </div>                
</form>

<a href="#" id="saveConfiguration" class="graybuttonBig">Save everything!</a>

And this js code:

$(document).ready(function(){
    $("#saveConfiguration").click(function(){
        alert( $("form").serialize() );   
    });
});

How come that all I get in the alert is an empty string?

The answer, by user Felix Kling, was:

You have to give your form elements names!

This is independent of jQuery. Every form element must have a name to be considered for form submission as successful control:

A successful control is “valid” for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.

jQuery just ignores those elements that don’t have a name (or, depending on how it gets the elements, it might not even see them as the form itself has no reference to them).

Books

The Hobbit – J. R. R. Tolkien

My favourite quotes from the book The Hobbit by J. R. R. Tolkien:

You are not easy to carry around, not even after few weeks of your starvation.

This would be a much happier world if more of us would stick to the eating, singing and happiness than to the vast piles of gold.

Programming

Notes from Sams Teach Yourself WPF in 24 hours

This is the new section that I’ll be posting in Programming category (parent Books); whenever I read a book I always take notes, so here they are now for easier access and search.

All in all I gave this book 5/5 in my Shelfari account as I think that it’s great, for beginners especially. This StackOverflow question may be useful if you’re searching for a good book on learning WPF.

WPF is an API for building graphical user interfaces (UI) for desktop applications with the .NET Framework.

WPF differs fundamentally in that it builds on top of DirectX. It also means that WPF will take advantage of hardware acceleration when it is available.

Graphics in WPF are vector based, in contrast to raster based. A general rule of thumb is that vector graphics are good for geometrical or cartoonish images and that raster is better for photographs and realistic images.

There are two types of templates in WPF: control templates and data templates.

WPF requires the .NET Framework 3.0 or later.

XAML (pronounced zammel) is the language used for creating user interfaces in WPF.

When you create a WPF application with Visual Studio, the XAML used in the application is compiled into the resulting executable.

Element in XAML is an instance of an object and attributes are properties on that object.

x:Name is not a property on the Button class. Instead, it’s a special attribute that provides a unique identifier for the object for accessing it in code. It is important to understand that any XAML element you want to reference, in code or elsewhere in the XAML, must have a unique value for x:Name. It’s pretty easy to get into trouble using the Name property, though, and unless you have a specific need, we recommend sticking with x:Name. It’s the convention that is generally adopted.

The child element is referred to as a property element. Property elements take the form of <ClassName.PropertyName />.

<Button Background=”{StaticResource ResourceKey=myColor}” Content=”Click Me” />
Markup extensions are indentified by the presence of curly brackets ({})

App.xaml represents the application itself. It is not visual, and it is primarily used to store resources that will be used throughout an application. App.xaml also defines which  window opens when the application launches.

MainWindow.xaml is the main window for the application. Its markup contains all the visual elements that represent the application on the screen, as well as declaring our application’s behavior.

The concept of partial classes was introduced with .NET 2.0. The essential idea is that a single class can be defined across multiple files. Each file contains a portion of the class. The files can even be of different file types; such as .cs and .xaml. The compiler is  responsible for dynamically combining the code into a single class as it is compiled.

Refactoring code means that you improve the maintainability of the code without changing the behavior.

Margin, present on all FrameworkElements, represents the amount of space around the outside of the element. Padding – amount of space inside itself.

Every Panel has a Children collection. This collection can be used to add or remove controls from the panel’s layout at runtime.

StackPanel organizes its child elements by stacking them one on top of the other. StackPanel also has an Orientation property that can be set to Horizontal, causing the panel to stack its children from left to right.

DockPanel is capable of attaching its children to any of its four sides and is often used as the root layout control of an application’s UI.

The Grid is WPF’s all-purpose layout panel. It can achieve most of the same behavior as the previous controls and much more. This power comes with a price; the requirement of  additional XAML and more attached properties.

<Grid ShowGridLines=”True” TextBlock.FontSize=”20”>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    
    <Grid.ColumnDefinitions>
	<ColumnDefinition />
	<ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Button Content=”0,0” />
    <Button Grid.Column=”1” Content=”0,1” />
    <Button Grid.Row=”1” Content=”1,0” />
    <Button Grid.Row=”1” Grid.Column=”1” Content=”1,1” />
</Grid>
<ColumnDefinition Width=”34” />
<ColumnDefinition Width=”1.5*” />
<ColumnDefinition Width=”2*” />
<ColumnDefinition Width=”auto” />

In this case, the first column would be 34 pixels wide, the last column would auto size to content and the middle columns would split the remaining space with the ratio 1.5:2.

The GridSplitter is a special control capable of letting a user resize rows or columns of a Grid at runtime.

WrapPanel is like a StackPanel, but it has the ability to “wrap” what it is stacking to the next line or column if it runs out of space.

Canvas does not add any special dynamic layout behavior to its child controls. A canvas must have an exact Width and Height, and all its child elements must have an exact size and position as well. Canvas arranges controls at strict Left (x) and Top (y) positions using attached properties. Although most panels will size to fit their children, if no size is declared for a Canvas it will collapse to zero.

Decorators – Border and Viewbox.

A Panel has a collection of Children that it arranges according to various rules, based on the type of panel. A Decorator, on the other hand, has only one Child to which it applies some additional set of behavior.

 TextBlock has many options (note LineBreak for, well, new line):

<TextBlock FontSize=”14” TextWrapping=”Wrap”>
    <Bold><Italic>Instructions:</Italic></Bold>
    <LineBreak />
    Select a <Underline>font</Underline> to view from the list
    <Italic>below</Italic>.
    <Span FontSize=”10”>You can change the text by typing in the region at the bottom.</Span>
</TextBlock>

Allow ENTER, TAB and wrap:

<TextBox x:Name="additionalNotes"
                 Grid.Row="3"
                 Grid.Column="1"
                 MinLines="5"
                 AcceptsReturn="True"
                 AcceptsTab="True"
                 TextWrapping="Wrap" />

In <Window definition make a habit of adding this:

FocusManager.FocusedElement=”{Binding ElementName=firstName}”

Use Label rather than TextBlock for forms as they provide shortcuts if you press Alt on the keyboard. In the listing below, the F would be underlined when Alt would be pressed.

<Label Content="_First Name:" Target="{Binding ElementName=firstName}" />

Using the tooltip:

<TextBox x:Name="SampleText" DockPanel.Dock="Bottom" MinLines="4" Margin="8 0" TextWrapping="Wrap">
            <TextBox.ToolTip>
                <TextBlock>
					<Italic Foreground="Red">Instructions: </Italic>
					Type here to change the preview text.
                </TextBlock>
            </TextBox.ToolTip>

            The quick brown fox jumps over the lazy dog.
</TextBox>

Data binding is a means of connecting the elements of a user interface with the underlying data that the application is interested in. Data binding is declarative rather than imperative. Declarative means that instead of writing a series of commands to be executed, you describe the relation that the data has to the elements in the UI.

Markup extensions are identified by curly brackets ({}), and a data binding extension always begins with the word Binding.

Two way binding:

<TextBox Text="{Binding ElementName=mySlider,Path=Value,Mode=TwoWay}" />
<Slider x:Name="mySlider" Minimum="0" Maximum="100" TickFrequency="1" IsSnapToTickEnabled="True"/>

{x:Static Fonts.SystemFontFamilies} – this markup extension is used for referencing static  value members on a class (fields, properties, constants, and enumeration values).

The WPF property system allows properties to participate in data binding, styling, animation, and several other exciting features. A property that is registered with the WPF property system is called a dependency property. A property must be a dependency  property to be the target of a data binding.

<TextBox Text=”{Binding Path=FirstName,Mode=TwoWay}” Margin=”4”/>

public Window1()
{
    InitializeComponent();
    DataContext = new Person(); //new class with only FirstName property
}

Remember, WPF automatically looks for an event based on the property’s name.

public string FirstName {get; set;}

public event EventHandler FirstNameChanged;
private void OnFirstNameChanged()
{
    if (FirstNameChanged != null)
        FirstNameChanged(this, EventArgs.Empty);
}

For dynamic size of the text inside the TextBlock, wrap it with a ViewBox, but without any additional sizes (width, height, font) set:

<Viewbox>
    <TextBlock TextWrapping="Wrap" Text="Some Text" />
</Viewbox>

XAML application, FontViewer for example, can work in IE if you change Window tag to Page and remove the IntegerUpDown control.

User controls are similar to windows and pages. They allow you to easily define your own controls that can be reused throughout your application. Do not confuse them with  custom controls. Custom controls are another way to create reusable elements for the UI, but I do not recommend them for a newcomer to WPF.

Open MainWindow.xaml and add the following Xml Namespace declaration to the Window: xmlns:local=”clr-namespace:TextEditor” in order to be able to load user controls like this:

<local:TextEditorToolbar x:Name=”toolbar” DockPanel.Dock=”Top” />

A TextRange represents a concrete selection of content within a document.

_currentFile = dlg.FileName;
using (Stream stream = dlg.OpenFile())
{
    TextRange range = new TextRange(
        _textBox.Document.ContentStart,
        _textBox.Document.ContentEnd
    );
    
    range.Load(stream, DataFormats.Rtf);
}

An application in WPF consists of many elements in a tree. If a user clicks the Image in our preceding example, WPF would route the event along the tree of elements until a handler was found. If no handler is implemented, the event continues beyond the Border all the way to the root element (which can be a Window or a Page).

Routed events are handled the same way except that the basic signature uses a
RoutedEventArgs.

void Handle_RoutedEvent(object sender, RoutedEventArgs e)

So how does PreviewKeyDown differ from the KeyDown event, which is also owned by
UIElement? Both of these are routed events, but the difference between the two is that one bubbles and the other tunnels. Remember we mentioned earlier that bubbling means the event is moving up toward the root element, and tunneling means the event is moving down toward its origin. The prefix Preview is a convention adopted in WPF to show that an event is a counterpart to another event. Thus PreviewKeyDown is the counterpart to KeyDown. When you press a key with an element in focus, first the PreviewKeyDown event is raised by the root element and tunnels down the tree to the actual element that was
in focus; then the KeyDown event is raised and bubbles back up to the root.

In WPF, a command is a function or action that can be bound to an input gesture. WPF binds the EditingCommands. ToggleBold command to the keyboard gesture Ctrl+B by default.

<ToggleButton x:Name=”boldButton” Command=”EditingCommands.ToggleBold” ToolTip=”Bold”>
<MenuItem Header=”_Edit”>
    <MenuItem Command=”ApplicationCommands.Undo” />
    <MenuItem Command=”ApplicationCommands.Redo” />

    <Separator />

    <MenuItem Command=”ApplicationCommands.Cut” />
    <MenuItem Command=”ApplicationCommands.Copy” />
    <MenuItem Command=”ApplicationCommands.Paste” />
    <MenuItem Command=”EditingCommands.Delete” />
</MenuItem>
<Window.InputBindings>
    <MouseBinding Gesture=”Control+WheelClick” Command=”ApplicationCommands.SaveAs” />
</Window.InputBindings>
<Window.CommandBindings>
    <CommandBinding Command=”ApplicationCommands.New” Executed=”NewDocument” />
</Window.CommandBindings>
<Window.InputBindings>
    <KeyBinding Key=”S” Modifiers=”Shift” Command=”ApplicationCommands.SaveAs” />
</Window.InputBindings>

We have talked about dependency properties before, but have not detailed how to create
them. We typically use this technique only when we need a property on a Window, UserControl, or custom control that must support data binding or other FrameworkElement-related features, such as animation or styling. The typical procedure for creating a dependency property is to declare a public, static field using
DependencyProperty.Register. It is advised that you append the word “Property” onto the field name. There are several overloads of the Register method, but at a minimum you must declare the actual property name, type, and owning type. You should then create instance getters and setters by using the static GetValue and SetValue methods inherited from DependencyObject. Use your dependency property’s field as the key to these  methods.

Use Path.Combine to safely and correctly build up directory and file paths.

All elements that are renderable must inherit from Visual.

MVC, despite its popularity, is commonly misunderstood. This may be because it tends to manifest itself differently in different scenarios—that is, web versus desktop applications.

Controllers traditionally functioned as mediators between the human and the application by handling user input from the mouse or keyboard. Controller doesn’t seem to fit exactly with modern UI toolkits like WPF. Very rarely would one need to write code to manually handle user input. What is really needed is an application-centric component that
can mediate between the View and the Model. This component would be capable of
responding to View interactions and translating those into application commands.
In the context of a contact manager, these commands would be actions like
SaveContact, DeleteContact, Search, and the like.

The mismatch between the MVC pattern and modern UI frameworks has been recognized by many people. Over time a new pattern called Model-View-Presenter has evolved from MVC.

Start a new project and add the following folders to the solution: Model, Presenters, Resources, UserControls and Views.

<TextBlock Text="Contacts" FontSize="14" FontWeight="Bold">
    <TextBlock.LayoutTransform>
        <RotateTransform Angle="90" />
    </TextBlock.LayoutTransform>
</TextBlock>

The Expander is a simple control whose primary purpose is to allow the user to collapse or expand a named region of the interface.

To serialize to disk .NET requires the [Serializable] attribute on the classes.

The important part of a repository is that it abstracts away the actual data store so that other parts of the application are able to work with a high-level API and not concern themselves with how the data is stored.

In a typical application, there is a need for an Application Controller or Application Presenter. This special type of presenter provides common application-level functionality to other presenters and manages various other cross-presenter issues.

This technique is known as constructor injection and is a specific type of dependency injection. DI is a technique that is commonly used to help enforce the principle of Separation of Concerns (SoC).

WPF uses a special type called a ResourceDictionary to store reusable “pieces” of an application. Everything that inherits from FrameworkElement has a Resources property. Colors cannot be applied to most WPF element properties like Background or
Foreground. These properties require the use of a Brush.

<SolidColorBrush x:Key=”brownBrush” Color=”{StaticResource brownColor}” />

<Color x:Key=”brownColor”>#FF513100</Color>

You will recall from earlier hours that Binding is a markup extension. Binding, along with StaticResource, make up the two most common extensions that you will use in WPF.

Refactoring the Resource files; in App.xaml instead of having all the mumbo jumbo, refactor to another file:

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source=”Resources\ColorsAndBrushes.xaml” />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Simply put, DynamicResource allows the resource to change after the point of reference, whereas StaticResource does not. This most often applies when you’re using system resources. For example, if you wanted to use a color from SystemColors, you would use a DynamicResource. This allows for the scenario where the user changed the system color theme while your application was running. If a DynamicResource was used, your application would update its colors on-the-fly whereas they would remain the same with a StaticResource. Because of the dynamic nature of the so-named resource, it is more resource intensive and less performant than StaticResource. You should prefer to use StaticResource and fall back to DynamicResource only when you need the special  capabilities it offers.

A Style resource is a special case because its key can be implicitly based on its TargetType value.

<Style x:Key=”header” TargetType=”{x:Type Border}”>
    <Setter Property=”Background” Value=”{StaticResource darkBlueBrush}” />
</Style>

<Border DockPanel.Dock=”Top”&nbsp;Style=”{StaticResource header}”>

WPF has a simple facility for letting you inherit styles one from another by using the BasedOn property:

<Style x:Key=”baseControlStyle” TargetType=”{x:Type Control}”>
    <Setter Property=”FontFamily” Value=”Arial” />
    <Setter Property=”FontSize” Value=”12” />
</Style>

<Style TargetType=”{x:Type Label}” BasedOn=”{StaticResource baseControlStyle}”>
    <Setter Property=”HorizontalAlignment” Value=”Right” />
    <Setter Property=”FontWeight” Value=”Bold” />
</Style>

By using the BasedOn property you can reference other styles and effectively enable
style inheritance. The basic constraint is that you must determine a compatible base
class for all the styles involved. In this case, both Button and Label inherit from
Control.

When WPF needs to find a resource, it first examines the Resources of the current element. If the resource with the requested Key is not found, WPF will look at that element’s parent’s Resources. WPF will follow this pattern until it reaches the root element in the UI. If the resource has not yet been found, it will look at the Application.Resources.

Styles can be applied by TargetType or Key. If an element has a specific style declared with a key, that style will override all other styles applied to that element. If no style is explicitly set, WPF will search for a style defined with a matching TargetType and apply it if found within the visible scopes; otherwise, the WPF default style will be used. A developer can always override individual aspects of a style by explicitly setting the properties on an element.

Binding headerBinding = new Binding(presenter.TabHeaderPath);

is equal to

{Binding Path=TabHeader}

Data templates are one of the two types of templates used in WPF. They provide a way to describe how data should be visualized in terms of UI elements. This is different from deciding how to render a DateTime value, or formatting a telephone number.

Styles are the simplest of the three, so if you are able to achieve what you want using styles, that is the best choice. Keep in mind that styles allow you to set nonvisual properties as well.

Control templates define the UI elements that compose a given control. That’s a lot more complicated than merely setting some properties. You should use control templates only when you really need to.

Data templates resemble control templates in that they allow you to compose UI elements. They are often used with list controls to define how items in a list
should be rendered.

We could state that the primary difference between these two base classes is that ContentControl supports the rendering of a single item, whereas ItemsControl supports the rendering of multiple items.

The important part is the call to Application. Current.Dispatcher.Invoke. This method executes the delegate on the UI thread according to the specified DispatcherPriority. This is important because WPF is not guaranteed to work properly with events firing on threads other than the UI thread.

Transformations:

<Canvas Height="600" Width="800">
    <TextBlock Text="No Transform" />
        
    <TextBlock Canvas.Left="200" Canvas.Top="100" Text="Skew Transform">
        <TextBlock.RenderTransform>
            <SkewTransform AngleX="45" />
        </TextBlock.RenderTransform>
    </TextBlock>
</Canvas>

When applying multiple transforms by using a TransformGroup, remember that
the order of the transforms can have a strong impact on the result.

Using a LayoutTransform allows an element to be transformed while still playing by the layout rules of the Panel in which it lives. WPF has such rich layout capabilities that it would be unfortunate if all transforms broke the layout rules. Essentially, a LayoutTransform occurs before a Panel performs layout; thus, any transforms that occur are taken into account when the Panel arranges its children. A RenderTransform happens independently of the layout mechanism.

Every UIElement has a BitmapEffect property that can be used to add various special shader-like effects to the element:

<Button Content="Blur">
    <Button.BitmapEffect>
        <BlurBitmapEffect Radius="4" />
    </Button.BitmapEffect>
</Button>

Control templates:

<Window.Resources>
    <Canvas x:Key=”Smiley” Width=”48” Height=”48”>
        <Ellipse Width=”48” Height=”48” Fill=”Yellow” />
        <Ellipse Width=”8” Height=”8” Canvas.Top=”12” Canvas.Left=”12” Fill=”Black”/>
        <Ellipse Width=”8” Height=”8” Canvas.Top=”12” Canvas.Right=”12” Fill=”Black” />
        <Path Data=”M10,30 C18,38 30,38 38,30” Stroke=”Black” />
    </Canvas>
</Window.Resources>

<Button HorizontalAlignment=”Center” VerticalAlignment=”Center”>
	<Button.Template>
		<ControlTemplate>
			<Border Background=”Black” Padding=”4” CornerRadius=”4” Child=”{StaticResource Smiley}” />
		</ControlTemplate>
	</Button.Template>
</Button>

Anytime you implement a control template, you’ll have to handle these effects yourself with triggers.

Templates are composed out of UI elements. Templates need to be explicitly told what type of control they are targeting. Use the TargetType attribute to do this. Templates need to know what to do with the control content. We used the ContentPresenter element to handle this for a button.

In style:

<Style TargetType=”{x:Type Slider}”>
	<Setter Property=”Template”>
		<Setter.Value>
			<ControlTemplate TargetType=”{x:Type Slider}”>
				<Grid x:Name=”root”>
					<Border Height=”4” CornerRadius=”2” Background=”{StaticResource sliderBg}”>
					</Border>

					<Track x:Name=”PART_Track”>
						<Track.Thumb>
							<Thumb />
						</Track.Thumb>
					</Track>
				</Grid>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>

We can bind elements in a template to the actual control:

<ControlTemplate x:Key=”CircleButton” TargetType=”{x:Type Button}”>
	<Grid HorizontalAlignment=”Center” VerticalAlignment=”Center” MinHeight=”36” MinWidth=”36”>
		<Ellipse Fill=”{TemplateBinding Background}” />
		<ContentPresenter />
	</Grid>
</ControlTemplate>

In this example, the Fill property on the Ellipse will be set to the Background property of the button that the template is applied to.

It is a common practice to keep a control template flexible through the use of template
binding. The idea is that you create a default style for your controls that sets the control template. However, you use template binding and set as many of the properties as possible in the style. That way, you can inherit from the default style, overriding specifics as needed, while retaining your control template.

This data binding:

{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}

is the equivalent of this template binding:

{TemplateBinding Background}

Triggers are a special feature of Style, ControlTemplate, DataTemplate, and FrameworkElement. Through the careful use of triggers, you can declaratively enable your UI and graphics to respond to mouse events, changes in dependency properties, and even changes in your application’s data model.

<ControlTemplate.Triggers>
	<Trigger Property="IsMouseOver" Value="True">
		<Setter TargetName="highlight" Property="Visibility" Value="Visible" />
	</Trigger>

	<Trigger Property="IsPressed" Value="True">
		<Setter TargetName="highlight" Property="Opacity" Value="0.5" />
	</Trigger>
</ControlTemplate.Triggers>

If multiple triggers alter the same UI properties, the last one wins.

<Style.Triggers>
	<DataTrigger Binding="{Binding Path=IsMuted, ElementName=mediaElement}" Value="True">
		<Setter Property="Visibility" Value="Visible" />
	</DataTrigger>
</Style.Triggers>

EventTrigger is the final type of trigger that WPF currently offers

<ControlTemplate.Triggers>
	<EventTrigger RoutedEvent=”UIElement.MouseEnter”>
		<BeginStoryboard>
			<Storyboard Storyboard.TargetName=”chromeEdge” Storyboard.TargetProperty=”RenderTransform.Angle”>
				<DoubleAnimation To=”90” Duration=”0:0:0.10” />
			</Storyboard>
		</BeginStoryboard>
	</EventTrigger>

	<EventTrigger RoutedEvent=”UIElement.MouseLeave”>
		<BeginStoryboard>
			<Storyboard Storyboard.TargetName=”chromeEdge” Storyboard.TargetProperty=”RenderTransform.Angle”>
				<DoubleAnimation To=”0” Duration=”0:0:0.10” />
			</Storyboard>
		</BeginStoryboard>
	</EventTrigger>
</ControlTemplate>

Notice the important RoutedEvent property, which is used to declare which event will trigger the action.

Sometimes a situation arises in which a simple Trigger can’t express the conditions under which a collection of setters should be applied. For these scenarios, WPF provides the MultiTrigger and the MultiDataTrigger. These represent more advanced versions of Trigger and DataTrigger, respectively. Instead of having a simple Property or Binding and a Value, they each have a collection called Conditions. To leverage this functionality, you add multiple Condition instances to this collection.

<DataTemplate.Triggers>
	<MultiDataTrigger>
		<MultiDataTrigger.Conditions>
			<Condition Binding=”{Binding Organization}” Value=”Blue Spire Consulting, Inc.” />
			<Condition Binding=”{Binding Address.City}” Value=”Tallahassee” />
		</MultiDataTrigger.Conditions>
	
		<MultiDataTrigger.Setters>
			<Setter TargetName=”border” Property=”Background” Value=”Blue” />
		</MultiDataTrigger.Setters>
	</MultiDataTrigger>
</DataTemplate.Triggers>

At its root, an animation is a series of images shown in rapid succession to give the illusion of motion. The individual images in an animation are referred to as frames. The number of frames per second (fps) is called the frame rate. Most television and film is somewhere between 20 and 30fps. The higher the frame rate, the smoother the animation will seem. Computer graphics generally target a frame rate around 60fps. Key frames are
the frames that represent significant points in the motion, such as the start and  end points. All the remaining frames, those in between the key frames, are called tweens. A timeline is a segment of time; it has a beginning point and duration.

<Window x:Class="LearningAnimation.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300">
    <Window.Triggers>
        <EventTrigger RoutedEvent="Window.Loaded">
            <BeginStoryboard>
                <Storyboard Storyboard.TargetName="Ball" Storyboard.TargetProperty="(Canvas.Left)">
                    <DoubleAnimation By="300" Duration="0:0:07.5"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Window.Triggers>
    
    <Canvas>
        <Ellipse x:Name="Ball" Width="20" Height="20" Fill="Red" Canvas.Top="50" Canvas.Left="0"></Ellipse>
    </Canvas>
</Window>

The Storyboard has a single child. It’s a DoubleAnimation because Canvas.Left is of type double.

<DataTemplate x:Key="PictureDataTemplate">
        <Image Source="{Binding Path=Thumbnail}" Width="75" Height="75" Margin="4">
            <Image.Triggers>
                <EventTrigger RoutedEvent="Image.MouseEnter">
                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetProperty="Width">
                            <DoubleAnimation By="25" Duration="0:0:0.25" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Image.MouseLeave">
                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetProperty="Width">
                            <DoubleAnimation To="{TemplateBinding Width}" Duration="0:0:0.25" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Image.Triggers>
        </Image>
    </DataTemplate>

Very basically a ControlTemplate describes how to display a Control while a DataTemplate  describes how to display Data.

Any element can trigger an animation. In addition to this technique, animations can be triggered from styles, control templates, and data templates. Inside of a Style, you cannot use Storyboard.TargetName. When you create an animation in a style, it will always target the element that the style is applied to. Likewise, you cannot specify the SourceName on a trigger. On the whole, a storyboard inside a style cannot reference dynamic resources or data bind.

<DoubleAnimation By=”300” AccelerationRatio=”0.4” DecelerationRatio=”0.4” Duration=”0:0:10”/>

With this markup, the ball will start at a speed of 0 and accelerate for 4 seconds. Then, beginning at the sixth second, it will slow down for 4 seconds.

<Button x:Name="button" Content="mybutton">
            <Button.Triggers>
                <EventTrigger RoutedEvent="Button.Click">
                    <BeginStoryboard>
                    <Storyboard Storyboard.TargetName="Ball" Storyboard.TargetProperty="(Canvas.Top)">
                        <DoubleAnimation By="300" Duration="0:0:07.5"/>
                    </Storyboard>
                </BeginStoryboard>
                <BeginStoryboard>
                    <Storyboard Storyboard.TargetName="Ball" Storyboard.TargetProperty="(Canvas.Left)">
                        <DoubleAnimation By="300"
AccelerationRatio="0.4"
DecelerationRatio="0.4"
Duration="0:0:10"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
            </Button.Triggers>
        </Button>
        <Ellipse x:Name="Ball" Width="20" Height="20" Fill="Red" Canvas.Top="50" Canvas.Left="0"></Ellipse>
    </Canvas>

 

<Window.Triggers>
        <EventTrigger RoutedEvent="Window.Loaded">
            <BeginStoryboard x:Name="BallStoryboard">
                <Storyboard Storyboard.TargetName="Ball" Storyboard.TargetProperty="(Canvas.Left)">
                    <DoubleAnimation By="300" Duration="0:0:07.5"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
        <EventTrigger RoutedEvent="Button.Click" SourceName="Pause">
            <PauseStoryboard BeginStoryboardName="BallStoryboard" />
        </EventTrigger>
        <EventTrigger RoutedEvent="Button.Click" SourceName="Resume">
            <ResumeStoryboard BeginStoryboardName="BallStoryboard" />
        </EventTrigger>
    </Window.Triggers>
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Button x:Name="Pause">Pause</Button>
            <Button x:Name="Resume">Resume</Button>
        </StackPanel>
        <Canvas>
            <Ellipse x:Name="Ball" Width="20" Height="20" Fill="Red" Canvas.Top="50" Canvas.Left="0"></Ellipse>
        </Canvas>
    </StackPanel>

Setting animation in code behind:

var animation = new ColorAnimation
{
From = Colors.Blue,
To = Colors.Yellow,
Duration = new Duration(TimeSpan.FromSeconds(2))
};
var button = new Button();
button.BeginAnimation(Button.BackgroundProperty,animation);

Ortogonality – things that are independent of one another.

Single Responsibility Principle – there should never be more than one reason for a class to change.

Separation of Concerns – embodies a “divide and conquer” approach to programming. Rather than having huge, complex classes, our system should be built from smaller, more focused components that work together.

Don’t Repeat Yourself – the key point is if you find yourself writing the same sort of
code over and over again, there’s something wrong.

Inversion of Control => The constructor signature is shown next:

public ApplicationPresenter(Shell view, ContactRepository contactRepository)

ApplicationPresenter is dependent on both a Shell view and a ContactRepository. It cannot function without these other components, yet it doesn’t take the responsibility of creating them. This is called Inversion of Control, often abbreviated IoC.

Dependency Injection – the control of dependency creation is inverted because the presenter has given up its right to create the components it depends on. It is relying on some outside source to hand it the pieces it needs to work. These dependencies are then
injected into the class via the constructor. This is known as Dependency Injection, or
DI, and it adds a great deal of flexibility and extensibility to your software design.

Ya Aren’t Gonna Need It – well, you just ain’t so why bother feature-stacking?

Stack Overflow

How to replace text between quotes in vi or vim?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was if for example we have this line of code:

$query = "SELECT * FROM table";

is there a command in vi/vim which can instantly delete everything between quotes and position the cursor between them so I can start typing immediatelly?

The answer, by user eugene y, was:

Use ci", which means: change what’s inside the double quotes.

You can also manipulate other text objects in a similar way, e.g.:

  • ciw – change inside a word
  • ci( – change inside parentheses
  • dit – delete inside an HTML tag, etc.

More about different vim text objects here.

Books

Therapy – Sebastian Fitzek

My favourite quotes from the book Therapy by Sebastian Fitzek:

Stories are worthless if they can’t be narrated to someone.

Show me your friends and I’ll tell you who you are.

Even the most intelligent people act from time to time very funny and unusual. Almost every owner of the TV remote has, for example, irreparable habit of pressing the buttons harder when batteries start to fade.

Stack Overflow

What is disableSelection used for in jQuery sortable?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was whether someone could help me understand why is disableSelection useful and when to use it. The simple usage example of disableSelection is this:

$("#sortable").disableSelection();

The answer, by user kba, was that:

It’s useful if you want to make text unselectable. If, for instance, you want to make drag-and-drop elements with text on, it’d be annoying to the user if the text on the box accidentally would get selected when trying to drag the box.

Books

Altered Carbon – Richard Morgan

My favourite quotes from the book Altered Carbon by Richard Morgan:

Somebody wants to kill me, and that’s not a nice feeling.

People envy me, people hate me. That’s the price of success. That was news to me, people hated me on ten different planets, but I never considered myself a successful man.

I trust those bastards as I would a cellophane condom.

Human eye is a marvelous device. With a little effort it can overlook even the greatest injustice.

Don’t judge, so that you won’t be judged.

They call that a Kemmerich gradient, and yours is so steep that you would need a bolt and ropes to climb it.

NodeJS

MEAN.io VS MEAN.js and deploying the latter on DigitalOcean

What are they?

MEAN.(io + js) are both full-stack JavaScript frameworks, and they are both comprised of these technologies:

  • MongoDB – leading NoSQL database, empowering businesses to be more agile and scalable
  • Express – minimal and flexible Node.js web application framework, providing a robust set of features for building single and multi-page, and hybrid web applications
  • Angular – lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop
  • Node.js – a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications

Which is which?

There seems to be a lot of confusion between the two, and this StackOverflow answer can help clarify it. Essentially:

Mean.js is a fork of Mean.io and both initiatives were started by the same guy. Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about his reasons here.

On their GitHub pages the MEAN.io has more stars, forks, and watchers but that may easily be to the fact that the MEAN.js is younger:

mean js github page

MEAN.js GitHub page

mean.io github page

MEAN.io GitHub page

How to get started?

I already wrote about MEAN.io and how to deploy it to Nodejitsu from Windows machine, and in this blog post I’ll show you how easy it is to deploy MEAN.js on DigitalOcean. Surely, you can deploy MEAN.io too on DigitalOcean, but you would have to install all the prerequisites on your own, and as you’ll see the MEAN.js is all set up automagically with few button clicks.

Disclamer: I am affiliated with DigitalOcean. If the post helped you, you can signup via my referral link. They regularly offer free credit (currently they offer 10$) so you can try it out without paying anything (I’m sure you have the Google skills to get the discount code).

So, from my experience with the cloud hostings I was pretty much amazed how fast you can get your root box up and running on DigitalOcean, additionally they have the (so called) droplet for MEAN ready so in basically less than 1 minute you’ll have everything ready to start coding your MEAN project. Let’s now see how to do this step by step.

Create a droplet

Naturally, first you have to signup up with DigitalOcean (remember to look for coupons), and once you do that you’ll be able to login to their web admin dashboard.

DigitalOcean calls its virtual servers, droplets; each droplet that you create is a new virtual server for your personal use. In order to create a new droplet from your web admin, click on the CREATE button, and select a custom hostname and size (as shown on the image below):

create_1

All on the same page (scroll down), select a region which is closest to you (London  1 in my case, as shown on the image below):

create_2

The most important part is selecting the actual distribution/application that will be installed on your droplet by default. Here you have quite a few options and I encourage you to test them as you see fit. In my example, however, we’re gonna use the MEAN on Ubuntu 14.04 (as shown on the image below).

create_4

Finally, you can leave the additional settings as they are and you can confirm the droplet creation by clicking on the Create Droplet button.

create_5

Login to your new droplet

Shortly after (less than 1 minute!) you’ve clicked the Create Droplet button you’ll get the email with the info on how to connect to your droplet. Below is the example of such an email. In order to connect to your droplet you can use PuTTY (a free implementation of Telnet and SSH for Windows and Unix platforms), and all you’ll have to do is enter the IP and click Open (it’s good to name this connection and save it for later use – digocean in the image below).connect_1

If the popup appears as shown on the image below, most likely you’ll want to click Yes.connect_2

When you log in with the username root and password that you got in the mail, you’ll be prompted to repeat the root’s password and to change it to something else, which is a standard security practice.connect_3

Run the application

Your application will be located in /opt/mean  folder, and in order to run it you just have to execute the following command in that folder:

grunt

Output that you’ll most likely see after running the grunt command can be seen on the image below:

run_1

To view your application in the browser, visit http://YOUR_DROPLET_IP:3000/ (in my case that would be http://178.62.47.198:3000) and you should see a screen similar to the one on the image below:run_2Finally, all done. Next logical step would be to check out he MEAN.js docs.

Happy building!

Page 47 of 51« First...102030«46474849»50...Last »

Recent posts

  • When espanso Breaks on Long Replacement Strings (and How to Fix It)
  • 2024 Top Author on dev.to
  • Hara hachi bun me
  • Discipline is also a talent
  • Play for the fun of it

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (78)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (41)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak