Friday, January 28, 2011

dsPICPRO4::PIC30F6014A::mikroC::Lcd Demo Code

The following code (mikroC) is the working code on MCU PIC30F6014A on the dsPICPRO4 development board:

sbit Lcd_D4 at LATD4_bit;
sbit Lcd_D5 at LATD5_bit;
sbit Lcd_D6 at LATD6_bit;
sbit Lcd_D7 at LATD7_bit;
sbit Lcd_RS at LATB4_bit;
sbit Lcd_EN at LATB6_bit;

sbit LCD_D4_DIRECTION at TRISD4_bit;
sbit LCD_D5_DIRECTION at TRISD5_bit;
sbit LCD_D6_DIRECTION at TRISD6_bit;
sbit LCD_D7_Direction at TRISD7_bit;
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB6_bit;

int MyLcdOutLen=0;
int MyLcdOutIdx=0;

void My_Lcd_Out(int row, int col, char* message)
{
 MyLcdOutLen=strlen(message);
 for(MyLcdOutIdx=0; MyLcdOutIdx != MyLcdOutLen; ++MyLcdOutIdx)
 {
  Lcd_Chr(row, col+MyLcdOutIdx, message[MyLcdOutIdx]);
 }
}

char text[6]="Hello";

void main() {
     Lcd_Init();
     Lcd_Cmd(_LCD_CLEAR);
     Lcd_Cmd(_LCD_CURSOR_OFF);
    
     My_Lcd_Out(1, 3, text);
     //Lcd_Out(1, 3, "HelloWorld"); //this line is not working
}

Interestingly the Lcd_Out and the Lcd Custom library is not working on the demo version of the mikroC IDE.

Saturday, January 15, 2011

When running the UltraDev Cassini Server explorer, you may run into errors with message such as "Name cannot begin with the '<' character, hexadecimal value 0x3C. Line 5, position 6.", to solve this problem, add the line

<trust level="Full" />

to the <System.Web> section of the web.config located in the Cassini Server explorer directory (e.g. C:\Program Files\UltiDev\Cassini Web Server Explorer), and rerun the explorer

The current trust level does not allow use of the 'debug' attribute

When testing your webservice, you might encounter an "The current trust level does not allow use of the 'debug' attribute" error, to solve the problem open the web.config file and add/change the trust level as follows:
<system.web>  
   <trust level="Full"/>
</system.web>

Finally, rebuild the project.

Automatically discover the com port for smslib

One of the challenging task in smslib is to detect the gsm device has been attached to which usb port as the port name is required during the smslib server initialization.

The manual way to find out the port is "Device Manager" panel of your Windows OS, and double click the item under "Modems" category, the com port name can be found in the "Modem" tab of the popup properties page.

The automatic way must allows the user to determine which port as there might be more than one gsm devices attached. therefore the function should return a set of possible candidate port names. this can be done by downloading the Wmi package from http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx which can be used to discover hardware settings in your machine. The following are the C# code that uses Wmi and SerialPort interface from C# to automatically discover the com port for smslib in C#:


            using System.IO.Ports;
            using baileysoft.Wmi;

            string[] port_names = SerialPort.GetPortNames();
            List<string> possible_ports = new List<string>();

            Connection.ApplicationPath = Application.StartupPath;
            Connection wmiConnection = new Connection();
          
            Win32_POTSModem x = new Win32_POTSModem(wmiConnection);

            foreach (string property in x.GetPropertyValues())
            {
                int split_index = property.IndexOf(": ");
                string property_name = property.Substring(0, split_index);
                string property_value = property.Substring(split_index+2);
                if (property_name == "AttachedTo")
                {
                    foreach (string port_name in port_names)
                    {
                        if (port_name == property_value)
                        {
                            possible_ports.Add(property_value);
                            break;
                        }
                    }
            }

In the above code, the possible ports returns the list of possible ports that might have the gsm devices attached.

Friday, January 14, 2011

System.Resources.MissingManifestResourceException" error message

Today i encountered this nusty error message when i was doing refactoring of my C# project in which i downgrade the original vs2010 project to vs2005 project and separate the project into a class project and a winform project. During the design time the winform partial class code its designer partial class code does not appear under the same subtree in the vs2005 explorer view. and after compile and build, the application runs into this error when run in debug mode. The problem is due to i create a folder and copy the code over from the original project within the vs2005. This problem is finally solved by creating the folder, then copy the codes manually from the original project folder, then select from the menu "Project->Show All Files", now the folder created will show up in the vs2005 explorer viewer, right-click the folder and select "Include in the Project". Now the winform partial class code will automatically attached with the designer partial class code and the error message will go away.

Wednesday, January 12, 2011

Multiple subreport appear even when they don't have any data

In my case, i have five subreports, each from a different business object list. Due to the initial mass-up, one business object dataset is copied into the rdlc subreport of the other 4. As a result, when this particular subreport has data, the other 4 subreport showed up as well even though they don't have data. The problem is solved by removing that particular object's dataset from the other 4 subreports

"A data source instance has not been supplied for the data source" exception w/ Report Viewer Control

This exception occurs in a number of scenarios, in my case, it pop up because i forgot to add this line before the refresh of the reportviewer in the form load event trigger:

 this.[data source name].DataSource = [data object];

where [data source name] is the data source object created and the [data object] is the business object that talks to the database to retrieve the relevant data for report display

Tuesday, January 11, 2011

Create and Send Xml in php

To create and send xml in php, the php code looks like this:

<?php

        // Start XML file, create parent node
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $node = $doc->createElement("rootnode");
        $parnode = $doc->appendChild($node);
        
        $node = $doc->createElement("childnode");
        $newnode = $parnode->appendChild($node);

        $newnode->setAttribute("description", "Some Description Text");
        $xmlfile = $doc->saveXML();
        header("Content-type: text/xml");
        echo $xmlfile;
?>

Singleton in php

The following php code create a Singleton class call "DataManager":


class DataManager
{
    // Hold an instance of the class
    private static $mInstance;

    // A private constructor; prevents direct creation of object
    private function __construct()
    {
      
    }

    // The singleton method
    public static function getSingleton()
    {
        if (!isset(self::$mInstance)) {
            $c = __CLASS__;
            self::$mInstance = new $c;
        }

        return self::$mInstance;
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }
  
    public function doSomething()
    {
    }

}

To call the doSomething() function of the DataManager singleton, using the following code
DataManager::getSingleton()->doSomething()

php date in mysql

To create a datetime field in mysql database, create a DATETIME fieldtype, e.g.
the sql "CREATE TABLE [tablename] id INT NOT NULL AUTO_INCREMENT PRIMARY KEY , last_updated DATETIME NOT NULL" will create a autoincrement primary key "id" and a DATETIME field "last_updated"

To insert a datetime into the above table from php, the php code looks like:
"INSERT INTO [tablename] (last_updated) value (\"".date("Y-m-d H:i:s")."\");" where date("Y-m-d H:i:s") is the php statement that gets the current date format.

Enable jScrollPane working with jquery TabControl

If a <div> element "scroll-pane" which requires to be rendered using jScrollPane is within another <div> element "tabs" rendered with jquery ui TabControl, it is necessary to call jScrollPane() method on the "scroll-pane" after "tabs" calls its tabs() method by calling $("#scroll-pane").jScrollPane() in "tabs" onShow event trigger. The jquery code look likes this:

 $(function(){
                    $( "#tabs" ).tabs({
                     show: function(event, ui) 
                     {
                        $("#scroll-pane").jScrollPane();
                     }
                    });                    
            });

Add Google Earth to your Google Map

Here is the javascript code that bind to a <div> element "map" for displaying the google earth 3d view on google map:


var map=new GMap2(document.getElementById("map"));
map.addMapType(G_SATELLITE_3D_MAP);

Sunday, January 9, 2011

Delete a folder in Qt

This code snippet allows programmer to delete a folder in Qt

#include <QDir>

void deleteDir(const std::string& foldername)
{

  QDir dir;
  dir.rmdir(foldername.c_str());
}

List directories in Qt

This code snippet allows programmer to list directories in a parent directory "C:\temp" by using Qt API

#include <QDir>

void list(QStringList& dirnames)
{

         QDir currentDir("C:\\temp");

currentDir.setFilter(QDir::Dirs);
QStringList entries = currentDir.entryList();
for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry )
{
//std::cout << *entry << std::endl;
QString dirname=*entry;
if(dirname != tr(".") && dirname != tr(".."))
{
dirnames.add(dirname);
}
}
}

Thursday, January 6, 2011

Report Samples and Object Data Source Setting in RDL report

How to set the external file path for an image used in RDL report

  1. add an "image" element to the rdlc report created, set its "Source" property to "External" and its "MIMEType" property to "image/png" if the image file is a png
  2. drag a data field into the "image" element, this data field will contains the [filepath] of the image file, the filepath should be something looks like "file:///C:/temp/image.png" or "file:///c:\\temp\\image.png"
  3. add a reportviewer named rpv to the winform, and in the winform constructor code, add "rpv.LocalReport.EnableExternalImages = true;"

How to embed subreports in a RDL report

  1. Create reports Main.rdlc and Sub1.rdlc, Sub2.rdlc, Main.rdlc will be the main report and Sub1.rdlc and Sub2.rdlc will be the subreports embedded into Main.rdlc, 
  2. add two "Subreport" elements to the Main.rdlc, with each element's reportname field set to "Sub1.rdlc" and "Sub2.rdlc" respectively,
  3. create a winform and add a reportviewer to it, set the report for the reportviewer to be "Main.rdlc", name the reportviewer rpv
  4. open "View Code" on the winform, and in the constructor add "rpv.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);"
  5. add a method "void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)" to the winform code, now create two List<Object> for each subreport in the method, and add "e.DataSources.Add(new ReportDataSource("Accounting_Core_Purchase_MiscPurchaseLine", [List<Object>]));" for each subreport

Tuesday, January 4, 2011

Solving the problem about the autoshrinking of report viewer table

The solution is to put the table in a rectangle element http://stackoverflow.com/questions/1255267/resizing-rdl-report-inside-reportviewer-control-in-asp-net

Get ReportViewer.dll for asp.net deployment

for asp.net that use reportviewer control, during deployment the reportviewer.dll must be copied into the "bin" directory. To do this follow these steps:


  1. open console, and type "cd c:\windows\assembly"
  2. type "cd gac_msil"
  3. type "xcopy microsoft.reportviewer.processingObjectModel c:\temp /i /h /s /r /y"
that's it. you get the reportviewer.dll copied into c:\temp, just copy them into the "bin" directory of your asp.net project

Monday, January 3, 2011

The procedure entry point _Z5qFreePv could not be located in the dynamic link library qtCore4.dll

To remove the issues with release build issue error "The procedure entry point _Z5qFreePv could not be located in the dynamic link library qtCore4.dll":
  1. Track down the source of the dll using depends.exe (downloadable from http://www.dependencywalker.com/)
    • Source of Problem 1: debug version of an app exe compiled and opened fine, release version of same app would compile fine but exe failed due to "entry point" in dll failure. There are some old QtCore and QtGui dll's in System32 directory.
    • Solution 1: The release version was referencing these dll's. I removed them.
    • Source of Problem 2: the QtCore.dll referenced is pointed to "C:\Qt\2009.02\bin" instead of "C:\Qt\2009.02\qt\bin"
    • Solution 2: remove "C:\Qt\2009.02\bin" from the path environmental variables

Totally remove Symbian SDK for Qt to use its make

The "make" error is quite annoying when you previously install Symbian SDK and now want to use Qt for build as the make tool will be set to that of  Symbian SDK instead of the Qt make. To remove the problem of "make" with the previous installation of symbian SDK:
  1. go to the global environmental variables
  2. go to the system variables, remove "C:\Program Files\Common Files\Symbians\Tools\..." from the "Path" variable

Print to console in Qt

To print to console in Qt
  1. write the code the usual console output way, e.g. "std::cout << ...", Note that any QString object must be quoted inside "qPrintable" function, e.g. "std::cout << qPrintable(QString("hello")) << .."
  2. enter "qmake -project"
  3. add "CONFIG += console" to the xxx.pro file
  4. enter "qmake"
  5. enter "make"

Sqlite in Qt

To connect to the Sqlite database in Qt
  1. add "#include "
  2. add "QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE")" in the code body
  3. enter "qmake -project"
  4. add "QT += sql" in the xxx.pro file
  5. enter "qmake"
  6. enter "make"

Regular Expression Replacement in Visual Studio

Text replacement in visual studio using Regular Expression can be very handy during refactoring in large projects.

E.g. to find "new DoubleFieldEntry(Convert.ToString(_obj.[Text to Keep]));" and replace with "new DoubleFieldEntry(_obj.[Text to Keep]);"

The find regular expression is "new DoubleFieldEntry\(Convert.ToString\({_obj.*}\)\);" and the replace regular expression "new DoubleFieldEntry\(\1\);"


The above replacement in the figure replaces codes in the current project such as "new IntFieldEntry(Convert.ToString(_obj.SaleID))" to "new IntFieldEntry(_obj.SaleID)"