Latest Entries »

Saturday, May 21, 2011

jQuery find function $.find('selector') versus traditional selecting $('selector')

Comming soon.

Saturday, April 9, 2011

SelectedIndexChanged doesn't fire with autopostback true in ASP.NET in List Control

Rarely when developing application in ASP.NET you stuck on any ListControl and AutoPostBack="true" and SelectedIndexChanged won't trigger. Even when server receive postback your control don't response at all.

Today I will show and explain the problem: duplicate values inside ListItem.

RatioButtonList example

Now let imagine we have that piece of code:



        protected void rblShippingMethods_IndexChanged(object sender, EventArgs e)
        {
            //This action is always performed when user change item in RadioButtonList Control
            do_rblShippingMethods_IndexChanged();
        }

Let imagine that our datasource produce something like that. In this scenario we have shipping method as text and shipping method price as value for RadioButtonList :

        
        
        


Nothing complicated and this will work almost everytime.

houston we have a problem!


But when we have ListControl with Binding from any datasource it may happen that one or more ListItem can have the same value.When that situation happen rblShippingMethods_IndexChanged won't trigger.



        
        
        
        
        



I'm really confused when I wrote a solution for this case because event is connected with Index not Value inside ListControl. But nothing is perfect.

Don't panic!

What to do when two or more ListItem have the same value? Maybe ask end user to put diffrent values in user form! Oh no really it's dummy thought! We make our users happy and everything will work as always.

First thing we need to observe is fact the PostBack is send to server. Breakpoint was hit. But not the SelectedIndexChanged.

Think, think, think... BINGO

So when we found that server receive request we have to find which control causes the postback to our server. We can do it with
//Return full ClientID of postback source. So we can find the name of control and index
//For example:
//control = ctl00$MainContent$wizSubmitOrder$rblShippingMethods$0
//control = ctl00$MainContent$wizSubmitOrder$rblShippingMethods$1
//control = ctl00$MainContent$wizSubmitOrder$rblShippingMethods$2
String control = Request["__EVENTTARGET"];
We can see that only last part after $ sign is changing. That is our SelectedIndex!
So we can put this piece of code inside Page_Load:
if (Page.IsPostBack)
{
    rblShippingMethods_CustomMethodIndexChanged();
}
protected void rblShippingMethods_CustomMethodIndexChanged()
{
    String control = Request["__EVENTTARGET"];
    String args = Request["__EVENTARGUMENT"];
    if (control != null)
    {
        if (control.Contains("rblShippingMethods"))
        {
            String selectedIndex = control.Substring(control.LastIndexOf("$") + 1);
            int si = 0;
            if (int.TryParse(selectedIndex, out si))
            {
                //We manually chage selectedIndex and then we call
                //the same method when normally rblShippingMethods_IndexChanged event
                //would occur
                rblShippingMethods.SelectedIndex = si;
                do_rblShippingMethods_IndexChanged();
            }
        }
    }
}

Tuesday, April 5, 2011

java insert and read image from mysql

Sometimes it may happen that we need to store a picture in some database table (MYSQL). At the beginning you should to create a table that will store our image data. Pictures and other binary files is kept in a BLOB data type inside table column. For this purpose we need to crate table.

CREATE TABLE IF NOT EXISTS `Images` (
  `ImageId` int(11) NOT NULL AUTO_INCREMENT,
  `Description` varchar(150) COLLATE utf8_polish_ci NOT NULL DEFAULT '-',
  `ImageData` blob NOT NULL,
  PRIMARY KEY (`ImageId`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci

And now to manipulate the database we use two methods:

    //Insert Image
    public void InsertImage(String description,FileInputStream fotos);
    //read image from table with specific id
    public  BufferedImage getMySqlPhoto(int ImageId);

public  BufferedImage getMySqlPhoto(int ImageId){
        BufferedImage BI = null;
        Statement S;
        ResultSet rs;
        String sqlStatement = "SELECT ImageData FROM Images WHERE ImageId = '"+ImageId+"'";
        try {
            S = con.createStatement();
            rs = S.executeQuery(sqlStatement);
            if (rs.next()){
                Blob image = rs.getBlob("ImageData");
                InputStream input = image.getBinaryStream();
                BI=ImageIO.read(input);
                // set read buffer size
                input.close();
            }
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return BI;
    }
    public void InsertIntoZdjecie(String Description,FileInputStream fotos)
    {
        String INSERT = "INSERT INTO Images(Description,ImageData) VALUES (?,?)";
        System.out.println(INSERT);
        PreparedStatement ps1;

        try {
            ps1 = con.prepareStatement(INSERT);
            ps1.setString(1, Description);
            ps1.setBinaryStream(2, fotos);
            ps1.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
            
        }
    }

Isn't it cute ? :-)

Wednesday, March 23, 2011

Android Candlestick Chart with Google Chart API

Good morning. Today I would like to share with other how to create CandleStick Chart with little support of Google Chart API.

Browsing around the web I hadn't found any good open source library for charting in android which directly support Candlestick Chart so I decided to use online solution based on HTTP GET/POST.

So let's start our sourvey.

First we need to take a look closer to Google Chart API. For this tutorial I will use simple basic text format to put series data inside HTTP GET request to get image I want to.
There is one thing which sadden me.
Basic text-formatted data lets you specify floating point values from 0—100, inclusive, as numbers. Values below zero are marked as missing; values above 100 are truncated to 100.

Preparing Chart Data

In most cases our data is larger than 100 and it would be stupid to have truncated all data. For this reason we need to do some scaling. Scaling will make all data suitable for requirements.
/**
     * This method transform any Double[] series to suitable series accepted by
     * Google Chart API
     */
    public static ArrayList<integer[]> transformChartSeries(ArrayList<double[]> input) {
        ArrayList<integer[]> scaledInput = new ArrayList<integer[]>();
        //Getting scale between minimum and maximum value from input series
        double scaleRatio = getScaleRatio(Min(input), Max(input));
        for (int i = 0; i &lt; input.size(); i++) {
            scaledInput.add(scale(input.get(i), scaleRatio));
            displayArray(scaledInput.get(i));
        }
        return scaledInput;
    }

    private static double Max(ArrayList<double[]> arr) {
        ArrayList<double> tmp = new ArrayList<double>();
        for (int i = 0; i &lt; arr.size(); i++) {
            tmp.add(Max(arr.get(i)));
        }
        return Collections.max(tmp);
    }

    private static double Max(Double[] input) {
        return Collections.max(Arrays.asList(input));
    }

    private static double Min(ArrayList<double[]> arr) {
        ArrayList<double> tmp = new ArrayList<double>();
        for (int i = 0; i &lt; arr.size(); i++) {
            tmp.add(Min(arr.get(i)));
        }
        return Collections.min(tmp);
    }

    private static double Min(Double[] input) {
        return Collections.min(Arrays.asList(input));
    }

    private static double getScaleRatio(double min, double max) {
        double ratio = 0;
        //Dividing value. You can manipulate this parameter to get 
        //smaller or bigger chart.
        int div = 80;
        ratio = (max - min) / div;
        return ratio;
    }
    private static Integer[] scale(Double[] input, double ratio) {
        Integer[] scaledData = new Integer[input.length];
        for (int i = 0; i &lt; input.length; i++) {
            scaledData[i] = new Integer((int) Math.round(input[i] / ratio));
        }
        return scaledData;
    }

Preparing Chart

Now when we finished data transformation we can create CandleStick Chart with Google Chart API :-) We will use cht=lc (Line Chart) as scaffolding for CandleStick Chart. Whole trick with line chart is that we will hide series data with chd:t0 parameter and next we will display CandleSticks with chm=F (CandleStick Markers). In chm=F link you have full documentation of markers.
public Intent execute(Context context) {
        Double[] _1st = CandleStickChart.generateRandomArray(seriesCount);
        Double[] _2nd = CandleStickChart.incrementArray(_1st, 1000d);
        Double[] _3rd = CandleStickChart.incrementArray(_1st, 2000d);
        Double[] _4th = CandleStickChart.incrementArray(_1st, 3000d);
        ArrayList<double[]> series = new ArrayList<double[]>();
        series.add(_1st);
        series.add(_2nd);
        series.add(_3rd);
        series.add(_4th);

        String abc = createCandleStickChart(series);
        Uri uri = Uri.parse(abc);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        return intent;
        // TODO Auto-generated method stub
    }

private String createCandleStickChart(ArrayList<double[]> dataSeries) {
        ArrayList<integer[]> chd = transformChartSeries(dataSeries);
        StringBuilder sbChart = new StringBuilder();
        //Four series data
        StringBuilder sb1 = new StringBuilder("-1,");
        StringBuilder sb2 = new StringBuilder("-1,");
        StringBuilder sb3 = new StringBuilder("-1,");
        StringBuilder sb4 = new StringBuilder("-1,");
        //Axis Labels
        StringBuilder axis = new StringBuilder("&amp;chl=");
        for (int i = 0; i &lt; chd.get(0).length; i++) {
            sb1.append((chd.get(0)[i]) + ",");
            sb2.append((chd.get(1)[i]) + ",");
            sb3.append((chd.get(2)[i]) + ",");
            sb4.append((chd.get(3)[i]) + ",");
            axis.append(i + "|");
        }

        sb1.append("-1|");
        sb2.append("-1|");
        sb3.append("-1|");
        sb4.append("-1");
        sbChart.append("https://chart.googleapis.com/chart?");//API URL
        sbChart.append("chs=800x200&amp;");//Chart Size
        sbChart.append("cht=lc&amp;chm=F,0000FF,0,,10&amp;");//CandleStick marker
        sbChart.append("chxt=y&amp;");//Visible axis: Left y-axis
        sbChart.append("chd=t0:");//Chart Data t0 - all series are hidden
        String chdd = sbChart.toString() + sb1.toString() + sb2.toString() + sb3.toString() + sb4.toString() + axis.toString();
        System.out.println(chdd);
     
     return chdd;
 }

Final result

Code above use Intent.ACTION_VIEW to open WebActivity for display generated image from Google Chart API

Source Code

You can download Charting Demo application from
here

Wednesday, March 16, 2011

Check/uncheck checkbox in table (GridView) with jQuery. Modern way.

Few moments ago I found a really preety and simple way to check/unckeck all input:checkbox inside GridView(table) column. I was really shocked!
And so you code:

.aspx
<asp:GridView ID="CmpJobOfferCandidatesGv" runat="server" AutoGenerateColumns="False"
 CssClass="EntityGridView">
 <Columns>
 <asp:TemplateField>
 <HeaderTemplate>
  <asp:CheckBox runat="server" ID="checkAllChb" />
 </HeaderTemplate>
  <ItemTemplate>
   <asp:CheckBox runat="server" ID="inviteToExamChb" style="width:20px;margin:0 auto;display:block;" />
  </ItemTemplate>
 </asp:TemplateField>
  <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="25px" />
 </Columns>
</asp:GridView>

.js
var chbClickEvent = function () {
    $('table[id*="CmpJobOfferCandidatesGv"] tr > td input:checkbox').each(function (index, Element) {
        $(this).trigger("click");
    })
}
$(document).ready(function () {
    $('input:checkbox[id*="checkAllChb"]').click(chbClickEvent);
});
                    

The magic above is caused because I trigger click event foreach checkbox in GridView Column instead of dealing with bunch of if statements to figure out state of checkbox.

$(document).ready(function () {
    $('input:checkbox[id*="checkAllChb"]').click(function () {
        $('table[id*="CmpJobOfferCandidatesGv"] tr > td input:checkbox').each(function (index, Element) {
            if ($(Element).attr('checked') == false) {
                $(Element).attr('checked', true);
            } else {
                $(Element).attr('checked', false);
            }
        });
    });
});