The Awesomeness Of Interfaces

It is a wonder how i went so long without the greatness of the vb.net Interfaces. We’ve all made classes that we about the same so we just made a base class to hold all of the like data and build from there. What about the times when the classes had absolutly nothing to do with each other but you need them to share common actions such as a run command or a poopsy command?

This is where the interface comes in. With an interface you can create your base actions or functions. then we can create our new class, code what we want to code with what ever names we want them to have then implement the connectors of the interface to those specific functions or events. here is some very basic code to get the idea. there are many ways to use or even abuse this so use with care

Module Module1

    Sub Main()

        Dim someclass As MyCoolInterface = InitInterface(MyClasses.Class1)

        AddHandler someclass.CoolEvent, AddressOf cooleventhandler

        someclass.run()
        someclass.Poopsy()

        someclass = InitInterface(MyClasses.Class2)

        AddHandler someclass.CoolEvent, AddressOf cooleventhandler

        someclass.run()
        someclass.Poopsy()

    End Sub

    Function InitInterface(ByVal cname As MyClasses) As MyCoolInterface
        If cname = MyClasses.Class1 Then
            Return New Class2
        ElseIf cname = MyClasses.Class2 Then
            Return New Class2
        Else
            'somehthings wrong
            Return Nothing
        End If
    End Function

    Public Sub cooleventhandler()
        'do something when event is triggered. 
    End Sub

End Module

Public Enum MyClasses
    Class1
    Class2
End Enum

Public Interface MyCoolInterface
    Sub run()
    Sub Poopsy()
    Event CoolEvent()
End Interface

Public Class Class1
    Implements MyCoolInterface

    Public Event CoolEvent() Implements MyCoolInterface.CoolEvent

    Public Sub Poopsy() Implements MyCoolInterface.Poopsy
        'do some stuff
        RaiseEvent CoolEvent()
    End Sub

    Public Sub run() Implements MyCoolInterface.run
        'do some more stuff
        RaiseEvent CoolEvent()
    End Sub
End Class

Public Class Class2
    Implements MyCoolInterface

    Public Event CoolEvent() Implements MyCoolInterface.CoolEvent

    Public Sub Poopsy() Implements MyCoolInterface.Poopsy
        'Do something else
        RaiseEvent CoolEvent()
    End Sub

    Public Sub run() Implements MyCoolInterface.run
        'do some more
        RaiseEvent CoolEvent()
    End Sub
End Class
Posted in Uncategorized | Tagged , , , | Comments Off on The Awesomeness Of Interfaces

Item Of the Day. Playing .net io.stream using FMOD

So lets say you want to connect to a website to stream their music through your app, but the problem is they dont give you a direct link only a connectstream from system.net.connectstream. How do you play this with fmod? well after much trial and error and understanding the concept i have found the solution.

Im assuming you already know how to setup FMOD so i wont go through that.

1) you will get your stream and you must know the length. You will have to rely on the content length send over the http stream since you cant get the length of a io.stream when using http.

2) This is the fun part. You will need to take that stream and load it into a byte array. If you want your data in real time and dont want to load the entire buffer(dowload the entire file) you will need to load the data in a thread. Then you will need to trigger for the orginal thread to continue once the initial buffer length of the data has been loaded into the new byte array.

3) once the initial data has been loaded into the byte array just pass that byte data to FMOD createStream function then OPENMEMORY Flag and also create a CREATESOUNDEXINFO and pass those items in and then play your sound. The thread will still be loading the data in the background while the app is playing the sound or music.

There is some extra code in SaveMemTask that gets the pointer to the mem but it is not needed since that approach didnt work too good for me.

Check out the code below.

 Sub PlaySong(ByRef songStream As System.IO.Stream, ByVal streamLength As UInt32, ByVal stitle As String)

        Dim result As FMOD.RESULT
        If channel IsNot Nothing Then channel.stop()
        If sound IsNot Nothing Then sound.release()

        Dim sinfo As New FMOD.CREATESOUNDEXINFO
        sinfo.cbsize = Runtime.InteropServices.Marshal.SizeOf(sinfo)
        sinfo.length = streamLength
        sinfo.format = FMOD.SOUND_FORMAT.MPEG

        Dim streamptr As IntPtr = StreamToByteArray(songStream, streamLength)

        result = sys.createStream(rawData, (FMOD.MODE._2D Or FMOD.MODE.HARDWARE Or FMOD.MODE.CREATESTREAM Or FMOD.MODE.OPENMEMORY), sinfo, sound)

        result = sys.playSound(FMOD.CHANNELINDEX.FREE, sound, False, channel)
End Sub
Protected Function StreamToByteArray(ByRef songstream As IO.Stream, ByVal streamLength As UInt32) As IntPtr
        WaitForThread = True
        Me.streamLength = streamLength
        AddHandler InitDataRecived, AddressOf InitDataReceivedHandler

        trd = New System.Threading.Thread(AddressOf SaveMemTask)
        trd.IsBackground = True
        Me.songstream = songstream
        Me.saveTo = saveTo
        trd.Start()

        While WaitForThread = True
            Threading.Thread.Sleep(100)
        End While

        Return MyStreamPtr
    End Function
 'Global Variables     Protected rawData() As Byte
    Dim streamLength As UInt32
    Private Sub SaveMemTask()

        ReDim rawData(streamLength)
        Dim ran As Boolean = False
        Dim sLength As Integer = 1024
        Dim buffer(sLength) As Byte
        Dim bytesRead As Integer = songstream.Read(Buffer, 0, sLength)
        Dim bpos As Integer = 0

        While (bytesRead > 0)

            For i As Integer = 0 To bytesRead - 1
                rawData(i + bpos) = buffer(i)
            Next

            bpos += bytesRead
            If ran = False Then
                ran = True
                rawDataHandle = GCHandle.Alloc(rawData, GCHandleType.Pinned)
                address = rawDataHandle.AddrOfPinnedObject()
                RaiseEvent InitDataRecived(address)
            Else

            End If

            bytesRead = songstream.Read(Buffer, 0, sLength)
        End While

    End Sub
    Private Sub InitDataReceivedHandler(ByVal ptr As IntPtr)
        MyStreamPtr = ptr
        WaitForThread = False
    End Sub
    Private songstream As IO.Stream
    Private saveTo As String
    Private WaitForThread As Boolean = True
    Private MyStreamPtr As IntPtr
    Protected Event InitDataRecived(ByVal ptr As IntPtr)
Posted in Uncategorized | Tagged , , , , , , | 16 Comments

Item of the Day: Transparent Textures with Android Opengl es

So on my quest to make a new android app i ran into an issue. My stupid texture would not filter the black from the image so that portion could become trasparent. But never fear after much searching and me having done it with the full version of opengl i have found my solution.

1) Turn your image into a PNG.

2) If you dont have an alpha channel just add one using GIMP. Its really easy to do just search it.

3) Load your Texture (This is loading from a resource)

InputStream is = context.getResources().openRawResource(R.drawable.circle);
Bitmap bitmap = null;
try {

	BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeStream(is, null, bitmapOptions);

	} finally {

	try {
		is.close();
		is = null;
	  } catch (IOException e) {
	  }
	}

	gl.glGenTextures(1, textures, 0);

	gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
	gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

	GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
	bitmap.recycle();

4)  Draw that texture

gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

gl.glFrontFace(GL10.GL_CCW);

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

gl.glDrawElements(GL10.GL_TRIANGLES, 6, GL10.GL_UNSIGNED_BYTE, indexBuffer);

gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

5) Done

See that was easy.

Posted in Uncategorized | Tagged , , , | 6 Comments

Website login through code

website logins are an easy thing to do. All you have to remember is post all inputs for the form. Also always check for any javascript in the form that might need to be implemented in your code. Once you do that you are good to go. Here is a snippet of the post function.

 Private Function WebPost(ByVal URL As String, ByVal PostData As String) As String
        Try

            Dim responsedata As String
            Dim responsereader As IO.StreamReader
            webrequest = CType(webrequest.Create(URL), Net.HttpWebRequest)
            webrequest.Method = "POST"
            webrequest.UserAgent = "Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101"

            webrequest.ContentType = "application/x-www-form-urlencoded"
            webrequest.CookieContainer = cookies
            ' write the form values into the request message
            Dim requestWriter As IO.StreamWriter = New IO.StreamWriter(webrequest.GetRequestStream())
            requestWriter.Write(PostData)
            requestWriter.Close()

            responsereader = New IO.StreamReader(webrequest.GetResponse().GetResponseStream())
            'and read the response
            responsedata = responsereader.ReadToEnd()
            responsereader.Close()
            webrequest.GetResponse().Close()

            Return responsedata
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        Return ""

    End Function
Posted in Uncategorized | 236 Comments

Blurb of the day

If you ever decide you need to load a datatable from an xml file just remember if you export from a datatable to an xml file it will use that data tables name in the xml file. Why is this important you might ask well it is because that name is case sensitive when you are loading into a new datatable for another project. If you try to load a table but the records wont go into the table check the table name to make sure it matches exactly whats in the xml file. empRecords is not the same as EmpRecords when loading datatables and naming them. Remember

empRecords is not the same as EmpRecords

Posted in Uncategorized | Tagged , , | 16 Comments

Interesting Item of the Day

In the process of making my media player, which is always changing, I wanted to add a plugin system to my player. One of the problems i always face is adding new features. Its not that i cant add them but i forget about them  and they never get done. So to alleviate that i implemented a plugin system.

It loads the dlls dynamically and i needed to figure out how to see if a class implemented the interface for the plugin, so that i could load only the ones who implment the interface in and i came across this jewel.

Type.IsAssignableFrom(type) is the piece of code that allowed for this to work correctly. heres snippet.

            Dim assm As Assembly = Assembly.LoadFrom(dlllocation)

            For Each assmtype As Type In assm.GetTypes

                If GetType(PluginContainer.IPlugin).IsAssignableFrom(assmtype) AndAlso Not assmtype.IsAbstract Then
                    ComboBox1.Items.Add(assmtype.FullName)
                End If

            Next

With this i was able load the dll, get all the classes and the see if any of them implement the interface. if they do then you can just show those and then for me i load them up to be used in the media player later. You can do anything you want with it.

Posted in Uncategorized | Tagged , , | 3 Comments

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!

Posted in Uncategorized | 2 Comments