A JavaScript Keyboard With Special Language Symbols That Appears When The User Starts Typing

This blog post will demonstrate how to create a keyboard that renders only when the user starts typing in a text box. When the user clicks outside the text box, the virtual keyboard disappears. There is another extra – a selection of languages to the right. When a language is selected, the keyboard renders only the special symbols from the selected language.

You can test the JS Hidden Keyboard sample online from this link.

The application uses MindFusion Virtual Keyboard for JavaScript. Here is a screenshot of the application:

Invisible keyboard in JavaScript

Virtual keyboard in JavaScript that renders only when the user starts typing. The keyboard renders special symbols for several languages.

I. The Keyboards for Spanish, German and French

The three keyboard layouts with special symbols for the three languages are created with the Virtual Keyboard Layout Creator tool, that is packed with the JavaScript Keyboard library. We create a new compact keyboard and delete most of the keys. We type the desired key as character for the rest and use the Properties tab to set the size of the keyboard, as well the layout and the key alignment. Finally, we export the new keyboard layout as a json file (File → Export JavaScript. It is a good idea to save the keyboard layout as xml as well (File → Save As). This way you can load the keyboard gain, when you need to create another layout based on it or correct this one.

We have created now three json files:

  • french-symbols.js
  • german-symbols.js
  • spanish-symbols.js

Let’s look at the contents of one of the json files:

var layoutDef =
{
	width: 565,
	height: 115,
	keys:
[	{	
		code: 162,
		type: "regular",
		content: "ù",
		left: 9,
		top: 10,
		width: 40,
		height: 40
	},
	{	
		code: 162,
		type: "regular",
		content: "û",
		left: 56,
		top: 10,
		width: 40,
		height: 40
	},
………
{	
		code: 162,
		type: "regular",
		content: "œ",
		left: 507,
		top: 58,
		width: 40,
		height: 40
	}
]
};

Each file contains an array named “numpadDef”. We need to change the name, because we will load each list when a certain language is selected, which means we must be able to differentiate among the languages. We rename the lists to layoutDefFr, layoutDefDe and layoutDefEs.

Here is what the Virtual Keyboard Layout Creator Tool looks like:

Keyboard layout creator tool

The virtual keyboard layout creator tool that is part of the JavaScript Keyboard library by MindFusion

II. The HTML Web Page

We create a simple web page, where we add a reference to the JavaScript file of the Virtual Keyboard library:

<a href="http://Keyboard.js">http://Keyboard.js</a>

Note that we place this reference at the end of the file, after the closing tag. The we need reference to the JavaScript files with the definitions of the virtual keyboards that we created in step I.


<script src="french-symbols.js" type="text/javascript"></script>
<script src="spanish-symbols.js" type="text/javascript"></script>
<script src="german-symbols.js" type="text/javascript"></script>

Finally, we add a reference to a JavaScript file that will hold the code for our sample. It will be empty for now.

<script src="HiddenKeyboard.js" type="text/javascript"></script>

The next step is to load the CSS file with the styling for the JS keyboard. We have chosen the Silver theme, you can choose whichever theme you want or create a custom one.

<link href="css/VirtualKeyboard.Silver.css" rel="Stylesheet" />

We have added also a reference to a a stylesheet that aligns correctly the

elements with the keyboard, the text area and the select list.

<link href="style.css" rel="Stylesheet">

It contains code purely to align correctly the elements and we will not examine its contents.

Now, let’s create the text area:

<form id="f1">
    <textarea id="text" cols="55" rows="15">
    </textarea>
</form>

We create a form, called f1 and there we create the HTML textarea element. It handles to events: onfocus and onblur.

Next, the form contains a select with the three languages, whose keyboards with special symbols we have prepared:

<select id="selectedLang" size="3">
<option value="Fr">French</option>
<option value="De">German</option>
<option value="Es">Spanish</option>

Outside the form, we place a dive with the keyboard:

<div id="keyboard" style="width: 565px;height: 115px" />

The virtual keyboard will be rendered with fixed size and by default is not rendered e.g. it’s display is set to “none”.

III. The JavaScript Code-Behind File

First, we add two namespace mappings:

var VirtualKeyboard = MindFusion.VirtualKeyboard;
var KeyboardLayout = MindFusion.KeyboardLayout;

Then we handle the DOMContentLoaded event to create the Virtual Keyboard object. We use the div element that represents the keyboard as a parameter to the VirtualKeyboard constructor. We have provided the div element with an id in the HTML page.

We also set the selected index of the elements in the language list to -1 e.g. by default no language is selected and the keyboard will show the standard English typing keyboard.

document.addEventListener("DOMContentLoaded", function (event)
{
	document.getElementById("selectedLang").selectedIndex = -1;
	
	var vk = VirtualKeyboard.create(
		document.getElementById("keyboard"));
	vk.setScaleToFitParent(false);	

…………………

});

Then we handle changes in the selection of the language:

 

f1.selectedLang.onchange = function (event)
	{
		
	switch (event.target.value) {
  case 'Fr':
    vk.setLayout(KeyboardLayout.create(layoutDefFr));
    break;
  case 'De':
  vk.setLayout(KeyboardLayout.create(layoutDefDe));
  break;
  case 'Es':
    vk.setLayout(KeyboardLayout.create(layoutDefEs));
    break;	
    } 
 }

When the user chooses one of our custom layouts we create a keyboard layout with the appropriate layoutDef object.

Next we handle the onfocus and onblur events with the methods showKeyboard() and hideKeyboard(). They just make the div with the keyboard visible or invisible:

function showKeyboard() { 
		
	var x = document.getElementById("keyboard"); 
		x.style.display = "block";			
	}
	
	function hideKeyboard() {
    var x = document.getElementById("keyboard");    
        x.style.display = "none";
    
	}

And that’s all. As you can see creating and loading a custom keyboard with MindFusion JS library is really as easy as 1, 2 3. You can download the complete source code of the sample from this link:

Download the Hidden Keyboard With Special Language Symbols JavaScript Sample

About MindFusion Virtual Keyboard for JavaScript: A highly interactive, highly customizable library written in pure JavaScript that provides your web application with screen typing capabilities similar to those on mobile devices. The keyboard supports three predefined layouts: compact, default and extended. You can also use the keyboard layout creator tool that provides a convenient GUI to create and arrange your own keyboards. The library offers a well documented API with self-explanatory API members and tutorials that guarantee flat learning curve. You can choose among 8 predefined keyboard styles or customize them to create your own styles. Licenses are royalty-free, perpetual with discounts for freelancers, startups, academic institutions to name just a few. Learn more at https://mindfusion.eu/javascript-keyboard.html

Fishbone (Ishikawa) Diagram in WPF

In this blog post we will use the WPF Diagram component to build a fishbone diagram as described in the Wikipedia “Ishikawa diagram” article cited below:

“Ishikawa diagrams (also called fishbone diagrams, herringbone diagrams, cause-and-effect diagrams, or Fishikawa) are causal diagrams created by Kaoru Ishikawa that show the causes of a specific event.

Common uses of the Ishikawa diagram are product design and quality defect prevention to identify potential factors causing an overall effect. Each cause or reason for imperfection is a source of variation. Causes are usually grouped into major categories to identify and classify these sources of variation.” Read more on https://en.wikipedia.org/wiki/Ishikawa_diagram

This tutorial will demonstrate how easy it is to create the same diagram using the WPF diagram library and writing several lines of code. This is the final diagram:

Ishikawa (fishbone) diagram in WPF with MindFusion WPF Diagram library

Ishikawa (fishbone) diagram in WPF with MindFusion WPF Diagram library

I. General Settings

We create an empty WPF project in Visual Studio called “Fishbone”. There we create an Assemblies folder where we place the necessary dll-s:

  • MindFusion.Common.dll
  • MindFusion.Diagramming.Wpf.dll

Then in the MainWindow.xaml file we create a mapping to the Diagramming namespace:

<window x:class="Fishbone.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:diag="http://mindfusion.eu/diagramming/wpf" title="MindFusion Fishbone Diagram" height="387" width="622">
</window>

Then we create the diagram inside the default Grid WPF control:

<grid>
 <diag:fishbonediagram x:name="fdiag">
 </diag:fishbonediagram>
</grid>

The code creates a new instance of the FishboneDiagram* class with the name “fdiag”. We can use this name to access the object in code.

II. Diagram Data

The FishboneDiagram class exposes an ItemsSource property that provides data for the diagram. The data is an object that contains the label for the main Clause and a list with the labels of the subclauses. We create a special class called FBClause that will represent each fishbone:

public class FBCause
	{
		public FBCause()
		{
			SubCauses = new List();
		}
		public string Label { get; set; }
		public List SubCauses { get; set; }
	}

Next, we create the necessary fishbones this way:

var c1 = new FBCause { Label = "Measurements" };
c1.SubCauses = new List { "Inspectors", "Microscopes", "Calibration" };
…………

Once we are done with all fishbones, we create the model, which will serve as data source for the fdiag object:

var model = new List { c1, c2, c3, c4, c5, c6 };

III. Building the Diagram

Now that the data is ready, we can assign it to the ItemsSource property of the FishboneDiagram class:

fdiag.ItemsSource = model;

We will use the LabelPath and SubCausesPath properties to bind the respective fields of our FBClause objects to the correct data properties of FishboneDiagram:

fdiag.LabelPath = "Label";
fdiag.SubCausesPath = "SubCauses";

If the subclauses of your model were objects instead of strings as in our FBClause class you should use the SubLabelPath property to set the name of the field that will provide data for the subclause labels.

Finally we call the diagram’s ResizeToFitItems method to make sure all fishbones will be visible:

fdiag.ResizeToFitItems(30);

Compile and run the sample and you will see a perfect fishbone diagram.
That’s the end of our tutorial, you can download the sample together with all necessary dll-s from this link:

Download MindFusion Fishbone (Ishikawa) Diagram in WPF Sample

* The FishboneDiagram class will be officially released with the next version of the WPF Diagram Tool.

About Diagramming for WPF: This is the right tool to create flowcharts in WPF that always meet your requirements. The library offers more than 100 predefined node shapes, extensive event set and more than 15 exporters and importers. Each diagram that you build has a completely customizable look through styles, themes and appearance properties for each part of the flowchart. The numerous samples and detailed documentation help you learn quickly how to integrate the component into your own application. You can download the trial version, which has no feature restrictions and does not expire from the WPF Diagram Page on MindFusion website.

Real-Time Chart in WinForms

In this sample we will build a line chart that reads its data in real time and gets updated each second.

Real-time WinForms Chart

We start by creating an empty WinForms project. We assume you have installed the Charting for WinForms component and you can see a list with chart components in the VisualStudio toolbox.

Drag the LineChart control and drop it on the form. You should now see references to the three libraries that you need automatically added to your project:

  • MindFusion.Charting;
  • MindFusion.Charting.WinForms;
  • MindFusion.Common;

1. Series and Data

Our chart will render time stamps at the X-axis. That’s why we choose the DateTimeSeries class to create the series for the chart. The constructor requires two lists – one with DateTime values and one with double values. They provide data for the X and Y axes respectively. We must also provide two more parameters: one for the start and one for the end of the time period.

List dates = new List();
List values = new List();

In order to mimic the real-time functionality we will use a timer. Our timer will generate a random number each second. At the beginning we will have a list with no values. Gradually, we will fill the values and once we reach the count of 100 we will start to delete the first value and add a new value at the end of the arrays.

That’s how we initialize the timer:

Random ran;
ran = new Random();         
        
Timer dataTimer = new Timer();
dataTimer.Tick += new EventHandler(GenerateData);
dataTimer.Interval = 1000;
dataTimer.Start();

Let’s look at the GenerateData method:

private void GenerateData(object sender, EventArgs e)
    {
         dates.Add(DateTime.Now);
         values.Add(2 + ran.NextDouble() * 8.0);

         if (dates.Count > 100)
         {
             dates.RemoveAt(0);
             values.RemoveAt(0);
         }
...
}

There we always add the current DateTime. Since the timer ticks every second that’s exactly what we want. Once the values are 100, we start to remove values at the beginning of the list.

Now let’s create the DateTime series. It requires parameters for the start and end of the period. We always allocate the first and last DateTime values as the bounds of the DateTime data for this series:

DateTimeSeries series = new DateTimeSeries(dates, values, dates[0], dates[dates.Count-1]);

Then we see if we have already added a Series and if so – replace it. If no Series has been added – add the new one:

if (lineChart1.Series.Count > 0)
       lineChart1.Series[0] = series;
else
       lineChart1.Series.Add(series);

By default the DateTimeSeries renders its values from the X-axis – the DateTime instances as labels at the X-axis. We can customize how they look with the DateTimeFormat property. The predefined DateTimeFormat members don’t have an option where the values are rendered as “14:23:34” as a time stamp. So, we choose as DateTimeFormat “CustomDateTime” and use the CustomDateTime to specify the format:

series.DateTimeFormat = DateTimeFormat.CustomDateTime;
series.CustomDateTimeFormat = "H:mm:ss"; 

2. The X-Axis

We want at each moment only the last 10 values to be visible. The other 90 or however they are should be rendered but the user must scroll to see them. We achieve with the MinValue and MaxValue properties of the DateTimeSeries:

series.MinValue = 0;
series.MaxValue = 0.1 * dates.Count;

In order to render only the last 10 series, we use the XAxis properties – MaxValue and MinValue Once the MaxValue of the DateTimeSeries is more than 1, which means that at least 10 values have been added, we adjust the visible range of values at the X-axis so that only the last 10 are visible:

if (series.MaxValue > 1)
  {
      lineChart1.XAxis.MaxValue = series.MaxValue;
      lineChart1.XAxis.MinValue = series.MaxValue - 1.0;
  }

We also set the Title for this axis:

lineChart1.XAxis.Title = "Time";

Let’s hide the numeric values from rendering at the top of the DateTime stamps with the ShowXCoordinates property:

lineChart1.ShowXCoordinates = false; 

3. The Y-Axis

By default the range of an axis is calculated based on the data. Let’s make our chart render the line graphics more to the beginning of the axis by increasing the MaxValue of the Y-axis while we fix the MinValue at 0:

lineChart1.YAxis.MinValue = 0;
lineChart1.YAxis.MaxValue = 20;
lineChart1.YAxis.Interval = 2;

We also change the axis Title and we use NumberFormat property to render the intervals with floating points:

lineChart1.YAxis.Title = "Visitors (in thousands)";
lineChart1.YAxis.NumberFormat = "N";

4. Grid

Let’s render vertical grid stripes. We want them to be dashed and light gray. We use GridType GridColor and GridLineStyle to customize the grid:

lineChart1.GridType = GridType.Vertical;
lineChart1.Theme.GridLineStyle = System.Drawing.Drawing2D.DashStyle.Dash;
lineChart1.Theme.GridLineColor = Color.FromArgb(192, 192, 192);

Note that GridColor and GridLineStyle are properties of the Theme property of LineChart add one extra – stop the grid stripes from moving around when the user scrolls the chart along the axis:

lineChart1.PinGrid = true;

5. Legend

The legend gets its labels from the Title property of a Series. In our case we set:

series.Title = "Server Requests";

We would like to change the legend background to make the legend easier to spot:

lineChart1.Theme.LegendBackground = new MindFusion.Drawing.SolidBrush(Color.FromArgb(120, 230, 230, 230));

We use a semi-transparent brush that let’s chart details be visible when the user moves the legend onto another chart element.

6. Line Colors

We want to render the line in red. We choose the MixedSeriesStyle class as the styling class for our application. You can use any other *SeriesStyle class that is appropriate in your case:

// assign a reb brush for the series
lineChart1.Plot.SeriesStyle = new MixedSeriesStyle()
    {  
         UniformStrokeThickness = 5,
         UniformStroke = new MindFusion.Drawing.SolidBrush(Color.Red),
         UniformFill = new MindFusion.Drawing.SolidBrush(Color.Red)
     };

With that our sample is complete. You can download the full code with the necessary charting dll-s from this link:

Download the WinForms Real-TimeChart Sample

About MindFusion Charting for WinForms: A versatile dashboard component that provides your WinForms application with the ability to create fascinating charts, interactive dashboards and practical gauges. The component combines a flexible API that allows custom combination of chart components to build any type of chart you want. You can add as many axes of any type you want, combine various chart series into a single chart with different data providers each. The control also supports pan and zoom, scroll, unlimited number of legends, grid and a dashboard panel. Linear and oval gauges complete the tool set and guarantee every feature you might need to build the perfect gauge, chart of any type or dashboard in WinForms is right at your fingertips. Learn more at https://mindfusion.eu/winforms-chart.html

Interactive Calendar With Events In JavaScript

In this blog post we will create a Google-like interactive monthly calendar where users will be able to create, edit and delete appointments in real time. We
will use the JavaScript Scheduler. Here is a screenshot of the finished application:

JavaScript Schedule That Mirrors the Google Calendar Features

JavaScript Schedule That Mirrors the Google Calendar Features

And you can run the sample online from this link.

I. Project Setup

We need a reference to the following file to start development:

  • MindFusion.Scheduling.js
  • light.css

The JavaScript file provides the scheduling functionality. The CSS file is responsible for the styling of our calendar. We create a subfolder named “themes” and we place the light.css file there.

We create an HTML file, a blank web page called GoogleSchedule and in the head section we place a reference to the CSS file:

<link href="themes/light.css" rel="stylesheet">

The reference to the JavaScript file goes at the bottom of the page, right before the closing body tag.

<a href="http://MindFusion.Scheduling.js">http://MindFusion.Scheduling.js</a>

We need a element that will represent the calendar, we create one in HTML code and assign it an id:

<div id="calendar" style="height: 100%; width: 100%;"></div>

We want the calendar to take the whole page, that’s why width and height are 100%.

II. Create and Customize the Scheduler

Now we are ready to do the real JavaScript programming of the calendar library. We create an empty JS file called “GoogleSchedule.js” and add a reference to it in the web page, at the bottom:

<a href="http://GoogleSchedule.js">http://GoogleSchedule.js</a>

In this JavaScript file we first create a mapping to the MindFusion.Scheduling namespace:

var p = MindFusion.Scheduling;

Then we create a Calendar instance using the Calendar DOM element from the web page:

// create a new instance of the calendar 
var calendar = new p.Calendar(document.getElementById("calendar"));

We set the calendar view to CalendarView .SingleMonth, which means the calendar shows one month at a time. We also set the theme that we referenced in the CSS file:

calendar.currentView = p.CalendarView.SingleMonth;
calendar.theme = "light";

Another customization we make – we use the itemSettings.titleFormat property to add a prefix before each event subject. The prefix is the start time of this event. here is how you set it:

calendar.itemSettings.titleFormat = "%s[hh:mm tt] %h";

Finally, we render the calendar:

//visualize the calendar
calendar.render();

III. Custom Form

By default, the form that renders when the user clicks on a cell or selection of cells in the calendar allows edit of the dates, but not hours. We will render our custom form, derived from BaseForm to change that. Our form will offer the users a list with hours for the selected dates.

We create a new, empty JavaScript file “TimeForm.js”. There we override the constructor of the BaseForm:

 TimeForm = function (calendar, item, type)
{
	p.BaseForm.call(this, calendar, item);

	this._id = "TimeForm";
	this._type = type;
	this.headerText = "Appointment";
	
}

As you can see from the constructor each BaseForm provides data for the calendar and the item that is created or edited. We will use that information later on. We create a prototype of our form and assign the constructor:

TimeForm.prototype = Object.create(p.BaseForm.prototype);
TimeForm.prototype.constructor = TimeForm;

TimeForm will be a simple one – it just renders a text area and two combo boxes with the possible hours for the start and end of the appointment. The combo boxes require a list with the members to be rendered. We create a list as a global variable:

var hoursList;

Then, in a new method we fill the list with the hours from 12 to 1, divided in intervals of 30 minutes:

// create an array of objects to fill the hours drop-down
TimeForm.prototype.getHourLabels = function ()
{
	hoursList = [];
	hoursList.push({ value: 0, text: "12:00am" });
	hoursList.push({ value: 1, text: "12:30am" });
	
	let index = 1;
	
	for(var i = 1; i < 12; i++)
	{
		hoursList.push({ value: index+1, text: i.toString() + ":00am" });
	    hoursList.push({ value: index+2, text: i.toString() + ":30am" });
		
		index += 2;
	}
	
	//add the first afternnon hours
	hoursList.push({ value: index + 1, text: "12:00pm" });
	hoursList.push({ value: index + 2, text: "12:30pm" });
	
	index += 2;
	
	for(i = 1; i < 12; i++)
	{
		hoursList.push({ value: index+1, text: i.toString() + ":00pm" });
	    hoursList.push({ value: index+2, text: i.toString() + ":30pm" });
		
		index += 2;
	}	
	
	return hoursList;
}

The next step is to override the drawContent function of BaseForm:

TimeForm.prototype.drawContent = function ()
{
	p.BaseForm.prototype.drawContent.call(this);

	var content = this.getContent();
.....
}

First, we create the text area:

var row = this.row();
	row.innerHTML = this.localInfo.subjectCaption;
	content.appendChild(row);
	
	// create a text-area for the item subject
	var textArea = this.createTextArea({ id: "subject", initValue: this.item.subject, events: { keydown: this._areaKeyDown} });
	textArea.element.style.width = "200px";
	this.addControl(textArea);

	row = this.row();
	row.appendChild(textArea.element);
	content.appendChild(row);

Before the text area we place a label with “Subject” on it. The createTextArea method requires several parameters. The first one is the id, then the initial content to be rendered and the events. We want the text area to be 200px wide. The row element places a row of controls in the BaseForm. We use it every time we want to start a new row with elements.

The text area reads its initial content from the value of the subject field in the item object that we receive as reference. After that we create a new row with elements: the drop-down with the hours for the start time:

       // create a drop-down list for start hours
	row = this.row();
	row.innerHTML = "Start Time";
	content.appendChild(row);

	var control = this.createDropDownList({ id: "start_time", items: this.getHourLabels(), initValue: this.getStartTimeIndex(), addEmptyValue: false });
	control.element.style.width = "200px";
	this.addControl(control);

	row = this.row();
	row.appendChild(control.element);
	content.appendChild(row);

The code is almost identical to the code for the text area, but here we call the getHourLabels method that returns the array with time values. There is one other new method: getStartTimeIndex(). It’s task is to check the start time of the item and to set the initial value of the drop-down control to that time.

Here is the method:

// get the index of the current item's index to set the value of the startTime drop-down:
TimeForm.prototype.getStartTimeIndex = function ()
{
	if (this.item != null && this.item.startTime != null)
	{
		
		let index  = this.item.startTime.__getHours() * 2;
		if(this.item.startTime.__getMinutes() > 0)
			index++;
		return index;		
		
	}
	return -1;
}

The method checks the hour value of the start time and multiplies it by two because for each hour we show two values in the drop-down: 9:00 and 9:30. If the user has selected half an hour we increment the index with 1.
We use almost the same code to create the endTime drop-down control, so we won’t discuss it here. You can check its code from the download with the source code files for this sample.

Our form needs two buttons – Save and Cancel. We create them in the drawButtons method:

// override BaseForm's drawButtons method to create form buttons
TimeForm.prototype.drawButtons = function ()
{
	var thisObj = this;

	var btnSave = this.createButton({
		id: "btnSave",
		text: this.localInfo.saveButtonCaption,
		events: { "click": function click(e)
		{
			return thisObj.onSaveButtonClick(e);
		}
		}
	});

	var btnCancel = this.createButton({
		id: "btnCancel",
		text: this.localInfo.cancelButtonCaption,
		events: { click: function click(e)
		{
			return thisObj.onCancelButtonClick(e);
		}
		}
	});

	var buttons = this.row();
	buttons.classList.add("mfp-buttons-row");
	buttons.appendChild(btnSave.element);
	buttons.appendChild(btnCancel.element);

	return buttons;
};

The BaseForm.createButton() method is similar to the methods that create text area and drop-down lists. We specify here that we will handle the click event for the two buttons. We place the buttons in a new row. Note that you don’t have to call the createButtons function anywhere – it is called automatically by BaseForm.

What happens when the user presses “Save”? Well, we’ll have to read the data from the hour drop-down controls and adjust the start and end time of the newly created Item:

TimeForm.prototype.onSaveButtonClick = function (e)
{
	// update the item with the form data
	 // update the item with the form data
   var startIndex = +this.getControlValue("start_time");
   var startTime = this.item.startTime.date.clone().addHours(startIndex * 0.5);

   var endIndex = +this.getControlValue("end_time");
   var endTime = this.item.endTime.date.clone().addHours(endIndex * 0.5);

   // if end time is specified, decrease it by one day
   if (endIndex != 0 && this.item.endTime.hour == 0)
    endTime.addDays(-1);

   // check for inconsistent start/end time
   if (startTime.valueOf() > endTime.valueOf())
         endTime = startTime.clone().addHours(1);

   // apply changes 
   this.item.subject = this.getControlValue("subject"); 
   this.item.startTime = startTime;
   this.item.endTime = endTime;

   // if a new item is created, add it to the schedule.items collection
   if (this.type === "new")
     this.calendar.schedule.items.add(this.item);

   // close the form
   this.closeForm();

   // repaint the calendar
   this.calendar.repaint(true);
};

First, we get the value of the startTime drop-down list and we calculate the amount of time to add to the startTime of an Item. A new Item always has a startTime at midnight. Then, we check the number of days the user has selected and calculate how many hours the event actually takes. We assign end time to a copy of the start time and add the calculated event duration to the value. Finally, if the event is new – we add it to the collection of item sin the schedule, if it’s old – we correct its data. Then we close the form and repaint the calendar.

IV. Using the Custom TimeForm

In order to use our custom form we have to add a reference to it in the HTML page, as we did with the other two files:

<script src="TimeForm.js" type="text/javascript"></script>

Then we edit the GoogleSchedule.js file First, we need to disable the built-in forms with the useForms property.

// disable this built-in forms for item creation and modification
calendar.useForms = false;

Then we have to handle the onSelectionEnd and onItemDoubleClick events to render our form. First, we wire up the events:

// handle the itemDoubleClick event to show the custom form for item editing
calendar.itemDoubleClick.addEventListener(handleItemDoubleClick);

// handle the selectionEnd event to show the custom form for item creation
calendar.selectionEnd.addEventListener(handleSelectionEnd);

Then we render the forms, below is the code that shows the TimeForm when a new item is created:

function handleSelectionEnd(sender, args)
{
	// create a new item with the start and end time of the selection
	var item = new p.Item();
	item.startTime = args.startTime;
	item.endTime = args.endTime;
	
	// create and show the custom form
	var form = new TimeForm(sender, item, "new");
	form.showForm();
}

We copy the start and end time of the selection from the event arguments. Then we use them in the constructor of the BaseForm.

And that’s the end of this tutorial. Here is a link to download the complete source code of the sample:

Download the Google Calendar in JavaScript Sample

About MindFusion JavaScript Scheduler: MindFusion Js Scheduler is the complete solution for all applications that need to render interactive timetables, event schedules or appointment calendars. Fully responsive, highly customizable and easy to integrate, you can quickly program the JavaScript scheduling library according to your needs. Find out more at https://mindfusion.eu/javascript-scheduler.html

Logic Model Software Demo

The logic model is a tool that helps managers evaluate the effectiveness of a program. The tool allows the user to list the input, output and outcomes of the process.

Logic Model Software Demo

Logic Model Software Demo

In our sample we have used the WinForms Diagram Control to create a sample software that lets users:

  • drag and drop tables that represent popular items in each of the three sections of the logic mode: input, output and outcomes;
  • edit the tables: add and delete rows, edit the text on rows;
  • connect table rows to illustrate the process flow.

I. Project Setup

We create a new project in Visual Studio and name it “LogicModel”. We add references to the following diagramming libraries:

MindFusion Libraries Used by the Logic Model Software

MindFusion Libraries Used by the Logic Model Software

After that we drag and drop the NodeListView control from the Toolbox and set its IconSize property to Size(50,50). This property tells the control how big the items in the NodeListView should be rendered.

nodeListView1.IconSize = new System.Drawing.Size(50, 50)

Then we drag and drop a DiagramView object that creates automatically a Diagram instance that represents the diagram. Here we need to set the AllowDrop and AllowInplaceEdit properties to “true”. This means the diagram can create new nodes from the items in the NodeListView that are dropped onto it. Then it allows the user to edit the nodes e.g. modify the text in the table cells:

this.diagramView1.AllowDrop = true;
this.diagramView1.AllowInplaceEdit = true;

Last but not least we set the Resize mode of the DiagramView to Fill, which means it will occupy all available space when the user changes the size of the application window.

II. The NodeListView

It holds TableNode instances that represent items in the logic model. Let’s look at a simple table. The first table called “Investment”. Here are the first three lines of code for it:

//the table with resources
TableNode tbResources = new TableNode();
tbResources.RedimTable(2, 4);
tbResources.Caption = "Investment";

The RedimTable method changes the number of rows and columns of the TableNode to be the ones specified as arguments. Each of the tables in the logic model has two columns – one for a bullet and one for the label. The count of rows varies.

Then we edit the text that is rendered by this TableNode:

tbResources[1, 0].Text = "People";
tbResources[1, 1].Text = "Money";
tbResources[1, 2].Text = "Technology";
tbResources[1, 3].Text = "Space";

Now is time for some styling. We set the Pen for the table, the pen for the caption and the CaptionBackBrush:

tbResources.Pen = new MindFusion.Drawing.Pen(Color.FromArgb(192, 192, 192));

tbResources.CaptionBrush = new MindFusion.Drawing.SolidBrush(Color.White);
tbResources.CaptionBackBrush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(247, 150, 70));

Then we set the background of the rest of the TableNode:

tbResources.Brush = new LinearGradientBrush(Color.FromArgb(252, 213, 181), Color.FromArgb(248, 234, 223));

Each diagram item has a Tag property. This useful property holds any information you find useful. It is of type Object and you can use it to store data used by your node. In our application we use the Tag property of a TableNode to store the URL to the bullet rendered before each of its labels:

//keep the bullet as a tag
tbResources.Tag = Image.FromFile("../../Resources/orange.png");
//set an orange bullet before each label

for (int i = 0; i < tbResources.Rows.Count; i++)
     {
        tbResources[0, i].Image = Image.FromFile("../../Resources/orange.png");
        //save the row index as a tag for cells with text
        tbResources[1, i].Tag = i;
     }

Then we use the Tag property of the TableNode.Cell objects to store their row index. We will use it later when we handle events.

Finally, let’s not forget to add the new TableNode to the NodeListView:

nodeListView1.AddNode(tbResources);

The other tables are created in a similar way.

III. The Containers

The three rectangles where users drop tables are ContainerNode-s. These are special kinds of DiagramNode -s that can hold other nodes. Once placed into them, the containing nodes move with the container. Containers can resize automatically to fit all items but in our case we will forbid this.

Here is the code that creates the third container – “Outcomes”:

//the last container
ContainerNode cOutcomes = diagram1.Factory.CreateContainerNode(0, 0, 20, 20);
cOutcomes.Tag = 2;
cOutcomes.Caption = "Outcomes";

Note that we use again the Tag property this time to keep the index of the container – first, second or third e.g. 0, 1 or 2. Then we add some styling using the Pen, CaptionBrush, CaptionBackBrush and Brush properties to define the background and border of the container and its caption:

cOutcomes.Pen = new MindFusion.Drawing.Pen(Color.FromArgb(80, 80, 80));
cOutcomes.CaptionBrush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(80, 80, 80));
cOutcomes.CaptionBackBrush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(168, 192, 120));
cOutcomes.Brush = new LinearGradientBrush(Color.FromArgb(209, 224, 180), Color.FromArgb(235, 238, 229));

Then we set some properties that define how the ContainerNode responds to new items being added or removed:

cOutcomes.AllowAddChildren = true;
//do not allow the container to change size or be folded
cOutcomes.AutoGrow = false;
cOutcomes.AutoShrink = false;
cOutcomes.Foldable = false;

We let the container accept new children and do not allow the user to fold, which means to collapse it.

The containers are sized relatively to the client area of the DiagramView:

//resize the containers according to the current size of the diagramView
private void resizeContainers()
  {
    //convert the size of the rectangle from client measure units to diagram units
    RectangleF viewRect = diagramView1.ClientToDoc(diagramView1.ClientRectangle);
   ...
}

First we convert the size of the DiagramView to diagram units calling the ClientToDoc method. Then we need to find the ContainerNode -s of the diagram and arrange them next to each other. When we do this we use the Tag property of each container that tells us which is the order of the container and where we should pace it:

//identify the containers
foreach (DiagramNode node in diagram1.Nodes)
     {
       ContainerNode c = node as ContainerNode;

       if (c != null)
       {
          //get the index that tells us if this is the first, second or third container
          int index = (int)c.Tag;
          //relocate the container rectangle based on its index
          c.Bounds = new RectangleF(viewRect.Left + viewRect.Width * (0.02F + index * 0.34F),
          viewRect.Top + viewRect.Height * 0.02F, viewRect.Width * 0.27F, viewRect.Height * 0.96F);
       }
    }

We call this method each time the DiagramView is resized by handling the ClientSizeChanged event:

//raised when the size of the ClientRectangle has changed.
private void diagramView1_ClientSizeChanged(object sender, EventArgs e)
  {
    //adjust the size of the containeres
     resizeContainers();
     ...
  }

IV. Diagram Events

We handle the NodeCreated diagram event each time the user drops a new node from the NodeListView onto any of the ContainerNode-s:

this.diagram1.NodeCreated += new System.EventHandler(this.diagram1_NodeCreated);

The method that handles the event should do three important things: 1) resize the new TableNode so all text fits into it; 2)assign to each cell its correct Tag (e.g. row index) and 3) find the ContainerNode onto which the TableNode was placed and add it to it. Here is the first part of the method:

//raised when the user has dropped a new TableNode
private void diagram1_NodeCreated(object sender, NodeEventArgs e)
  {            
     TableNode tNode = e.Node as TableNode;

    if (tNode != null)
    {
        //adjust the node size
        resizeNode(tNode);
        //arrange the tags for the table cells
        arrangeTags(tNode);
                   
     }

The resizeNode and arrangeTags methods adjust the size of the TableNode and assign to each cell in the second column of the node its row index as a Tag. We won’t list the methods here, you can check them in the source code available for download.

We find the ContainerNode, if any onto which the TableNode was placed by checking if its top left corner is inside the container:

//find out the container onto which the node was dropped, if any
foreach (DiagramNode diagramNode in diagram1.Nodes)
  {
    if (diagramNode.ContainsPoint(e.Node.Bounds.Location))
    {
       ContainerNode container = diagramNode as ContainerNode;
       if (container != null)
       {                       
         //add the new node to its container
         container.Add(tNode);
                       
         break;
       }
 }
}

If it is within the container we add the node.

V. Context Menu

The context menu is rendered at right mouse click. We handle the CellClicked event of a diagram to show it:

//tracks when the user clicks on a table cell
diagram1.CellClicked += new EventHandler(diagram1_CellClicked);

We also declare a global TableNode.Cell clickedCell variable that keeps track of the clicked cell. We will use the data later:

//keeps the cell the user has clicked on
TableNode.Cell clickedCell = null;

In the diagram1_CellClicked event we check if the right mouse button was clicked and then show a ContextMenuStrip object:

//handles the cellClicked event
void diagram1_CellClicked(object sender, CellEventArgs e)
  {
    //if the user has clicked with the right mouse button
    if(e.MouseButton == MouseButton.Right)
      {
        //we should keep track of the clicked cell
        clickedCell = e.Cell;
        //and show the context menu
        cMenu.Show(Cursor.Position);
              
       }
  }

We handle the ItemClicked event of the ContextMenuStrip:

if (clickedCell != null)
   {
      TableNode tNode = clickedCell.Table;

      //if the user has selected to add a row
      if (e.ClickedItem.Text.Equals("Add row"))
         {
            //add a row
            tNode.AddRow();
            //assign the image URL kept as a tag to the first cell in the new row
            tNode[0, tNode.Rows.Count - 1].Image =
                 tNode.Tag as Image;
            //type in some dummy text in the text cell
            tNode[1, tNode.Rows.Count - 1].Text = "[edit text]";               
        }
..............
}

In the first part of the method we handle the case when the user has chosen to add a new row. The new row is inserted at the end of the table with the AddRow method. We use the Tag property of the TableNode which points to the location of the bullet for this table and we render it to the first cell of the new row.
If the user wants to delete a row we show first a warning message. Here we render the name of the detected row to be deleted. If the user agrees we get the index of the row using its Tag and we remove it from the TableNode:

 else if (e.ClickedItem.Text.Equals("Delete row"))
      {
          cMenu.Close();

          //display a warning, which shows which row is about to be deleted
          string message = "Do you want to delete row " + clickedCell.Text + "?";
          string caption = "Confirm Delete";
          MessageBoxButtons buttons = MessageBoxButtons.YesNo;
          DialogResult result;

          // Displays the MessageBox.
          result = MessageBox.Show(message, caption, buttons);
          //if the user has decided to delete the row
          if (result == System.Windows.Forms.DialogResult.Yes)
            {
                                        
             //get the index of the row that is to be deleted
             int rowIndex = (int)clickedCell.Tag;                        
             tNode.DeleteRow(rowIndex);                        
                        
           }   
...
}

Both actions of delete and insert of a new row require the indices of the table rows to be rearranged and the size of the table to be adjusted. We call:

//adjust the node size
resizeNode(tNode);
//arrange the table tags
arrangeTags(tNode);

VI. Links

Users can draw links between rows of the tables. To achieve this we first change the default Behavior of the DiagramView :

this.diagramView1.Behavior = MindFusion.Diagramming.Behavior.LinkTables;

Then we add some styling for the links:

//styling the links
diagram1.LinkShape = LinkShape.Cascading;
diagram1.LinkCascadeOrientation = MindFusion.Diagramming.Orientation.Horizontal;
diagram1.LinkHeadShape = ArrowHeads.Triangle;
diagram1.LinkHeadShapeSize = 4;

Here we define the shape of the links as “Cascading” and we change the default LinkHeadShape and LinkHeadShapeSize properties. Further styling of the links is done with a Theme and a DiagramLinkStyle:

//create a theme to apply additional link styling
Theme theme = new Theme();
DiagramLinkStyle style = new DiagramLinkStyle();
style.Brush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(192, 192, 192));
style.Stroke = new MindFusion.Drawing.SolidBrush(Color.FromArgb(80, 80, 80));
theme.RegisterStyle(typeof(DiagramLink), style);
diagram1.Theme = theme;

There we specify the Brush for the links and the Stroke. When new links are created we want them to have 3 segments because this looks good. So, we handle the LinkCreated event to specify this:

this.diagram1.LinkCreated += new System.EventHandler(this.diagram1_LinkCreated);

..................

//raised when the user draws a link between two tableNode-s.
private void diagram1_LinkCreated(object sender, LinkEventArgs e)
  {
    //the link should have 3 segments
    e.Link.SegmentCount = 3;
  }    

With this our Logic Mode demo application is ready. The complete code for the application with all necessary libraries of the diagramming component is available for free direct download download from here:

Download the Logic Model Demo Application Source Code

About MindFusion.Diagramming for WinForms: A programming component that provides any WinForms application with a full set of features for creating and customizing all types of diagrams, flowcharts, schemes, hierarchies, trees, graphs etc. The control provides numerous ways to save and load a diagram, six auxiliary controls and more than 15 automatic graph layout algorithms. Diagram elements include scrollable tables, container nodes, multi-segment arrows, custom diagram item types and many more. Further details here.

Diagramming for WinForms is a royalty-free component, clients get 12 month upgrade subscription when buying a license. The source code is also available for purchase. Visit the buy page for a list with the current license prices.