Working with Amiga C using Visual Studio Code

Working with Amiga C using Visual Studio Code

I’ve found it rather difficult to go back to coding on the Amiga with the available editors. Most of them lack decent syntax highlighting, formatting, intellisense and autocomplete.

Professionally I’m used to using the likes of Visual Studio which supplies all those features. Using Visual Studio Code, a free IDE from Microsoft, with a few extensions I’ve been able to code in Amiga C on windows quite well.

In the screenshot below, I have a folder on google drive set up in the following structure.

  • DH0 and DH1 are Workbench and Work respectively
  • Original System is a fresh install of Workbench 3.1 that I can use to setup a new hard drive in a matter of seconds
  • I have a copy of the RKM Companion Disk as a helpful reminder of things
  • A Backup of both DH0 and DH1 when both areworking correctly
  • Various adf’s of Devpac, Dice C, and SAS C v6

I’ll skip the installing of Workbench and SAS/C; suffice it to say it’s a case of inserting disk 1 running the install file and then inserting the other 5 as prompted.

You can obtain SAS/C from tosec or possibly the eab

I have my WinUAE hard drives set up like this: (running as an a1200, fasted possible setting on the CPU)

My copy of Visual Studio Code has the following extensions installed, you may not need all of them but I’m pretty sure you need C/C++ from Microsoft. (see image)

I Create a folder in windows at C:\Users\Joe\Google Drive\_Amiga\DH1\Projects\Joe5, this will be where I store all the files

As this is shared via WinUAE it’s now possible to do the following in CLI:

  • cd Work:/Projects/Joe5
  • scsetup

This creates some files used by/with sas/c

In Visual Studio Code, go to File->Open Folder, and select the Joe5(or relevant) folder, this will give you a window similar to that below:

All be it without the main.c, which needs to be created ( done by clicking on the file icon under the project explorer)

Next, the include files need to be imported. This is currently a bit obtuse in it’s implimentation, but it’s the only realistic way I can find of doing it; by causing a problem in your code.
In the image below I try to reference the exec/types.h, VSCode does not yet know what that file is!

This is advantageous though as Clicking on the ‘Edit “includePath” setting’ allows us to then point VSCode to add Sas/C’s include directory. (your path’s may be different) see below:

When this is set, save and close main.c and you should have intellisense and autocomplete, very useful!.. allowing for things like this:

On the Amiga side, we can now run mkmk to create a makefile, after the make file has been created we can then smake

Due to my sloppy coding, I forgot to do a few things correctly, Which caused errors during the build process, I was able to output the results of the build to a file, also viewable in VSCode:

So I fix the code, and then run smake

Type main (the name of the program)

And that’s it!

P.S. This was written rather quickly, so any spelling mistakes or glaring errors I apologise for!

Download the example project.

[Solution]Barclays Mobile Banking isn’t compatible Galaxy s7 rg030 error

Today I had an issue with Barclays mobile banking. Essentially the app had stopped working, requesting I do an update to proceed, giving me an RG030 error. When I try to update it says ‘your device is not compatible with this version’.

I have a Galaxy S7 Edge and it appears to be an error prone to these devices. I’ve not looked into the reasons too much but a semi-educated assumption from discussions I’ve had with some of their tech team; leads me to believe it’s related to either firmware versions, versions of google play or a related service (if you try installing it on a rooted device you’re out of luck, they check this kind of thing and prevent it).

The Solution presented to me, as bizarre as it may sound is as follows

  1. Turn on Flight mode
  2. Then enable wifi
  3. Restart the phone
  4. Wipe the google play store cache and data
    This can be done through the
    Settings -> Apps ->Google Play store -> Storage -> Clear Data
  5. Restart the phone
  6. Install the update for Barclays mobile banking

This worked for me. I do have the latest firmware for my Galaxy S7 Edge

Also suggested was to ensure that the date and time of your phone was correct (i.e. you’re getting net time not one set manually, no VPN’s or proxies and also to re enter your play store details

XML Serialization quick and easy csharp

Serialization with XML and C#

this is mainly here as a reminder for me on how to do it!

To serialize to a file:


using System.Xml;
using System.Xml.Serialization;
// other code

List<string> mylist = this.getList();

Type stype = typeof(List<string>);

var serializer = new XmlSerializer(stype);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; // this is because of microsofts dodgy xml tag
using (var writer = XmlWriter.Create("outputfile.xml",settings))
{
serializer.Serialize(writer,mylist);
}
 

To serialize to a string:

string r = "";
List<string> mylist = this.getList();
   using (MemoryStream memS = new MemoryStream())
    {
      //set up the xml settings
      XmlWriterSettings settings = new XmlWriterSettings();
      settings.OmitXmlDeclaration = true;
      Type stype = typeof(mylist);
      var xmlSerializer = new XmlSerializer(stype);
      StringBuilder retString = new StringBuilder();
      using (XmlWriter writer = XmlTextWriter.Create(memS, settings))
       {
         //write the XML to a stream
         xmlSerializer.Serialize(writer, mylist);
         writer.Close();
       }
    //encode the memory stream to xml
    string v = Encoding.UTF8.GetString(memS.ToArray());
    r = v;             
    memS.Close(); // the using should do this anyway
    }        

To de-serialize xml from a string

public List<string> getMyStrings(string xmlString)
{
 XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
   using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
    {
      return (List<string>)serializer.Deserialize(ms);
    }
}

That’s it, any errors are due to me typing most of it from memory, so if it doesn’t work it’s probably missing a ‘;’ or something

You will need these usings:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

Bootstrap compatible asp.net button

Similar to my previous post, you can use the following code to create a custom asp.net button with the ‘button’ tags used in HTML5 and bootstrap.

  [ParseChildren]
   public class bsButton : Button
    {

        private string _ButtonCss = "btn btn-default";
        [Browsable(true), Description("The css class"),]
        public string ButtonCss
        {
            get
            { return _ButtonCss; }
            set
            {
                _ButtonCss = value;
            }
        }

        private string _glyphicon = "";
        [Browsable(true), Description("GlyphiconName"),]
        public string glyphIcon
        {
            get
            {
                return _glyphicon;
            }
            set
            {
                _glyphicon = value;
            }

        }


        protected override void Render(HtmlTextWriter writer)
        {

            if (glyphIcon == "")
            {
                System.Web.UI.HtmlControls.HtmlGenericControl
                            btn = new System.Web.UI.HtmlControls.HtmlGenericControl("button");
                btn.Page = this.Page;
                btn.ID = this.ClientID;
                btn.InnerText = this.Text;
                btn.Attributes.Add("class", ButtonCss);
                btn.Visible = this.Visible;
                btn.Attributes.Add("name", this.UniqueID);
                btn.Attributes.Add("onchange", "__doPostBack('" + this.ClientID + "', 'OnClick',true)"); // fire postback
                btn.RenderControl(writer);
            }

            else {
                System.Web.UI.HtmlControls.HtmlGenericControl groupbtn = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                groupbtn.Attributes.Add("class", "input-group-btn");

                System.Web.UI.HtmlControls.HtmlGenericControl
                       btn = new System.Web.UI.HtmlControls.HtmlGenericControl("button");
                System.Web.UI.HtmlControls.HtmlGenericControl
                    ithing = new System.Web.UI.HtmlControls.HtmlGenericControl("i");

                Literal litText = new Literal();

                ithing.Attributes.Add("class", "glyphicon glyphicon-" + glyphIcon);

                btn.Page = this.Page;
                btn.ID = this.ClientID;
                litText.Text = this.Text;
                btn.Attributes.Add("class", ButtonCss);
                btn.Visible = this.Visible;
                btn.Attributes.Add("name", this.UniqueID);
                btn.Attributes.Add("onchange", "__doPostBack('" + this.ClientID + "', 'OnClick',true)"); // fire postback
                btn.Controls.Add(ithing);
                btn.Controls.Add(litText);
                groupbtn.Controls.Add(btn);

                groupbtn.RenderControl(writer);


            }


        }
    }

you will need to surround that with

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Controls
{
//..Code here
}

Or append it to the class used for the radio button list.

Bootstrap compatible asp.net radio button list

Recently I have had the requirement to make some of my asp.net controls ‘bootstrap compatible’

In this instance it has been asp.net’s radio button list that is causing me consternation!

An inline bootstrap radio button list has the mark up of this:

<div class="radio">
                <label class="radio-inline">
                    <input type="radio" value="Ac" name="optArchive" checked="checked">Active</label>
                <label class="radio-inline">
                    <input type="radio" value="Ar" name="optArchive">Archive</label>
            </div>

You could use hidden fields and JavaScript to control Postbacks and capture the data.I feel this is not a reliable option.

The easiest and I think the best method I have found so far is to extend the RadioButtonList to do my bidding.

I started by creating a class file to contain all of my bootstrap friendly controls, in this instance I named it ‘/App_Code/bsFriendly.cs’, creating a namespace in that class called Controls

In that file I extend the RadioButtonList, so far it looks like this:


//bsFriendly.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Controls
{
    public class bsRadioButtonList : RadioButtonList
    {
    }
}

Nothing too exciting.

Within our ‘bsRadioButtonList’ the RenderItem method has to be overridden. In VS this is a case of typing ‘protected override’ to get IntelliSense to present a list of override-able properties and methods. From that list select ‘RenderItem’, Visual Studio will create the override with a call back to it’s base.

Remove the base call and instead replace it with the following:

namespace Controls
{
    public class bsRadioButtonList : RadioButtonList
    {
 
   
        protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
        {




            RadioButton radioButton = new RadioButton(); // to hold our radio button
            Literal litText = new Literal(); //to hold our labels text
            radioButton.Page = this.Page;
            radioButton.GroupName = this.UniqueID;
            radioButton.ID = this.ClientID + "_" + repeatIndex.ToString();
            radioButton.Attributes["value"] = this.Items[repeatIndex].Value;
            radioButton.Checked = this.Items[repeatIndex].Selected;
            radioButton.TextAlign = this.TextAlign;
            radioButton.AutoPostBack = this.AutoPostBack;
            radioButton.Attributes.Add("onchange", "__doPostBack('" + this.ClientID + "_" + repeatIndex.ToString() + "',' ')"); // fire postback
            radioButton.TabIndex = this.TabIndex;
            radioButton.Enabled = this.Enabled;
            System.Web.UI.HtmlControls.HtmlGenericControl gnLabelHolder = new System.Web.UI.HtmlControls.HtmlGenericControl("label"); // our label holder
            gnLabelHolder.Attributes.Add("for", this.ClientID + "_" + repeatIndex.ToString()); //associated to the radio button
            gnLabelHolder.Attributes.Add("class", "radio-inline"); //give it the bootstrap inline class, could extend as a property
            litText.Text = this.Items[repeatIndex].Text;

            gnLabelHolder.Controls.Add(radioButton); // add in the correct order of radio button then texts
            gnLabelHolder.Controls.Add(litText);
           
            
            gnLabelHolder.RenderControl(writer); //render to the writer


        }
    }

}

This will now act as new control.

To include the control on a page, simply add:

<%@ Register TagPrefix="bs" Assembly="App_Code" Namespace="Controls" %>

At the top of the page, below the Language and Codefile definitions at the top.

As a control in the page:

          <bs:bsRadioButtonList AutoPostBack="true" OnSelectedIndexChanged="test_SelectedIndexChanged" ID="test" runat="server" RepeatLayout="Flow"  RepeatDirection="Horizontal">
                    <asp:ListItem Selected="True">Active</asp:ListItem>
                    <asp:ListItem>Archive</asp:ListItem>

                </bs:bsRadioButtonList>

And in our back end cs file:

    protected void test_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

That’s all there is to it.

Caveats:

  1. In the mark up you need to select an item, not doing so could cause confusion with postbacks
  2. AutoPostBack needs to be set to true to allow the hookup on __DoPostBack

Calculate a fraction in javascript

Calculating a fraction from a double in javascript

The following code will allow you to calculate a fraction in javascript

 function getFraction(dblValue, dblTolerance)
    {
        var f0 = 1 / dblValue;

        var f1 = 1 / (f0 - Math.floor(f0));

        var a_t = Math.floor(f0);

        var a_r = Math.round(f0);

        var b_t = Math.floor(f1);

        var b_r = Math.round(f1);

        var c = Math.round(1 / (f1 - Math.floor(f1)));

        if (Math.abs(1.0 / a_r - dblValue) <= dblTolerance)
        {
            return [1, a_r];
        }
        else if (Math.abs(b_r / (a_t * b_r + 1.0) - dblValue) <= dblTolerance)
        {
            return [b_r, a_t * b_r + 1];
        }
        else {
            return [c * b_t + 1, c * a_t * b_t + a_t + c];

        }
    }

For example the following code examples give you a numerator and a denominator

console.log(getFraction(0.75,0.02));
/*[3, 4]*/
/***********************************/

console.log(getFraction(0.5,0.02));
/*[1, 2]*/
/***********************************/

console.log(getFraction(0.25,0.02));
/*[1, 4]*/
/***********************************/

console.log(getFraction(0.33,0.02));
/*[1, 3]*/
/***********************************/

Hope that’s of use to somebody!

Javascript Dynamic Event

Javascript Dynamic Events / Javascript Custom Events

I often asked myself: How do I create a custom event in javascript?

Something I have been using for quite awhile now is my own custom event handler for javascript, it’s pretty simple compact and easy to use

To use; just copy the devent function to the page in which it needs to be used.

Initialize it by xxEventName = new devent()

You can set what happens when the event is fired by assigning a function to the XXEventName.myEvent property, and you can trigger the event by using the XXEventName.fire() method.

The example below is the best method on which to use it.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>oop Example</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        function devent(runonce)
        {

            /******************
            * Javascript Dynamic Events
            * (c) joesblog.me.uk 2011
            *******************/

            // event has run
            this.onEvent_hasrun = false;

            // only allow running once
            this.onEvent_runonce = runonce;

            // event function
            this.myEvent = function () { };

            // now obsolete
            this.myCallback = null;

            //data to be passed to event
            this.myEvent_Data = null;

            // how many times the event has been fired
            this.myEventCount = 0;

            //fire the event , in other words execute the function assigned in myEvent
            this.fire = function ()
            {
                if (this.myEvent != null)
                {
                    if (!this.onEvent_runonce)
                    {
                        this.onEvent_hasrun = true;
                        this.myEventCount++;
                        this.myEvent();
                        return;
                    }
                    else
                    {
                        if (!this.onEvent_hasrun)
                        {
                            this.onEvent_hasrun = true;
                            this.myEventCount++;
                            this.myEvent();
                        } else
                        { return; }
                    }
                }
            }
        }

        ///An example of a static javascript class
        var myStaticClass = new function ()
        {
            // the event for when the sum has been done
            this.mathsDone = new devent();

            // the result of the addition
            this.simpleMaths = null;
            //The interval object timer.
            this.waitInterval = null;
            //self explainatory 
            this.countDown = 5; 
            
            //default countdown
            this.defaultCount = 5;

            //initialise all the objects and things that we need in this class
            this.init = function ()
            {
         
                //clear the interval 
                 this.waitInterval = null;

                //set the coutndown to its starting position
                 this.countDown = this.defaultCount;
            }

            //function called no the interval 'pulse'
            this.controlTime = function ()
            {
                if (myStaticClass.countDown == 0)
                {   ///if all the countdown has reached zero, do the maths, reset the countdown and clear the interval object

                    myStaticClass.doSimpleMaths(); 
                    myStaticClass.countDown = myStaticClass.defaultCount;
                    clearInterval(myStaticClass.waitInterval);
                }
                else
                {
                    myStaticClass.countDown--;
                }

                document.getElementById('countdown').innerHTML = myStaticClass.countDown

            }


            this.doSimpleMaths = function ()
            {
                myStaticClass.simpleMaths = (100 * 100) + 5;
                this.mathsDone.fire(); //fire the mathsDone event and cause the function we have set to run
            }

            this.start = function ()
            {
                myStaticClass.waitInterval = setInterval(myStaticClass.controlTime, 1000);
            }
        }
        //An example of a nonStaticClass
        function nonStaticClass(constructorVar1, constructorVar2)
        {
            this.aVar = constructorVar1;
            this.bVar = constructorVar2;
            this.result = 12;
            this.method = function () { this.result = this.aVar + this.bVar;  alert('do something'); }
        }

        var nonStaticClass_Instance = null;

        $('document').ready(function ()
        {
            //init the class
            myStaticClass.init();
            //assign a function to the mathsdone event
            myStaticClass.mathsDone.myEvent = function ()
            {
                alert(myStaticClass.simpleMaths);
            }

            nonStaticClass_Instance = new nonStaticClass(5, 12);

        });
    </script>

    <style type="text/css">
        body {
            font-family: verdana;
        }

        .centerDiv {
            height: 500px;
            width: 500px;
            background-color: #eaeaea;
            margin: auto;
            border-radius: 5px;
            border: solid 1px #ccc;
        }

            .centerDiv p {
                padding: 10px;
            }

        input[type=button] {
            padding: 10px;
            margin: 10px;
        }
    </style>
</head>
<body>
    <div class="centerDiv">
        <p>Click below and then Wait <span id="countdown">5</span> seconds</p>
        <input type="button" value="click ME" onclick="myStaticClass.start()" />
        <input type="button" value="click ME non Static method" onclick="nonStaticClass_Instance.method()" />

    </div>
</body>
</html>

Demo of the code

Using XSD/XML With LINQ; Serializing and Deserializing – Visual Studio .Net 4.0


In this example i am using VS2010 with .Net 4.0 as the framework.

The XML i am using is:

<!--?xml version="1.0" encoding="utf-8"?-->

 File.html

 List.html

 Data.html

 A4

Located in VS2010, and most likely VS2008 is the CreateSchema option in the XML menu, this becomes available when editing XML documents.

Using create schema on the above XML sheet would create a XSD document as below:


Using the XSD tool (Found in C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\xsd.exe with VS2010) it is possible to create a LINQ query-able Dataset/Class from XML.

Running the following from a CMD prompt will generate a class file that you can use in your application:

“C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\xsd.exe” C:\_DEVELOPMENT\Your.xsd /c /eld /edb /o:C:\_DEVELOPMENT\

What the command line parameters mean:

  • The Location of the xsd.exe
  • The Location of your xsd file
  • The Arguments:
  • /c indicates we are creating a class.
  • /eld indicates we are creating a dataset that can be queryable by LINQ
  • /edb indicates we are to allow data binding
  • The destination of the class file, in this instance it will be called Your.cs and placed in the C:\_DEVELOPMENT\ dicrectory.

Import the Your.cs class into the project you are working on.

I Have used all the following namespaces, plus the standard ones for a application/webapp:

using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

//The following function can de-serialze the ‘Convert Object’ from an XML document
public Convert GetConvert(string FilePath)
{
Convert res = null;
if (System.IO.File.Exists(FilePath)) //Check to see if the file is there
{
using (FileStream fs = new FileStream(FilePath, FileMode.Open)) // Load the file into a file stream
{
using (XmlReader reader = XmlReader.Create(fs)) // Create an XMLReader from the 
{
XmlSerializer serializer = new XmlSerializer(typeof(Convert)); //Prepare a serializer, with the Convert Object type
Convert deserializedconverts = serializer.Deserialize(reader) as Convert; // Deserialize an object
res = deserializedconverts; // * return the deserialized object.
}
}
}
return res; // * return the deserialized object.
}
//The following function can serialize a ‘Convert Object’ to an XML Document
public bool WriteConvert(string FilePath, Convert input)
{
try
{
using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate)) // Open or create a file named by the filepath param.
{
XmlWriterSettings writerSettings = new XmlWriterSettings() { Encoding = new UTF8Encoding(false) }; // set the encoding to UTF8
using (XmlWriter writer = XmlWriter.Create(fs, writerSettings)) // Create a new xml writer
{
XmlSerializerNamespaces names1 = new XmlSerializerNamespaces(); names1.Add(“”, “”); // Remove any silly microsoft namespaces
XmlSerializer serializer = new XmlSerializer(typeof(Convert)); // create us a serializer
serializer.Serialize(fs, input, names1); // serialize the object.
}
}
return true; // if it worked return true
}
catch (Exception ex)
{
return false; // if it didnt work return false
}
}

 

That’s essentially it, You may have to add references to both the System.Xml.Linq and the System.Data.DataSetExtensions if you get build Errors.

Copying Data Between/Within Tables in Sql

Simple method of copying data between tables or within the same table in SQL.

The following can be used to copy data within its own table, altering fields as required:

INSERT INTO Table1
(

[Some_Id],
,[Position]
,[Name]
,[Description]
,[LastAction]

)

SELECT

954 as Some_Id,
,[Position]
,[Name]
,[Description]
,[LastAction]
FROM Table1 where Some_Id = 52

The following can be used to copy data from a different table:

INSERT INTO Table1
(

[Some_Id],
,[Position]
,[Name]
,[Description]
,[LastAction]

)

SELECT

43 as Some_Id,
,[Position]
,[Name_First] + ‘ ‘ + [Name_Last]
,[Job_Title]
,NOW()
FROM tblStaff where Job_Title  like ‘%developer%’