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);

Sunday, March 31, 2013

android app dev assign int value to a TextView

This is rather wierd, when you want to assign an integer to a TextView apparently you need to assign the combination of "" +  and your integer value.


e.g. 
myTextView = (TextView) findViewById(R.Id.myTextView);
myTextView.setText(""+myIntegerValue);

Thursday, March 21, 2013

asp.net webforms app with mvc, unable to find "/Account/Login"

I have an asp.net webforms application with later on added mvc component. The login view is embeded inside the homepage Default.aspx. When I type into browser and try to open a login controlled URL without loggged in, i should be redirected to the Default.aspx homepage for login, but instead I get 404 not found error looking for "/Account/Login".

The solution worked for me is rather wierd:
add the following setting in AppSettings section of your web.config



Wednesday, March 20, 2013

radgrid initial filter


if (!page.ispostback)
{

RadGrid1.MasterTableView.FilterExpression = "([Country] LIKE \'%Germany%\') ";
        GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("Country");
        column.CurrentFilterFunction = GridKnownFunction.Contains;
        column.CurrentFilterValue = "Germany";
        RadGrid1.MasterTableView.Rebind();
}

Friday, March 15, 2013

tsql find table name by index name


EXEC sp_MSforeachdb 'USE ?
select ''?'' as DatabaseName, st.name as TableName,si.name as IndexName from sys.indexes si
inner join sys.tables st
on
si.object_id = st.object_id
where si.name like ''%NC_explore_user%'''

Monday, March 11, 2013

deploy mvc 4 razor application onto shared hosting 404 default document not found error

the solution for me is to have this under


also you need to make sure your hosting environment is setup for .net v4.x and integrated mode

Sunday, March 10, 2013

mvc temperary value options

ViewData/ViewBag : only eixsts for single controller request on single view


TempData: exists beyond single controller request inside same controller, expires once the value is requested

Session: exists for multiple controller requests within same controller, expires once navigated away to other controller

Monday, March 04, 2013

mvc 4 custom server validation on multiple fields

Imaging there is a many to many relationship between category and product and there are some specific information required on this many to many relationship, therefore we need a dedicated entity CategoryProduct to work with. On submission I need to validate whether the combination of category and product selections already exist.

in validation controller provide:


public JsonResult ValidateCategoryProduct(int? categoryProductId, int categoryId, int productId)
        {
            if (!categoryProductId.HasValue)
            {
                categoryProductId = -1;
            }

            var validationResult = categoryProductRepository.ValidateCategoryProduct(categoryProductId.Value, categoryId, productId);
            if (validationResult)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                string output = "This category product relationship has already been setup.";
                return Json(output, JsonRequestBehavior.AllowGet);
            }
        }

in my model I have


[DisplayName("CategoryId")]
        [Remote("ValidateCategoryProduct", "ValidationLogic", AdditionalFields = "CategoryProductId,ProductId")]
        [Editable(true)]
        public int CategoryId { get; set; }

        [DisplayName("ProductId")]
        [Required(ErrorMessage = "Please select a Product")]
        [Remote("ValidateCategoryProduct", "ValidationLogic", AdditionalFields = "CategoryProductId,CategoryId")]
        [Editable(true)]
        public int ProductId { get; set; }

in my view I have the following under the category textbox
@Html.ValidationMessageFor(model => model.CategoryId, "*")
I also have the following under the productid textbox
@Html.ValidationMessageFor(model => model.ProductId, "*")

now we are good to go, the only issue left is that we need to figure out a way to apply validation result to both properties at once..... puzzled at the moment.

Friday, March 01, 2013

KendoUI Grid MVC4 hide delete button in the list if there is depent records




.CellAction(cell=>{
                     if (cell.Column.Title == "Delete" && cell.DataItem.ChildRecords.Count > 0)
                     {
                         cell.HtmlAttributes["style"] = "visibility:hidden";
                     }
                 })

alternatively:


columns.Template(
                          @@Html.ActionLink("Delete", "Delete", new { id = item.ChildRecordId}, (item.ChildRecords.Count > 0 ? new {style = "display: none"} : null))
                          ).Title("Delete");

raddatepicker get selected date client side into a string

RadDatePicker1.get_dateInput().get_selectedDate().format("dd/MM/yyyy");

radtextbox get value from client side


$find("<%= RadTextBox1.ClientID %>").get_value();

Monday, February 04, 2013

aspx dropdownlist get selected text from client side using javascript

$('[id*=ddlCountry] option:selected').text()

Tuesday, January 22, 2013

asp.net membership default setup

with these settings inside   you are set to go.


tsql add default constraint



IF NOT EXISTS(select * from sys.DEFAULT_CONSTRAINTS where NAME like 'def_myconstraint1%')
BEGIN

 ALTER TABLE mytable1
 ADD CONSTRAINT def_myconstraint1 DEFAULT 1 FOR mycolumn1
END
GO

Friday, January 18, 2013

css center a div

tried to use text-align:center didnt work, the correct way is:

width: 10240px ;
  margin-left: auto ;
  margin-right: auto ;

Saturday, January 12, 2013

asp.net web application update web.config SMTP settings in global.ascs application_start():

asp.net web application update web.config SMTP settings in global.ascs application_start():


System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/");
            System.Net.Configuration.MailSettingsSectionGroup mailSettingsGroup = config.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup;
            mailSettingsGroup.Smtp.Network.Host = Properties.Settings.Default.SMTPServer;
            mailSettingsGroup.Smtp.Network.Port = Properties.Settings.Default.SMTPPort;
            mailSettingsGroup.Smtp.Network.DefaultCredentials = Properties.Settings.Default.SMTPAuthenticationEnabled;
            if (mailSettingsGroup.Smtp.Network.DefaultCredentials)
            {
                mailSettingsGroup.Smtp.Network.UserName = Properties.Settings.Default.SMTPUsername;
                mailSettingsGroup.Smtp.Network.Password = Properties.Settings.Default.SMTPPassword;
            }

Wednesday, January 09, 2013

prevent double click on asp.net button control

headache solved after search and search and search for solutions:

OnClientClick="this.disabled = true; this.value = 'Submitting...';__doPostBack('SaveChangesButton','')"