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