Wednesday, December 23, 2015

TSQL: find out which table a constraint belongs to

TSQL: find out which table a constraint belongs to


SELECT
   OBJECT_NAME(o.parent_object_id)
FROM
   sys.objects o
WHERE
   o.name = 'ConstraintABC' AND o.parent_object_id <> 0

Friday, August 28, 2015

Google Chrome cannot connect to internet after upgrade from Windows 8.1 to Windows 10

this solution worked for me (https://productforums.google.com/d/msg/chrome/ZE4c98nklAw/47xvIIz8zN8J) 1. run cmd as administrator 2. type in "netsh winsock reset" 3. restart pc

Tuesday, August 19, 2014

mvc checkboxlist


//Set up a viewmodel MyViewModel to contain the following

        [DisplayName("Available Products")]
        public IList AvailableProducts { get; set; }
        public IList SelectedProducts { get; set; }

        public PostedProducts PostedProducts { get; set; }



//The definition of ProductDropdownItemViewModel and PostedProducts are:

    public class PostedProducts
    {
        public int[] ProductIds { get; set; }
    }

    public class ProductDropdownItemViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }        
    }


//In your controller method populate the above viewmodel

  e.g. 
                MyViewModel.AvailableProducts = db.Products
                .Select(p => new ProductDropdownItemViewModel 
            {
                Id = p.Id,
                Name = p.Name
            }).ToList();


//In your view display the checkbox list this way

  e.g. the postback method name is Edit

     @model MyViewModel
     @using (Html.BeginForm("Edit", FormMethod.Post, new { enctype = "multipart/form-data" }))
     {
        @Html.CheckBoxListFor(x => x.PostedProducts.ProductIds,
                      x => x.AvailableProducts,
                      x => x.Id,
                      x => x.Name,
                      x => x.SelectedProducts,
                      MvcCheckBoxList.Model.Position.Vertical)
     }


//In your postback method Edit use the following code to retrieve your selected items


       public ActionResult Edit(PostedProducts postedProducts)
       {

                foreach (var id in postedProducts.ProductIds)
                {
                     //do whatever you like with the selected product id
                }

       }

Tuesday, August 05, 2014

tsql create table if not already exists


IF  NOT EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[table1]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[table1](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Name] [nvarchar](150) NOT NULL,
 CONSTRAINT [PK_abc] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]



END
go

c# read data from .xsl


public void ReadExcel(HttpPostedFileBase file, string currentUserName)
        {

            DataTable tbContainer = new DataTable();
            string strConn = XlsConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file.FileName +";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
            string sheetName = "sheet1";
            FileInfo fileInfo = new FileInfo(file.FileName);
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
            DataSet ds = new DataSet();
            oda.Fill(tbContainer);
            var newParcelTubeExport = new ParcelTubeExport();

            //your code to utilize the data

         }

Thursday, July 31, 2014

javascript round decimal to preferred number of decimal places

function round(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

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

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','')"

Wednesday, December 26, 2012

asp.net Response.RedirectToRoute issue

In my global.ascx I have the routing setup: 
routeCollection.MapPageRoute("My Home Page", "myhomepage/{myid}", "~/MyHomePage.aspx");
I use Response.RedirectToRoute() with a parameter to open a page. I identified that in the following cases the redirect will fail:
  • The parameter is not given. e.g. Response.RedirectToRoute("My Home Page");
  • The parameter as null value. e.g. Response.RedirectToRoute("My Home Page", new {myid = null});
  • The parameter as null value. e.g. Response.RedirectToRoute("My Home Page", new {myid = string.empty});

Apparently you MUST give a non-empty value to the parameter.

regular expression for character range

regular expression for character range:
e.g. between 1 and 500:
^.{1,500}$

Thursday, December 20, 2012

fix asp.net checkboxlist wierd layout

on one page my checkboxlist shows up correctly, on another it never does. After hours of trying I figured this out: assign CheckBoxList class to your css class of the checkboxlist, play with the properties inside the class will help you fix the issues.


         .CheckBoxList input
        {
            margin-left: -10px;
        }
        .CheckBoxList td
        {
            padding-left: 10px;
            width:80%;
        }

t-sql change a column from nullable to not null and add default value it


--1.make sure all records have a value in the column
update [TableName]
SET [ColumnName] = [Default Value]

--2. change the column to not null
ALTER TABLE [TableName]
ALTER COLUMN [ColumnName] [data type] NOT NULL
GO

--3. add default value constraint to the column
ALTER TABLE [TableName] WITH NOCHECKADD CONSTRAINT [DF_DefaultName] DEFAULT [Default Value] FOR [ColumnName]
GO

Wednesday, December 05, 2012

jquery to check if an asp.net checkbox control is selected or unselected:

$('input[id$=cb1]').is(':checked'){
          //your code here
}

Saturday, November 24, 2012

Telerik OpenAccess Service works locally but not hosted

I have 3 projects, one with the entity model, another one with the OData v3 service generated from the entity model, the third one is an asp.net web application.

During local development the service reference I added into the web app is from same solution: http://localhost:55001/MyModelService.svc

After everything was successfully tested I then published the service project and hosted it on a third party hosting service. I was able to browse the service successfully by going: http://service.myapp.com/MyService.svc

I then re-added the existing service reference into my web app with the remote url shown above, published the web app on another hosting service.

When I load up the web app I got an error:
DataServiceQueryException was unhandled by user code
An error occurred while processing this request.

The issue turned out to be really fundamental which I missed out through all my WCF learnings: the cross domain policy xml!

The solution is to add a clientaccesspolicy.xml into the OpenAccess Service WCF app root folder with the following content:



Wednesday, August 22, 2012

Friday, August 03, 2012

MS Office EXCEL 2010 the safest way to open .csv file and maintain leading zeros

Step 1:
Open EXCEL, click on tab "Data", select "From Text".

Step 2:
Browse to your local file folder and open the .csv file.

Step 3:
In the "Text Import Wizard - Step 1 of  3" popup, select "Delimited" and click on "Next".



Step 4:
In the "Text Import Wizard - Step 2 of  3" popup, select "Comma", un-select all other options, and click on "Next".



Step 5:
In the "Text Import Wizard - Step 3 of  3" popup, in "Data Preview" click to select the column you want to maintain leading zeros, then select "Text" in "Column data Format", now click on "Finish".




Step 6:
In the "Import Data" popup click on "OK".


Now you can see all leading zeros in EXCEL!

Thursday, July 12, 2012

get selected values form a checkboxlist c# asp.net web application

List selectedRoles = cblRolesAdd.Items.Cast().Where(n => n.Selected).Select(n => n.Value).ToList();

Wednesday, June 20, 2012

asp.net c# write to txt file


string path = HttpContext.Current.Server.MapPath("~/xxxxxxxx.txt");
                if (!System.IO.File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = System.IO.File.CreateText(path))
                    {
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                        sw.WriteLine("------------------------Some explanation of the purpose of this file-----------------------------");
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                    }
                }
                using (StreamWriter sw = System.IO.File.AppendText(path))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
                    sb.AppendLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
                    sb.AppendLine("WHEN: " + DateTime.Now.ToString());
                    sb.AppendLine("WHO: " + GetCurrentUser());
                    IPHostEntry host;
                    host = Dns.GetHostEntry(Dns.GetHostName());
                    foreach (IPAddress ip in host.AddressList)
                    {
                        if (ip.AddressFamily.ToString() == "InterNetwork")
                        {
                            sb.AppendLine("WHERE: " + ip.ToString());
                            break;
                        }
                    }
                    sb.AppendLine("WHAT: " + errorMsg);
                    sb.AppendLine();
                    sb.AppendLine();
                    sb.AppendLine();
                    sw.WriteLine(sb.ToString());
                }


Tuesday, June 19, 2012

.NET Web Application install default SqlMembershipProvider schema

find and run the following executable inside "%Windows\Microsoft.NET\[framework number]\[version number]\"

aspnet_regsql.exe

Friday, June 15, 2012

RadGrid ItemCommand Find Control

if the control you are looking for is a button:
((Button)e.CommandSource)


if the control you are looking for is a label:
((Label)e.CommandSource)

Thursday, June 14, 2012

RadWindow Resize by Percentage


var width = $telerik.$(window).width() * 0.8;
                    var height = $telerik.$(window).height() * 0.95;
                    ExpWindow.setSize(width, height);
                    ExpWindow.center();

StimulSoft Report Web Designer Save Report

protected void StiWebDesigner1_SaveReport(object sender,

StiWebDesigner.StiSaveReportEventArgs e)
{
StiReport report = e.Report;
        string file = report.ReportFile;
        report.Save(file);
}

Monday, May 28, 2012

RadGrid bind detail table in code behind

protected void RadGrid1_DetailTableDataBind(object source, Telerik.Web.UI.GridDetailTableDataBindEventArgs e) { GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem; switch (e.DetailTableView.Name) { GetDataByParentId(dataItem.GetDataKeyValue("Id").ToString()); } }

Thursday, May 17, 2012

c# .net web application add server control into literal using stringbuilder

StringBuilder sb = new StringBuilder();
TextBox TextBox1 = new TextBox ();
TextBox1.ID = "TextBox1";
TextBox1.Text = "Hello World";
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
TextBox1.RenderControl(tw);
}
}

Wednesday, May 16, 2012

tsql update datetime value

datetime value can be updated using the following query:
e.g. I want to replace the year value with '2012'

update table1

set date = convert(datetime,'2012'+'-'+convert(varchar(3),MONTH(date))+'-'+convert(varchar(3),DAY(date))+' '+ convert(varchar(12),convert(time,date))),

  CompletedDate = convert(datetime,'2012'+'-'+convert(varchar(3),MONTH(CompletedDate))+'-'+convert(varchar(3),DAY(CompletedDate))+' '+ convert(varchar(12),convert(time,CompletedDate)))

where [condition]

Tuesday, May 08, 2012

tsql add primary key column on existing table

I can add a new column to an existing table no problem, but i had problem making it an autoincrement int primary key. After some research I found the solution: "Identity" keyword:

if not exists(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'table1' AND COLUMN_NAME = 'ID')
begin

    ALTER TABLE dbo.table1
    add ID int identity not null
       
end
go

Wednesday, May 02, 2012

solution to: c# asp.net usercontrol javascript only executes first time

I have this line to run a javascript from code behind:
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "sbScript", sbScript.ToString(), false);

This line is inside pageload event of the usercontrol that I used my my aspx page. The user control is used multiple times on the aspx page. The javascript is therefore called multiple times. However the script only works the first time.

The reason being is because the script name specified is always "sbScript" which has been assigned value when first run. The solution is to make sure the script name is set to different values everytime the line is executed.

Tuesday, May 01, 2012

Attempt by security transparent method 'xxxxxxxxx' to access security critical method 'xxxxxxxx' failed.


I converted my website to a web application and upgraded .net framework from v3.5 to v4. I also setup a class library to host entity framework models for the web app to consume. At run time when the business logic calls the entity framework class library I got this error below.

Attempt by security transparent method 'xxxxxxxxx' to access security critical method 'xxxxxxxx' failed.

Assembly 'xxxxxxxxxxx' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model.  Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

 The solution is to specify the security level in the business logic project AssemblyInfo.cs, add the following line:
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]


 

Monday, April 30, 2012

asp.net web application: assembly generation failed referenced assembly does not have a strong name

in my asp.net web application I got this problem when added a new class library into my solution and trying to build the solution:
"assembly generation failed referenced assembly does not have a strong name"

Apparently the solution is to go to the class Project properties: Solution Explorer > right click > properties, click on Signing tab, select "Sign the assembly", then browse the key shared among other projects within the same solution.

Tuesday, April 24, 2012

Tuesday, March 13, 2012

jquery get asp.net label text

var labelText = $('#<%= lblabc.ClientID %>').html();

jquery find server control checkbox checked state

if ($('#isAgeSelected').is(':checked')){
//your code here
}

Friday, March 09, 2012

tsql get part of a datetime value

DATEPART(portion, datetimevalue)

the options for portion are:

Ms for Milliseconds
Yy for Year
Qq for Quarter of the Year
Mm for Month
Dy for the Day of the Year
Dd for Day of the Month
Wk for Week
Dw for the Day of the Week
Hh for Hour
Mi for Minute
Ss for Second

e.g.
select startdate,DATEPART(Hh,a.startdate)

this returns the hour of startdate

Wednesday, February 29, 2012

mvc format databound datetime column

if you want something like "22/11/2012 15:00" then use
columns.Bound(o => o.MyDateTimeValue).Format("{0:dd/MM/yyyy HH:mm}").Width(120);

if you want something like "22/11/2012 3:00 PM" then use
columns.Bound(o => o.MyDateTimeValue).Format("{0:dd/MM/yyyy hh:mm tt}").Width(120);

Tuesday, February 28, 2012

t-sql add new line in code

i keep forgetting this simple solution:
char(13)
now I save it here so that I never forget again

Tuesday, February 14, 2012

c# split multi-line postal address

I have a multi-line postal address (string PostalAddressString) like this:

Address1:12 Garden Street
Address2:
Suburb:Abc
PostCode:123
State:BC
Country:ABCDE


In order to separate details and access them individually i need to do this:



NameValueCollection lines = new NameValueCollection();
string[] TempArray = PostalAddressString.Split(Environment.NewLine.ToCharArray());
if (TempArray.Count() > 5 || TempArray[0].ToLower() != "n/a")
{
foreach (string line in TempArray)
{
string[] parts = line.Split(':');
if (line.Length > 0)
lines.Add(parts[0].Trim(), parts[1].Trim());
}

string PostalAddressLine1String = lines.Get("Address Line 1");
string PostalAddressLine2String = lines.Get("Address Line 2");
string PostalSuburbString = lines.Get("Suburb");
string PostalPostCodeString = lines.Get("PostCode");
string PostalStateString = lines.Get("State");
string PostalCountryString = lines.Get("Country");
}

Thursday, February 09, 2012

Telerik RadGrid how to bind detailtable from code behinde

Use this method:

OnDetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)

The ParentKeyValues can be accessed this way:

e.DetailTableView.ParentItem.GetDataKeyValue("StoreId")

Tuesday, February 07, 2012

t-sql update table with join


update d
set d.dname = "HR"
from Department d
inner join employee e
on e.employeeID = d.employeeID
where d.departmentID = 1

Tuesday, November 22, 2011

Stimulsoft relax Master Detail table relationships

When I setup master detail table relationship in my report i noticed that the master records which do not have any related detail records will not be shown.

The trick is to set "Print if Detail Empty" property of the master data band to "true"

Friday, November 11, 2011

Asp.Net retrieve Web.config AppSettings in c# code behind

have a reference:

using System.Web.Configuration;

then use this code to retrieve the value:
WebConfigurationManager.AppSettings["propertyName"]

Thursday, October 20, 2011

Telerik RadGrid databinding throws error when open template edit form in insert mode with boolean controls e.g. checkbox

solution is to have a corresponding GridBoundColumn, and set DefaultInsertValue="false" in the column definition

Telerik RadGrid shows second page after opening the insert form

my radgrid uses Tempalte in EditFormSettings. It current contains 2 pages of data.
When I click on Add New Record the command button on top of the grid, the edit form opens correctly in insert mode. However when I look closely at the data, it actually shows the second page, and the page number on the bottom of the grid shows "2".


The solution is to set

Wednesday, September 07, 2011

tsql rename table and column

--rename a table:
EXEC sp_rename 'OldTableName', 'NewTableName'
--rename a column:
EXEC sp_rename
@objname = 'TableName.OldColumnName',
@newname = 'NewColumnName',
@objtype = 'COLUMN'

Friday, September 02, 2011

c# assign values to object property by property name

Class1 obj= new Class1();
string propertyName = "name1";
string objValue = "";
Type type = obj.GetType();
PropertyInfo prop = type.GetProperty(propertyName );
prop.SetValue(obj, objValue , null);

Thursday, September 01, 2011

c# aspnet download file from server side

string text1 = this.Server.MapPath("~/" + [FileFolder]);
if (Directory.Exists(text1))
{
string text2 = text1 + @"\[File Name with extension]";
if (System.IO.File.Exists(text2))
{
FileStream stream1 = new FileStream(text2, FileMode.Open, FileAccess.Read);
byte[] buffer1 = new byte[((int)stream1.Length) + 1];
stream1.Read(buffer1, 0, (int)stream1.Length);
stream1.Close();

//Writes the file out the Response object
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment;filename=\"[File Name with extension]\";");
Response.WriteFile(text2, true);
Response.ContentType = "application/x-zip-compressed";
Response.BinaryWrite(buffer1);
Response.End();
}
}

Thursday, August 25, 2011

helpful linq to sql article

http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx

Wednesday, August 24, 2011

some useful keyboard shortcuts for Visual Studio

found this helpful
http://visualstudiohacks.com/general/confessions-of-a-keyboard-junkie/

Wednesday, August 17, 2011

import from excel c# aspnet

String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + RadUpload.UploadedFiles[0].FileName+";" +
"Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
OleDbCommand cmdSelectAdditions = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
OleDbDataAdapter AdapterForAdditions = new OleDbDataAdapter();
AdapterForAdditions.SelectCommand = cmdSelectAdditions;
DataSet dsAdditions = new DataSet();
AdapterForAdditions.Fill(dsAdditions);
objConn.Close();

Tuesday, August 16, 2011

aspnet c# generate .pdf

this article helped me, hope it helps you too!
http://www.4guysfromrolla.com/articles/030911-1.aspx

I need to parse HTML into the pdf, the implementation is:

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Transactions.pdf");

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Document document = new Document(PageSize.A1, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(document, Response.OutputStream);

// Open the Document for writing
document.Open();

string documentContent = string.Empty;
document.NewPage();
documentContent = "Confirmation" + "
" + body;
StringReader sr = new StringReader(documentContent);
foreach (object item in HTMLWorker.ParseToList(sr, null).ToList())
{
document.Add((IElement)item);
}

document.Close();

Response.Write(document);
Response.End();

Thursday, August 11, 2011

How to query and display excel data by using ASP.NET, ADO.NET, and Visual C# .NET

found this article very helpful
http://support.microsoft.com/kb/306572/

I modified it a bit to work for me (I am using RadUpload to get the file):

// Create connection string variable. Modify the "Data Source"
// parameter as appropriate for your environment.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + ruImporter.UploadedFiles[0].FileName+";" +
"Extended Properties=Excel 8.0;";

// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);

// Open connection with the database.
objConn.Open();

// The code to follow uses a SQL SELECT command to display the data from the worksheet.

// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);


// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;

// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();

// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1);



// Clean up objects.
objConn.Close();

Tuesday, June 14, 2011

tsql split full name into firstname and lastname

this script only works with combination of firstname+' '+lastname.

--firstname
SUBSTRING(fullname, 1, CHARINDEX(' ', fullname) - 1) as firstname

--lastname
SUBSTRING(fullname, CHARINDEX(' ', fullname) + 1, LEN(fullname)) as lastname

Tuesday, June 07, 2011

tsql split up a comma seperated string into a table with duplicate records removed

thanks to many similar sources on the web, I came up with my script, it splits up a comma seperated string into a table with duplicate records removed



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Spliter]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].Spliter
GO
CREATE FUNCTION Spliter(@String varchar(max), @Delimiter char(1))
returns @temptable TABLE (items varchar(max))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0 and (select count(items) from @temptable where items = @slice)=0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
GO


SELECT i.items FROM dbo.Spliter(@tempstring,',') AS i where items not in (select comparesource from comparesourcetable)

Thursday, June 02, 2011

Stimulsoft Web Designer restrictions

found these properties quite handy when you want to give end user limited access when designing the report in web browser, especially when you want to hide the connection string credentials.

StiWebDesignerOptions.Dictionary.AllowModifyDictionary = true;
StiWebDesignerOptions.Dictionary.AllowModifyConnections = false;
StiWebDesignerOptions.Dictionary.ShowConnectionType = false;
StiWebDesignerOptions.Dictionary.AllowModifyDataSources = false;
StiWebDesignerOptions.Dictionary.AllowModifyVariables = true;


just put them before swdCustomReport.Design(report); in your code

Monday, May 30, 2011

MS SQL Server Management Studio 2008 cannot save table change

I got this message:
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-cretead.

the solution is:
Tools > Options > Designers > Table and Database Designers
unselect 'Prevent saving changes that require the table to be re-created' check box

Wednesday, May 25, 2011

find radtextbox and hide radtextbox in javascript



var rtbName = $find("<%= rtbName.ClientID %>");
rtbName.set_value('Hello World');

Wednesday, May 11, 2011

tsql remove leading zeros in a string that is 10 characters in length

SUBSTRING([TheString], patindex('%[^0]%',[TheString]), 10)

Monday, May 02, 2011

C# get opposite colour of a given colour

public static Color FindeOppositeColor(Color InputColour)
{
return Color.FromArgb(255 - InputColour.R, 255 - InputColour.G, 255 - InputColour.B);
}

Thursday, April 14, 2011

sometimes i need to open radwindow from server side, I use this code snippet from Telerik:


protected void Button1_Click(object sender, EventArgs e)
{
Telerik.WebControls.RadWindow newwindow = new Telerik.WebControls.RadWindow();
newwindow.ID = "RadWindow1";
newwindow.NavigateUrl = "http://www.google.com";
newwindow.VisibleOnPageLoad = true;
RadWindowManager1.Windows.Add(newwindow);
}


the intellisense in Visual Studio 2010 doesn't give me "width" or "height" when i try to see if it is allowed to specifiy size for radwindow. The answer is YES, forget about the intellisense, just type it in, there you are, worked!


newwindow.Width = Unit.Pixel(500);
newwindow.Height = Unit.Pixel(500);
newwindow.Behaviors = WindowBehaviors.Move | WindowBehaviors.Close;

Wednesday, March 30, 2011

internet explorer 8 developer tools window shows in task bar but not showing

what a frustrating 5 minutes....

try Windows key + Up key

enjoy

Tuesday, March 29, 2011

move all contents from one folder to another c#

oldPath and newPath should look like "c:/FolderABC" or "~/FolderABC"


System.IO.Directory.Move(@oldPath, @newPath);

Monday, March 21, 2011

sql shrink log files

found this useful to keep necessary usage of disk space with sql db installed

USE myDatabase
GO
DBCC SHRINKFILE(myDatabase_log, 1)
BACKUP LOG myDatabase WITH TRUNCATE_ONLY
DBCC SHRINKFILE(myDatabase_log, 1)

Tuesday, March 15, 2011

radeditor doesnt open properly when first randered within a grid html edit column

found the solution at:

http://www.telerik.com/community/forums/aspnet-ajax/editor/incorrect-rendering-of-radeditor-when-shown-with-ajax-in-initially-hidden-parent.aspx

Wednesday, February 09, 2011

radgrid integer filter enter text cause error

when I enter a random text instead of an integer into the filter, and select any option in the filter options dropdown, i get error
the solution is kind of tricky:
EnableLinqExpressioins property of grid as false

Tuesday, January 11, 2011

in my radgrid i use template as EditFormType. When I open the edit form for a grid item I want to show or hide a texbos based on the value populated in it. It can be achieved this way:

Protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
GridEditFormItem item = (GridEditFormItem)e.Item;
TextBox TextBox1 = (TextBox)item.FindControl("TextBox1");
//OR/// TextBox txtbox = (TextBox)item["TextBox1"].Controls[0];
if (TextBox1.Text == "your value")
{
TextBox1.Visible = false;
}
}
}

Friday, January 07, 2011

radwindow pops up all the time unexpected

I use the following line in code behind to open a radwindow:




During as soon as I opened the window once, any postback will cause this window to popup again.

The solution is simple, just put the following code into page_load event.
RadWindow1.Visible = false;