Monday, May 04, 2009

Notes ASP do tNet

NotesASPdotNet


Contents
=========

Tutorial
Structure
ASP.Net Configuration
Connecting Events
HTML Control Class
Web / Server Control Class
ASP postback - eg like AJAX

ADO.Net - Accessing Data the Easy Way
ADO.Net - Example 
ADO.Net - command parameters
ADO.Net - Data Binding
ADO.Net - Data Binding - DataList
ADO.Net - Styles and Templates summary
Windows Service Applications
VS Setup Projects
Understanding ADO.Net - from AppDev video tutorial
Using MySQL in Visual Studio 
Configuring MySQL with ASP.Net
DropDownList
DataGrid - Sorting
WebService in ASP.Net
ASP.Net Custom Control


Tutorial
=========
1. Visual Studio 2005 -> Help -> Contents -> .Net Development
-> Web Applications -> ASP.Net Quickstart Tutorials


Structure
===========

System.Web.UI - Generic Page Class
    |
V
custom page class (my *.cs file, eg HelloClass.cs)
    |
V
custom aspx file (my *.aspx file, eg Hello.aspx)
    |
V
Page object


System.Web.HttpApplication 
    |
V
class GlobalApp (global.cs)
    |
V
global.asax   -> contain event handling code, each application can have one global.asax.


The classes are linked together like this:

VS2005: Global.asax no longer created automatically but can be added by:
Add new item -> Global Application Class.
Also the code behind global.asax.cs is no longer created, instead put the code inline in global.asax

Hello.aspx
-----------
<%@ Page Language="CS" Inherits="HelloClass" Src="HelloClass.cs" %> - if source is supplied
<%@ Page Language="CS" Inherits="HelloClass"  %> - if dll is supplied
<html>
<body>
<form id="Form" runat="server">
    <asp:Label id="lblTest" runat="server" />
</form>
....

HelloClass.cs
--------------
public class HelloClass : System.Web.UI.Page {
   protected System.Web.UI.WebControls.Label lblTest;

   private void Page_Load(){
      lblTest.Text = "Hello World";
   }
}

some basic event available to global.asax inherited from HttpApplication:
Application_OnStart
Application_OnEnd
Application_OnBeginRequest
Application_OnEndRequest
Application_OnError
Session_OnStart
Session_OnEnd

ASP.Net Configuration
======================
1. machine.config  - one per server, located at:
Microsoft.Net/Framework/Version/Config/

2. web.config - one per application, as well as one in each virtual sub-directory.

3. Structure and contents of web.config
+++++++++++++
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<!-- custome settings - using your own keyword -->
<appSettings>
<add key="ConnectionString" value="Data Source=localhost;Initial Catalog=Pubs;User ID=sa"/>
<add key="SelectSales" value="Select * FROM Sales"/>
</appSettings>

<system.web>
<httpRuntime />
<pages />
<compilation />
<customErrors />
<authentication />
<authorization />
<identity />
<trace />
<sessionState />
<httpHandlers />
<httpModules />
<globalization />
</system.web>

</configuration>
+++++++++++++

4. To make use of the special custom settings, eg.
++++++++++
using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project
{
    public partial class ShowCustomConfigSettings : System.Web.UI.Page
    {
        protected Label lblTest;
        protected void Page_Load(object sender, EventArgs e)
        {
            lblTest.Text = "This app will connect with the connection string <br><br>";
            lblTest.Text += ConfigurationSettings.AppSettings["ConnectionString"];
            lblTest.Text += "<br><br> and will execute the SQL statement <br>";
            lblTest.Text += ConfigurationSettings.AppSettings["SelectSales"];
        }
    }
}
++++++++++


Connecting Events
===================
case: A button called id="Convert" on the aspx page. Functionality is in the function called
"Convert_ServerClick"

On the aspx page, have the attribute in the <%@Page .... >
AutoEventWireup="false"

To connect the function "Convert_ServerClick" to the event:
1.     protected override void OnInit(EventArgs e)        {
            InitializeComponent();
            base.OnInit(e);
        }

2.      private void InitializeComponent() { 
            Convert.ServerClick += new EventHandler(Convert_ServerClick);
        }

Note that EventHandler is a DELEGATE that connects a the function "Convert_ServerClick" 
The EventHandler delegate would have the same prototype of the function it points to, ie.:
        protected void Convert_ServerClick(Object sender, EventArgs e)

The ServerClick would be a type of the EventHandler delegate; perhaps
        public event EventHandler ServerClick
perhaps defined under the Convert's class - HtmlInputButton

HTML Control Class
=======================
System.Object
System.Web.UI.Controls
    HtmlControl   ---> System.Web.UI.HtmlControls namespace
    HtmlImage
HtmlInputControl
    HtmlInputButton
HtmlInputCheckBox
                HtmlInputFile
HtmlInputHidden
HtmlInputImage
HtmlInputRadioButton
HtmlInputText
HtmlContainerControl
                HtmlAnchor
HtmlButton
HtmlForm
HtmlGenericControl
HtmlSelect
HtmlTable
HtmlTableCell
HtmlTableRow
HtmlTextArea

Web / Server Control Class
============================
System.Object
System.Web.UI.Controls    
         Repeater         ---> System.Web.UI.WebControls
WebControl
     AdRotator
Calendar
ValidationSummary
BaseDataList (abstract)
    DataGrid
DataList
ListControl  (abstract)
    CheckBoxList
DropDownList
ListBox
RadioButtonList
     Button
CheckBox
    RadioButton
Hyperlink
Image
    ImageButton
     Label
    BaseValidator   (abstract)
    CompareValidator
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator
LinkButton
Panel
Table
TableCell
    TableHeaderCell
     TableRow
TextBox

ASP postback - eg like AJAX
============================
1. Web control events that can use POSTBACK, when AutoPostBack property is set
to true:
Events                Web Control
=======               ===========================
Click                 Button, ImageButton
TextChange            TextBox
CheckChanged          CheckBox, RadioButton
SelectedIndexChange   DropDownList, ListBox, CheckBoxList, RadioButtonList
   
2. ASP.Net automatically adds these to the HTML page:
<input type="hidden" name="__EVENTTARGET" value=""/>
<input type="hidden" name="__EVENTARGUMENT" value=""/>
<script language="javascript">
<!--
   function __doPostBack(eventTarget, eventArgument){
      var theform = document.Form1;
  theform.__EVENTTARGET.value = eventTarget;
  theform.__EVENTARGUMENT.value = eventArgument;
  theform.submit();
   }
-->
3. Add event handlers to the InitializeComponent() method
i.e.  <button>.<Event> += new EventHandler(<functionName>)
eg    txt.TextChanged += new  EventHandler(CtrlChanged)

4. Implement using the added function:
private void CtrlChanged(Object sender, EventArgs e) {    }


ADO.Net - Accessing Data the Easy Way
=============================
To retrieve information
1. Create Connection, Command and DataReader objects
2. Use DataReader to retrieve info and display it on web
3. Close connection.
4. Send page to user.

To add or update information
1. Create new Connection and Command objects.
2. Execute the Command

ADO.Net - Example 
=========
using System.Data; 
using System.Data.SqlClient;  // for MS SQL
using System.Data.OleDb;      // for general connector

// Define the connection to Database
<x>={Sql, OleDb, ...}
<x>Connection myConn = new <x>Connection();
myConn.ConnectionString = "Provider=SQLOLEDB.1; Data Source=localhost;" + " Initial Catalog=Pubs; User ID=root";
  // the provider is need when <x>=OleDb, but not when <x>=Sql.
  // Password is not passed here if using "Integrated Windows Authentication"
myConn.ConnectionString = "Provider=SQLOLEDB.1; Data Source=localhost;" + " Initial Catalog=Pubs; Integrated Security=SSPI";

// Making the connection
try{
   myConn.Open();
   lblInfo.Text="<b>Server Version: </b>" + myConn.ServerVersion;
   lblInfo.Text+="<br><b> Connection is:</b> " + myConn.State.ToString();
} catch(Exception err) {
lblInfo.Text = "Error reading the database.";
lblInfo.Text += err.Message;
} finally {
    myConn.Close();
lblInfo.Text += "<br> Now Connection is";
lblInfo.Text += myConn.State.ToString();
}

//Alternative connection
using{
   myConn.Open();
   lblInfo.Text="<b>Server Version: </b>" + myConn.ServerVersion;
   lblInfo.Text+="<br><b> Connection is:</b> " + myConn.State.ToString();
}
lblInfo.Text += "<br> Now Connection is";
lblInfo.Text += myConn.State.ToString();

// Creating the SQL statement and assigning to Command
<x>Command myCmd = new <x>Command();
myCmd.Connection = myConn;
myCmd.CommandText = "Select * from Authors";
//Alternative
<x>Command myCmd = new <x>Command("Select * from Authors", myConn);

// Using Command with DataReader
<x>DataReader myReader;
myReader = myCmd.ExecuteReader();

// Reading objects
myReader.Read();      // reads an object at a time sequentially

// Cleanup
myReader.Close();
myConn.Close();

ADO.Net - command parameters
==============================
Instead of using this:
  insertSQL "Insert INTO authors (au_id) VALUES ('txtID.Text')"
.... where txtID is a from the GUI on the webpage.

This method can be hacked via SQL Injection. To solve this, Command Parameters are used:
  insertSQL "Insert INTO authors (au_id) VALUES (?)"
  cmd.Parameters.Add("?", txtID.Text);

where cmd is a OleDBCommand, and note that "?" is for OleDB only.
MySQL or MSSQL may have different symbols or notation for their command parameters.


ADO.Net - Data Binding
=======================
Simple Data Binding:
1) in the aspx page, have something like:
<asp:Label id="lbLabel" runat="server">
   There were <%# TransactionCount %>
</asp:Label>
2) In the code behind, have something like:
private void Page_Load(...){
   TransactionCount = 10;
   this.DataBind();

Alternative to data bind above is to do this in-code.
3) private void Page_Load(...){
      TransactionCount = 10;
      lblDynamic.Text = "There were " + TransactionCount.ToString();

Multiple Binding:
1. Form an array list from whereever:
   eg. ArrayList fruit = new ArrayList(); 
       fruit.Add("Kiwi");  
   or from database
2. Define binding for list controls; eg
   MyListBox.DataSource = fruit;
   MyDropDownListBox.DataSource = fruit;
   MyHTMLSelect.DataSource = fruit;
   MyCheckBoxList.DataSource = fruit;
   MyRadioButtonList.DataSource = fruit;
3. Activate the binding, eg.
   this.DataBind();        // this refers to the current page.


Multiple Binding with hashtables:
1. Create hashtable with key,val pair
   Hashtable fruit = new Hashtable();
   fruit.Add(1, "Kiwi");
   fruit.Add(2, "Pear");
2. Binding specific fields
   MyListBox.DataTextField = "Value"  -> put the Value of hastable into the Text of the Control
   MyListBox.DataValueField = "Key"  -> put the Key of hastable into the value of the Control
3. Define databinding and activate
   MyListBox.DataSource = fruit;
4. The result is the following HTML will be rendered:
   <select name="MyListBox" id="MyListBox">
      <option value="1">Kiwi</option>

Databinding with databases:
1. Some possible namespaces (when using OleDB):
   using System.Data;
   using System.Data.OleDb;
2. Making data using dataset example:
   DataSet ds = new DataSet();
   ds.Tables.Add("Users");
   ds.Tables["Users"].Columns.Add("Name");
   ds.Tables["Users"].Columns.Add("Country");
   DataRow dr = ds.Tables["Users"].NewRow();
   dr["Name"] = "John";
   dr["Country"] = "Uganda";
   ds.Tables["Users"].Rows.Add(rd);
3. Bind table to data source:
   lstUser.DataSource = ds.Tables["Users"];
   lstUser.DataTextField = "Name";
or Bind whole DataSet to data source:
   lstUser.DataSource = ds;
   lstUser.DataMember = "Users";
   lstUser.DataTextField = "Name";
4. Activate the Binding:
   this.DataBind();
or to bind just the list box
   lstItems.DataBind()

ADO.Net - Data Binding - DataList
=====================================
1. Code Behind:
   public class BasicAuthorList: Page
   {
protected DataList listAuthor;
// (Initialisation code omitted)
private string connectString ="Provider ......."

private void Page_Load(Object sender, EventArgs e)
{
string SQL = "SELECT * FROM AUTHORS";
OleDbConnection con = new OleDbConnection (connectString);
OleDbCommand cmd = new OleDbCommand(SQL, con);
OleDbAdapter adapt = new OleDbAdapter(cmd);
DataSet pubs = new DataSet();
con.Open();
adapter.Fill(pubs, "Authors");
con.Close();

//Bind the DataSet and activate the data bindings for the page
listAuthor.DataSource = pubs.Tables["Authors"];
this.DataBind();

2. ASPX DataList template 
   <asp:DataList id=listAuthor runat="server">
      <ItemTemplate>
      <font face="Verdana" size="2">
          <b><%# DataBinder.Eval(Container.DataItem, "au_fname") %>
  <%# DataBinder.Eval(Container.DataItem, "au_lname") %></b></font>
  <br> Address: <%# DataBinder.Eval(Container.DataItem, "address") %>
  <br> City: <%# DataBinder.Eval(Container.DataItem, "city") %>
  </font>
   </ItemTemplate>
   </asp:DataList>

3. Formating Values - for DataBinder
eg    DataBinder.Eval(Container.DataItem, "Price", "{0:C}")
{0:C}    Currency
{0:E}    Scientific (Exponential)
{0:P}    Percentage
{0:F?}   Fixed Decimal
see MSDN Help for more.

4. Adding different styles to Templates
a) Manual option - hand coding on aspx file
  <HeaderTemplate>
     <h2> title </h2>
  </HeaderTemplate>
  <ItemTemplate>
     (Item style1)
  </ItemTemplate>
  <AlternatingItemTemplate>
       (Item style2)
  </AlternatingItemTemplate>
  <SeparatorTemplate>
     <h2> title </h2>
  </SeparatorTemplate>
  <FooterTemplate>
     <h2> title </h2>
  </FooterTemplate>

b) Using VS.Net right-click DataList properties

c) AutoFormat link from the DataList properties

d) To make columns and rows, check out the RepeatDirection and RepeatColumns properties.


ADO.Net - Data Binding - DataGrid
=====================================
1) DataList may have columns and rows, but DataGrid has columns such that the columns
correspond to certain fields of the data item; eg phone - city - zip code as different
columns. 

2) Features include: automatic paging, sorting, editing, selecting.

3) Examples that show the Columns tag and the use of styles:
<asp: DataGrid id=gridauthor runat="server" AutoGenerateColumns="false"
BorderColor="#..." BorderStyle="None" CellSpacing="2"
BackColor="#..." CellPadding="3" BorderWidth="1px">

    <FooterStyle ForeColor="#..."  BackColor="#..." ></FooterStyle>
    <HeaderStyle ForeColor="#..."  BackColor="#..." ></HeaderStyle>
    <ItemStyle ForeColor="#..."  BackColor="#..." ></ItemStyle>

<Columns>
<asp:TemplateColumn HeaderText="AuthorName">
          <ItemTemplate>
              <%# DataBinder.Eval(Container.DataItem, "au_fname") %>
      <%# DataBinder.Eval(Container.DataItem, "au_lname") %>
      </ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

4) DataGrid has special columns including:
TemplateColumn - contents here include <ItemTemplate> and other stuff that can go into
                 DataList.
BoundColumn - a particular field from database
ButtonColumn
EditCommandColumn
HyperlinkColumn

All these columns should exist within <Columns> ... </Columns>


ADO.Net - Data Binding - Repeater
=====================================
Repeater has not much formatting by itself. It depends on formatting provided
in the html. Example:
<asp:Repeater id=repeatauthor runat="server">
    <HeaderTemplate> <table> </HeaderStyle>
    <ItemTemplate><tr>
          <%# DataBinder.Eval(Container.DataItem, "au_fname") %>
</ttr></ItemTemplate>
    <FooterTemplate> </table> </FooterStyle>
</asp:DataGrid>



ADO.Net - Styles and Templates summary
=======================================
Styles 
DataList             DataGrid             Repeater
-----------------------------------------------------------
AlternatingItemStyle AlternatingItemStyle None
EditItemStyle         EditItemStyle 
FooterStyle             FooterStyle 
HeaderStyle             HeaderStyle 
ItemStyle             ItemStyle 
SelectedItemStyle     SelectedItemStyle 
SeparatorStyle         PagerStyle 


Template 
DataList             DataGrid*         Repeater
-----------------------------------------------------------
AlternatingItemTemplate FooterTemplate     AlternatingItemTemplate
EditItemTemplate     HeaderTemplate     FooterTemplate
FooterTemplate         ItemTemplate     ItemTemplate
HeaderTemplate         EditItemTemplate SeparatorTemplate
ItemTemplate 
SelectedItemTemplate 
SeparatorTemplate 

* only supported by Template column

1) Do not bind the grid in the Page.Load event handler, otherwise info is
   lost about which button user clicked or item selected.

   private void Page_Load......
       if(!this.PostBack) {
          DataSet ds = GetDataSet();
  BindGrid(ds);
  .........
   }

   private DataSet GetDataSet(){
       string SQL = "...."
   OldDbConnection ...
   OldDbCommand cmd = 
   OleDbAdapter = ...
   DataSet dsPubs = ...
   adapter.Fill(dsPubs, "Authors");
   con.Close();
   return dsPubs;
    }

private void BindGrid(DataSet ds){
       gridAuthor.DataSource = ds.Table["Authors"];
       this.DataBind();
}


Windows Service Applications
=============================
1. Do not have any in/output to screen or Windows, or it will crash the app.

2. Error messages should be logged in the Windows event log rather than raised in the user interface. 

3. To control, use Services Control Manager, or Server Explorer, or the ServiceController class (use this 
to control the service from another app).

4. States of the service include: start, stop, pause, resume
   Corresponding methods in code: OnStart, OnStop, OnPause, OnContinue, OnShutdown, OnCustomCommand, OnPowerEvent.

5. Two types of services: Win32OwnProcess, Win32ShareProcess.

6. VisualStudio has installation components that can install resources, register the service and let Services Controller
Manager know. Add these installers to the app and also create a separate setup project.

7. Must inherit from System.ServiceProcess.ServiceBase class. The project must contain installation components.
   To create the Service:
      - set ServiceName property
  - create installers
  - override methods for OnStart and OnStop.

8. System.ServiceProcess.ServiceProcessInstaller and System.ServiceProcess.ServiceInstaller 
?You use these classes to install and uninstall your service. 

9. Execution Process:
  Add Installers in project
      Build
      Install: installutil yourproject.exe    / Uninstall: installutil /u yourproject.exe
  Start the Service

10. Debugging:
      Install service
  Start service
  In VS, Debug->Process
  Click Show System Processes
  Attach process
  add any break points
  use Services Control Manager to control the service.

11. To add Installers:
      -In Solution Explorer, go to Design View of the service.
  -Click on background of designer and AddInstaller.
      -A new class, ProjectInstaller, and two installation components, ServiceProcessInstaller and ServiceInstaller, 
  are added to your project, and property values for the service are copied to the components. 
      -Click the ServiceInstaller component and verify that the value of the ServiceName property is set to the 
  same value as the ServiceName property on the service itself. 
      -To determine how your service will be started, click the ServiceInstaller component and set the StartType property 
  to the appropriate value. { Manual, Automatic, Disabled }
      - To determine the security context in which your service will run, click the ServiceProcessInstaller 
  component and set the appropriate property values. For more information, see How to: Specify the Security Context for Services.
      - Override any methods for which you need to perform custom processing. For more information, see How to: Override Default Methods on Installation Components.
      - Perform steps 1 through 7 for each additional service in your project. 
        Note: For each additional service in your project, you must add an additional ServiceInstaller component 
to the project's ProjectInstaller class. The ServiceProcessInstaller component added in step 
three works with all of the individual service installers in the project. 
      - Create your setup project and custom action to deploy and install your service. 
  For more information on setup projects, see Setup Projects. 
  - After you add installers to your application, the next step is to create a setup project that will install 
  the compiled project files and run the installers needed to install your service. To create a complete 
  setup project, you must add the service project's output to the setup project and 
  then add a custom action to have your service installed. For more information on setup projects, see Setup Projects. For more information on custom actions, see Walkthrough: Creating a Custom Action.
      (see VS Setup Projects for more details)


VS Setup Projects
=====================
1. Design, code, build your project in VS Studio say project ProjA in solution SolnA.
2. Create the setup project SetupA, in SolnA: Add Project -> New Project -> Other Project Types -> Setup and Deployment.
3. Right click setupA -> Install -> Add Project Output. Select ProjA and choose "Primary Output".
4. Right click setupA -> View -> Custom Actions.
5. Right click on Custom Actions -> Add Custom Option. Select Application Folder -> Primary output from ProjA.
6. Build.
7. The msi and exe file will be created. 


Understanding ADO.Net - from AppDev video tutorial
====================================================
Object Model:
   Connected Object (Specific to DB engine or provider)
   -> .Net Data Provider (incl. MySql.Data.MySqlClient or SystemData.ODBC|OleDB|SqlClient|OracleClient)
         -> Connection: Transaction
         -> Command: Parameters (eg to execute some command)
         -> DataReader:
         -> DataAdapter:
            -> Fills DataTable: SelectComm
            -> Updates Database: InsertComm, UpdateComm, DeleteComm
   DisConnected Object (can work with data in a disconnected state)         
   -> DataSet (analogous to Database) <-> XML
         -> DataTableCollection
-> DataTable:
   -> DataRowCollection - storing the data
   -> DataColumnCollection - names and properties of columns
   -> ConstraintCollection - eg unique key or foreign key constraints.
         -> DataRelationCollection
   -> DataView
      -> Row Filter
      -> Sort
      -> Extended support for Data Binnding
   -> DataTableReader
      -> A DataReader for DataTables and DataSets
      -> Fast forward only reading
      -> resilient to adding or deleting rows while reading     
    
  
... to be continued at Data Caching Object
         
Using MySQL in Visual Studio 
=============================
1. View -> Server Explorer
2. Look for database server and connect
         
Configuring MySQL with ASP.Net
===============================
It is easy to use MySQL with ASP.Net. becasue by default the local ASP.Net enables you with FULL TRUST permission.
This section shows how to configure ASP.Net to work with MySQL where the ASP.Net is stored in a ISP's server,
which usually uses MEDIUM TRUST, not FULL TRUST.

To the SQL administrator:
1. There are two options, one is to modify the web_mediumtrust.config; the other option is to copy and rename the config file.
The web_mediumtrust.config is located typically in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\ 
Add the SOCKPermission to this file.

<SecurityClass ............. 
<SecurityClass Name="SocketPermission" Description="System.Net.SocketPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> 
... 
... 
<IPermission 
class="SocketPermission" 
version="1" 
Unrestricted="true"/> 

2. If we choose the second option in step 1. to make a new file and called web_mediumMySQLtrust.config, then we need
to register this in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config with the following line:

<trustLevel name="Medium" policyFile="web_mediumtrust.config" />         .... already there
<trustLevel name="MediumMySQL" policyFile="web_mediumMySQLtrust.config" />    .... add this new one

Also in the same file, add this within the <system.web>
<trust level="Medium" originUrl="" /> 
or 
<trust level="MediumMySQL" originUrl="" /> 


To the Developer:
1. In the web application, in the web.config file, insert the line about <trust> just before </system.web>
eg.
    <system.web>
        ......
        ......
        <trust level="Medium" originUrl="" />
    </system.web>

         
DropDownList
============
To add first element, add a ListItem and the property AppendDataBoundItems set to true.
Eg.
<asp:dropdownlist id="suburbDropList"  AppendDataBoundItems="true" AutoPostBack="True" runat="server" >
    <asp:ListItem Text="(Select a Suburb)" Value="" />
</asp:dropdownlist>

DataGrid - Sorting
===================
To allow for sorting on the DataGrid, the following are needed.
1. Right click on the GUI design of the DataGrid and set "AllowSorting" to "true".
2. Add the following in the aspx code file in the DataGrid item:
   OnPageIndexChanging="PageChangeFunction" OnSorting="SortingFunction"
3. Set property AutoGenerateColumns to true, i.e.TestMenu.AutoGenerateColumns = true;   


WebService in ASP.Net
======================

*.asmx      - web service file
WSDL        - Web Service Description Language, describes the methods and parameters in a web service.
              The elements of WSDL are: definitions, types, message, portType, binding, service.
SOAP        - way to encode info to pass to web service
HTTP        - protocol through which SOAP messages are sent
DISCO       - discovery standard that contains links to web services
UDDI        - business registry that lists all info about companies and web services they provide, with
              URLs for their WSDL contracts and DISCO.

Data types: Basic / primitives, Enumerations, DataSets, XmlNode, Custom Objects, Arrays


Testing the web service
------------------------
http://<domain>/<webservice>.asmx      -> to view the web service directly
http://<domain>/<webservice>.asmx?WSDL -> to view the WSDL.
http://<domain>/<webservice>.asmx?op=<methodName>      -> to access the web service method directly



The use of web services in C# ASP.Net is illustrated with the example below:
----------------------------------
1.<%@ WebService Language="C#" Class="Util" %>
2. using System.Web.Services;
3. using System;
4. [WebService(Namespace="http://www.contoso.com/")]
5. public class Util: WebService 
6. {
7.     [ WebMethod]
8.     public long Multiply(int a, int b) 
9.     {
10.         return a * b;
11.     }
12. }
----------------------------------
or
----------------------------------
in file: Util.asmx
1.«%@ WebService Language="C#" CodeBehind="Util.asmx.cs" Class="Util" %»

in file: Util.asmx.cs
2. using System.Web.Services;
3. using System;
4. [WebService(Namespace="http://www.contoso.com/", Description="test utility")]
5. public class Util: WebService 
6. {
7.     [WebMethod(Description=" test a method "]
8.     public long Multiply(int a, int b) 
9.     {
10.         return a * b;
11.     }
12. }
----------------------------------

1. Declare the webservice using «%@ WebService....
Option 1: Place the above code inside *.asmx file with the C# code.
Option 2: Put only the <%@ WebService in the asmx class and put the C# code somewhere else.
Then the declaration would be:
     <%@ WebService Language="C#" Class="MyName.MyWebService,MyAssembly" %>
... where MyAssembly is the name of the assembly.

2. Deriving the WebService class - this is optional. Lines 2,5.

3. Apply WebService attribute and specify domain to avoid confusion with other webservices.
   see line 4.

4. Define the web service method using [ WebMethod ] - see line 7.

5. State Management for Web Services is achived by deriving from the WebService class. It provides 
   access to ASP.NET objects such as:
   Session     - client specific state information
   Application - used to store data globally and available to all clients
   Server      - utility functions
   User        - info about current client including authentication
   Context     - provides access to Request, Response and Cache

7. Storing and access state in a client session:
   Declare: [ WebMethod(EnableSession=true) ]
   Store:   Session["MyServiceUsage"] = 1;
   Access:  Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;

8. Storing and access state in Web application hosting the Web service:
   Declare: [ WebMethod ]
   Store:   Application["appMyServiceUsage"] = 1;
   Access:  Application["appMyServiceUsage"] =  ((int) Application["appMyServiceUsage"]) + 1;


ASP.Net Custom Control
=======================
The following describes Custom Control for web applications (*.aspx). The Custom Control for console
applications are similar, but not exactly.

1. To add a user control, right click on the web application project in the Solution Explorer. Click
New Item, then choose Web User Control, and name it WUC.


2. In Visual Studio, this will auto create 3 files:
   - WUC.ascx - with Design and Code view
   - WUC.ascx.cs - the code to be edited or added.
   - WUC.ascx.designer.cs 

3. Put the collection of controls in your custom control withing the WUC.ascx file. For example,
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WUC.ascx.cs" 
Inherits="ParentWebApp.WUC" %>
<asp:Label ID="lblFooter" runat="server" Height="87px" Text="Label" Width="214px"></asp:Label>

4. The Label control above can be also created by using the WUC.ascx design view. Just
drag the Label button from the toolbox onto the form.

5. In the code behind file WUC.ascx.cs, make the WUC class inherit from System.Web.UI.UserControl. And 
in the Page_Load, enter code for what the controls need to do. For example, 

    public partial class WebUserControlFooter : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblFooter.Text = "This page was served at ";
            lblFooter.Text += DateTime.Now.ToString();
        }
    }

6. To use this custom control on any aspx web page:
a) Register the custom control on those aspx web pages, eg.
<%@ Register TagPrefix="cr" TagName="WUC" Src="~/WUC.ascx" %>
b)  Add the custom control, eg.
        <cr:WUC id=Footer1 runat="server" />

Note that the TagPrefix name is the alias for the custom control to be used in the aspx web page.

Saturday, May 02, 2009

How to connect Set Top Box

Connecting Set-Top box to TV and VHS/DVD Player
================================================
There are 3 hardware that need to be connected here.
i) TV set (analog, non-digital)
ii) Set top box (for receiving digital TV stations onto non-digital TV)
iii) VHS Recorder / DVD player combo.

Requirements - what we want:
i) To be able to view non-digital TV stations
ii) To be able to view digital tv stations
iii) To be able to use VHS recorder player to record both digital and non-digital stations.
iv) To be able to play DVD.

I am writing here to share my experience after I bought the set top box. I already had the TV and the VHS/DVD unit before. Basically, on top of the old functionalities, I wanted to view Digital TV as well as record it after I bought the set top box.

The connections are very simple once I figured it out - but initially, the instructions did not make much sense. Here is the KEY - the TV as well as the VHS/DVD units have multiple inputs for video signal known as AV1, AV2, etc. Once I understood this, everything became easy.

Connection TYpe: We will be using the 3 plug (RCA) Composite cables.
Red and White are for audio, Yellow is for the Video signal.

TV aerial:
i) Connect Wall Antenna to set top box (IN) with one TV cable.
ii) Connect the set top box (OUT) to the VHS/DVD unit (IN) with a second TV cable.

This is like chaining the antenna from wall to set top box to video recorder.

Set top box to VHS/DVD: connect this together via the composite cable (red-white-yellow plugs) from the output of the set top box to AV1 (input) of the VHS/DVD unit.

VHS/DVD to TV: Use a second set of composite cable to connect from the VHS/DVD unit (OUT) to an input on the TV set (eg another AV1).

What's Happening? Essentially the analog TV signal first goes to the set top box which converts to analog signal. From the set top box, the raw analog TV signal (analog TV channels) is re-transferred to the VHS player. The composite cable from set top box to VHS unit carries the digital TV channels.

Since the VHS/DVD player now has both analog and digital tv stations, the key to access both is that:
i) analog channels are accessed by switching the channels on the VHS/DVD unit.
ii) digiatal channels require the VHS/DVD unit to use AV1 or AV2 depending on which port you plug the 3 cables to the unit.
iii) the VHS can record both analog and digital channels.

VHS/DVD to TV: This requires one connection only using the 3plug composite cable. The signal from the VHS/DVD unit (OUT) to the TV (IN AV1, or IN AV2) can carry both analog and digital channels. So both analog and digital channels are available. Note that the AV1 or AV2 here belongs to the TV, and is different to the AV1 of the VHS/DVD unit. We must select AV1, or AV2, in order to get the signals from the VHS/DVD player.


Operating the Remote Controls
==============================
There are 3 remote controls, let's call them:
RC-STB for Set Top Box
RC-DVD for DVD
RC-TV for analog TV

The operation described works for the specific connections that I have described above. If you choose different connections, eg using AV2 instead of AV1, then you have to operate the Remote Control accordingly.

1. Switch on TV, DVD/VHS and Set Top Box in any order
2. Use RC-TV to select the TV's AV1 - never change this again.
3. For viewing or recording Digital TV signals (analog and digital from Set Top Box),
- use RC-DVD and select VHS in the VHS/DVD option buttons
- use RC-DVD and select A1 (stands for AV1)
- use RC-STB to flip through the digital channels and/or record to VHS tape.
4. For viewing or recording Analog TV signals (raw analog signal)
- use RC-DVD and flip through 1,2,3, etc..... and view and/or record to VHS tape.
- no need to use RC-STB at all here.

Monday, January 05, 2009

How to use Brook+ for GPU computing

AMD Stream Computing allows developers to use the GPU to perform parallel computations for HPC applications. This guide is meant to complement the AMD Stream Computing User Guide. It is essential to read the official User Guide to gain a brief understanding before following the notes below.

Ref: http://ati.amd.com/technology/streamcomputing/Stream_Computing_User_Guide.pdf

System - The following notes are compiled based on the following system.
Intel CPU
ATI Radeon (Check cards for GPU computing capability)
Microsoft Visual Studio .Net with C/C++ compilers - for C/C++ code
Intel Visual Fortran Compilers - for Fortran code
Brook+ SDK by AMD - to compile Brook code


br source file
================
The Brook+ source file contain code that follow C/C++ syntax and is compiled/pre-processed by the Brook+ compiler into C/C++ file. Both Brook+ functions and C/C++ functions can exist within the same *.br file. The Brook+ functions are the functions that utilises the GPU hardware.

Example of a Brook+ function is given below:
kernel void sumaa(float a<>, float b<>, out float c<>){
c = a + b;
}

1. Special Brook+ keywords (ie. Not C/C++ words): kernel, out
2. Note the template like structures "float a<>" which are recognized by the Brook+ compiler. They indicate stream / GPU data type and are not the same as C++ templates.
3. Multiple functions like the above can exist in the same *.br file. Other normal C/C++ functions can also exist inside the *.br file.


Compiling Brook+ Code (*.br)
=============================
0. Open up a Command Console and go to the directory where the *.br file is located.

1. To compile code called sum.br:
\sdk\bin\brcc_d -k sum.br
where is the installation directory of the Brook SDK from AMD.

2. This the brook+ compiler / preprocessor creates the following in the same directory.
sum.cpp
sum.h
sum_gpu.h

3. A few notes to consider
i) There are two compilers: brcc and brcc_d. They correspond to brook.lib/dll and brook_d.lib/dll respectively.
Using the wrong combination may crash the program during execution.
ii) The -k option generates intermediate code that may be useful for use with the AMD's Stream Kernel Analyzer.
iii) The C/C++ code that are generated need to be compiled using standard C/C++ compilers and link to the proper libraries and dlls, hence the next section.
iv) Before v1.3, C/C++ wrapper functions, also known as host side code, exist within the *.br source file. As of v1.3, the host side code can be written in C++ and exist in a separate normal C++ file, provided it is configured with the proper include and lib directory information.



Compiling the C/C++ code
==========================
This step produces a win32 DLL from the C/C++ code that are generated by Brook+. The resultant DLL should be
able to be used by other win32 applications (eg C++ or Fortran).

1. From Visual Studio .Net, Open a new solution / project by:
Add Project -> Visual C++ -> Win32 -> Win32 project.
In the Application Settings dialog, select DLL, Export Symbols

2. Add the *.br and the files generated by the Brook+ compiler into the current project by using
"Add existing file".

3. Under the Project Property configuration pages, add the following settings:
C++ -> Additional Include Directories: \sdk\include
C++ -> Code Generation -> Runtime Library: Multi-threaded Debug DLL (/MDd)
C++ -> Advanced -> Calling Convention: __cdecl (/Gd)
Linker -> Additional Library Directories: \sdk\lib
Linker -> Input -> Additional Dependencies: \sdk\lib\brook_d.lib

4. When the *.br is modified, compile the *.br files in Command Console, then compile the generated c/c++ code from within the VisualStudio.Net environment.

Some Notes:
i) One can configure VisualStudio.Net to accept *.br files and compile using the Brook+ compiler. However, I find
that it still requires the user to manually initiate compilation for Brook files and then for C/C++ files. Hence,
I don't find it to be any efficient than compiling by command line.
ii) The *.br source files can be added to the project and can be edited using the VS.Net environment.


The C/C++ driver or library wrapper
====================================
The Brook+ functions need to be wrapped or called directly from C/C++ functions. For the purpose of creating DLL functions, we will put C/C++ wrappers over the Brook+ functions.

The usage of the Brook+ functions involve 3 steps. Each of these step are described with examples here:

Declaring and sizing variables - the meaning and reason for the declarations will become clear in the following sections.
// Normal C/C++ variables
float input_a[10][10];
float input_b[10][10];
float input_c[10][10];
float input_a1[10];
float input_b1[10];
float input_c1[10];

// For dimensioning Brook+ variables
unsigned int ileng = 10;
unsigned int dims[2] = {10,10};
unsigned int dim1[1] = {10};

// Equivalent Brook+ variables
brook::Stream a(2, dims);
brook::Stream b(2, dims);
brook::Stream a1(1, dim1);
brook::Stream b1(1, dim1);
brook::Stream *c = new brook::Stream(1, &ileng);
brook::Stream *d = new brook::Stream(2, dims);
brook::Stream d1(1, dim1);


// Assign values to normal C/C++ vectors and matrices for:
// input_a1, input_b1, input_a, input_b
..................

1. Reading normal C/C++ variables into Brook+ variables
a.read(input_a);
b.read(input_b);
a1.read(input_a1);
b1.read(input_b1);
This step transforms a normal C/C++ variable into a Brook+ variable which the GPU can understand. No other manipulation need to be done to the Brook+ variable.

2. Performing the computation by calling the Brook+ function
sumaa(a,b,*d); // operating on a matrix
sumaa(a1,b1,d1); // operating on a vector

3. Writing the output from Brook+ into normal C/C++ variables
// old method
streamWrite(*d, input_c);
streamWrite(d1, input_c1);
// new method
d->write(input_c);
d1.write(input_c1);
Once the Brook+ variable has been copied back to a normal C/C++ variable, one can perform other standard operations to the normal C/C++ variable as desired.

Note the use of pointer d* and non-pointer d1 is just to show that both ways are possible.


Using with Fortran
====================
Brook+, being like an extension to C/C++, is better called from C/C++ functions. But, provided that C/C++ wrappers are built for the Brook+ functions and then packaged into a DLL library, then any other language, eg Fortran, can use the GPU by calling on the C/C++ wrappers in the DLL.
Brook+ functions <--- C/C+ wrappers <--- Windows DLL / Unix shared objects <--- Fortran

Wednesday, December 24, 2008

Using VB JoinView class in C# web application

JoinView is a class developed by Microsoft to address a feature that is lacking in ADO.Net, up to .Net framework 3.5. The main functionality is to provide something like a DataView for when two or more tables are joined via DataRelations. For more details, and the VB.Net source code, see
HOW TO: Implement a Custom DataView Class in Visual Basic .NET
http://support.microsoft.com/kb/325682

Using the VB JoinView class in a C# application is explained nicely at in the article:
Data From Multiple Tables in a DataGridView
http://www.onteorasoftware.net/post/Data-From-Multiple-Tables-in-a-DataGridView.aspx

However the article above does not explain how to actually make the VB code into a usable product, ie. a dll, so that it can be used in C#.
This blog explains how to construct the VB JoinView class into a dll and how to link it to a C# application.

1. Download the source file JoinView.vb from the first link above. The actual file to be downloaded is called JoinView.exe.

2. Assuming you are working in a C# project called Cproj, inside the solution called Soln. Then in the Soln solution, add a new VB project called JoinViewProj.

3. Manually copy the JOinView.vb file into the location of JoinViewProj.

4. In VisualStudio, use "Add Existing Item" to add the JoinView.vb file into the JoinViewProj project.

5. Build the JoinViewProj project.

6. Go to the Cproj project and add reference. Browse and locate the file JoinViewProj\bin\Debug\JoinView.dll and add this as the reference.

7. In the C# code add this statement: "using JoinViewProj;"

8. Now we are ready to use the JoinView class in our C# code. For example: "JoinView jv;"

The actual usage of the JoinView class is as follows:

ds.Relations.Add("CustOrd", ds.Tables["Cust"].Columns["CustomerID"], ds.Tables["Ord"].Columns["CustomerID"]);
ds.Relations.Add("EmpOrd", ds.Tables["Emp"].Columns["EmployeeID"], ds.Tables["Ord"].Columns["EmployeeID"]);
JoinView jv;
jv = new JoinView(ds.Tables["Ord"],
"OrderID,CustomerID,EmployeeID,OrderDate,CustOrd.CompanyName Company,CustOrd.ContactName Contact,CustOrd.ContactTitle Position,EmpOrd.FirstName,EmpOrd.LastName",
"OrderID='312'", "CustomerID DESC");

First argument: This appears to be the common child table in the two DataRelations.

Second argument: This is the names of the columns of the tables directly, such as "OrderID" which belongs to the "Ord" table. Other names like "CustOrd.CompanyName Company" comes from the Data Relation "CustOrd" and field "CompanyName"; and the name "Company" is an alias that will appear in the grid view.

Third argument: Filter the rows. In the example, only OrderID being 312 are selected. Note it appears taht the field, eg OrderID, must belong to the specified table, in this case, the "ord" table.

Fourth argument: Sort the rows in ASC or DESC order. In the example, it is sorted by CustomerID in a descending way. Note it appears the field, eg CustomerID, must belong to the specified table, in this case, the "ord" table.

Wednesday, December 03, 2008

Online Scanning websites and links for virus, malware, spyware

The content of this site has been moved to Online Scan - Websites
It contains links to online scanning tools to scan websites to check if websites are infected with trojans or malware.

Friday, August 22, 2008

Technical Links

Programming - Memory
Understanding Virtual Memory - http://www.ualberta.ca/CNS/RESEARCH/LinuxClusters/mem.html

Programming - Tips
How to Write Unmaintainable Code - Ensure a Job for life ;)
http://thc.org/root/phun/unmaintain.html


The hidden power of Google Earth
http://www.pcpro.co.uk/features/145593/the-hidden-power-of-google-earth.html
from PC Authority Mar 2008

Includes the following topics:

Peel back the layers
Make your own virtual tours
Share photos with the world
Reach for the stars
Take to the skies
Model your house in 3D
How Google Earth works


Boost your broadband speed for free
http://www.pcauthority.com.au/Feature/119238,boost-your-broadband-speed-for-free.aspx
from PC Authority Aug 2008


Web's Best 50 Free Downloads
Stack your system full of software without paying a penny, with our guide to essential downloads
from PC Authority June 2008

Wednesday, July 23, 2008

Callback to C# from Unmanaged Fortran

Using unmanaged code eg Fortran to callback to C# can be a nightmare to get right. But once you know it, it is just following a recipe. Hence without further explanation, an example and recipe is given below. It is quite self-expalnatory I hope.

Just note that, the example is more than a simple call back. The C# actually calls a Fortran function in a dll. Within the Fortran function calls the callback in C#.

--- Fortran code -----
module f90Callback

contains

subroutine func1(iArr, progressCllBak)
!DEC$ ATTRIBUTES DLLEXPORT ::func1
!DEC$ ATTRIBUTES REFERENCE :: iArr, progressCllBak
implicit none
external progressCllBak
integer :: iCB
integer, INTENT(OUT) :: iArr(2)

! Variables

! Body of f90Callback
print *, "Hello Before"
iCB = 3
iArr(1) = 5
iArr(2) = 7
call progressCllBak(iCB)
print *, "setting callback value in Fortran as :", iCB
print *, "Hello After"

return
end subroutine func1

end module f90Callback


------- C# code ---------

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace CScallbackDriver
{
class Program
{
// 0. Define a counter for the Progress callback to update
public int localCounter;

// 1. Define delegate type
[UnmanagedFunctionPointer(CallingConvention=CallingConvention.Cdecl)]
public delegate void dgateInt(ref int numYears);

// 2. Create a delegate variable
public dgateInt dg_progCB;


public Program() {
// 3. Instantiate delegate, typically in a Constructor of the class
dg_progCB = new dgateInt(onUpdateProgress);
}

// 4. Define the c# callback function
public void onUpdateProgress(ref int progCount) {
localCounter = progCount;
}

int iArg;
static void Main(string[] args)
{

Program myProg = new Program();
myProg.localCounter = 0;
int[] iArrB = new int[2];

//6. Call normal Fortran function from DLL, and passing the callback delegate
func1(ref iArrB[0], myProg.dg_progCB);


Console.WriteLine("Retrieve callback value as {0}", myProg.localCounter);
Console.ReadKey();
}

// 5. Define the dll interface
[DllImport("f90Callback", EntryPoint="F90CALLBACK_mp_FUNC1", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public static extern void func1([In, Out] ref int iArr, [MarshalAs(UnmanagedType.FunctionPtr)] dgateInt blah);




}
}

Sunday, July 13, 2008

Online Scan - AntiVirus

As with Firewalls, there should be at most, one Antivirus program running on your PC. More than that will cause uncertain behaviour. But how do we know that our antivirus is a good one. Or if we scan a file and it passed our antivirus scan, are we sure it is OK? One solution is to scan the file or files using online scanners available from the web. Here are a few of them:

http://housecall.trendmicro.com/
http://www.kaspersky.com/virusscanner
http://www.bitfender.com/scan8/ie.html
http://www.pandasecurity.com/homeusers/solutions/activescan
http://us.mcafee.com/root/mfs
http://onecare.live.com/site/en-US/default.htm
http://pestpatrol.com/
http://www.f-secure.com/en/web/labs_global/removal/online-scanner

Even easier is to upload one file and have it scanned by multiple antivirus software. This can be done at: http://www.virustotal.com/

Malware can be checked by submitted a file to this website:
http://malwr.com/about/

Alternatively, one can use a sandbox to test our suspicious applications first. Some of the sandbox are:
Norman Sandbox - www.norman.com/microsites/nsic

(this article can also be found at:
http://pckingsford.com//index.php?option=com_content&task=blogcategory&id=19&Itemid=39 )

Saturday, July 12, 2008

Firewall Testing (Hardening)

Here are some tools and techniques to test if your firewall is up to scratch:
1. www.pcflank.com
Contains various test for the firewall including: port scanners, stealth testing, leak test and others.
For leak test, download PCFlankLeaktest.exe. This test tries to send some information out of your PC to the PCFlank site. The results are shown in http://www.pcflank.com/pcflankleaktest_results.htm

. According to PCFlank, only Outpost Firewall Pro and Tiny Personal Firewall pass the leaktest. At PCKingsford, we have tried the FREE Comodo Firewall Pro (CFP) and this works. If it fails, you just need to be sure that you have not tell CFP to ALLOW it. To check whether an application is allowed in CFP, open up the CFP, go to the Defense+ on top, then go to the Advanced tab on the left menu, then click Computer Security Policy. Look for the application name and edit the rules for it.

2. ShieldsUp at http://www.grc.com/faq-shieldsup.htm
Click on Services tab on the website, then select ShieldsUp. Follow the instruction to test your firewall via this website. The tests include:
File Sharing
Common Ports
All Service Ports
Messenger Spam
Browser Helpers

3. Leaktest 1.2 at http://www.grc.com/lt/leaktest.htm This is one of the original firewall leaktest program that started it all.

4. Firewall Leak Tester - www.firewallleaktester.com
This is a one-stop shop for leak tester programs you can use to test your software. It has over 26 leak testers. The website published results comparing various firewalls but note that the comparison was done in 2006 so that may have been outdated. You can always download the leak testers and test individually.
Other leak testers are:
http://www.pcflank.com/pcflankleaktest.htm

(this article can be seen at
www.pckingsford.com)

5. Testing exploits to PC.
http://www.pcflank.com/exploits.htm - simulates Denial of Service attacks on your system.

6. Question on "How Does a Router Protect?" has some answers here:
http://xtechnotes.blogspot.com.au/2012/04/how-does-router-protect.html

7. Linux - IPTABLES
For Linux users, the software firewall IPTABLES allow maximum configurability.
More details can be found in the "Linux Firewall" section in: http://xtechnotes.blogspot.com.au/2012/05/notes-linux.html

A list of simple rules is given here as an example  for
Super Stealth mode
----------------
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -F
iptables -X
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
----------------
Once you've executed them, use this command for the stealth config to stick:
Code:
service iptables save

The above rules are quite strict. For simple web browsing, try this:
Basic Web Browsing mode
-----------------------------------
iptables -F
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --sport 80 -j ACCEPT
iptables -A INPUT -p udp --sport 53 -j ACCEPT
iptables -A INPUT -j DROP
iptables -A OUTPUT -j ACCEPT
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
iptables-save > /etc/sysconfig/iptables
----------------------------------

then to restart:
service iptables save
service iptables start

Links to IPTABLES configuration:
http://www.thegeekstuff.com/2011/06/iptables-rules-examples/
http://www.thegeekstuff.com/2012/08/iptables-log-packets/
http://www.thegeekstuff.com/2011/01/redhat-iptables-flush/
http://www.thegeekstuff.com/2011/03/iptables-inbound-and-outbound-rules/
http://www.thegeekstuff.com/2011/02/iptables-add-rule/
http://www.thegeekstuff.com/2011/01/iptables-fundamentals/


Tuesday, December 25, 2007

Notes Matlab

Notes Matlab
============

Contents
=========
Help
MEX - C


MEX - C
========

A list of mx-MEX functions is found in:
Help -> MATLAB -> C and Fortran Functions

Mex interface in C code:
******************
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* more C code ... */
******************



Help:
=====
>matlab -help

Setup Matlab's path - save the following into startup.m
*********************
% Add my test directory as the first entry
% on MATLAB's search path

path('/import/george/Applied/chee/programs/RKohn/SallyW',path)
*********************

To Run Matlab m-file, just type the name WITHOUT the ".m"
eg to run Hello.m, type "Hello"


Running Matlab:
1. GUI environment: /usr/local/matlab/bin/matlab
2. NO GUI: /usr/local/matlab/bin/matlabl -nojvm



*********************
RESHAPE

>> crshp(:,:,1)=[1,2,3,4;5,6,7,8;9,10,11,12]
>> crshp(:,:,2)=[13,14,15,16;17,18,19,20;21,22,23,24]
crshp(:,:,1) =
1 2 3 4
5 6 7 8
9 10 11 12
crshp(:,:,2) =
13 14 15 16
17 18 19 20
21 22 23 24

>> reshape(crshp(:,:,1), 12, 1)
ans =
1
5
9
2
6
10
3
7
11
4
8
12

Monday, November 26, 2007

Notes Joomla

Notes Joomla
================

HowTos
Install on Localhost
Transfer from localhost
Errors


HowTos
========
How to hide Details of Author, Category, Published, Hits for articles?
- Ensure each article set to global
- Go to Component - Articles, then select Show/Hide for each of Author, Category, Published, Hits

How to display template?
After selecting templates, go to Extension -> Discover

How to create a banner
- From Components - Banner
-- create a New client
-- create a New category
-- create a New banner, choose the created client and category
- From Extensions - Modules
-- create Banner (Module Type), and assign the previously created banner.



Install on Localhost
========================
https://sourceforge.net/projects/xampp/
Download XAMPP first (Windows/Linux) - which has got all necessary server components for Joomla.
Eg Apache, MySQL, PhP, etc

On Windows, DO NOT install from *.exe, instead use the 7z version of installer and unpack to c:\xampp

On Windows7, it may complain about:
"The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing from your computer. Try reinstalling the program to fix this problem"
Solution:
Download from 'official' Microsoft site only, the update for Universal C Runtime:
https://support.microsoft.com/en-us/help/2999226/update-for-universal-c-runtime-in-windows
Choose: "All supported x64-based versions of Windows 7" or similar.

You may also need to install the " Microsoft Visual C++ Redistributable for Visual Studio 2017" from:
https://support.microsoft.com/en-au/help/2977003/the-latest-supported-visual-c-downloads

To run XAMPP (on Win7):
- go to c:\xampp
- run: xampp-control.exe
- start these: Apache, MySQL
- Check Apache by using a browser and go to: http://localhost
- Check MySQL by  using a browser and go to: http://localhost/phpmyadmin

Now ready to install Joomla
- Download the package, eg Joomla_3.9.1-Stable-Full_Package.zip
- Configure Joomla for FIRST TIME, by going to: http://localhost
-- Page1, enter Site: eg blah.com   email: pck..@gmail  user:pck...   pass: usual web
-- Page2 DB questions:  local MySQLi: user/pwd:root/blank  DBname: joomla391  Prefix: jstg3_
- Installed webpages are:
Joomla: http://localhost
Joomla admin page: http://localthost/administrator



Transfer from localhost
========================
Three step process.

1. Zip and transfer the Joomla public directory
- use 7zip to zip up public_html directory or similar.
- upload zip file to destination Joomla folder.
- while in CPanel or similar, click Extract on the zip file.
- put the contents in public_html in destination

2. Export the MySQL DB from localhost, and then import while on the destination's DB.
- login to phpAdmin and connect to source Joomla's DB
- Export the DB (use custom option)
- login to phpMyAdmin and connect to destination Joomla's DB
- manually create the same DB, eg joomla391, with same name as original DB.
- Import the DB file.

3. Modify the config.php file
$dbtype
$host
$user
$password
$db
$dbprefix
$log_path - eg 'public_html/blah/joomla/logs'
$tmp_path - eg 'public_html/blah/joomla/tmp'




Errors

=======

Message: "Error on page" at the bottom left corner of browser

Cause: ...

Solution: Check the entry in public_html\configuration.php for the value of $mosConfig_sitename. If the value is "mydomain.org" instead of "www.mydomain.org", then need to go into administrator as http://mydomain.org/administrator, i.e. without "www"

Tuesday, October 30, 2007

Notes CSS

NotesCSS
=========



Contents
=========
References
Basic Syntax
Examples
Class Selectors
Inserting Stylesheet
Margins


References
===========
1. http://www.htmlhelp.com/reference/css/structure.html#pseudo
2. http://www.w3schools.com/css/css_syntax.asp


Basic Syntax
=============

General Syntax:
<Selector> { <Property> : <Value> ; [<Property> : <Value>] }

Selector is HTML tag, eg:
body, p, etc......
Property is HTML attribute eg:
color, font-family
Value is value of the HTML attributes


Examples
==========
body {color: black} -> simple example
p {font-family: "sans serif"} -> multiple worded Value
p {text-align:center;color:red} -> multiple Property

p -> alternative layout syntax
{
text-align: center;
color: black;
font-family: arial
}

h1,h2,h3,h4,h5,h6 -> multiple selector with same property
{
color: green
}

p.right {text-align: right} -> <p class="right"> This paragraph will be right-aligned.</p>

p.right {text-align: right} -> <p class="right centre"> This paragraph will be right-aligned.</p>
p.center {text-align: center}

.center {text-align: center} -> applies to ALL selector with class "center"

#green {color: green} -> applies to ALL id="green" selector, eg <p id="green"> .....

p#para1 -> applies to p selector with id="para1", eg <p id="para1"> .....
{
text-align: center;
color: red
}

input[type="text"] {background-color: blue} -> apply to selectors with certain elements, eg input-type

/* this is a comment */ -> comments

Class Selectors
================
<div class="sidenav">
<h2> Site navigation</h2>
</div>

div.sidenav { blah } /* styles overall div */
div.sidenav h2 { blah } /* styles h2 within the div */

ID Selectors
=============
#navigation { width: 12em; color: #333; }
div#navigation { width: 12em; color: #333; }



The major difference is that IDs can only be applied once per page,
while classes can be used as many times on a page as needed.

Classes can be used as many times as needed within a document.
IDs can only be applied once within a document.
So, if you need to use the same specific selector more than once, classes are a better choice.



Inserting Stylesheet
=======================

Cascading Order from least to most important:
- Browser default
- External style sheet
- Internal style sheet (inside the <head> tag)
- Inline style (inside an HTML element)


External style sheet
<head>
<link rel="stylesheet" type="text/css"
href="mystyle.css" />
</head>


Internal style sheet (inside the <head> tag)
<head>
<style type="text/css">
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
</style>
</head>


Inline style (inside an HTML element)
<p style="color: sienna; margin-left: 20px">
This is a paragraph
</p>


Multiple Sytlesheets
- in external CSS:
h3 {color: red;text-align: left;font-size: 8pt}
- in internal CSS:
h3 {text-align: right; font-size: 20pt}

Then the result will be:
color: red; text-align: right; font-size: 20pt


Margins
========

BODY { margin: 5em } /* all margins 5em */
P { margin: 2em 4em } /* top and bottom margins 2em,
left and right margins 4em */
DIV { margin: 1em 2em 3em 4em } /* top margin 1em,
right margin 2em,
bottom margin 3em,
left margin 4em */

Wednesday, October 24, 2007

Notes Windows Power Shell

Notes Windows Power Shell
=======================


Contents
=========
Commands
Scripting
Printing
Digital Signing and Certificates
Search





Commands
=========
get-alias list the real name of old command
get-content list contents of file
get-help get-service help on get-service command
get-command *-service list commands that manipulate services
get-member list the members of the object
get-service list the services running
| Out-Host -Paging prints one page at a time, user scrolling


Scripting
============
1. Extension *.ps1 (p-s-One)
2. To run script
/file.ps1 absolute path
./file.ps1 relative path
3. Line continuation '
4. Execution policy to run on local machine,
Set-ExecutionPolicy remoteSigned
5. Comments starts with #


Printing
==========
To print to a printer:
...blah... | Out-Printer -name "\\iaunsw024.au.cbainet.com\SYD48MP-L8-LXOP"

Search
=======
- Select-String
- findstr

Thursday, August 02, 2007

Notes Fortran

NotesFortran

Contents
=========

FORTRAN95 features
!DEC$ - compiler Directives
Keyword - SEQUENCE
Keyword - PURE
Initialize Data with slash /
Subroutines passed as argument of another subroutine
Allocatable Pointers / Array of Pointers
Using pointers in procedures
Dynamic Memory Allocation with Pointers
Declaration Statements for Arrays
Derived Data Types - with pointer components and being used as dummy pointer arguments
OpenMP
Static, Stack, Heap
Converting Integer to Character OR Writing to variable
Handling Character Strings between C# and Fortran
OpenMP programming warnings
Fortran Editors
String Manipulation



FORTRAN95 features
===================
List of F95 features implemented in Intel Fortran

1. FORALL -
2. PURE - for safety - ensure only INTENT(OUT,INOUT) arguments are changed.
3. ELEMENTAL - a type of PURE routine. Allow operation of arrays on element level.
4. CPU_TIME -
5. NULL intrinsic function - allow allocatable arrays to be pointed to this.


!DEC$ - compiler Directives
============================
Compaq (Digital) Visual Fortran (http://www.canaimasoft.com/f90vb/onlinemanuals/usermanual/TH_60.htm)


Compaq's Visual Fortran compiler (CVF) offers a great deal of flexibility to
create DLLs callable from C and/or Visual Basic. The compiler has a good set of
options to modify name-mangling, calling conventions and the method used to pass
arguments. Most of these options can be indicated through the use of compiler
directives (or pragmas) embedded in the source code. CVF compiler directives are
defined as comment lines, starting with DEC$.


To indicate that a subroutine should conform to the standard calling convention,
you add the DEC$ATTRIBUTE STDCALL compiler directive to the declaration of the
subroutine. For example:


subroutine MySub(argument1, argument2)  
   !DEC$ATTRIBUTES STDCALL:: GenDNASequence

In Compaq Visual Fortran, adding the STDCALL attribute also changes the default
method used to pass arguments, so you need to tell the compiler that arguments to
subroutine MySub are passed by reference. You can do this with the
DEC$ATTRIBUTE REFERENCE directive:

subroutine MySub(argument1, argument2)
!DEC$ATTRIBUTES STDCALL:: MySub
!DEC$ATTRIBUTES REFERENCE:: argument1, argument2


Also, when a procedure is declared with the standard calling convention (STDCALL),
Compaq Visual Fortran mangles its name. The name-mangling performed by CVF converts
the name of the procedure to all uppercase, adds an underscore as a prefix to the name,
and appends an at symbol (@) followed by the size of the stack (in bytes) at the end of
the name. The size of the stack is equal to 4 times the number of arguments in the
subroutine. MySub has 2 arguments, so the mangled name will be:


_MYSUB@8


Having to use this name to call our DLL procedure would be awful in most languages,
and illegal in Visual Basic. You can use another DEC$ATTRIBUTES compiler directive to
indicate an alias for the mangled name of the exported subroutine:



!DEC$ATTRIBUTES ALIAS: 'MySub'::MySub



The first argument is the alias (i.e. the name by which the subroutine would be available
to external programs using the DLL), the second argument is the Fortran name of the subroutine.



Finally, to indicate that the subroutine must be exported to the DLL as a public procedure,
you add the DEC$ATTRIBUTES DLLEXPORT compiler directive to the body of the subroutine:

!DEC$ATTRIBUTES DLLEXPORT:: MySub

So the full declaration of MySub would look like this:

subroutine MySub(argument1, argument2)
!DEC$ATTRIBUTES STDCALL:: MySub
!DEC$ATTRIBUTES DLLEXPORT:: MySub
!DEC$ATTRIBUTES ALIAS: 'MySub'::MySub
!DEC$ATTRIBUTES REFERENCE:: argument1, argument2



To create a DLL, you compile and link using the /dll switch. The following command-line
would compile and link MySub.f90 (containing subroutine MySub) into MySub.dll:


f90 MySub.f90 /dll /out:MySub.dll


Keyword - SEQUENCE
===================
SEQUENCE cause the components of the derived type to be stored in the same sequence they are
listed in the type definition. If SEQUENCE is specified, all derived types specified in component
definitions must be sequence types.


Keyword - PURE
===================
Pure Procedures
A pure procedure is a user-defined procedure that is specified by using the prefix PURE (or
ELEMENTAL) in a FUNCTION or SUBROUTINE statement. Pure procedures are a feature of
Fortran 95.
A pure procedure has no side effects. It has no effect on the state of the program, except for the
following:    
• For functions: It returns a value.
• For subroutines: It modifies INTENT(OUT) and INTENT(INOUT) parameters.
The following intrinsic procedures are implicitly pure:    
• All intrinsic functions  
• The elemental intrinsic subroutine MVBITS
• The intrinsic subroutine MOVE_ALLOC
A statement function is pure only if all functions that it references are pure.



Initialize Data with slash /
==============================
Variables are not auto-initialized. To initialize a variable as you declare it,
put the initial value between two slashes. This kind of initialization is done once
when the unit is first loaded, and hence, it should not be used in a subprogram that
gets invoked repeatedly (use an assignment instead). For symbolic constants,
initialization is achieved via the parameter statement.

    character title*20 / 'York' /
    integer*2 count / 0 /
    real*4 amount / 1.0 /
    !---------------------------------------------------
    ! Note that title will have 20 characters even though
    ! we stored only 4 (they will be padded by blanks).


Subroutines passed as argument of another subroutine
======================================================
subroutine subA( subB )

The subroutine named subB needs to be declared EXTERNAL and hence not be in a module.
If a function needs to be in the same module then can be done as follows:

module test
  contains
     subroutine subA(subB)
external subB
     .....
     subroutine subC()
end module
subroutine subB()
   use test
   call subC()
end subroutine


Allocatable Pointers / Array of Pointers
=========================================
REF: Fortran 90/95 for Scientists and Engineers, Stephen J Chapman
1. It is illegal to have array pointers of native data types in Fortran:
   REAL, DIMENSION(:), POINTER :: PTR
   - the dimension attribute refers to the pointer's target, not of the pointer.
   - the dimension must be deffered shape and the size is the size of the target, not
     the pointer.
2. It is legal to have array pointers by using derived data types:
  TYPE :: ptr
     REAL, DIMENSION(:), POINTER :: P
  END TYPE
  TYPE(ptr), DIMENSION(3) :: P1

REF: Intel Fortran Language Reference
1. In contrast to allocatable arrays, a pointer can be allocated a new target even if it is currently associated with target. The previous association is broken and the pointer is then associated with the new target.
2. If the previous target was created by allocation, it becomes inaccessible unless it can still be referred to by other pointers that are currently associated with it.


Using pointers in procedures
===============================
Pointers may be used as dummy arguments in procedures and may be passed as actual arguments to procedures.
1. If a procedure has dummy arguments with either POINTER or TARGET attributes, then the procedure must have an explicit interface.
2. if a dummy argument is a pointer, then the actual argument passed to the procedure must be a pointer of the same type, kind and rank.
3. a pointer dummy argument must not have the intent attribute
4. a dummy argument cannot appear in an ELEMENTAL procedure in Fortran95.


Dynamic Memory Allocation with Pointers
========================================
REF: Fortran 90/95 for Scientists and Engineers, Stephen J Chapman

REAL, DIMENSION(:), POINTER :: ptr1
ALLOCATE (ptr1(1:10))

This statement creates an unnamed data object of the specified size and the pointer's type and sets the pointer to point to the object. Because the new data object is unnamed, it can only be accessed by using the pointer. After the statement is executed, the association status of the pointer becomes associated. If the pointer was associated with another data object before the ALLOCATE statement is executed, then that association is lost.

The data object created by using the pointer ALLOCATE statement is unnamed and so can only be accessed by the pointer. If all pointers to that memory are either nullified or reassociated, with other targets, then the data object is no longer accessible by the program. The object is still present in memory, but it is no longer possible to use it => MEMORY LEAK.

If a piece of allicated memory is deallocated, then all pointers to that memory should be nullified or reassigned. One of them is automatically nullified by the DEALLOCATE statement, and any others should be nullified in NULLIFY statements.

Declaration Statements for Arrays
===================================
SUBROUTINE SUB(N,C,D,Z)
   REAL, DIMENSION(N,15) :: IARRY        !explicit shape array
   REAL, C(:), D(0:)                     !assumed shape array
   REAL, POINTER :: B(:,:)               !deferred shape array pointer
   REAL, ALLOCATABLE, DIMENSION(:) :: K  !deferred shape allocatable array
   REAL :: Z(N,*)                        !assumed size array

Automatic Arrays - local array in a function, whose size is one of the arguments
Adjustable Arrays - array which is an argument, whose size is also one of the arguments.

To use arrays efficiently, see Optimizing Applications -> Programming Guidelines -> Using Arrays Efficiently.
When passing arrays as arguments, either the starting (base) address of the array or the address of an
array descriptor is passed:
When using explicit-shape (or assumed-size) arrays to receive an array,
the starting address of the array is passed.

When using deferred-shape or assumed-shape arrays to receive an array,
the address of the array descriptor is passed (the compiler creates the array descriptor).

Automatic vs Save
Automatic variables can reduce memory use because only the variables currently being used are allocated to memory.

By default, the compiler allocates local variables of non-recursive subprograms, except for
allocatable arrays, in the static storage area. The compiler may choose to allocate a variable in
temporary (stack or register) storage if it notices that the variable is always defined before
use. Appropriate use of the SAVE attribute can prevent compiler warnings if a variable is used
before it is defined.




Derived Data Types - with pointer components and being used as dummy pointer arguments
========================================================================================
Given a derived data type with pointer arguments:
   type varDDT
      type(BigDDT), pointer :: rComp
   end type
Given that it is used as a dummy pointer argument
   subroutine foo(aDDT)
      type(varDDT), pointer :: aDDT
 ....
    end subroutine

Then, in another function which uses "foo", the DDT can be used as:
program
  type(varDDT), pointer :: aDDT_p
  type(varDDT) :: vDDT

  call testFoo(vDDT)   ! vDDT contains the data found in testFoo
  nullify(aDDT_p)
    end program

    subroutine testFoo(vDDT_local)
  type(varDDT) :: vDDT_local
       aDDT_p => vDDT_local

  call foo(aDDT_p)
       ! vDDT_local will be able to pass to outside routine safely.
    end subroutine


Note that this method is not required if the DDT concerned does not contain components
which are also DDT.


OpenMP
=======

Prerequisite:
Before inserting any OpenMP parallel directives, verify that your code is safe for parallel execution by doing the following:

Place local variables on the stack. This is the default behavior of the Intel Fortran Compiler when -openmp is used.

Use -automatic (or -auto_scalar) to make the locals automatic. This is the default behavior of the Intel Fortran Compiler when -openmp is used. Avoid using the -save option, which inhibits stack allocation of local variables. By default, automatic local scalar variables become shared across threads, so you may need to add synchronization code to ensure proper access by threads.

Static, Stack, Heap
====================
Heap area stores dynamic arrays
Static storage area store variables that are available for the life time of the program.
In C, local variables are stored in the stack.

In Fortran,
"By default, the compiler allocates local scalar variables on the stack. Other, non-allocatable variables of non-recursive subprograms are allocated in static storage by default. This default can be changed through compiler options. Appropriate use of the SAVE attribute may be required if your program assumes that local variables retain their definition across subprogram calls."

For openMP, local variables in Fortran will become automatic and thus stored in the stack. Note that
OpenMP threading model is based on threads and each has its own stack.



"static" as a descriptive term refers to the lifetime of C++ memory or storage locations. There are several types of storage:
        - static
        - dynamic (heap)
        - auto (stack)
A typical storage layout scheme will have the following arrangement, from lowest to highest virtual memory address:
        text (program code)
        static (initialized and uninitialized data)
        heap
        (large virtual address space gap)
        stack
with the heap and stack growing toward each other. The C++ draft standard does not mandate this arrangement, and this example is only an illustration of one way of doing it.


heap-array in Intel Fortran - This option puts automatic arrays and arrays created for temporary computations on the heap instead of the stack.
on Windows:
    /heap-arrays-        = no heap arrays (default)
    /heap-arrays[:size]  = where arrays of size (in kb) or larger are put on the heap.
on Linux:
    -no-heap-arrays        = no heap arrays (default)
    -heap-arrays [size]    = where arrays of size (in kb) or larger are put on the heap.
Example:
    In Fortran, an automatic array gets it size from a run-time expression. For example:
RECURSIVE SUBROUTINE F( N )
INTEGER :: N
REAL :: X ( N )     ! an automatic array
REAL :: Y ( 1000 )  ! an explicit-shape local array on the stack Array X in the example above
                    ! is affected by the heap-array option. Array Y is not.





Converting Integer to Character OR Writing to variable
========================================================
Example:
   CHARACTER(LEN=15), ALLOCATABLE  :: cPctile(:)
   ALLOCATE( cPctile(nPctile) )
   write(cPctile(jj), '(F15.7)') pctile(jj)

The number in pctile(jj) is being written into a CHARACTER variable called cPctile. Note the character has length of
15 which is enough to write 15 characters specified by the Format F15.7.



Handling Character Strings between C# and FortranSubmit New Article
Last Modified On :   December 6, 2009 6:09 PM PST
Rate Please login to rate! Current Score: 0 out of 0 usersPlease login to rate! Current Score: 0 out of 0 usersPlease login to rate! Current Score: 0 out of 0 usersPlease login to rate! Current Score: 0 out of 0 usersPlease login to rate! Current Score: 0 out of 0 users






Handling Character Strings between C# and Fortran
=================================================================

Passing Character Strings as In parameters from C# to Fortran

C# provides built-in reference type "string" representing a string of Unicode characters. It is an alias for String in the .NET Framework. When passing "string" type by value from C# to Fortran function or subroutine platform invoke service copies string parameters, converting them from the .NET Framework format (Unicode) to the unmanaged format (ANSI), if needed. The unmanaged format is null-terminated so the C# method prototype of Fortran function or subroutine must account for the length argument passed along with the string address.


Passing Strings as In/Out parameters from C# to Fortran

Managed strings are immutable, platform invoke does not copy them back from unmanaged memory to managed memory when the function returns. If the Fortran function or subroutine wants In/Out parameters you need use StringBuilder Class in C#. StringBuilder Class represents a string-like object whose value is a mutable sequence of characters.

Fortran subroutine
subroutine FPassStringSub (Int_Arg, Str_In, Str_Out)
!DEC$ ATTRIBUTES DLLEXPORT :: FPassStringSub
integer, intent(in) :: Int_Arg
character*(*), intent(in) :: Str_In
character*(*), intent(out) :: Str_Out
end subroutine



C# method prototype
        [DllImport("FDLL.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern void FPASSSTRINGSUB(ref int Int_Arg, string Str_In, StringBuilder Str_Out, int Str_In_Len, int Str_Out_Len);
STR_IN_LEN, int STR_OUT_LEN);



Returning Character Data Types from Fortran to C#

Similar to how C language handles Fortran function returning character data type the corresponding C# method prototype must add two additional arguments to the beginning of the argument list:
-  The first argument is a StringBuilder object where the called function should store the result.
-  The second argument is an int value showing the maximum number of characters that must be returned, padded with blank spaces if necessary.


Fortran function

function FRetString(Int_Arg)
!DEC$ ATTRIBUTES DLLEXPORT :: FRetString
character(*) :: FRetString
integer, intent(in) :: Int_Arg
end function


C# method prototype
        [DllImport("FDLL.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern void FRETSTRING(StringBuilder Str_Result, int Res_Len, ref int Int_Arg);



How to avoid Race Conditions in OpenMP programming
===================================================
This section aims to cover a few points to watch for when doing parallel programming using OpenMP in Fortran.
The tips here could also apply to different languages with OpenMP such as C/C++.
1. First danger sign of parallel programming bug is inconsistent behaviour.
2. When a program stalls or hangs indefinitely sometimes, but other times run to completion.
3. When a program crashes sometimes, but other times run to completion.
4. When OpenMP is applied to a higher level function that calls many small low level functions, check  whether module variables have SAVE attribute.
5. If module variables have save attributes, then check if those variables can be declared PRIVATE too so that no outside functions can use them.
6. When the SAVE module variables are being altered in a function in the module, check to see if the function can be encapsulated in a OMP parallel region.
7. When checking for race conditions using tools like Intel Thread Checker, ensure that the number of threads specified is not greater than the number of processors / cores.


Fortran Editors
=================

The following list are GUI based Fortran editors development environment.

Force
http://force.lepsch.com/

Plato - for Silverforst FTN95
http://www.silverfrost.com/16/ftn95/plato.aspx

Photran - on Eclipse IDE
http://www.eclipse.org/photran/

Geany - GTK based
http://www.geany.org/Main/AllFiletypes


There are many other general purpose editors that can edit Fortran including: Vi, Emacs, EditPlus.

String Manipulation
====================
There is a misconception that the string manipulating and handling capabilities are limited. However, it may not be as limited as initially thought. Here are a few useful string handling features from poplular languages that also exist in Fortran.

Comparing Substring:
   INDEX( string, substring) -> returns integer representing the first position of occurance of the substring in string.
   Converting Integer to String
write(charWord, '(I5)') ii-1
where ii is an integer which is written to the character variable 'charWord'.

Thursday, July 26, 2007

Notes Video Capture

Notes Video Capture
===================

See also NotesDVD

Contents
=========
Abstract
Capture Video via Virtual Dub
Experiment with Virtual Dub - Video Compression
Compress AVI (video and audio uncompressed) using Virtual DUB.
VirtualDub with DivX

VirtualDub filters plugins
VirtualDub MPEG2 codecs
How to Improve Video Capture Quality


Abstract
==========
These instructions uses
- Virtual Dub
- DivX codec
- mp3 codec
- video capture / tv tuner card

Video capture is done from miniDV camcorder into *.avi file using Virtual Dub.
The second stage compresses the *.avi file into another *.avi file.
Note between the two *.avi processes, an intermediate process is required to extract the sound from the first avi file into a separate wav file.


Capture Video via Virtual Dub
================================
1. Connect AV cable on Canon to COMPOSITE on TV card, yellow-video, red/white-audio

Do NOT
2. Switch on TV View program.
3. Select Video Source on TView program (select until display on PC screen)


DO:
2. Open Virtual Dub
3. File -> Capture AVI (to go to capture mode)
3.5 Video -> Video source -> Video Composite
4. Device -> Conexant Capture
5. File -> Set Capture File (give a filename)
6. Video -> Compression
Cinepak Codec = 6.6:1
Indeo Video 5.1 = 10:1
(Experiment with Virtual Dub - Video Compression)



Experiment with Virtual Dub - Video Compression
=================================================
Set the following:
- Capture - "Hidden display while capture", 29.97 fps
- Video - "Noise reduction enable", "Enable RGB filtering"
- Audio - MP3, 48kBit, 22kHz
- Record Duration about 20s

Uncompressed RGB YUV = 95.977MB
Cinepak Codec = 1.842MB
Indeo 5.1 = 2.734MB
Indeo 3.2 = 7.197MB
Indeo 4.5 = 2.591MB
Intel YUV = 55.044MB
MS Video1 = 41.639MB

MSVideo - Smoothest picture with smallest filesize

Audio better is using:
1) Raw (no compression)
2) Windows Recording Line Volume = 38%, better than higher volume.

Video - choose either
1) Intel YUV (better compression with DivX)
2) MS Video1


Compress AVI (video and audio uncompressed) using Virtual DUB.
===============================================================
1. Exit the capture mode from previous process
2. Open and select the *.avi file which contain the video and uncompressed audio from previous video capture process.
3. Audio - Source Audio, Full processing mode, Compression (mp3, 48kBit, 22kHz)
4. File -> "Save WAV ..." as MP3 - this process strips the sound from the previous *.avi file into a separate *.wav file.
5. Audio -> Audio From Other File - Select the file that was saved.
6. Video -> Full Processing Mode - Compression (DivX, High Quality)
for Good quality DivX, try
6.5 Audio -> Interleaving - adjust by testing if video out of sync with audio
7.File -> Save as AVI -> this will combine the video from the previous *avi and the newly saved *.wav file to produce a compressed DivX, MP3 *.avi file.
In terms of size, continuing from the experiment, the now compressed files have the following sizes:
IntelYUV_mp3 55.044MB -> 2.046MB
IntelYUV_raw audio 38%Vol 55.416MB -> 1.867MB
MSVideo1 raw audio 40.452MB -> 1.879MB
MSVideo1 raw audio 38%Vol 44.390MB -> 5.443MB


VirtualDub with DivX
======================
1. From the main Menu -> Video -> Compression -> DivX Codex -> Configure
2. In the DivX Codec Properties -> Main -> Profile = "High Definiion Profile" -> Rate Control = "1 Pass" -> Bitrate = 1500 kbps
Fairly good quality vs size -> Profile = "1080HD Profile" -> Encoding Presets = 8 -> Rate Control = "1 Pass" -> Bitrate = 3000 kbps



VirtualDub with DivX
======================
1. From the main Menu -> Video -> Compression -> DivX Codex -> Configure
2. In the DivX Codec Properties -> Main -> Profile = "High Definiion Profile" -> Rate Control = "1 Pass" -> Bitrate = 1500 kbps
      Fairly good quality vs size       -> Profile = "1080HD Profile" -> Encoding Presets = 8 -> Rate Control = "1 Pass" -> Bitrate = 3000 kbps


VirtualDub filters plugins
============================
Filter pack from Dee Mon:
http://www.infognition.com/VDFilterPack/
Jim Leonard's White Balance filter
http://neuron2.net/whitebalance/whitebalance.html

flaXen filter
http://neuron2.net/flaxen/flaxen.html


To use this filter, install Virtual Dub, then install these plugins into the VirtualDub's plugins folder.


VirtualDub MPEG2 codecs
========================
To use the Virtual Dub and encode with the MPEG2, the following codes need to be installed.
Panasonic VfW DV codec
http://www.free-codecs.com/download/panasonic_dv_codec.htm
 Adaptec VfW DV codec
http://www.free-codecs.com/download/adaptec_dvsoft_codec.htm


How to Improve Video Capture Quality
======================================
This step may require additional filters for VirtualDub. See the previous section for filters available for VirtualDub.

White Balance Filter - Jim Leonard
- to correct for white balance problems.
- Example: when the video in general looks orange, blue or too dark.
- may occur when white balance is on automatic mode, so different types of light having different temperatures causes this problem
- this filter can also be used to adjust Hue, Saturation, Intensity, Brightness, Contrast

Deinterlacing filter
- used to remove the effect of interlacing, ie. when not all frames are processed.
- fast motion causes edges of objects to look jagged.
- the filter will also make the video look far sharper

Sharpening Filter
- used when video seem to have soft edges or lack detail.

Dynamic Noise Reduction
- used when video is grainy

Chroma Noise Reduction Filter
- used when there is chroma noise; ie where rainbow effects shimmer across the screen.

VHS filter - flaXen
- used when video has timing issues and skips a bit
- try using the Stabilize section of this filter only

NotesDVD

NotesDVD
=========
(see also NotesDVD)

Contents
=========
PAL/NTSC Aspect Ratio
DVD to DivX



PAL/NTSC Aspect Ratio
======================
Resolutions that video streams can use, are:

720x480 (NTSC, only with MPEG-2)
720x576 (PAL, only with MPEG-2)
704x480 (NTSC, only with MPEG-2)
704x576 (PAL, only with MPEG-2)
352x480 (NTSC, MPEG-2 & MPEG-1)
352x576 (PAL, MPEG-2 & MPEG-1)
352x240 (NTSC, MPEG-2 & MPEG-1)
352x288 (PAL, MPEG-2 & MPEG-1)


PAL/NTSC 720 x 576 / 720 x 480
Size Ratio
720 x 544 1.32:1
640 x 480 1.33:1
592 x 448 1.32:1
544 x 416 1.30:1
512 x 384 1.33:1
448 x 336 1.33:1
400 x 304 1.32:1
384 x 288 1.33:1
336 x 256 1:31:1
320 x 240 1.33:1


PAL/NTSC 720 x 576 / 720 x 480
Size Ratio
720 x 384 1.87:1
640 x 336 1.87:1
576 x 304 1.89:1
512 x 272 1.88:1
480 x 256 1.87:1
448 x 240 1.86:1



DVD to DivX
===========

Summary
1. Rip DVD VOB files from DVD to Hard Drive
2. Convert VOB into AVI
3. Convert VOB into WAV
4. Combine AVI and WAV into another AVI file

Method A: Using mpeg2avi, ac3decode, VirtualDub, Danii's GUI
Step 1 - assuming this is done .....
Step 2 - using mpeg2avi with Danii's GUI
Step 3 - using ac3decode with Danii's GUI
Step 4 - using VirtualDub

Convert VOB into AVI
- open Danii's GUI v0.20
- click MPEG2AVI
- fill in location of:
i) mpeg2avi program
ii) VOB file for single VOB file or
*.lst file for multiple VOB files (containing a list of all VOB files to be combined)
iii) output folder
- click on "DivX Auto"
i) Low motion
ii) 10 Keyframes
iii) 70% compression control
iv) 600 kbps (varies)
v) click Save
- fps = 25 (for PAL)
- q0 High quality
- r1 32bit MMX iDCT
- Output = o8 AVI-YV12 for DivX
- PAL - 4:3
- Crop and Resize (see Resolutions data above)
- Click Create My AVI

Convert VOB into WAV
- open Danii's GUI v0.20
- click AC3DEC
- fill in location of:
i) ac3dec program
ii) VOB file
iii) output folder
- Global Output Gain = 300
- Check - "Span over multiple VOBS automatically"
- Click Create My WAV

Combine AVI and WAV into another AVI file
- open Virtual Dub
- File -> Open video file (output from step 2)
- Video -> Direct Stream Copy (because already compressed to DivX/AVI)
- Audio -> WAV Audio
- Audio -> Full processing mode
- Audio -> Compression - MP3
- Audio -> Interleaving - adjust by testing if video out of sync with audio
- File -> Save As AVI

Saturday, July 21, 2007

Building own PC

Case:
Thermaltake Wing RS100
- $59 http://www.skycomp.com.au/ sydney

Windows Vista Readiness
- check out readiness from
http://www.microsoft.com/windows/products/windowsvista/buyorupgrade/upgradeadvisor.mspx

Thursday, June 14, 2007

NotesWeb

Registering your website
Resources


Resources
==========
https://fontawesome.com/?from=io
http://glyphicons.com/


Registering your website
============================
1. www.google.com/addurl
2. search.yahoo.com/info/submit.html
3. search.msn.com/docs/submit.aspx
4. www.dmoz.org

To analyse your website to see how spiders or bots rate your site:
Submit Express


Search Engine Optimization and SEO Tools



Web Hosting - free ones can be found in:
1. [free-webhosts](http://www.free-webhosts.com/)
2. [Best free web hosting of 2018](https://www.techradar.com/au/news/best-free-web-hosting-sites-of-2018)
- [Infinityfree](https://infinityfree.net/)
- [Freehostia](https://www.freehostia.com/)
- [5GBfree](https://www.5gbfree.com/hosting-plans/)
- [FreeHosting.com](https://www.freehosting.com/client/cart.php)
- [Byethost](https://byet.host/free-hosting)
- [x10hosting](https://x10hosting.com/free-web-hosting)

A few things to consider when choosing Free Webhosting.
1. When they say unlimited or infinite - that cannot be really true. Just remember this.
2. Check if they let you bring your own domain name, if you have already registered elsewhere.
3. If you would like to have multiple sub-websites, eg using multiple technologies like some using Joomla, some using Wordpress, etc, you may need to look for
i) how many databases do they offer?
ii) do they allow subdomains? For example your main site is www.main.com where you use Wordpress. Then you install Joomla on subA subdirectory, then the ability to make subA website to appears as subA.main.com is the subdomain.

For low-cost Webhosting sites - see:
https://www.hostingadvice.com/reviews/cheap/