Thursday, July 31, 2014

javascript validation for decimal(10,2)

$(function () {
    $('.decimal10n2').keyup(function () {
        if (!$(this).val().match(/./gi) || !$(this).val().match(/[0-9]+/g)) {
            $(this).val("");
        }
        else if ($(this).val().split('.').length - 1 > 1)
        {
            this.value = $(this).val().slice(0, -1);
        }
        else if ($(this).val().indexOf('.') != -1) {
            if($(this).val().split(".")[0].length > 10)
            {
                if (isNaN(parseFloat(this.value))) return;
                this.value = $(this).val().split(".")[0].slice(0,-1);
            }
            else if ($(this).val().split(".")[1].length > 2) {
                if (isNaN(parseFloat(this.value))) return;
                this.value = parseFloat(this.value).toFixed(2);
            }
        }

        return this;
    });
});


Tuesday, April 29, 2014

jquery close navigation submenu when click away

$(document).ready(function () {
    $(".navbar-sub-opener").click(function (evt) {
        //close submenu when click away - part 2
        evt.stopPropagation();
        //hide all submenus
        $(".navbar-sub").hide();
        //only open the one that's immediate inside the clicked parent menu item
        $(this).next($(".navbar-sub")).show();
    });

    //close submenu when click away - part 1
    $('html').click(function () {
        $(".navbar-sub").hide();
    });
});

Thursday, April 10, 2014

jquery center div


jQuery.fn.center = function () {
    this.css("position", "fixed");
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

Wednesday, April 02, 2014

mvc partial view popup dialog form

required javascript:

$(document).ready(function () {
    $(".popupformContainer").dialog({
        height: 600,
        width: 300,
        autoOpen: false,
        modal: true,
        open: function (event, ui) {
            $(this).load("/controllername/actionname", { "parameter": $(this).data("parametervalue") }, function (html) {
            });
        },
        close: function (event, ui) {
            event.preventDefault();
            alert("closing");
        },
        buttons: {
            text: "提交", click: function (event) {
                event.preventDefault();
                $.validator.unobtrusive.parse("#PopupForm");
                $("#PopupForm").validate();
                if ($("#PopupForm").valid()) {
                    $("#PopupForm").submit();
                }
                else {
                    event.preventDefault();
                    alert("invalid");
                }
            }
        }
    });

    $(".btnOpenPopupForm").click(function () {
        $(".popupformContainer").data("parameter", $(this).attr("value")).dialog("open");
    });


});
in the parent view you need the button to open popup with class "btnOpenPopupForm" and an empty div with class "popupformContainer" for hosting the popup
in the partial view for the popup all you need is the form and all the form elements, the buttons are automatically generated unless you want some custom buttons

Thursday, March 27, 2014

tsql where clause checking even or odd number

update student
set isOdd = 1, isEven = 0
where exammark % 2 =1

Wednesday, March 26, 2014

Monday, March 10, 2014

mvc refresh current view without losing stuff like sorting, filtering etc

return Redirect(Request.UrlReferrer.ToString());

Saturday, March 01, 2014

mvc HttpPostedFileBase always null

make sure the form declaration in the view has all necessary attributes, e.g.


@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
      ...
}

found a useful way to show div as a modal

http://jsfiddle.net/r77K8/1/

Friday, February 28, 2014

asp.net mvc c# upload image, generate and upload thumbnail

public void UploadProductImage(HttpPostedFileBase file)
        {
            string subPath = "~/Images/";

            bool isExists = System.IO.Directory.Exists(Server.MapPath(subPath));

            if (!isExists)
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
            }

            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(Server.MapPath(subPath), pic);

                file.SaveAs(path);

                UploadProductImageThumbnail(file, productId);
            }
        }


public void UploadProductImageThumbnail(HttpPostedFileBase file)
        {
            using (var image = Image.FromStream(file.InputStream, true, true))
            {
                var thumbWidth = 50;
                var thumbHeight = 50;

                using (var thumb = image.GetThumbnailImage(
                    thumbWidth,
                    thumbHeight,
                    () => false,
                    IntPtr.Zero))
                {
                    var jpgInfo = ImageCodecInfo.GetImageEncoders()
                        .Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();

                    using (var encParams = new EncoderParameters(1))
                    {
                        string thumbPath = "~/Images/Thumbnails";
                        bool isExists = System.IO.Directory.Exists(Server.MapPath(thumbPath));

                        if (!isExists)
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath(thumbPath));
                        }

                        var thumbPathFull = Path.Combine(Server.MapPath(thumbPath), file.FileName);
                        long quality = 100;
                        encParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
                        thumb.Save(thumbPathFull, jpgInfo, encParams);
                    }
                }
            }
        }

Friday, February 21, 2014

linq compare int with string

products = products.Where(p =>
                    SqlFunctions.StringConvert((double)p.ProductId).Trim() == searchString);

Tuesday, June 25, 2013

RadGrid access the control inside command item template in DataBound event

protected void RadGrid1_DataBound(object sender, eventargs e)
{
     GridItem commandItem = RadGrid1.MasterTableView.GetItems(GridItemType.CommandItem)[0];
     Button button1 = commandItem.FindControl("button1") as Button;
}

Friday, June 21, 2013

the updated way to open radwindow from server side

string script = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "key", script, true);

Tuesday, June 11, 2013

what if jquery toggle doesn't work?

alternative is to use plain javascript, doesn't behave as nice but it works.

function toggleCourseDescriptions(conditioner) {

            var targetCtrl = document.getElementById("divCourseDescription");
            var triggerControl = document.getElementById("aToggleCourseDescription");


            if (targetCtrl.style.display == 'none') {
                targetCtrl.style.display = null;
            } else {
                targetCtrl.style.display = 'none';
            }

            if (triggerControl.text == "-") {
                triggerControl.text = "+";
            } else {
                triggerControl.text = "-";
            }
        }

Wednesday, May 15, 2013

linq integer division convert to percentage without decimal points

((int)(((decimal)(a.Category.Sum(l => l.Quantity) : 0) / MyDividerInteger) * 100)).ToString() + "%",

Tuesday, May 07, 2013

windows phone 8 toolkit contextmenu change menuitem header text dynamically




MenuItem item = menu.FindName("ContextMenuItemToggleReporting") as MenuItem;// .Single(i=>((MenuItem)item).Name == "ContextMenuItemToggleReporting") as MenuItem;
            if ([you condition logic here. e.g. MyEntity.IsReportingEnabled])
            {
                item.Header = "Disable Reporting";
            }
            else
            {
                item.Header = "Enable Reporting";
            }

Monday, May 06, 2013

windows phone 8 LongListSelector with ContextMenu

* you need to import the Windows Phone Toolkit from NuGet in order to be able to use ContextMenu

in .xaml page you need this:

    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <phone:LongListSelector x:Name="MainLongListSelector" Margin="0,0,-12,0" >
                <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Margin="0,0,0,17">
                            <toolkit:ContextMenuService.ContextMenu>
                                <toolkit:ContextMenu Name="ListItemContextMenu" Opened="ListItemContextMenu_Opened" >
                                    <toolkit:MenuItem Name="ContextMenuItemCopy" Header="Copy" Click="MenuItem_Click"/>
                                    <toolkit:MenuItem Name="ContextMenuItemEdit" Header="Edit" Click="MenuItem_Click"/>
                                    <toolkit:MenuItem Name="ContextMenuItemDelete" Header="Delete" Click="MenuItem_Click"/>
                                </toolkit:ContextMenu>
                            </toolkit:ContextMenuService.ContextMenu>
                            <TextBlock Text="{Binding DisplayString}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                        </StackPanel>
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
            </phone:LongListSelector>
        </Grid>


in .xaml.cs you need this

using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

        YourViewModel selectedItem;
        private void ListItemContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            ContextMenu menu = sender as ContextMenu;
            selectedItem = menu.DataContext as YourViewModel;
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            if (menuItem != null && selectedItem != null)
            {
                switch (menuItem.Name)
                {
                    case "ContextMenuItemCopy":
                        ActionCopy();
                        break;
                    case "ContextMenuItemEdit":
                        ActionEdit();
                        break;
                    case "ContextMenuItemDelete":
                        ActionDelete();
                        break;
                }
            }
        }

Friday, April 26, 2013

Android ScrollView and bottom AdMob overlap

I have a relative layout with a scrollview and a AdMob in it. The AdMob on the bottom overlaps the the scrollview so that the bottom part of the scrollview can never be seen. After a lot of trial and error I found that the solution is simple: set the ScrollView to android:layout_above="@+id/adView".

So the layout structure is something like this:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<ScrollView
        android:id="@+id/scrollView_home"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/adView"
        android:layout_alignParentTop="true"
        android:background="@drawable/background"
        android:orientation="vertical" >

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

</ScrollView>

    <com.google.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="abcdefg"
        ads:loadAdOnCreate="true" />

</RelativeLayout>

Thursday, April 25, 2013

Android app development prevent user from entering reserved characters

for example you want to reserve '-'

Step 1: create a class call it InputFilterReservedCharacters:

Step 2: in your activity do this in your onCreate event:

newNameText.setFilters(new InputFilter[]{new InputFilterReservedCharacters()});

Monday, April 08, 2013

Android app dev with SQLite ignore case

use COLLATE NOCASE

e.g. db.query("mytable", new String[]{.....}, "productname = '" + value + "' COLLATE NOCASE", null, null, null, null);