Search This Blog

Wednesday, April 20, 2011

C# SMILE.NET; SMILE.Network; SetNodeDefinition(); CPT; Conditional Probability Table

The order of probabilities is given by considering the state of the first parent of the node as the most significant coordinate (thinking of the coordinates in terms of bits), then the second parent, and so on, and finally considering the coordinate of the node itself as the least significant one.

The order of CPT depends on the order of adding nodes and arcs, as well as the order of defining states.

            net.AddNode(Network.NodeType.Cpt, "R");
            net.SetOutcomeId("R", 0, "T");
            net.SetOutcomeId("R", 1, "F");
            net.AddNode(Network.NodeType.Cpt, "C");
            net.SetOutcomeId("C", 0, "T");
            net.SetOutcomeId("C", 1, "F");
            net.AddNode(Network.NodeType.Cpt, "Hr");
            net.AddArc("R", "Hr");
            net.AddArc("C", "Hr");

So T is the first state; R is the first parent and C is the second parent. Here we have T state = 1; F state = 0;

node itself (Hr) first parent (R) second parent (C)
1 1 1
0 1 1
1 1 0
0 1 0
1 0 1
0 0 1
1 0 0
0 0 0

Tuesday, April 19, 2011

Flex downloading data of type ‘Date’ from DB to DataGrid; null value problem; null value is automatically converted to current_date instead of empty string;

The problem occurs while downloading data from DB into Flex’s DataGrid. If we have a Date column and it’s filled with null values, these values will automatically get the current date (time) value in the process of conversion (when new Date() object is created). To avoid this we can override labelFunction in DataGrid and prevent current_data values from being displayed.

In the DataGridColumn add labelFunction:

<mx:DataGridColumn headerText="STOPDATE" dataField="STOPDATE" labelFunction="removeNullValuesLabelFunction"/>

Define removeNullValuesLabelFunction in main <mx:Script>:

public function removeNullValuesLabelFunction(item:Object, column:DataGridColumn):String
            {
                var currentDate:Date = new Date();
                var nmbrOfSeconds:int = 3;
                currentDate.setTime( currentDate.time - ( nmbrOfSeconds * 1000 ) );
                if (item.STOPDATE > currentDate)
                {
                    return "";
                }
                else
                {
                    return String(item.STOPDATE);
                }
            }

Wednesday, April 13, 2011

C# sending mail with embedded image; Image content id; System.Net.Mail.MailMessage; C# embedding image in attachment into HTML email

What we want to do is send an email with embedded image. The email is of course in HTML format. What DID not work for me is:

- setting mail body type to HTML, adding attachment of png format and content id set to ID_IMAGE  and using <img src=”cid:ID_IMAGE”>

I did it in a different way:

You can define AlternateView and add LinkedResource to it of type = “image/png”. Then define image’s content id and transfer encoding type. This solution does not prevent you from adding different attachments as well.

 

using System.Net.Mail;
using System.Net.Mime;

string subject = "some subject";
string body += "<img alt=\"\" src=\"@@IMAGE@@\">" + "<br/>";

MailMessage mMailMessage = new MailMessage();
mMailMessage.From = new MailAddress(from);
mMailMessage.To.Add(new MailAddress(to));
//mMailMessage.Bcc.Add(new MailAddress(bcc));
//mMailMessage.CC.Add(new MailAddress(cc));
mMailMessage.Subject = subject;
mMailMessage.Body = body;
mMailMessage.Priority = MailPriority.Normal;

//you can add another attachments as well
//Attachment log_attachment = new Attachment(Program._LOG_FILE_LOCALISATION, MediaTypeNames.Text.Plain);
//mMailMessage.Attachments.Add(log_attachment);

string contentID = Path.GetFileName(Program._VL_LOGO_LOCALISATION).Replace(".", "") + "@domain";
body = body.Replace("@@IMAGE@@", "cid:" + contentID);

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
LinkedResource imagelink = new LinkedResource(Program._VL_LOGO_LOCALISATION, "image/png");
imagelink.ContentId = contentID;
imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imagelink);
mMailMessage.AlternateViews.Add(htmlView);

SmtpClient mSmtpClient = new SmtpClient();
mSmtpClient.Host = "127.0.0.1";
mSmtpClient.Send(mMailMessage);
return true;


 

Tuesday, April 12, 2011

C# get the actual executable directory (not the current working directory); C# get any source class directory;

Getting the actual executable directory comes handy when you need to execute the program remotely (e.g. from STAF). The execution directory is then different than the actual executable (*.exe) location. With the tricks below you need to create a *.log file near the (*.exe) file:

 

Console.WriteLine(Application.StartupPath);
Console.WriteLine(Path.GetDirectoryName(Application.ExecutablePath));
Console.WriteLine(Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Program)).CodeBase));
Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().Location);
Console.WriteLine(System.IO.Path.GetDirectoryName(Application.ExecutablePath));

These all return the actual executable directory path.

Friday, April 8, 2011

Flex Downloading data from database; mx.rpc.AsyncToken result object; Flex No data in AsyncToken.result field. Flashbuilder downloading data from database using RPC calls

When you use a service connected to db’s methods (get data from db) in flex you have to use rpc calls to get the data. When you just fire service.getSth() method it will return an AsyncToken object with nothing in AsyncToken.result field.

One way is to do something like this:

            var resultObj:AsyncToken;
            var responder:AsyncResponder = new AsyncResponder( resultHandlerAddInfo, faultHandlerAddInfo );
            //resultObj = testService.getTestIDForSpecLogId(int(logIDForViewingAddInfo));
            resultObj = testService.getAdditionalInfoForSpecLogId(int(logIDForViewingAddInfo));
            resultObj.addResponder( responder );
               
               
               
            public function resultHandlerAddInfo( event:ResultEvent, token:Object=null ):void
            {
                //Alert.show( "RESULT: "+ event.result as String );
                var rpcRes:String = event.result as String;
                FlexGlobals.topLevelApplication.viewLogAddInfoVar.addInfoTextArea.text = rpcRes;
            }
           
            public function faultHandlerAddInfo( event:FaultEvent, token:Object=null ):void
            {
                Alert.show( "FAULT: " + event.fault.message );
            }

Source.

Monday, April 4, 2011

Flex DataGrid get current row in ItemRenderer; Flex DataGrid disable specific cell; Flex DataGrid set visible = false for button in specific row

The problem can be described as follows:

We have an ItemRenderer with a Button inside (Column in DataGrid with buttons doing something). We want these buttons to be visible/invisible depending on a specific column value in a row. DataGrid’s dataProvider is a database (mysql).

All we have to do to achieve this behavior is to extend ItemRenderer and override its function set data(value:Object):void;

Source can be downloaded here.

Create new ActionScript class (File->New->Action Script class):

package
{
    import mx.collections.IList;
    import mx.controls.DataGrid;
    import mx.controls.Label;
    import mx.controls.dataGridClasses.DataGridListData;
    import mx.controls.listClasses.BaseListData;
    import mx.controls.listClasses.ListBase;
   
    import spark.components.supportClasses.ItemRenderer;
   
   
    public class RowNumberItemRenderer extends mx.controls.dataGridClasses.MXDataGridItemRenderer
    {
        public var rowNumberFromItemRenderer;
       
        public function RowNumberItemRenderer()
        {
            super();
        }
       
        override public function set data(value:Object):void
        {
            super.data = value;
           
            rowNumberFromItemRenderer = String(IList(ListBase(listData.owner).dataProvider).getItemIndex(data));           
        }
    }
}

 

Change your ItemRenderer type to local:RowNumberItemRenderer;

 

<?xml version="1.0" encoding="utf-8"?>
<local:RowNumberItemRenderer xmlns:fx="
http://ns.adobe.com/mxml/2009"
                          xmlns:s="library://ns.adobe.com/flex/spark"
                          xmlns:mx="library://ns.adobe.com/flex/mx"
                          xmlns:local="*"
                          focusEnabled="true" width="70" height="20" initialize="mxdatagriditemrenderer1_initializeHandler(event)" alpha="0.75" toolTip="Force test to end here">

    <fx:Script>
        <![CDATA[
            import mx.controls.*;
            import mx.controls.Alert;
            import mx.controls.DataGrid;
            import mx.controls.dataGridClasses.DataGridListData;
            import mx.controls.listClasses.ListBase;
            import mx.core.Application;
            import mx.core.FlexGlobals;
            import mx.core.UIComponent;
            import mx.effects.*;
            import mx.events.EffectEvent;
            import mx.events.FlexEvent;
            import mx.utils.OnDemandEventDispatcher;
            import mx.utils.object_proxy;
           
            import services.testservice.TestService;
           
            public var buttonEndTest:spark.components.Button = null;
           
            protected function button1_clickHandler(event:MouseEvent):void
            {
                //not relevant here
            }
           
           
            protected function getDataGrid()
            {
                if (FlexGlobals.topLevelApplication.tabNavigator.selectedIndex == 1)
                { //today's tests
                    return FlexGlobals.topLevelApplication.dataGrid_todaysTests;   
                }
                else //running tests
                {
                    return FlexGlobals.topLevelApplication.dataGrid;
                }
            }
           
            protected function getDataProvider()
            {
                if (FlexGlobals.topLevelApplication.tabNavigator.selectedIndex == 1)
                { //today's tests
                    return FlexGlobals.topLevelApplication.dataGrid_todaysTests.dataProvider;   
                }
                else //running tests
                {
                    return FlexGlobals.topLevelApplication.dataGrid.dataProvider;
                }
            }

            protected function mxdatagriditemrenderer1_initializeHandler(event:FlexEvent):void
            {
                //not relevant here
            }

            protected function button1_creationCompleteHandler(event:FlexEvent):void
            {
                var buttonFromEvent:spark.components.Button = event.target as spark.components.Button;
                buttonEndTest = buttonFromEvent;
               
                var row_index_current:int = -1;
                row_index_current = int(rowNumberFromItemRenderer);
               
                //dataGrid is the id (name) of our dataGrid table
                var dataGrid = getDataGrid();
                var dataProvider = getDataProvider();
                var item = null;
                item = dataProvider.getItemAt(row_index_current);
                var testSTATUS = item.STATUS;
                if (testSTATUS == -1)
                {//failed
                    buttonFromEvent.visible = false;
                }
                else if (testSTATUS == 1)
                {//ok
                    buttonFromEvent.visible = false;
                }
                else
                {//running
                    //buttonFromEvent.visible = false;
                }  
            }

        ]]>
    </fx:Script>

    <mx:HBox>
        <s:Button x="8" y="-1" label="End test" click="button1_clickHandler(event)" fontWeight="bold" alpha="1" creationComplete="button1_creationCompleteHandler(event)"/>
    </mx:HBox>
</local:RowNumberItemRenderer>