Monday, November 3, 2014

ASP.NET: Force client to update javascript files after each new build


Problem

How to force a client to update cached javascript files after each new build

Solution

Add build number property to your page class

Protected ReadOnly Property CurrentVersion() As Integer
        Get
            Return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Build
        End Get
End Property

And update script source to utilize the build number property


<script src="Script/Functions.js?v=<%= CurrentVersion%>" type="text/javascript"></script>


After each new build script source url is changed so browser will update javascript-file to the cache


Wednesday, December 5, 2012

EF 4: How to execute stored procedure with Entity Framework Code First?


Problem

How to execute stored procedure with Entity Framework Code First?

Solution

This would execute a stored procedure which returns a single integer value as result
using (var db = new MyEntities())
{
 var param1 = new System.Data.SqlClient.SqlParameter("@param1", 1000);
 var param2 = new System.Data.SqlClient.SqlParameter("@param2", 2000);
 int? result = db.Database.SqlQuery("MySproc @param1, @param2", param1, param2).FirstOrDefault();
}

This would execute a stored procedure which returns a table data as result
using (var db = new MyEntities())
{
 var cmd = db.Database.Connection.CreateCommand();
 cmd.CommandText = "MyStoredProc @param1, @param2, @param3";
 cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@param1", 1300));
 cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@param2", 60));
 cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@param3", false));

 db.Database.Connection.Open();
 var reader = cmd.ExecuteReader();
 while (reader.Read())
 {
  var resultvalue1 = reader.GetValue(0);
  var resultvalue2 = reader.GetValue(1);
 }
 db.Database.Connection.Close();
}

Friday, June 8, 2012

ASP.NET MVC: How to get model values from separate javascript file


Problem
How to get ASP.NET MVC model values from separate javascript file?

Solution
There are many ways to get model values from separate javascript file. Here are a couple of way to do it:

1. If you are using HTML5 you can use custom data attributes
 <div id="baseTargetUrl" data-basetargeturl="<%= Url.Content("~/") %>" />  
and get custom attribute value from javascript file
 var rootUrl = location.protocol + '//' + location.host +  
 $('#baseTargetUrl').data('basetargeturl');  
2. Set javascript variable from view
 <script type="text/javascript">  
 var baseTargetUrl= <%= Url.Content("~/") %>;  
 </script>  
and use this variable from separate javascript file

3. Extend jQuery to allow own namespace to store values. Here is a great example how to do it

Wednesday, March 28, 2012

WinForms and C#: How to sort a ListView by column

Problem

How to sort a "WinForms.ListView" content when one of the columns are clicked

Solution

I don't remember where I found this great Sorter-class but just copy-paste it to your project as a new ListViewSorter class
public class ListViewSorter : System.Collections.IComparer
{
        public int Compare(object x, object y)
        {
            int result = 0;

            if (!(x is ListViewItem))
            {
                return result;
            }
            if (!(y is ListViewItem))
            {
                return result;
            }

            // Determine whether the type being compared is a date type.
            try
            {
                System.DateTime firstDate = DateTime.Parse(((ListViewItem)x).SubItems[ByColumn].Text);
                System.DateTime secondDate = DateTime.Parse(((ListViewItem)y).SubItems[ByColumn].Text);
                result = DateTime.Compare(firstDate, secondDate);
            }
            catch
            {        
                // Compare the two items as a string. 
                result = String.Compare(((ListViewItem)x).SubItems[ByColumn].Text, ((ListViewItem)y).SubItems[ByColumn].Text);
            }

            // Determine whether the sort order is descending. 
            if (((ListViewItem)x).ListView.Sorting == SortOrder.Descending)
            {
                // Invert the value returned by compare. 
                result *= -1;
            }

            LastSort = ByColumn;
            return result;
        }

        public int ByColumn
        {
            get { return Column; }
            set { Column = value; }
        }
        int Column = 0;

        public int LastSort
        {
            get { return LastColumn; }
            set { LastColumn = value; }
        }
        int LastColumn = 0;
}

After your class is ready you must declare a sorter object in the form:
private ListViewSorter listSorter = new ListViewSorter();

and create a new event for ListView ColumnClick to handle sorting
private void listMyList_ColumnClick(object sender, ColumnClickEventArgs e)
{
        listMyList.ListViewItemSorter = listSorter;
        if (listSorter.LastSort == e.Column)
        {
            // Change sort order for current column
            if (listMyList.Sorting == SortOrder.Ascending)
            {
                listMyList.Sorting = SortOrder.Descending;
            }
            else
            {
                listMyList.Sorting = SortOrder.Ascending;
            }
        }
        else
        {
            listMyList.Sorting = SortOrder.Descending;
        }
        listSorter.ByColumn = e.Column;
        listMyList.Sort();
}

Thursday, March 22, 2012

ASP.NET: How to pass value back from user control to the page with events

Problem
This is simple tutorial how to pass a value back from user control to the page with event. In this example textbox value is passed back to the label on default page

Solution
After creating a new web site with default page create a simple user control called InputBox. Inputbox should have one TextBox and two buttons

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="InputBox.ascx.cs" Inherits="Testi.InputBox" %>
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblUserInput" runat="server" Text="User input:"></asp:Label>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:TextBox ID="txtUserInput" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="btnOk" runat="server" Text="OK" onclick="btnOk_Click" />
        </td>
        <td>
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" 
                onclick="btnCancel_Click" />
        </td>
    </tr>
</table>

Open user control code-behind and create a new EventArgs class

public class InputEventArgs : EventArgs
{
    public string UserInput{ get; set; }
}
Then add two events to the user control which uses InputEventArgs

    public event EventHandler<InputEventArgs> OKClicked;
    public event EventHandler<InputEventArgs> CancelClicked;

Add following code to the OK and Cancel -button event handlers to fill InputEventArgs:

        protected void btnOk_Click(object sender, EventArgs e)
        {
            // Create a new event argument when OK is clicked
            if (OKClicked != null)
            {
                EventHandler<InputEventArgs> tmp = OKClicked;
                if (tmp != null)
                {
                    // Take value from textbox 
                    tmp(this, new InputEventArgs() { UserInput = txtUserInput.Text });
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Create a new event argument when Cancel is clicked
            if (CancelClicked != null)
            {
                EventHandler<InputEventArgs> tmp = CancelClicked;
                if (tmp != null)
                {
                    tmp(this, new InputEventArgs() { UserInput = null });
                }
            }
        }
Now you can open your default.aspx page and register user control

<%@ Register TagPrefix="Test" TagName="InputBox" Src="InputBox.ascx" %>

Add the user control and result label inside form

        <table>
            <tr>
                <td>
                    <b>For example you can place this user control inside modal confirmation...</b>
                </td>
            </tr>
            <tr>
                <td>
                    <Test:InputBox ID="inputBox" runat="server" OnOKClicked="InputBox_OKClicked" 

OnCancelClicked="InputBox_CancelClicked" />
                </td>
            </tr>
            <tr>
                <td>
                    <b>Display input value from user control:</b>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblInputBoxResult" runat="server" Text=""></asp:Label>
                </td>
            </tr>
        </table>


Then open default page code-behind and create two event handlers to handle clicks from user control

        protected void InputBox_OKClicked(object sender, InputEventArgs e)
        {
            lblInputBoxResult.Text = e.UserInput;
        }

        protected void InputBox_CancelClicked(object sender, InputEventArgs e)
        {
            lblInputBoxResult.Text = "User clicked cancel";
        }


Now you can run and test if value from user control is passed to the event handler at default page...

Friday, September 16, 2011

.NET Framework 4: Unable to cast object of type 'system.string' to type

Problem

For example you are binding pricelist-objects to a combobox in WinForms application like this

cmbPricelist.DataSource = BL.GetPricelists();
cmbPricelist.ValueMember = "PricelistCode";
cmbPricelist.DisplayMember = "PricelistName";

and later you trying to get selected item from combobox like this

Pricelist p = (Pricelist)cmbPricelist.SelectedValue;

you might get an error "Unable to cast object of type 'system.string' to type..."

Solution

If you are using .NET Framework 4 Client profile ComboBox.SelectedValue method returns object (in this example Pricelist).

But if you are using .NET Framework 4 Full profile ComboBox.SelectedValue method returns ValueMember as String

Monday, July 4, 2011

ASP.NET: Prevent button double-click

Problem

How to prevent button double-click on ASP.NET page

Solution

Add following code to Page_load. This code prevents button double-click on client-side but still executes code at server-side:

VB.Net

btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, Nothing) + ";")

C#

btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");

Thursday, November 25, 2010

CRM Adapter 4.0 installation to Biztalk Server 2010

Problem

You might receive an error "Microsoft Biztalk Server 2006 is not installed. You must install Microsoft Biztalk Server 2006. Then, try running Setup Again" when running CRM Adapter 4.0 setup

Solution

Edit ProductName value at HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\BizTalk Server\3.0 to Microsoft BizTalk Server 2006 and then run setup again. After setup is complete you can change ProductName back to Microsoft BizTalk Server 2010

Thursday, November 18, 2010

There was a failure executing the receive pipeline: Verify the schema for this document specification is deployed and is in the Global Assembly Cache

Problem

You might receive this error "There was a failure executing the receive pipeline: Verify the schema for this document specification is deployed and is in the Global Assembly Cache" in Biztalk 2010 while trying to submit a message to the receive location which is published with the WCF Service Publishing Wizard.

Solution

By default WCF service is running inside AppPool which is configured to use .Net Framework 2.0. Change WCF service AppPool to one which uses .Net Framework 4.0

Wednesday, August 11, 2010

Workaround: Running ASP.NET 1.1 on Windows 64-bit

Problem

IIS manager crashes when modifying ASP.NET 1.1 sites on 64-bit Windows

Solution

Here is a long and good explanation how to solve the problem: http://blogs.iis.net/wonyoo/archive/2009/06/18/workaround-running-asp-net-1-1-on-vista-sp2-ws08-sp2.aspx

Short explanation:
1. Create the Framework64 directory for 1.1 \windows\microsoft.net\framework64\v1.1.4322\config\
2. Copy the 32bit config to 64bit config location created in step 1.
Copy file from \windows\microsoft.net\framework\v1.1.4322\config\machine.config to \windows\microsoft.net\framework64\v1.1.4322\config\

Wednesday, March 24, 2010

WCF: Error in deserializing body of reply message

Problem

You got an error "Error in deserializing body of reply message" when calling WCF service.

Solution

If your response message size is huge then check the reader quota settings in client app/web.config-file at bindings section and change them. For example:

<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>

Note that you must have same binding, which settings you are changing, in server side also!

More about reader quota: http://msdn.microsoft.com/en-us/library/ms731325.aspx

Tuesday, March 16, 2010

WCF Oracle adapter: Field xxx has a value with time zone information set. Specify a value without time zone

Problem

I tried to call a Oracle stored procedure from orchestration with WCF Oracle Adapter.

My source message contains a date element like this <deliveryDate>2010-03-17T16:20:34.252125+02:00</deliveryDate> and when I put that value to destination message which is sent to Oracle: <DELIVERYDATE>2010-03-15T16:20:34.2365000Z</DELIVERYDATE>

I got an error "Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: Field DELIVERYDATE has a value with time zone information set. Specify a value without time zone.


Solution
Destination messsage date value should be modified to XML date format without timezone:

DateTime date = XmlConvert.ToDateTime(xmldate, XmlDateTimeSerializationMode.Unspecified);
DestinationElementValue = date.ToString("yyyy-MM-ddThh:mm:ss"));

Wednesday, December 30, 2009

Looping in stored procedure

Problem
How to loop through the select result in a stored procedure

Solution
DECLARE @MyId int
DECLARE Scroller SCROLL CURSOR
FOR SELECT MyId FROM MyTable

OPEN Scroller
FETCH NEXT FROM Scroller INTO @MyId
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO MyTable2 (ReferenceId) VALUES (@MyId)
FETCH NEXT FROM Scroller INTO @MyId
END

CLOSE Scroller
DEALLOCATE Scroller

Tuesday, September 22, 2009

ORA-03114: not connected to ORACLE and Biztalk Oracle Adapter

Problem

You receive an error "ORA-03114: not connected to ORACLE" when you are trying to connect to the Oracle database with Biztalk Oracle Adapter. This error can occur even if you was connected to the database just few seconds ago.


Solution

Problem relates to the connection pool.

If the connection pooler detect that the connection with the server has been broken it will remove the broken connection from the connection pool. This doesn't happen all the time and you actually get a bad connection from the pool.

Workaround is to change Send port settings: Change useOracleConnectionPool to false at Bindings tab

Tuesday, March 24, 2009

Biztalk: Specified value has invalid CRLF characters

Problem

You may receive an error "System.ArgumentException: Specified value has invalid CRLF characters" when sending message to the WCF send port


Solution

Remove all linebreaks and spaces from send port's "Soap Action Header" action box

Wednesday, February 18, 2009

ASP.NET: UpdatePanel and Response.Write()

Problem

When you are modifying Response with Response.Write() from control which is inside UpdatePanel you may receive an error "Message received from the server could not be parsed"

Solution

Solution is to add a trigger to UpdatePanel like this:

</ContentTemplate>
  <Triggers>
    <asp:PostBackTrigger ControlID="btnExportToExcel" />
  </Triggers>
</asp:UpdatePanel>

This causes an UpdatePanel to refresh the page only in control specified in Triggers section

Tuesday, December 9, 2008

ASP.NET: UpdatePanel and popup with javascript

Problem

How to open popup-window with javascript when there is a UpdatePanel control in the page

Solution

You must use ScriptManager.RegisterStartupScript() instead of ClientScript.RegisterStartupScript(). That's because ScriptManager enables partial page update what AJAX needs but ClientScript doesn't enable partial page updates.

Tuesday, November 25, 2008

ASP.NET: Response.Redirect throws an exception

Problem

Response.Redirect throws an exception when trying redirect to the another page

Solution

Use Response.Redirect(url, false) instead of Response.Redirect(url)

Friday, October 31, 2008

Gacutil: Failure adding assembly to the cache: Unknown Error

Problem

Gacutil gives an error: "Failure adding assembly to the cache: Unknown Error" when adding assembly to the cache

Solution

Each version of .Net Framework contains own gacutil. If you are trying to add .net 2.0 assembly to the cache you must use .net Framework 2.0 gacutil, not 1.1 or 3.0 gacutil.

You can also manually copy assembly file to the cache. Cache is located at Windows\Assembly

Tuesday, October 28, 2008

Biztalk 2006: How to use Biztalk message in C# code

Problem

How to use a Biztalk message in C# code

Solution

1. Add reference to Microsoft.XLANGs.BaseTypes.dll which is inside Biztalk installation directory
2. Add using Microsoft.XLANGs.BaseTypes; to your class
3. Declare variable like this: XLANGMessage BiztalkMessage