Wednesday, January 27, 2016

Syntax error, '>' expected in Sitecore CMS

When I was a developer in a large corporation before, I was assigned to a Sitecore CMS project. While working on the CMS's services in getting the contents, I encountered an error as mentioned in a title post.

After doing some research, I found out that the CMS's parser does not recognize special characters of the data returned from it's search query.

So the workaround that I found from an article was to surround the data returned with hash tags.
In the sample codes below, I just added a snippet to insert hashtags to data returned from the parser.

Sample Data Returned: Tel-Aviv
Formatted data: #Tel-Aviv#

Original method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public static IEnumerable<IUniversity> GetSchoolsByState(Guid stateProvinceId, Language languageVersion)
{
    if (stateProvinceId.Equals(Guid.Empty))
        return null;
 
    var stateProvinceReferenceItem = Context.Database.GetItem(ID.Parse(stateProvinceId));
    if (stateProvinceReferenceItem == null)
        return null;
        
    return GetSchoolsByStateProvince(stateProvinceReferenceItem.Paths.Path, languageVersion);
}

Modified Method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public static IEnumerable<IUniversity> GetSchoolsByState(Guid stateProvinceId, Language languageVersion)
{
    if (stateProvinceId.Equals(Guid.Empty))
        return null;
 
    var stateProvinceReferenceItem = Context.Database.GetItem(ID.Parse(stateProvinceId));
    if (stateProvinceReferenceItem == null)
        return null;
                
    //added code fix
    var path = stateProvinceReferenceItem.Paths.Path;
    if (path.Substring(path.LastIndexOf("/", StringComparison.Ordinal)).Split(new string[] { "-" }, 
          StringSplitOptions.RemoveEmptyEntries).Length > 1)
    {
        path = path.Insert(path.LastIndexOf("/", StringComparison.Ordinal) + 1, "#");
        path = path.Insert(path.Length, "#");
        return GetSchoolsByStateProvince(path, languageVersion);
    }         
    
    return GetSchoolsByStateProvince(stateProvinceReferenceItem.Paths.Path, languageVersion);
}

Saturday, January 23, 2016

$(...).valid is not a function in ASP.NET MVC 5

I created an ASP.NET MVC 5 simple application with entry forms integrating bootstrap and jQuery validation. Upon testing, the valid() built-in function is not recognized by the browser as stated in the title of this post. After series of investigation, I found out that by default, ASP.NET MVC does not render the jQuery validation scripts by default in _Layout.cshtml. Only jQuery core scripts.

The fix is to render jqueryval validation scripts in _Layout.cshtml. The scripts have already been bundled in the BundleConfig file.
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval") @*code fix*@
@Scripts.Render("~/bundles/bootstrap")

On page load, the scripts are indeed rendered to the browser using chrome dev tools.

Monday, January 18, 2016

WPF Add/Delete Rows using Observable Collection

Here's a simple way of adding/deleting WPF Datagrid rows using observable collection.
XAML Code
1
2
3
4
5
6
7
8
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" Margin="12,12,12,41" Name="dataGrid1" CanUserResizeRows="False" CommandManager.PreviewExecuted="UserDataGrid_PreviewDeleteCommandHandler" RowEditEnding="dataGrid1_RowEditEnding" RowHeaderWidth="20">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="User name" Width="230">
        </DataGridTextColumn>
        <DataGridTextColumn Binding="{Binding FirstName,  Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="First Name" Width="245">
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public partial class MainWindow : Window
    {
        private ObservableCollection<User> users = new ObservableCollection<User>();
        private StringBuilder builder;
 
        public ObservableCollection<User> AllUsers
        {
            get { return users; }
            set { users = value; }
        }
 
        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        { }
 
        public MainWindow()
        {
            InitializeComponent();
            users.Add(new User() { UserName = "Walter", FirstName = "Walter North" });
            dataGrid1.ItemsSource = AllUsers;
            AllUsers.CollectionChanged += AllUsers_CollectionChanged;
        }
 
        private void dataGrid1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            // Get Items From Source
            builder = new StringBuilder();
            if (e.EditAction == DataGridEditAction.Commit)
            {
                foreach (object item in AllUsers)
                {
                    if (item.GetType().Equals(typeof(User)))
                        builder.AppendLine(String.Format("{0},{1}", ((User)item).UserName, ((User)item).FirstName));
                }
 
                MessageBox.Show(String.Format("{0}",builder.ToString()), "Items in collection!");
            }
        }
 
        private void UserDataGrid_PreviewDeleteCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command == DataGrid.DeleteCommand)
            {
                if (!(MessageBox.Show(String.Format("Delete Current Item {0} ?", ((User)((DataGrid)sender).CurrentItem).UserName), 
                    "Please confirm.", MessageBoxButton.YesNo) == MessageBoxResult.Yes))
                {
                    e.Handled = true; // Cancel Delete.
                }
            }
        }
 
        private void AllUsers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            // If action is remove, show current collection
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                builder = new StringBuilder();
                foreach (var item in AllUsers)
                {
                    builder.AppendLine(String.Format("{0},{1}", ((User)item).UserName, ((User)item).FirstName));
                }
 
                MessageBox.Show(String.Format("{0}", builder.ToString()), "Items in collection!");               
            }
        }
    }

Screenshot
:-)

Saturday, January 16, 2016

ASP.NET MVC Sales Dashboard Demo Application

As I was doing some research on chart controls to be integrated in ASP.NET MVC, I found a working from Shield UI which is MVC 4 regarding Sales Dashboard. As I was running the application to the browser, only the left container shows the chart.
The right and bottom part does not show anything. It seems the remaining chart samples will be manually shown to the browser by entering the correct URL. To solve this, I added a ViewModel class, modified the HTML markup in the Index view and modified the codes in Home Controller. See updates below:

SalesDashboardViewModel.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace SalesDashboardMVC.Models
{
    public class SalesDashboardViewModel
    {
        public IEnumerable<QuarterlySales> Quarterly_Sales { get; set; }
        public IEnumerable<SalesByProduct> Sales_By_Products { get; set; }
        public IEnumerable<PerformanceData> Performance_Data { get; set; }        
    }
}

Home Controller
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class HomeController : Controller
    {
        private SalesDashboardViewModel modelSalesDashboard;
 
        public ActionResult Index()
        {
            modelSalesDashboard = new SalesDashboardViewModel();
            modelSalesDashboard.Quarterly_Sales = QuarterlySales.GetData();
            modelSalesDashboard.Performance_Data = PerformanceData.GetDataByQuarter("Q1");
            modelSalesDashboard.Sales_By_Products = SalesByProduct.GetDataByProductAndQuarter("Men", "Q1");
 
            return View(modelSalesDashboard);
        }}

Index View
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@model SalesDashboardMVC.Models.SalesDashboardViewModel
 
<div class="dashboard">
    <div class="header">        
        Sales DashBoard using <span class="highlight">Shield UI ASP.NET Chart</span>        
    </div>
    <div class="topleft">
        @(Html.ShieldChart(Model.Quarterly_Sales)
            .Name("quarterlySales")
            .HtmlAttribute("class", "chart")
            .PrimaryHeader(header => header.Text("Quarterly Sales"))
            .Export(false)
            .Tooltip(tooltip => tooltip.CustomPointText("Sales Volume: <b>{point.y}</b>"))
            .AxisX(axisX => axisX.CategoricalValues(model => model.Quarter))
            .AxisY(axisY => axisY.Title(title => title.Text("Quarterly Overview")))
            .DataSeries(dataSeries => dataSeries
                .Bar()
                .Data(model => model.Sales)
                .EnablePointSelection(true))
            .ChartLegend(chartLegend => chartLegend
                .Align(Shield.Mvc.UI.Chart.Align.Center))
            .Events(events => events.PointSelect("app.quarterSelected")))
    </div>
    <div class="topright">
         @(Html.ShieldChart(Model.Performance_Data)
            .Name("productsByQuarter")
            .HtmlAttribute("class", "chart")
            .Export(false)
            .PrimaryHeader(header => header.Text("Select a Quarter to show products sales"))
            .AxisY(axisY => axisY.Title(title => title.Text("Break-Down for selected quarter")))
            .DataSeries(dataSeries => dataSeries
                .Donut()
                .Name("Q Data")
                .Data(model => new
                {
                    collectionAlias = model.Product,
                    x = model.Product, 
                    y = model.Data,
                })
                .EnablePointSelection(true)
                .AddToLegend(true))
            .ChartLegend(chartLegend => chartLegend.Align(Shield.Mvc.UI.Chart.Align.Center))
            .Events(events => events.PointSelect("app.productSelected")))      
      
    </div>
    <div class="bottom">  
         @(Html.ShieldChart(Model.Sales_By_Products)
            .Name("salesDetails")
            .HtmlAttribute("class", "chart")
            .PrimaryHeader(header => header.Text("Select a product to show sales details"))
            .Export(false)
            .DataSeries(dataSeries => dataSeries
                .Line()
                .Data(model => model.QuarterSales)
                .AddToLegend(false)))
    </div>
</div>

Screenshot:
Original Sample Code and Article Here: ASP.NET MVC Sales Dashboard Application

Greg Esguerra

Friday, January 15, 2016

Simple ASP.NET MVC Image Helper in C#

Here's a simple Image Helper for showing known image types. I've tested this for old format such as bitmaps and images with OLE headers.
This helper sets the image width and height with fixed values. You may change it dynamically or update this helper to accept parameters for width and height.
C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/// <summary>
/// Helper for showing images
/// </summary>
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, byte[] photo, string id) {
 string imageSrc = null;
 if (photo != null) {
  using(MemoryStream ms = new MemoryStream()) {
   string imageBase64 = string.Empty;
   Image xImage = (Bitmap)((new ImageConverter()).ConvertFrom(photo));
   if (ImageFormat.Bmp.Equals(xImage.RawFormat)) {
    // strip out 78 byte OLE header (don't need to do this for normal images)
    ms.Write(photo, 78, photo.Length - 78);
   } else {
    ms.Write(photo, 0, photo.Length);
   }
   imageBase64 = Convert.ToBase64String(ms.ToArray());
   imageSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
  }
 }

 return new MvcHtmlString("<img id='" + id + "' src='" + imageSrc + "' alt=\"Image\" style=\"height:150px;width:150px;\" />");
}

Call the helper inside the view:
@Html.ImageLink(item.Photo, "mainPhoto")

Sample Screenshot:

Cheers! :-)