Form Validation and Submit using Semantic UI and JQuery

Bootstrap, despite all the effort to make it easily understandable, always relied heavily on its short hand notations for css classes. This seemed okay, until Semantic UI entered the race with its near perfect usage of natural language. The fact that it is well integrated with jQuery makes it a good choice for web developers.

One of the most common tasks in any web development has to do with form. The following code illustrates how to validate the form and submit it using the Semantic UI APIs.

 

                <form class="ui large form" method="POST" role="form" id="ValidateUser">
                    <section class="ui stacked segment">
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="user icon"></i>
                                @Html.TextBoxFor(a => a.UserName, new { placeholder = "UserName",id="username" })
                                @Html.ValidationMessageFor(a => a.UserName)
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                @Html.PasswordFor(a => a.Password, new { placeholder = "Password",id="password" })
                                @Html.ValidationMessageFor(a => a.Password)
                            </div>
                        </div>

                        <input id="submitbutton" class="ui submit fluid large green button" type="submit" value="Login"/> 
                        <!-- <div class="ui blue submit button">Submit</div> -->
                        <div class="ui hidden negative message" id="formresult"></div>
                        <div class="ui error message" id="formvalidation"></div>
                    </section>
                </form>
$(document).ready(function () {

            var urllink = '@Url.Action("Login", "Validation")';


            $('#ValidateUser').form(
                                     {
                                         on: 'blur',
                                         fields: {
                                             username: {
                                                 identifier: 'username',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Username cannot be empty'
                                                 }]
                                             },
                                             password: {
                                                 identifier: 'password',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Password cannot be emtpy'
                                                 }]
                                             }
                                         },
                                         onSuccess: function (event) {
                                             $('#formresult').hide();
                                             $('#formresult').text('');
                                             event.preventDefault();
                                             return false;
                                         }

                                     }
                                   )
                                 .api({
                                     url: urllink,
                                     method:'POST',
                                     serializeForm: true,
                                     data: new FormData(this),
                                     onSuccess: function (result) {
                                        $('#formresult').show();
                                        if (result.Success) {
                                            window.location = "/Dashboard/Dashboard";
                                        }
                                        else {

                                            $('#formresult').append(result.Msg);
                                        }
                                        return false;
                                    }
                    });


        });

Adapter Pattern

There is already a large amount of literature on the Internet which discusses Adapter Pattern. However, the purpose of article is to showcase the implementations of the Adapter Pattern, rather than discussing the application of the pattern. In this post, adapter class is implemented using

1. Inheritance
2. Dependency Injection
3. Generics

Consider your old legacy code, which has a single method, GetEmployeeList.

public interface IHRSoftware
    {
        List<string> GetEmployeeNameList();
    }
    public class HRSoftware : IHRSoftware
    {
        public List<string> GetEmployeeNameList()
        {
            return new List<string>() { "Jia", "Anu", "Sreena" };
        }
    }

Client, consumes the class as follows.

            IHRSoftware hrsoft = new HRSoftware();
            foreach (var item in hrsoft.GetEmployeeNameList())
            {
                Console.WriteLine(item);
            }

Now, it so happened that the Client has gone through an overhaul and is now looking to use a new contract (interface), namely INewAgeSoftware, which exposes a property EmployeeList, replacing the GetEmployeeNameList Method. The interface declaration is as shown below.

    public interface INewAgeHRSoftware
    {
        List<string> EmployeeList { get;  }
    }

You however, would like to use your old existing code, without actually going ahead and making the changes in your legacy code. This is where adapter pattern come in handy. Following are different implementations of Adapter Class

1. Using Inheritance.

    public class AdapterWithInheritence : HRSoftware, INewAgeHRSoftware
    {
       
        public List<string> EmployeeList
        {
            get
            {
                return this.GetEmployeeNameList();
            }
        }
    }

2. Using Dependency Injection

    public class AdapterWithDI : INewAgeHRSoftware
    {
        private IHRSoftware _HRInstance;
        public AdapterWithDI(IHRSoftware HRSoftInstance)
        {
            _HRInstance = HRSoftInstance;
        }
        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

3. And Finally, using Generics

    public class AdapterWithGenerics<T> : INewAgeHRSoftware where T : HRSoftware
    {
        private T _HRInstance;
        public AdapterWithGenerics(T Instance)
        {
            _HRInstance = Instance;
        }
      
        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

Your new Client class would now look as follows

 Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Inheritence");
            INewAgeHRSoftware newhrsoftInheritence = new AdapterWithInheritence();
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via DI");
            INewAgeHRSoftware newhrsoftDI = new AdapterWithDI(new HRSoftware());
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }
           
           
            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Generics");
            INewAgeHRSoftware newhrsoftGenerics= new AdapterWithGenerics<HRSoftware>(new HRSoftware());
            foreach (var item in newhrsoftGenerics.EmployeeList)
            {
                Console.WriteLine(item);
            }

360 Degree Evaluation

360 Degree Feedback/Review System is a much abused term in many companies these days. While many Organizations and Managers effectively use the ‘jargon’ on a day to day basis, it makes me wonder how many actually perform a complete 360 Degree Review System, particularly in Performance Appraisals.

Ideally, an effective 360 Degree Review System should include 6 major parties

  1. Senior Management
  2. Immediate Supervisor
  3. Peers
  4. Subordinates.
  5. Clients
  6. Self.

Together, this 6 parties provide a complete 360 Degree view of an employees performance. It is quite disheartening to see some of the companies that boosts of a 360 Degree Performance Review System, often, conveniently forgets some of the major links in the chain, including Peers and Subordinates, and while some might even forget taking Immediate Supervisors feedbacks. What it leads to is some of the better traits of employees gets unnoticed.

Instead, if the companies were to focus on all the 6 parties, there is whole lot they could achieve. There are certain traits or skills which is more visible to certain groups more than others and that’s what makes the 360 Degree Evaluation such an effective practice if done well.

For example, Peers are in better position than anyone else to access a coworker’s skills such as team work and communication. They also probably know more about the person’s knowledge due to day to day interaction at work. In fact, studies reveal that peers are more often than not excellent predictors of future performances.

On other hand, the immediate supervisor would be an effective observer for accessing a wide range of skills including Job Knowledge, Approach to work and Quality of work. This might not be as effectively observable for members of Senior Management, whose vision would be more on metrics such as On Time Delivery Index and Quality Metrics.

Similarly, a subordinate would be in the best position to review a supervisor’s leadership and mentoring skills. Most often than not, it is the supervisor’s management skills (or lack of it) which makes the team member either an active participator or pushes him to resign.

Studies also reveal that there is a direct relation between on for how long the reviewers know the person and the rating they give. It has been observed that if the reviewer knows the employee for 1-3 years, the probability of the rating is being more accurate is high. Whereas, the chances of favoritism or personal affection influencing the review increasing as the years go by. On other hand, a person whom the reviewer knows for less than an year would not be in a position to understand the skills correctly. In short, the reviewer should have known the employee long enough to go past first impression and not long enough to generalize favorably.

One of the points held against 360 Degree Evaluation is how the employee could manipulate the feedbacks and conflicting opinions creating doubts on the accuracy. However, if practiced well, a confidential 360 Degree Evaluation program with weighted rating according to role played by the reviewer in the cycle would work much better than any other system. The key to success lies to in the companies approaching the method as a tool for positive feedback, rather than an instrument to criticize the employee.

Appending Strings and Parameters in Firebird.

One of the issues I recently faced while working with Firebird was how to use a string within a ‘Execute Statement’. For example,

 


execute statement 'ALTER TABLE TESTTABLE ADD COLNAME VARCHAR(20) DEFAULT 'HELLO'';

This throws an error. though the answer looked farely simple when done. You need to two Single Quotes.


execute statement 'ALTER TABLE TESTTABLE ADD COLNAME VARCHAR(20) DEFAULT ''HELLO''';

There might be another situation, when you need to append string based on a variable. Here a way out to do the same, using Pipe Character.


EXECUTE BLOCK AS
DECLARE PARAM VARCHAR(20);
BEGIN
PARAM = 'DYNAMICCOL';
if (NOT exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'TESTTABLE' and rf.RDB$FIELD_NAME = 'DYNAMICCOL'))
then
BEGIN
execute statement 'ALTER TABLE TESTTABLE ADD '||PARAM||' SMALLINT;';
END
END ^
SET TERM ; ^

Xamarin SearchBar in Android 7

Searchbar is one of the most sought after controls in Xamarin Forms. One of the recent issues it ran into was when it was tested with Android 7. The Control just disappeared when ran in Android 7, while the same worked well in earlier version.
The solution or rather the work around for it is simple. All you need to is explicitly the height for the control. And you are all set.

Collection of Custom Configuration

Adding application configuration in app.config, especially under the appSetting key is something which every developer is used to.

 <appSettings>
<add key="Version" value="1.0" />
<add key="AutoSave" value="True" />
<add key="LoadOnWindowsStartUp" value="True" />
</appSettings>

What if we need to add our own customer collection. For example,

 <PluginSettings>
<Plugins>
<Plugin ID="906260f8-57ab-417a-8d83-015c73f4a5c8" IsEnabled="true"></Plugin>
<Plugin ID="906260f8-57ab-417a-8d83-015c73f4a5c9" IsEnabled="true"></Plugin>
</Plugins>
</PluginSettings>

That’s when we need to write up code to define these customized segments. We will begin with the basic element first, which in this case is


<Plugin ID="906260f8-57ab-417a-8d83-015c73f4a5c8" IsEnabled="true"></Plugin>

As seen, the basic element has two properties, a GUID named ID and a boolean value called IsEnabled. Let’s go ahead and define them. Our custom class needs to inherit from ConfigurationElement Class.


public class PluginConfigurationElement:ConfigurationElement
 {
 private const string XML_PLUGIN_ID = "ID";
 private const string XML_TITLE = "Title";
 private const string XML_IS_ENABLED = "IsEnabled";

[ConfigurationProperty(XML_PLUGIN_ID,IsRequired =true,IsKey =true)]
 public Guid ID
 {
 get
 {
 return (Guid)this[XML_PLUGIN_ID];
 }
 set
 {
 this[XML_PLUGIN_ID] = value;
 }
 }
 [ConfigurationProperty(XML_IS_ENABLED, IsRequired = true, DefaultValue =false)]
 public bool IsEnabled
 {
 get
 {
 return (bool)this[XML_IS_ENABLED];
 }
 set
 {
 this[XML_IS_ENABLED] = value;
 }
 }
 }

As seen in the example configuration, what we need is a collection of the defined Basic element. We will go ahead and define the collection now. Similar to basic element, we have a base class to inherit from.


public class PluginCollection:ConfigurationElementCollection
 {
internal const string PropertyName = "Plugin";

public override ConfigurationElementCollectionType CollectionType
 {
 get
 {
 return ConfigurationElementCollectionType.BasicMapAlternate;
 }
 }
 protected override string ElementName
 {
 get
 {
 return PropertyName;
 }
 }
 protected override bool IsElementName(string elementName)= elementName.Equals(PropertyName, StringComparison.InvariantCultureIgnoreCase);
 public override bool IsReadOnly() = false;
 protected override ConfigurationElement CreateNewElement()= new PluginConfigurationElement();
 protected override object GetElementKey(ConfigurationElement element) = ((PluginConfigurationElement)(element)).ID;
 protected override void BaseAdd(ConfigurationElement element) = base.BaseAdd((PluginConfigurationElement)element);

public void Add(PluginConfigurationElement element) = this.BaseAdd(element);
 public void Remove(Guid Key) = this.BaseRemove(Key);
 public void Clear() = this.BaseClear();

public PluginConfigurationElement this[int idx]
 {
 get
 {
 return (PluginConfigurationElement)BaseGet(idx);
 }
 }

 }

The final class we need to define is the actual Section itself.


public class PluginSection:ConfigurationSection
 {

 private const string XML_PLUGINS = "Plugins";

 [ConfigurationProperty(XML_PLUGINS)]
 public PluginCollection Plugins
 {
 get { return ((PluginCollection)(base[XML_PLUGINS])); }
 set { base[XML_PLUGINS] = value; }
 }
}

We are almost ready now. The final step required is to reference the class in app.config.


<configSections>
<section name="PluginSettings" type="MyNamespace.PluginSection, MyNamespace " />
</configSections>

Make sure you put this as the first step in app.config, right below the root element . Now you are all set to write your own configuration. Happy Coding.

Binding Navigated Event in WebView Control

WebView Control in Xamarin.Form is a highly useful control for displaying a Web Page within your Mobile Application. You can either specify the URI that needs to displayed or you can provide the entire HTML Source to be displayed by assigning an instance of UrlWebViewSource to the Source Property of the control.

From an MVVM point of view, you can bind Source Property of the control to an instance of UrlWebViewSource.
<WebView Source="{Binding GatewayPageSource,Mode=TwoWay}" WidthRequest="500" HeightRequest="500"></WebView>

For Binding the control to an External URI, you could bind your ViewModel Property as follows.


public HtmlWebViewSource GatewayPageSource
 {
 get { return _GateWaySource; }
 set
 {
 SetProperty(ref _GateWaySource, value);
 }
 }

this.GatewayPageSource.BaseUrl = "urlpath";

For Binding the control to an HTML String, you could bind your ViewModel Property as follows.


this.GatewayPageSource.Html = "HtmlString"

One of the caveats however, is that two of the most important Events of the control, namely, Navigating and Navigated, is not Bindable. There are ways to get around this problem though.
The first method that was suggested to me was to use Behavior. I will probably try implementing this in one of later posts. The second approach, was possibly the easiest – create a custom control overriding the WebView and add the required properties.
public class AdvancedWebView : WebView
{
public static readonly BindableProperty NavigatedCommandProperty =
BindableProperty.Create(nameof(NavigatedCommand), typeof(ICommand), typeof(AdvancedWebView), null);

public AdvancedWebView()
{
Navigated += (s, e) =>
{
if (NavigatedCommand?.CanExecute(e) ?? false)
NavigatedCommand.Execute(e);
};
}

public ICommand NavigatedCommand
{
get { return (ICommand)GetValue(NavigatedCommandProperty); }
set { SetValue(NavigatedCommandProperty, value); }
}
}

The XAML with new Control would be as follows


<controls:AdvancedWebView Source="{Binding GatewayPageSource,Mode=TwoWay}"
NavigatedCommand="{Binding WebViewNavigatedCommand}"
WidthRequest="500" HeightRequest="500"/>

For keeping things simple, I have implemented only Navigated Event in the example, however, we could extend this functionality with Navigating Event as well.