Tuesday, April 24, 2012

ASP.NET - A FileUpload inside an UpdatePanel problem solved

The explaining of this problem is quite simple, though it took me plenty of time to solve. The FileUpload control requires a full PostBack for the file loading. (I hope everyone knows that UpdatePanel is a partial Postback)
Two things have to be done to cause a full PostBack:
A. Register the control that triggers the form submitting as a full PostBack trigger of the update panel.
B. Assign the enctype specification of the form containing the UpdatePanel.



<form id="form1" runat="server" enctype="multipart/form-data">
<asp:UpdatePanel runat="server" ID="my_update_panel" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="btn_submit_form" />
</Triggers>
       <ContentTemplate>
              <asp:FileUpload ID="file_upload_01" runat="server" />
              <asp:Button ID="btn_submit_form" runat="server" onclick="do_on_submit_form" />
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

Enjoy!

C# making string's first letter UpperCase


    public static string first_Char_To_Upper(string input)
    {
        input = input.ToLower();
        return input.First().ToString().ToUpper() + String.Join("", input.Skip(1));
    }

Sunday, April 22, 2012

ASP.NET bypassing validation on Cancel button

If we have a form with required field validations, how do we add a "Cancel" control without having our validation controls get triggered? 
Very simple: we need to set the CauseValidation parameter to False. That's it.

<asp:LinkButton ID="lnkbtn_cancel_form" runat="server" Text="Cancel" CausesValidation="False"></asp:LinkButton>

Enjoy!

Friday, April 20, 2012

SQL - Querying the data using a non-English clause

Seems that the system by default is not set to read or write Unicode Characters even though the declaration of the column is NVARCHAR.


This query returns nothing (Russian clause in this case):
SELECT * FROM MY_TABLE WHERE RUS_COLUMN = 'ФПГ'


Also this INSERT will only store question marks in the DB:
INSERT INTO MY_TABLE (MY_COLUMN) VALUES ('ФПГ')



In order to solve this issue all that has to be done is adding a N character just before the non-English Expression:
SELECT * FROM MY_TABLE WHERE RUS_COLUMN = N'ФПГ'
INSERT INTO MY_TABLE (MY_COLUMN) VALUES (N'ФПГ')


Enjoy!



Wednesday, April 18, 2012

ASP.NET AJAX - Invalid postback or callback argument

Sometimes when we have "web-serviced" control or some AJAX partial postbacks on the page, the events might be prevented from validation because the result is unexpected. MSDN quote about this issue like this:
Control registers its events during rendering and then validates the events during postback or callback handling. For example, if a list control includes options numbered 1, 2, or 3 when the page is rendered, and if a postback request is received specifying option number 4, ASP.NET raises an exception. All event-driven controls in ASP.NET use this feature by default.


Actually all that has to be done is to add this line either in the web.config file:



<pages validateRequest="false" enableEventValidation="false"></pages>



Or this line on any desired page:



<asp:Page EnableEventValidation="False" />




Enjoy!





C#: Loop through DataRowView in DataView

It could be a bit different than looping through rows in DataTable, yet it's working just fine:



    public string[] get_Cities(string param)
    {

        DataView dv = new DataView((System.Data.DataTable)Application["cached_data_table"], "column_x = '" + param + "'", "sort_column", DataViewRowState.CurrentRows);

        foreach (DataRowView dr in dv)
        {
            list_cities.Add(dr["city_name"].ToString()); 
        }

        return list_cities.ToArray();



Enjoy!

Tuesday, April 17, 2012

AJAX - Cascading DropDown List WebSerive database binding

Everything's great with official ASP.NET tutorials and videos concerning the Cascading DropDown Lists... they just forgot to mention one important thing without you will get am WebMethod Error 500. - is to uncomment one line in the asmx file (Marked in Yellow):



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using AjaxControlToolkit;
using System.Data;

/// <summary>
/// Summary description for new_ad_service
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class new_ad_service : System.Web.Services.WebService {

    public new_ad_service ()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public CascadingDropDownNameValue[] get_Data()
    {
        List<CascadingDropDownNameValue> my_list = new List<CascadingDropDownNameValue>();

        DataTable dt = DAL.get_provinces(); //gets DataTable from SQL server db
        foreach (DataRow dr in dt.Rows)
        {
            my_list.Add(new CascadingDropDownNameValue(dr[0].ToString(), dr[0].ToString()));
        }
        return my_list.ToArray();
    }
}

Enjoy!

Friday, April 13, 2012

JavaScript - Disabling the TAB key on page

Yep, sometimes you want to disable the TAB key on your web page, for example if you want to eliminate that orange frame there is when the user "selects" images or links.
That's the way it works:

    <%--disabling the "Tab" key on page--%>
    <script type="text/javascript">               
        function cancelKey(e) {
            var e = (window.event) ? event : e;
            if (e.keyCode == 9) { // Tab
                if (window.event) {
                    window.event.returnValue = false;
                    }
                else {
                    if (e.cancelable) { e.preventDefault(); }
                        }
                    }
                }
                document.onkeydown = cancelKey;
    </script>



Cheers!

ASP.NET/AJAX LinkButton in ListView inside UpdatePanel causes full PostBack

If you have a LinkButton in ListView within the UpdatePanel - clicking the LinkButton will cause Postback of the entire page. The solution is quite simple - in web.config we need to add:

<system.web>
    <pages clientIDMode="AutoID"></pages>
</system.web>

That's it, enjoy the partial PostBack the way Bill Gates intended! :)

Monday, April 9, 2012

JavaScript: protect web pages content

There's always an option to save the html/aspx/php page via browser options, however not every average user awares of this feature, so we at least can try and disable some basic web page features, including text selection and/or mouse right-click.



    <%--disables text select--%>
    <script type="text/javascript">
        function disableselect(e) {
            return false
        }
        function reEnable() {
            return true
        }
        //if IE4+
        document.onselectstart = new Function("return false")
        //if NS6
        if (window.sidebar) {
            document.onmousedown = disableselect
            document.onclick = reEnable
        }
    </script>

    <%--disables mouse right-click--%>
    <script type="text/javascript">
    var message = "Sorry, right-click has been disabled";

    function clickIE() { if (document.all) { (message); return false; } }
    function clickNS(e) {
        if
    (document.layers || (document.getElementById && !document.all)) {
            if (e.which == 2 || e.which == 3) { (message); return false; }
        }
    }
    if (document.layers)
    { document.captureEvents(Event.MOUSEDOWN); document.onmousedown = clickNS; }
    else { document.onmouseup = clickNS; document.oncontextmenu = clickIE; }
    document.oncontextmenu = new Function("return false")
    </script>