//        connect s6 via usb .
        // turn on wifi!
        // kill adb

        //"x:\util\android-sdk-windows\platform-tools\adb.exe"  tcpip 5555
        // restarting in TCP mode port: 5555

        //13: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
        //    inet 192.168.1.126/24 brd 192.168.1.255 scope global wlan0
        //       valid_lft forever preferred_lft forever

        // on red
        // "x:\util\android-sdk-windows\platform-tools\adb.exe" connect  192.168.1.126:5555
        // connected to 192.168.1.126:5555



        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151121
        // http://stackoverflow.com/questions/17513502/support-for-multi-window-app-development

        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this);

            b.setText("Vibrate!");

            b.AtClick(
                delegate
                {
                    var vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);

                    vibrator.vibrate(600);
                }
            );

            ll.addView(b);



            this.setContentView(sv);


            //this.ShowLongToast("http://my.jsc-solutions.net x");
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            var activity = this;

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);



            b.WithText("before AtClick");
            b.AtClick(
                v =>
                {
                    b.setText("AtClick");
                }
            );


        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);



            b.WithText(Foo.Bar("hello via .java"));
            b.AtClick(
                v =>
                {
                    b.WithText(Foo.Bar("click!"));
                }
            );



            this.setContentView(sv);
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);



            b.WithText("popup");
            b.AtClick(
                v =>
                {
                    XStandOutWindow.closeAll(this, typeof(XWidgetsWindow).ToClass());
                    XStandOutWindow.show(this, typeof(XWidgetsWindow).ToClass(), XStandOutWindow.DEFAULT_ID);

                    this.finish();

                }
            );

            this.setContentView(sv);
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);


            
            b.WithText("before AtClick");
            b.AtClick(
                v =>
                {
                    b.setText("AtClick");
                }
            );

            var b2 = new Button(this);
            b2.setText("The other button!");
            ll.addView(b2);

            this.setContentView(sv);
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            var b = new Button(this);
            b.setText("I don't do anything, but I was added dynamically. :)");
            ll.addView(b);


            Action onclick = delegate
            {
                b.setText("onclick");
            };

            b.setText("before AtClick");
            b.AtClick(
                v =>
                {
                    b.setText("AtClick");
                }
            );

            var b2 = new Button(this);
            b2.setText("The other button!");
            ll.addView(b2);

            this.setContentView(sv);
        }
        // http://stackoverflow.com/questions/6274141/trigger-background-service-at-a-specific-time-in-android
        // http://stackoverflow.com/questions/7144908/how-is-an-intent-service-declared-in-the-android-manifest
        // http://developer.android.com/guide/topics/manifest/service-element.html


        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // http://developer.android.com/guide/topics/ui/notifiers/notifications.html

            base.onCreate(savedInstanceState);

            ScrollView sv = new ScrollView(this);

            LinearLayout ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);

            sv.addView(ll);

            #region startservice
            var startservice = new Button(this);
            startservice.setText("Start Service to send Notification");
            startservice.AtClick(
               delegate
               {
                   this.ShowToast("startservice_onclick");

                   var intent = new Intent(this, typeof(NotifyService).ToClass());

                   this.startService(intent);
               }
            );
            ll.addView(startservice);
            #endregion

            #region stopservice
            var stopservice = new Button(this);
            stopservice.setText("Stop Service");
            stopservice.AtClick(
                delegate
                {
                    this.ShowToast("stopservice_onclick");

                    Intent intent = new Intent();
                    intent.setAction(NotifyService.ACTION);
                    intent.putExtra("RQS", NotifyService.RQS_STOP_SERVICE);
                    this.sendBroadcast(intent);

                }
            );
            ll.addView(stopservice);
            #endregion

            this.setContentView(sv);

            this.ShowToast("http://jsc-solutions.net");


        }
Ejemplo n.º 8
0
        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // why isnt jsc doing automatic ref?
            var r = default(global::ScriptCoreLib.Android.Windows.Forms.IAssemblyReferenceToken_Forms);

            ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext = this;

            // X:\jsc.svn\examples\java\android\forms\FormsMessageBox\FormsMessageBox\Library\ApplicationControl.cs

            // cmd /K c:\util\android-sdk-windows\platform-tools\adb.exe logcat
            // Camera PTP

            // http://developer.android.com/guide/topics/ui/notifiers/notifications.html

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            var b = new android.widget.Button(this);

            // jsc is doing the wrong thing here
            //var SDK_INT = android.os.Build.VERSION.SDK_INT;

            //b.setText("Notify! " + new { SDK_INT, android.os.Build.VERSION.SDK });
            b.setText("Notify! ");
            int counter = 0;

            b.AtClick(
                delegate
            {
                counter++;



                var f = new Form1();

                var value = f.ShowDialog();

                b.setText("ShowDialog! " + new { value, f.textBox1.Text });
            }
                );

            ll.addView(b);

            this.setContentView(sv);
        }
        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // why isnt jsc doing automatic ref?
            var r = default(global::ScriptCoreLib.Android.Windows.Forms.IAssemblyReferenceToken_Forms);
            ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext = this;

            // X:\jsc.svn\examples\java\android\forms\FormsMessageBox\FormsMessageBox\Library\ApplicationControl.cs

            // cmd /K c:\util\android-sdk-windows\platform-tools\adb.exe logcat
            // Camera PTP

            // http://developer.android.com/guide/topics/ui/notifiers/notifications.html

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            var b = new android.widget.Button(this);

            // jsc is doing the wrong thing here
            //var SDK_INT = android.os.Build.VERSION.SDK_INT;

            //b.setText("Notify! " + new { SDK_INT, android.os.Build.VERSION.SDK });
            b.setText("Notify! " );
            int counter = 0;

            b.AtClick(
                delegate
            {
                counter++;



                var f = new Form1();

                var value = f.ShowDialog();

                b.setText("ShowDialog! " + new { value, f.textBox1.Text });
            }
            );

            ll.addView(b);

            this.setContentView(sv);
        }
        static __InitializeAndroidActivity()
        {
            Console.WriteLine("StaticInvoke");

            //  Exception Ljava/lang/RuntimeException; thrown while initializing LTryHideActionbarExperiment/StaticInvoke;
            try
            {


                // https://groups.google.com/forum/?fromgroups=#!topic/android-developers/suLMCWiG0D8
                var c = ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext;


                (ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext as Activity).runOnUiThread(
                    a =>
                    {
                        // http://stackoverflow.com/questions/4451641/change-android-layout-programatically

                        var sv = new ScrollView(a);
                        var ll = new LinearLayout(a);
                        //ll.setOrientation(LinearLayout.VERTICAL);
                        sv.addView(ll);

                        var b = new Button(a).AttachTo(ll);



                        b.WithText("before AtClick");
                        b.AtClick(
                            v =>
                            {
                                b.setText("AtClick");
                            }
                        );

                        var b2 = new Button(a);
                        b2.setText("The other button!");
                        ll.addView(b2);

                        a.setContentView(sv);
                    }
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + new { ex.Message, ex.StackTrace });
            }
        }
        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            //// http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/

            base.onCreate(savedInstanceState);

            ScrollView sv = new ScrollView(this);

            LinearLayout ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);

            sv.addView(ll);


            var b = new Button(this);

            b.setText("Vibrate!");

            b.AtClick(
                delegate
                {
                    var vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);

                    vibrator.vibrate(600);
                }
            );

            ll.addView(b);





            this.setContentView(sv);


            //this.ShowLongToast("Monese circle progressbar");

            //circularSeekbar = new CircularSeekBar(this);
            //circularSeekbar.setMaxProgress(100);
            //circularSeekbar.setProgress(100);
            //setContentView(circularSeekbar);
            //circularSeekbar.invalidate();

            //circularSeekbar.setSeekBarChangeListener(new TestAndroidCircleProgressbar.Activities.CircularSeekBar.MyOnSeekChangeListener());

        }
        // http://stackoverflow.com/questions/19954156/android-build-separate-apks-for-different-processor-architectures
        // "X:\jsc.svn\examples\java\android\Test\TestChromeAsAsset\TestChromeAsAsset.sln"

        //  [aapt] W:\bin\AndroidManifest.xml:14: error: Error: No resource found that matches the given name (at 'label' with value '@string/app_name').



        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this);

            b.setText(
                // X:\jsc.svn\examples\c\android\Test\TestNDKAsAsset\TestNDKAsAsset\Program.cs
                // http://stackoverflow.com/questions/19954156/android-build-separate-apks-for-different-processor-architectures


                //  <package id="TestNDKAsAssetFromSharedLibrary" version="1.0.0.0" targetFramework="net4" userInstalled="true" />
                // X:\jsc.svn\examples\java\android\synergy\OVRVrCubeWorldNativeActivity\OVRVrCubeWorldNativeActivity\ApplicationActivity.cs

                // can we load that native so into a separate process?
                // switch to native and back?
                TestNDKAsAsset.xActivity.stringFromJNI()
            //"Vibrate!"
            );

            b.AtClick(
                delegate
                {
                    var vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);

                    vibrator.vibrate(600);
                }
            );

            ll.addView(b);



            this.setContentView(sv);


            //this.ShowLongToast("http://my.jsc-solutions.net x");
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);



            b.AtClick(
                v =>
                {
                    b.setText("AtClick");
                }
            );

            //var b2 = new Button(this);
            //b2.setText("The other button!");
            //ll.addView(b2);

            var ipa = Dns.GetHostAddresses(getLocalIpAddress())[0];

            var port = 8080;

            b.WithText(ipa + ":" + port);

            ClassLibrary1.Class1Shared.CreateServer(
                ipa,
                port,
                x =>
                {
                    //b.WithText(x);
                    android.util.Log.wtf("APKWebServer", x);
                }
            ).Start();

            this.setContentView(sv);
        }
        // http://www.codeproject.com/Tips/623446/Style-Any-Activity-as-an-Alert-Dialog-in-Android
        // android:theme="@android:style/Theme.Holo.Dialog"



        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext = this;

            // X:\jsc.svn\examples\java\android\forms\AndroidFormsActivity\AndroidFormsActivity\ApplicationActivity.cs

            // cmd /K c:\util\android-sdk-windows\platform-tools\adb.exe logcat
            // Camera PTP

            // http://developer.android.com/guide/topics/ui/notifiers/notifications.html

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            var b = new android.widget.Button(this);

            // jsc is doing the wrong thing here
            var SDK_INT = android.os.Build.VERSION.SDK_INT;

            b.setText("Notify! " + new { SDK_INT, android.os.Build.VERSION.SDK });
            int counter = 0;



            // http://stackoverflow.com/questions/12900795/how-to-get-a-pin-number-password-keyboard-in-android
            //var t = new EditText(this);
            //t.setInputType(android.text.InputType.TYPE_NUMBER_VARIATION_PASSWORD);
            //t.setTransformationMethod(android.text.method.PasswordTransformationMethod.getInstance());
            //ll.addView(t);

            // ScriptCoreLib.Ultra ?
            b.AtClick(
                delegate
            {
                counter++;

                // X:\jsc.svn\examples\javascript\android\Test\TestPINDialog\TestPINDialog\ApplicationWebService.cs

                var alertDialog = new AlertDialog.Builder(this);

                alertDialog.setTitle("Hello world");



                alertDialog.setPositiveButton("OK",
                                              new xOnClickListener
                {
                    yield = delegate
                    {
                        b.setText("clicked! " + new { id = Thread.currentThread().getId() });
                    }
                }

                                              );


                var cc = new AndroidFormsActivity.ApplicationControl();


                //ScriptCoreLib.Extensions.Android.AndroidFormsExtensions.AttachTo(
                //    cc,

                // X:\jsc.svn\core\ScriptCoreLibAndroid.Windows.Forms\ScriptCoreLibAndroid.Windows.Forms\Extensions\Android\AndroidFormsExtensions.cs

                __Control _cc = cc;

                _cc.InternalSetContext(this);

                alertDialog.setView(_cc.InternalGetElement());


                // skip icons?
                //alertDialog.setIcon(android.R.drawable.star_off);

                // can we do async yet?
                alertDialog.create().show();
            }
                );

            ll.addView(b);

            this.setContentView(sv);

            // X:\jsc.svn\examples\java\android\HelloOpenGLES20Activity\HelloOpenGLES20Activity\ScriptCoreLib.Android\Shader.cs

            // Error	1	'FormsMessageBox.Activities.ApplicationActivity' does not contain a definition for 'ShowLongToast' and no extension method 'ShowLongToast' accepting a first argument of type 'FormsMessageBox.Activities.ApplicationActivity' could be found (are you missing a using directive or an assembly reference?)	X:\jsc.svn\examples\java\android\FormsMessageBox\FormsMessageBox\ApplicationActivity.cs	80	18	FormsMessageBox
            //this.ShowLongToast("http://jsc-solutions.net");
        }
        // http://stackoverflow.com/questions/17513502/support-for-multi-window-app-development

        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this);

            b.setText("Vibrate!");

            b.AtClick(
                async delegate
                {
                    var vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);

                    vibrator.vibrate(600);

                    // or jump to laptop pointerlock?

                    SwitchToCompiler.Invoke(
                        delegate
                        {
                            // did we jump back to compiler?
                            // UDP?
                            // RSA?


                        }
                    );

                    // or

                    //        [javac] W:\src\ADBSwitchToCompiler\Activities\ApplicationActivity___onCreate_b__0_0_d__MoveNext_0600000f.java:48: error: cannot find symbol
                    //[javac]         ApplicationActivity___onCreate_b__0_0_d__MoveNext_0600000f.__workflow(next_0600000f0, ref_awaiter1, ref_compiler2, ref_create_b__0_0_d3);
                    //[javac]                                                                                                                            ^

                    // roslyn wont like it?
                    await default(SwitchToCompiler);
                    // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTab\ChromeExtensionHopToTab\Application.cs

                    // did we jump back to compiler?
                    // UDP?
                    // RSA?


                    Console.WriteLine("record screen");

                    Console.WriteLine("pull");

                    // https://developers.google.com/youtube/v3/code_samples/dotnet

                }
            );

            ll.addView(b);



            this.setContentView(sv);


            //this.ShowLongToast("http://my.jsc-solutions.net x");
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            var file1 = "http://a.tumblr.com/tumblr_m8ueqqpyyy1rs64dko1.mp3";
            var name1 = "E43 Understanding the Dangers of Ego-Depletion by Tim";

            base.onCreate(savedInstanceState);

            var downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
            var preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new android.widget.Button(this).AttachTo(ll);

            downloadReceiver = new MyDownloadReceiver
            {

            };

            //            O:\src\AndroidDownloadManagerActivity\Activities\ApplicationActivity___c__DisplayClass2___c__DisplayClass4.java:60: cannot find symbol
            //symbol  : class Button
            //location: class AndroidDownloadManagerActivity.Activities.ApplicationActivity___c__DisplayClass2___c__DisplayClass4
            //                    ViewExtensions.<Button>WithText(this.CS___8__locals3.b, "Download " + this.CS___8__locals3.name1);
            //                                    ^

            b.WithText("Download " + name1);
            b.AtClick(
                v =>
                {

                    b.setText("Downloading...");
                    b.setEnabled(false);

                    var downloadUri = android.net.Uri.parse(file1);

                    // http://developer.android.com/reference/android/app/DownloadManager.Request.html
                    var request = new DownloadManager.Request(downloadUri);

                    request.setTitle("idea-remixer");
                    request.setDescription(name1);

                    // W/DownloadManager(15222): Aborting request for download 166: while trying to execute request: 
                    // java.net.UnknownHostException: Unable to resolve host "a.tumblr.com": 
                    // No address associated with hostname
                    var id = downloadManager.enqueue(request);

                    Toast.makeText(this, new { id, downloadUri }.ToString(), Toast.LENGTH_LONG).show();

                    //Save the request id   

                    //var PrefEdit = preferenceManager.edit();
                    //PrefEdit.putLong(strPref_Download_ID, id);
                    //PrefEdit.commit();

                    downloadReceiver.AtReceive = delegate
                    {
                        DownloadManager.Query query = new DownloadManager.Query();
                        //query.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0));
                        // http://developer.android.com/reference/android/app/DownloadManager.Query.html#setFilterById(long...)
                        query.setFilterById(new[] { id });
                        Cursor cursor = downloadManager.query(query);

                        if (cursor.moveToFirst())
                        {
                            int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                            int status = cursor.getInt(columnIndex);

                            if (status == DownloadManager.STATUS_FAILED)
                            {
                                Toast.makeText(this, new { id, status }.ToString(), Toast.LENGTH_LONG).show();

                                b.WithText("(failed) Download " + name1);
                                b.setEnabled(true);
                            }
                            else if (status == DownloadManager.STATUS_SUCCESSFUL)
                            {
                                //Retrieve the saved request id     
                                //long downloadID = preferenceManager.getLong(strPref_Download_ID, 0);
                                var uri = downloadManager.getUriForDownloadedFile(id);


                                Toast.makeText(this, new { id, uri }.ToString(), Toast.LENGTH_LONG).show();

                                // jsc ignores this type in import?
                                Button __ref0;

                                b.WithText("Download " + name1);
                                b.setEnabled(true);

                                //ParcelFileDescriptor file;
                                //try
                                //{
                                //    file = downloadManager.openDownloadedFile(downloadID);
                                //    //FileInputStream fileInputStream       = new ParcelFileDescriptor.AutoCloseInputStream(file); 
                                //    //Bitmap bm = BitmapFactory.decodeStream(fileInputStream);
                                //    //image.setImageBitmap(bm);   
                                //}
                                //catch // (FileNotFoundException e) 
                                //{      // TODO Auto-generated catch block   
                                //    //e.printStackTrace();     
                                //    throw;
                                //}
                            }
                        }
                    };

                }
            );


            this.setContentView(sv);
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var b2 = new Button(this);
            {
                var ll = new LinearLayout(this);
                //ll.setOrientation(LinearLayout.VERTICAL);
                sv.addView(ll);

                var b1 = new Button(this).AttachTo(ll);



                b1.WithText("LANBroadcastListener createMulticastLock");


                var c = 0;

                b1.AtClick(
                    v =>
                    {
                        //                 server error { Message = , StackTrace = android.os.NetworkOnMainThreadException
                        //at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
                        //at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
                        //at libcore.io.IoBridge.sendto(IoBridge.java:473)
                        //at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182)
                        //at java.net.DatagramSocket.send(DatagramSocket.java:284)

                        new Thread(
                            delegate()
                            {

                                try
                                {
                                    var socket = new DatagramSocket(); //construct a datagram socket and binds it to the available port and the localhos

                                    c++;

                                    var b = Encoding.UTF8.GetBytes(c + " hi from jvm!");    //creates a variable b of type byte
                                    var dgram = new DatagramPacket((sbyte[])(object)b, b.Length, InetAddress.getByName("239.1.2.3"), 40404);//sends the packet details, length of the packet,destination address and the port number as parameters to the DatagramPacket  
                                    //dgram.setData(b);
                                    //System.Console.WriteLine(
                                    //    "Sending " + b.Length + " bytes to " + dgram.getAddress() + ":" + dgram.getPort());//standard error output stream
                                    socket.send(dgram); //send the datagram packet from this port
                                }
                                catch (Exception ex)
                                {
                                    System.Console.WriteLine("server error " + new { ex.Message, ex.StackTrace });
                                }

                            }
                                )
                               {

                                   Name = "sender"
                               }.Start();
                    }
                );

                b2.setText("The other button!");
                ll.addView(b2);

                this.setContentView(sv);
            }


            // http://www.zzzxo.com/q/answers-android-device-not-receiving-multicast-package-13221736.html



            new Thread(
                delegate()
                {
                    // http://stackoverflow.com/questions/12610415/multicast-receiver-malfunction
                    // http://answers.unity3d.com/questions/250732/android-build-is-not-receiving-udp-broadcasts.html

                    // Acquire multicast lock
                    wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
                    multicastLock = wifi.createMulticastLock("multicastLock");
                    //multicastLock.setReferenceCounted(true);
                    multicastLock.acquire();

                    System.Console.WriteLine("LANBroadcastListener ready...");
                    try
                    {
                        byte[] b = new byte[0x100];

                        // https://code.google.com/p/android/issues/detail?id=40003

                        var port = 40404;

                        MulticastSocket socket = new MulticastSocket(port); // must bind receive side
                        socket.setBroadcast(true);
                        socket.setReuseAddress(true);
                        socket.setTimeToLive(30);
                        socket.setReceiveBufferSize(0x100);
                        
                        // https://code.google.com/p/android/issues/detail?id=40003
                        // http://stackoverflow.com/questions/6550618/multicast-support-on-android-in-hotspot-tethering-mode
                        // http://www.massapi.com/class/java/net/InetSocketAddress.java.html
                        // http://www.javadocexamples.com/java/net/MulticastSocket/joinGroup(SocketAddress%20mcastaddr,NetworkInterface%20netIf).html
                        // http://grokbase.com/t/hadoop/common-issues/117jsjk8d7/jira-created-hadoop-7472-rpc-client-should-deal-with-the-ip-address-changes

                        var group = InetAddress.getByName("239.1.2.3");
                        var groupSockAddr = new InetSocketAddress(group, port);

                        // what lan interfaces do we have?
                        socket.joinGroup(groupSockAddr,
                            NetworkInterface.getByName("wlan0")
                        );

                        System.Console.WriteLine("LANBroadcastListener joinGroup...");
                        while (true)
                        {
                            DatagramPacket dgram = new DatagramPacket((sbyte[])(object)b, b.Length);
                            socket.receive(dgram); // blocks until a datagram is received

                            var bytes = new MemoryStream((byte[])(object)dgram.getData(), 0, dgram.getLength());


                            var listen = Encoding.UTF8.GetString(bytes.ToArray());

                            System.Console.WriteLine("Received "
                                + dgram.getLength()
                                + " bytes from " + dgram.getAddress());
                            //dgram.setLength(b.Length); // must reset length field!s



                        }
                    }
                    catch
                    {
                        System.Console.WriteLine("client error");
                    }
                }
            )
            {

                Name = "client"
            }.Start();

        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            var activity = this;
            // http://stackoverflow.com/questions/11425020/actionbar-in-a-dialogfragment
            //To show activity as dialog and dim the background, you need to declare android:theme="@style/PopupTheme" on for the chosen activity on the manifest
            //activity.requestWindowFeature(Window.FEATURE_ACTION_BAR);
            //activity.getWindow().setFlags(WindowManager_LayoutParams.FLAG_DIM_BEHIND, WindowManager_LayoutParams.FLAG_DIM_BEHIND);
            //activity.getWindow().setFlags(WindowManager_LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager_LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //var @params = activity.getWindow().getAttributes();
            ////@params.height = WindowManager_LayoutParams.FILL_PARENT;
            ////@params.width = 850; //fixed width
            ////@params.height = 450; //fixed width
            //@params.alpha = 1.0f;
            //@params.dimAmount = 0.5f;
            //activity.getWindow().setAttributes(@params);
            //activity.getWindow().setLayout(850, 850);
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);


            // https://stackoverflow.com/questions/1898886/removing-an-activity-from-the-history-stack

            b.WithText("start secondary");
            b.AtClick(
                v =>
                {
                    foo = "hi";

                    Intent intent = new Intent(this, typeof(SecondaryActivity).ToClass());
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }
            );

            this.AtPause += delegate { b.setText("AtPause"); };
            this.AtResume += delegate { b.setText("AtResume"); };


            AtPrepareOptions +=
                value =>
                {
                    value.clear();

                    var item1 = value.add(
                         (java.lang.CharSequence)(object)"http://abstractatech.com"
                    );



                    item1.setIcon(android.R.drawable.ic_menu_view);

                    var item2 = value.add(
                        (java.lang.CharSequence)(object)"http://jsc-solutions.net"
                    );

                    //item2.setIcon(android.R.drawable.ic_menu_edit);
                    item2.setIcon(android.R.drawable.ic_menu_view);

                    var i = new Intent(Intent.ACTION_VIEW,
                        android.net.Uri.parse("http://jsc-solutions.net")
                    );

                    // http://vaibhavsarode.wordpress.com/2012/05/14/creating-our-own-activity-launcher-chooser-dialog-android-launcher-selection-dialog/
                    var ic = Intent.createChooser(i, "http://jsc-solutions.net");


                    item2.setIntent(
                        ic
                    );
                };

            AtOption +=
                item =>
                {

                    //b.WithText("menu was clicked!" + (string)(object)item.getTitle());
                    b.WithText("menu was clicked!" + new { item });
                };

            var b2 = new Button(this);
            b2.setText("The other button!");
            ll.addView(b2);

            this.setContentView(sv);



            vConfigurationChanged = e =>
            {
                var orientation = getScreenOrientation();

                var SystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();

                b2.setText(
                    new
                    {
                        orientation,
                        SystemUiVisibility
                    }.ToString()
                );


                if (orientation == Configuration.ORIENTATION_LANDSCAPE)
                {
                    hideSystemUI();
                }
                else
                {
                    showSystemUI();
                }
            };

            vConfigurationChanged(null);
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            var file1 = "http://a.tumblr.com/tumblr_m8ueqqpyyy1rs64dko1.mp3";
            var name1 = "E43 Understanding the Dangers of Ego-Depletion by Tim";

            base.onCreate(savedInstanceState);

            var downloadManager   = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
            var preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new android.widget.Button(this).AttachTo(ll);

            downloadReceiver = new MyDownloadReceiver
            {
            };

            //            O:\src\AndroidDownloadManagerActivity\Activities\ApplicationActivity___c__DisplayClass2___c__DisplayClass4.java:60: cannot find symbol
            //symbol  : class Button
            //location: class AndroidDownloadManagerActivity.Activities.ApplicationActivity___c__DisplayClass2___c__DisplayClass4
            //                    ViewExtensions.<Button>WithText(this.CS___8__locals3.b, "Download " + this.CS___8__locals3.name1);
            //                                    ^

            b.WithText("Download " + name1);
            b.AtClick(
                v =>
            {
                b.setText("Downloading...");
                b.setEnabled(false);

                var downloadUri = android.net.Uri.parse(file1);

                // http://developer.android.com/reference/android/app/DownloadManager.Request.html
                var request = new DownloadManager.Request(downloadUri);

                request.setTitle("idea-remixer");
                request.setDescription(name1);

                // W/DownloadManager(15222): Aborting request for download 166: while trying to execute request:
                // java.net.UnknownHostException: Unable to resolve host "a.tumblr.com":
                // No address associated with hostname
                var id = downloadManager.enqueue(request);

                Toast.makeText(this, new { id, downloadUri }.ToString(), Toast.LENGTH_LONG).show();

                //Save the request id

                //var PrefEdit = preferenceManager.edit();
                //PrefEdit.putLong(strPref_Download_ID, id);
                //PrefEdit.commit();

                downloadReceiver.AtReceive = delegate
                {
                    DownloadManager.Query query = new DownloadManager.Query();
                    //query.setFilterById(preferenceManager.getLong(strPref_Download_ID, 0));
                    // http://developer.android.com/reference/android/app/DownloadManager.Query.html#setFilterById(long...)
                    query.setFilterById(new[] { id });
                    Cursor cursor = downloadManager.query(query);

                    if (cursor.moveToFirst())
                    {
                        int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        int status      = cursor.getInt(columnIndex);

                        if (status == DownloadManager.STATUS_FAILED)
                        {
                            Toast.makeText(this, new { id, status }.ToString(), Toast.LENGTH_LONG).show();

                            b.WithText("(failed) Download " + name1);
                            b.setEnabled(true);
                        }
                        else if (status == DownloadManager.STATUS_SUCCESSFUL)
                        {
                            //Retrieve the saved request id
                            //long downloadID = preferenceManager.getLong(strPref_Download_ID, 0);
                            var uri = downloadManager.getUriForDownloadedFile(id);


                            Toast.makeText(this, new { id, uri }.ToString(), Toast.LENGTH_LONG).show();

                            // jsc ignores this type in import?
                            Button __ref0;

                            b.WithText("Download " + name1);
                            b.setEnabled(true);

                            //ParcelFileDescriptor file;
                            //try
                            //{
                            //    file = downloadManager.openDownloadedFile(downloadID);
                            //    //FileInputStream fileInputStream       = new ParcelFileDescriptor.AutoCloseInputStream(file);
                            //    //Bitmap bm = BitmapFactory.decodeStream(fileInputStream);
                            //    //image.setImageBitmap(bm);
                            //}
                            //catch // (FileNotFoundException e)
                            //{      // TODO Auto-generated catch block
                            //    //e.printStackTrace();
                            //    throw;
                            //}
                        }
                    }
                };
            }
                );


            this.setContentView(sv);
        }
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151212/androidudpclipboard
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160101/ovrwindwheelndk

        //        connect s6 via usb .
        // turn on wifi!
        // kill adb

        //"x:\util\android-sdk-windows\platform-tools\adb.exe"  tcpip 5555
        // restarting in TCP mode port: 5555

        //13: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
        //    inet 192.168.1.126/24 brd 192.168.1.255 scope global wlan0
        //       valid_lft forever preferred_lft forever

        // on red
        // "x:\util\android-sdk-windows\platform-tools\adb.exe" connect  192.168.1.126:5555
        // connected to 192.168.1.126:5555



        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151121
        // http://stackoverflow.com/questions/17513502/support-for-multi-window-app-development

        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this);

            b.setText("Vibrate!");

            var sw = Stopwatch.StartNew();



            Action cleanup = delegate { };

            Notification reuse = null;
            var notificationIntent = new Intent(this, typeof(ApplicationActivity).ToClass());
            var contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Action<string> SetClipboard = value =>
            {
                Console.WriteLine("SetClipboard " + new { value });

                this.runOnUiThread(
                    delegate
                    {
                        cleanup();

                        b.setText(value);




                        if (reuse != null)
                        {
                            reuse.setLatestEventInfo(
                                 this,
                                 contentTitle: value,
                                 contentText: "",
                                 contentIntent: contentIntent);

                            return;
                        }

                        var xNotificationManager = (NotificationManager)this.getSystemService(Activity.NOTIFICATION_SERVICE);

                        // see http://developer.android.com/reference/android/app/Notification.html
                        var xNotification = new Notification(
                            //android.R.drawable.ic_dialog_alert,
                            android.R.drawable.ic_menu_view,
                            //tickerText: "not used?",
                            tickerText: value,


                            when: 0
                            //java.lang.System.currentTimeMillis()
                        );

                        //notification.defaults |= Notification.DEFAULT_SOUND;



                        // flags = Notification.FLAG_ONGOING_EVENT 

                        var FLAG_ONGOING_EVENT = 0x00000002;
                        //notification.flags |= Notification.FLAG_ONGOING_EVENT;
                        //xNotification.flags |= FLAG_ONGOING_EVENT;

                        xNotification.setLatestEventInfo(
                            this,
                            contentTitle: value,
                            contentText: "",
                            contentIntent: contentIntent);

                        //notification.defaults |= Notification.DEFAULT_VIBRATE;
                        //notification.defaults |= Notification.DEFAULT_LIGHTS;
                        // http://androiddrawableexplorer.appspot.com/

                        var id = (int)sw.ElapsedMilliseconds;

                        xNotificationManager.notify(id, xNotification);

                        var xVibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);
                        xVibrator.vibrate(600);



                        #region setPrimaryClip
                        android.content.ClipboardManager clipboard = (android.content.ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("label", value);
                        clipboard.setPrimaryClip(clip);
                        #endregion

                        reuse = xNotification;


                        cleanup += delegate
                        {
                            // https://developer.android.com/reference/android/app/Notification.html

                            if (xNotification == null)
                                return;

                            xNotificationManager.cancel(id);
                        };
                    }
                );
            };


            b.AtClick(
                delegate
                {
                    SetClipboard("hello");
                }
            );



            // Z:\jsc.svn\examples\c\android\Test\TestNDKUDP\TestNDKUDP\xNativeActivity.cs

            #region lets listen to incoming udp
            // could we define our chrome app inline in here?
            // or in a chrome app. could we define the android app inline?
            #region ReceiveAsync
            Action<IPAddress> f = async nic =>
            {
                b.setText("awaiting at " + nic);


                WifiManager wifi = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
                var lo = wifi.createMulticastLock("udp:49814");
                lo.acquire();

                // Z:\jsc.svn\examples\java\android\AndroidUDPClipboard\ApplicationActivity.cs
                // X:\jsc.svn\examples\java\android\forms\FormsUDPJoinGroup\FormsUDPJoinGroup\ApplicationControl.cs
                // X:\jsc.svn\examples\java\android\LANBroadcastListener\LANBroadcastListener\ApplicationActivity.cs
                var uu = new UdpClient(49814);
                uu.JoinMulticastGroup(IPAddress.Parse("239.1.2.3"), nic);
                while (true)
                {
                    // cannot get data from RED?
                    var x = await uu.ReceiveAsync(); // did we jump to ui thread?
                    //Console.WriteLine("ReceiveAsync done " + Encoding.UTF8.GetString(x.Buffer));
                    var data = Encoding.UTF8.GetString(x.Buffer);



                    // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150704
                    // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150704/mousedown
                    SetClipboard(data);
                }
            };

            // WithEach defined at?
            NetworkInterface.GetAllNetworkInterfaces().WithEach(
                n =>
                {
                    // X:\jsc.svn\examples\java\android\forms\FormsUDPJoinGroup\FormsUDPJoinGroup\ApplicationControl.cs
                    // X:\jsc.svn\core\ScriptCoreLibJava\BCLImplementation\System\Net\NetworkInformation\NetworkInterface.cs

                    var IPProperties = n.GetIPProperties();
                    var PhysicalAddress = n.GetPhysicalAddress();



                    foreach (var ip in IPProperties.UnicastAddresses)
                    {
                        // ipv4
                        if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            if (!IPAddress.IsLoopback(ip.Address))
                                if (n.SupportsMulticast)
                                    f(ip.Address);
                        }
                    }




                }
            );
            #endregion


            #endregion

            // jsc could pass this ptr to ctor for context..
            var t = new EditText(this) { };

            t.AttachTo(ll);

            ll.addView(b);



            this.setContentView(sv);


            //this.ShowLongToast("http://my.jsc-solutions.net x");
        }
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201412/20141207
        // how can we shot this from NDK?
        // what if we are in vr?
        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150607-1/surfaceview


        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // cmd /K c:\util\android-sdk-windows\platform-tools\adb.exe logcat
            // Camera PTP

            // http://developer.android.com/guide/topics/ui/notifiers/notifications.html

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);

            sv.addView(ll);


            int counter = 0;

            Action yield = delegate
            {
                counter++;
                var nm = (NotificationManager)this.getSystemService(Activity.NOTIFICATION_SERVICE);


                // see http://developer.android.com/reference/android/app/Notification.html
                var notification = new Notification(
                    android.R.drawable.stat_notify_sync,
                    "not used?",

                    0
                    //java.lang.System.currentTimeMillis()
                );

                notification.defaults |= Notification.DEFAULT_SOUND;
                //notification.vibrate = new long[] { 100, 200, 200, 200, 200, 200, 1000, 200, 200, 200, 1000, 200 };
                notification.vibrate = new long[] { 1000 };

                //             script: error JSC1000: Java : unable to emit newarr at 'AndroidNotificationActivity.Activities.ApplicationActivity+<>c__DisplayClass2.<onCreate>b__0'#004c: System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
                //at jsc.Languages.Java.JavaCompiler.<>c__DisplayClass1a7.<>c__DisplayClass1be.<CreateInstructionHandlers>b__162() in x:\jsc.internal.git\compiler\jsc\Languages\Java\JavaCompiler.OpCodes.cs:line 1720

                var notificationIntent = new Intent(this, typeof(ApplicationActivity).ToClass());
                var contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);


                notification.setLatestEventInfo(
                    this,
                    "Visible in Gear VR!",
                    "yet it wont vibrate",
                    contentIntent);

                //notification.defaults |= Notification.DEFAULT_VIBRATE;
                //notification.defaults |= Notification.DEFAULT_LIGHTS;
                // http://androiddrawableexplorer.appspot.com/
                nm.notify(counter, notification);
            };


            var b = new Button(this);

            b.setText("Notify!");

            // ScriptCoreLib.Ultra ?
            b.AtClick(
                delegate
                {
                    yield();
                }
            );

            ll.addView(b);

            this.setContentView(sv);

            // X:\jsc.svn\examples\java\android\HelloOpenGLES20Activity\HelloOpenGLES20Activity\ScriptCoreLib.Android\Shader.cs

            // Error	1	'AndroidNotificationActivity.Activities.ApplicationActivity' does not contain a definition for 'ShowLongToast' and no extension method 'ShowLongToast' accepting a first argument of type 'AndroidNotificationActivity.Activities.ApplicationActivity' could be found (are you missing a using directive or an assembly reference?)	X:\jsc.svn\examples\java\android\AndroidNotificationActivity\AndroidNotificationActivity\ApplicationActivity.cs	80	18	AndroidNotificationActivity
            //this.ShowLongToast("http://jsc-solutions.net");
            this.ShowToast("http://jsc-solutions.net");

            yield();

        }
        // "x:\util\android-sdk-windows\platform-tools\adb.exe"  tcpip 5555
        // restarting in TCP mode port: 5555

        // "x:\util\android-sdk-windows\platform-tools\adb.exe" connect 192.168.1.126:5555
        // connected to 192.168.1.126:5555

        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201505/20150513

        // lets verify this thing . deploy over wifi.

        //C:\Windows\system32> "x:\util\android-sdk-windows\platform-tools\adb.exe" shell netcfg
        //wlan0    UP                               192.168.1.126/24  0x00001043 e8:50:8b:7d:27:7c

        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);

            b.WithText("before AtClick");
            b.AtClick(
                v =>
                {
                    b.setText("AtClick");
                }
            );


            this.setContentView(sv);



            var s = new SemaphoreSlim(0);

            //java.lang.Object, rt
            //enter async { ManagedThreadId = 1 }
            //awaiting for SemaphoreSlim{ ManagedThreadId = 1 }
            //after delay{ ManagedThreadId = 8 }
            //http://127.0.0.1:8080
            //{ fileName = http://127.0.0.1:8080 }
            //enter catch { mname = <0032> nop.try } ClauseCatchLocal:
            //{ Message = , StackTrace = java.lang.RuntimeException
            //        at ScriptCoreLibJava.BCLImplementation.System.Net.Sockets.__TcpListener.AcceptTcpClientAsync(__TcpListener.java:131)

            new { }.With(
                async delegate
                {
                    //System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
                    //enter async { ManagedThreadId = 1 }
                    //awaiting for SemaphoreSlim{ ManagedThreadId = 1 }
                    //after delay{ ManagedThreadId = 4 }
                    //http://127.0.0.1:8080
                    //awaiting for SemaphoreSlim. done.{ ManagedThreadId = 1 }
                    //--
                    //accept { c = System.Net.Sockets.TcpClient, ManagedThreadId = 6 }
                    //System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
                    //accept { c = System.Net.Sockets.TcpClient, ManagedThreadId = 8 }
                    //{ ManagedThreadId = 6, input = GET / HTTP/1.1


                    Console.WriteLine("enter async " + new { Thread.CurrentThread.ManagedThreadId });

                    // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAsync\ChromeTCPServerAsync\Application.cs
                    await Task.Delay(100);

                    Console.WriteLine("after delay" + new { Thread.CurrentThread.ManagedThreadId });

                    // Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted
                    // close the other server!
                    var l = new TcpListener(IPAddress.Any, 8080);

                    l.Start();


                    var href =
                        "http://127.0.0.1:8080";

                    Console.WriteLine(
                        href
                    );



                    this.runOnUiThread(
                        delegate
                        {
                            var i = new Intent(Intent.ACTION_VIEW,
                               android.net.Uri.parse(href)
                           );

                            // http://vaibhavsarode.wordpress.com/2012/05/14/creating-our-own-activity-launcher-chooser-dialog-android-launcher-selection-dialog/
                            var ic = Intent.createChooser(i, href);


                            this.startActivity(ic);
                        }
                    );



                    new { }.With(
                        async delegate
                        {
                            while (true)
                            {
                                var c = await l.AcceptTcpClientAsync();

                                Console.WriteLine("accept " + new { c, Thread.CurrentThread.ManagedThreadId });

                                yield(c);
                            }
                        }
                    );

                    // jump back to main thread..
                    s.Release();
                }
            );
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);



            b.WithText("UDP!");
            b.AtClick(
                v =>
                {

                    Action<IPAddress> sendTracking = nic =>
                    {
                        var port = new Random().Next(16000, 40000);

                        //new IHTMLPre { "about to bind... " + new { port } }.AttachToDocument();

                        // where is bind async?
                        // X:\jsc.svn\examples\java\android\vr\OVRWindWheelNDK\UDPWindWheel\Program.cs
                        var socket = new UdpClient(
                             new IPEndPoint(nic, port)
                            );

                        Console.WriteLine("about to bind " + new { nic, port });

                        //  x:\util\android-sdk-windows\platform-tools\adb.exe logcat 
//I/System.Console(15571): 3cd3:0001 enter __UdpClient ctor
//I/System.Console(15571): 3cd3:83e5 exit __IPAddress worker { ElapsedMilliseconds = 7 }
//I/System.Console(15571): 3cd3:0001 enter __UdpClient before this.Client
//I/System.Console(15571): 3cd3:0001 enter __UdpClient after this.Client { Client = ScriptCoreLibJava.BCLImplementation.System.Net.Sockets.__Socket@3777711a }
//I/System.Console(15571): 3cd3:0001 about to bind { nic = 192.168.1.126, port = 17052 }
//I/System.Console(15571): 3cd3:0001 enter __Socket Bind { vBind = ScriptCoreLibJava.BCLImplementation.System.Net.Sockets.__Socket_BindDelegate@166d444b }
//D/AndroidRuntime(15571): Shutting down VM
//E/AndroidRuntime(15571): FATAL EXCEPTION: main
//E/AndroidRuntime(15571): Process: TestUDPSend.Activities, PID: 15571
//E/AndroidRuntime(15571): java.lang.RuntimeException

                        //socket.Client.Bind(
                        //     new IPEndPoint(nic, port)
                        //);

                        // who is on the other end?
                        var nmessage = "hello!";

                        var data = Encoding.UTF8.GetBytes(nmessage);      //creates a variable b of type byte


                        //new IHTMLPre { "about to send... " + new { data.Length } }.AttachToDocument();

                        // X:\jsc.svn\examples\javascript\chrome\apps\ChromeUDPNotification\ChromeUDPNotification\Application.cs
                        Console.WriteLine("about to Send");
                        socket.Send(
                             data,
                             data.Length,
                             hostname: "239.1.2.3",
                             port: 49834
                         );




                    };

                    #region udp broadcast
                    // overkill at 60hz
                    NetworkInterface.GetAllNetworkInterfaces().WithEach(
                         n =>
                         {
                             // X:\jsc.svn\examples\java\android\forms\FormsUDPJoinGroup\FormsUDPJoinGroup\ApplicationControl.cs
                             // X:\jsc.svn\core\ScriptCoreLibJava\BCLImplementation\System\Net\NetworkInformation\NetworkInterface.cs

                             var IPProperties = n.GetIPProperties();
                             var PhysicalAddress = n.GetPhysicalAddress();



                             foreach (var ip in IPProperties.UnicastAddresses)
                             {
                                 // ipv4
                                 if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                 {
                                     if (!IPAddress.IsLoopback(ip.Address))
                                         if (n.SupportsMulticast)
                                         {
                                             //fWASDC(ip.Address);
                                             //fParallax(ip.Address);
                                             //fvertexTransform(ip.Address);
                                             sendTracking(ip.Address);
                                         }
                                 }
                             }




                         }
                     );



                    #endregion

                }
            );


            this.setContentView(sv);
        }
        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // cmd /K c:\util\android-sdk-windows\platform-tools\adb.exe logcat
            // Camera PTP

            // http://developer.android.com/guide/topics/ui/notifiers/notifications.html

            base.onCreate(savedInstanceState);

            ScrollView sv = new ScrollView(this);

            LinearLayout ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);

            sv.addView(ll);


            Button b = new Button(this);

            b.setText("AlertDialog! " + new { id = Thread.currentThread().getId() });
            int counter = 0;

            // ScriptCoreLib.Ultra ?
            b.AtClick(
                delegate
            {
                counter++;

                // http://www.tomswebdesign.net/Articles/Android/number-pad-input-class.html
                // https://android.googlesource.com/platform/frameworks/base/+/b896b9f/packages/Keyguard/src/com/android/keyguard/KeyguardSimPinView.java
                // http://xmlstackoverflow.blogspot.com/2014/07/how-to-use-alertdialog-to-prompt-for-pin.html
                // http://incidencias-ctt.administracionelectronica.gob.es/websvn/filedetails.php?repname=clienteafirma&path=%2Fproject%2Fafirma-mobile%2Fafirma-android%2Ftrunk%2Fafirma-ui-android%2Fsrc%2Fes%2Fgob%2Fafirma%2Fandroid%2Fgui%2FPinDialog.java&peg=4040

                // X:\jsc.svn\examples\java\android\forms\FormsMessageBox\FormsMessageBox\ApplicationActivity.cs
                // X:\jsc.svn\examples\java\android\Test\TestAlertDialog\TestAlertDialog\ApplicationActivity.cs
                AlertDialog alertDialog = new AlertDialog.Builder(this).create();

                alertDialog.setTitle("Reset...");
                alertDialog.setMessage("Are you sure?");
                alertDialog.setButton("OK",
                    new xOnClickListener
                {
                    yield = delegate
                    {
                        b.setText("clicked! " + new { id = Thread.currentThread().getId() });
                    }
                }

                    );

                // skip icons?
                //alertDialog.setIcon(android.R.drawable.star_off);

                // can we do async yet?
                alertDialog.show();


            }
            );

            ll.addView(b);

            this.setContentView(sv);

            // X:\jsc.svn\examples\java\android\HelloOpenGLES20Activity\HelloOpenGLES20Activity\ScriptCoreLib.Android\Shader.cs

            // Error	1	'TestAlertDialog.Activities.ApplicationActivity' does not contain a definition for 'ShowLongToast' and no extension method 'ShowLongToast' accepting a first argument of type 'TestAlertDialog.Activities.ApplicationActivity' could be found (are you missing a using directive or an assembly reference?)	X:\jsc.svn\examples\java\android\TestAlertDialog\TestAlertDialog\ApplicationActivity.cs	80	18	TestAlertDialog
            //this.ShowLongToast("http://jsc-solutions.net");
            //this.ShowToast("http://jsc-solutions.net");


        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            // https://forums.oculus.com/viewtopic.php?f=67&t=22766

            var activity = this;
            // http://stackoverflow.com/questions/11425020/actionbar-in-a-dialogfragment
            //To show activity as dialog and dim the background, you need to declare android:theme="@style/PopupTheme" on for the chosen activity on the manifest
            //activity.requestWindowFeature(Window.FEATURE_ACTION_BAR);
            //activity.getWindow().setFlags(WindowManager_LayoutParams.FLAG_DIM_BEHIND, WindowManager_LayoutParams.FLAG_DIM_BEHIND);
            //activity.getWindow().setFlags(WindowManager_LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager_LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //var @params = activity.getWindow().getAttributes();
            ////@params.height = WindowManager_LayoutParams.FILL_PARENT;
            ////@params.width = 850; //fixed width
            ////@params.height = 450; //fixed width
            //@params.alpha = 1.0f;
            //@params.dimAmount = 0.5f;
            //activity.getWindow().setAttributes(@params);
            //activity.getWindow().setLayout(850, 850);
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);



            b.WithText("before AtClick");
            b.AtClick(
                v =>
                {
                    b.setText("AtClick");
                }
            );


            AtPrepareOptions +=
                value =>
                {
                    value.clear();

                    var item1 = value.add(
                         (java.lang.CharSequence)(object)"http://abstractatech.com"
                    );



                    item1.setIcon(android.R.drawable.ic_menu_view);

                    var item2 = value.add(
                        (java.lang.CharSequence)(object)"http://jsc-solutions.net"
                    );

                    //item2.setIcon(android.R.drawable.ic_menu_edit);
                    item2.setIcon(android.R.drawable.ic_menu_view);

                    var i = new Intent(Intent.ACTION_VIEW,
                        android.net.Uri.parse("http://jsc-solutions.net")
                    );

                    // http://vaibhavsarode.wordpress.com/2012/05/14/creating-our-own-activity-launcher-chooser-dialog-android-launcher-selection-dialog/
                    var ic = Intent.createChooser(i, "http://jsc-solutions.net");


                    item2.setIntent(
                        ic
                    );
                };

            AtOption +=
                item =>
                {

                    //b.WithText("menu was clicked!" + (string)(object)item.getTitle());
                    b.WithText("menu was clicked!" + new { item });
                };

            var b2 = new Button(this);

            var sw = System.Diagnostics.Stopwatch.StartNew();

            // SystemService
            Action update = delegate
            {
                // newer SDKS hide it

                // X:\opensource\ovr_mobile_sdk_0.5.1\VRLib\jni\VrApi\VrApi.cpp
                int cpuCore = 0;


                var online =
                    System.IO.File.ReadAllText("/sys/devices/system/cpu/cpu4/online").Trim();

                if (online == "1")
                    cpuCore = 4;

                var cpuFreq =
                    System.IO.File.ReadAllText("/sys/devices/system/cpu/cpu" + cpuCore + "/cpufreq/scaling_cur_freq").Trim();

                var cpuFrezMhz =
                    long.Parse(cpuFreq) / 1000;

                // 0 if gpu is not used?
                var gpuFreq =
                  System.IO.File.ReadAllText("/sys/devices/14ac0000.mali/clock").Trim();


                // const int64_t cpuFreq = ReadFreq( "/sys/devices/system/cpu/cpu%i/cpufreq/scaling_cur_freq", cpuCore );

                b2.setText(
                    new { cpuCore, online, cpuFrezMhz, gpuFreq }.ToString()
                    + "\n " + sw.ElapsedMilliseconds
                    );
            };

            var h = new Handler();

            var next = default(Action);

            next = delegate
            {
                // await 1?

                update();

                h.postDelayed(
                    new xRunnable
                    {
                        yield = delegate
                        {
                            next();
                        }
                    },
                1);
            };

            next();


            ll.addView(b2);

            this.setContentView(sv);



            vConfigurationChanged = e =>
            {
                var orientation = getScreenOrientation();

                var SystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();

                //b2.setText(
                //    new
                //    {
                //        orientation,
                //        SystemUiVisibility
                //    }.ToString()
                //);


                if (orientation == Configuration.ORIENTATION_LANDSCAPE)
                {
                    hideSystemUI();
                }
                else
                {
                    showSystemUI();
                }
            };

            vConfigurationChanged(null);
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            var b = new Button(this).AttachTo(ll);


            var ip = getLocalIpAddress();



            b.WithText("server at " + ip);
            b.AtClick(
                v =>
                {
                    var random = new System.Random();

                    // Error 312 (net::ERR_UNSAFE_PORT): Unknown error.
                    var port = random.Next(1024, 32000);

                    var uri = "http://" + ip;

                    uri += ":";
                    uri += ((object)(port)).ToString();

                    b.setText(uri);

                    Toast.makeText(
                          this,
                          "connect to this web server", 
                          Toast.LENGTH_LONG
                      ).show();

                    var ipa = Dns.GetHostAddresses(ip)[0];


                    Action<string> log = x => Log.wtf("ApplicationActivity", x);

                    // jsc does not import generic param, why?
                    //Action<NetworkStream> AtConnection =
                    NetworkStreamAction AtConnection =
                        s =>
                        {

                            //log("AtConnection");

                            var r = new StreamReader(s);

                            var h0 = r.ReadLine();

                            //log("ReadLine done");

                            var m = new MemoryStream();

                            Action<string> WriteLineASCII = (string e) =>
                            {
                                var x = Encoding.ASCII.GetBytes(e + "\r\n");

                                m.Write(x, 0, x.Length);
                            };

                            WriteLineASCII("HTTP/1.1 200 OK");
                            WriteLineASCII("Content-Type:	text/html; charset=utf-8");
                            //WriteLineASCII("Content-Length: " + data.Length);
                            WriteLineASCII("Connection: close");


                            WriteLineASCII("");
                            WriteLineASCII("");
                            WriteLineASCII("<html>");

                            WriteLineASCII("<body><h1 style='color: red;'>Hello world</h2><h3>jsc</h3><pre>" + h0 + "</pre></body>");

                            WriteLineASCII("</html>");

                            log("write done");

                            var oa = m.ToArray();

                            s.Write(oa, 0, oa.Length);

                            s.Flush();
                            s.Close();
                        };

                    //                    AndroidTcpListenerActivity.AndroidActivity 003e create: AndroidTcpListenerActivity.Activities.ApplicationActivity+<>c__DisplayClass8+<>c__DisplayClassb
                    //switch to STA Exception:
                    //System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The IL Generator cannot be used while there are unclosed exceptions.
                    //   at System.Reflection.Emit.ILGenerator.BakeByteArray()
                    //   at System.Reflection.Emit.MethodBuilder.CreateMethodBodyHelper(ILGenerator il)
                    //   at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
                    //   at System.Reflection.Emit.TypeBuilder.CreateType()

                    new Thread(
                            delegate()
                            {
                                var r = new TcpListener(ipa, port);

                                //try
                                //{
                                r.Start();

                                while (true)
                                {
                                    //log("AcceptTcpClient");
                                    var c = r.AcceptTcpClient();
                                    //log("AcceptTcpClient done, GetStream");

                                    var s = c.GetStream();
                                    //log("AcceptTcpClient done, GetStream done");

                                    new Thread(
                                        delegate()
                                        {
                                            //log("before AtConnection");
                                            AtConnection(s);
                                        }
                                    )
                                    {
                                        IsBackground = true,
                                    }.Start();
                                }

                                //}
                                //catch
                                //{
                                //    log("AcceptTcpClient error!");

                                //    throw;
                                //}


                            }
                        )
                    {
                        IsBackground = true,
                    }.Start();
                }
            );

            var b2 = new Button(this);
            b2.setText("The other button!");
            ll.addView(b2);

            this.setContentView(sv);
        }
        // https://github.com/opersys/raidl


        // http://stackoverflow.com/questions/6274141/trigger-background-service-at-a-specific-time-in-android
        // http://stackoverflow.com/questions/7144908/how-is-an-intent-service-declared-in-the-android-manifest
        // http://developer.android.com/guide/topics/manifest/service-element.html

        // https://github.com/android/platform_frameworks_base/blob/master/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java

        //AtBootCompleted hack1;

        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            // http://developer.android.com/guide/topics/ui/notifiers/notifications.html

            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);

            ll.setOrientation(LinearLayout.VERTICAL);

            sv.addView(ll);

            #region startservice
            var startservice = new Button(this);
            startservice.setText("Start Service to send Notification");
            startservice.AtClick(
                delegate
                {
                    startservice.setEnabled(false);
                    //this.ShowToast("startservice_onclick");

                    //var intent = new Intent(this, NotifyService.Class);
                    var intent = new Intent(this, typeof(NotifyService).ToClass());
                    this.startService(intent);

                    // http://developer.android.com/reference/android/app/Activity.html#recreate%28%29
                    this.recreate();
                }
            );
            ll.addView(startservice);
            #endregion

            #region stopservice
            var stopservice = new Button(this);
            stopservice.setText("Stop Service");
            stopservice.AtClick(
                delegate
                {
                    this.ShowToast("stopservice_onclick");

                    var intent = new Intent();
                    intent.setAction(NotifyService.ACTION);
                    intent.putExtra("RQS", NotifyService.RQS_STOP_SERVICE);
                    this.sendBroadcast(intent);

                    // seems stop takes a while

                    //Task.Delay(100);

                    Thread.Sleep(30);

                    this.recreate();
                }
            );
            ll.addView(stopservice);
            #endregion

            stopservice.setEnabled(false);

            // http://stackoverflow.com/questions/12891903/android-check-if-my-service-is-running-in-the-background
            var m = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);


            Console.WriteLine("getRunningServices");

            var s = m.getRunningServices(1000);

            Console.WriteLine("getRunningServices " + s.size());

            var se =
                // http://stackoverflow.com/questions/7170730/how-to-set-a-control-panel-for-my-service-in-android

                from i in Enumerable.Range(0, s.size())
                let rsi = (android.app.ActivityManager.RunningServiceInfo)s.get(i)
                let cn = rsi.service.getClassName()
                let cp = m.getRunningServiceControlPanel(rsi.service)

                //orderby cn
                orderby cp != null

                select new { i, rsi, cn, cp };
            //java.lang.JavaSystem.ex
            //     I/System.Console( 1617): { i = 45, cn = android.hardware.location.GeofenceHardwareService, cp =  }
            //I/System.Console( 1617): { i = 17, cn = ccc71.at.services.at_service, cp =  }
            //I/System.Console( 1617): { i = 34, cn = com.android.bluetooth.a2dp.A2dpService, cp =  }
            //I/System.Console( 1617): { i = 13, cn = com.android.bluetooth.btservice.AdapterService, cp =  }
            //I/System.Console( 1617): { i = 23, cn = com.android.bluetooth.gatt.GattService, cp =  }
            //I/System.Console( 1617): { i = 68, cn = com.android.bluetooth.hfp.HeadsetService, cp =  }
            //I/System.Console( 1617): { i = 0, cn = com.android.bluetooth.hid.HidService, cp =  }
            //I/System.Console( 1617): { i = 84, cn = com.android.bluetooth.pan.PanService, cp =  }
            //I/System.Console( 1617): { i = 80, cn = com.android.defcontainer.DefaultContainerService, cp =  }
            //I/System.Console( 1617): { i = 37, cn = com.android.incallui.InCallServiceImpl, cp =  }
            //I/System.Console( 1617): { i = 71, cn = com.android.incallui.MCIDService, cp =  }
            //I/System.Console( 1617): { i = 55, cn = com.android.incallui.SecInCallService, cp =  }
            //I/System.Console( 1617): { i = 73, cn = com.android.internal.backup.LocalTransportService, cp =  }
            //I/System.Console( 1617): { i = 81, cn = com.android.phone.TelephonyDebugService, cp =  }
            //I/System.Console( 1617): { i = 66, cn = com.android.providers.media.MtpService, cp =  }
            //I/System.Console( 1617): { i = 65, cn = com.android.server.DrmEventService, cp =  }
            //I/System.Console( 1617): { i = 57, cn = com.android.server.telecom.BluetoothPhoneService, cp =  }
            //I/System.Console( 1617): { i = 50, cn = com.android.server.telecom.BluetoothVoIPService, cp =  }
            //I/System.Console( 1617): { i = 62, cn = com.android.stk.StkAppService, cp =  }
            //I/System.Console( 1617): { i = 15, cn = com.android.systemui.ImageWallpaper, cp = PendingIntent{2759cef2: android.os.BinderProxy@181ef173} }
            //I/System.Console( 1617): { i = 44, cn = com.android.systemui.SystemUIService, cp =  }
            //I/System.Console( 1617): { i = 12, cn = com.android.systemui.keyguard.KeyguardService, cp =  }
            //I/System.Console( 1617): { i = 21, cn = com.dsi.ant.server.AntService, cp =  }
            //I/System.Console( 1617): { i = 48, cn = com.fmm.dm.XDMService, cp =  }
            //I/System.Console( 1617): { i = 22, cn = com.google.android.gms.analytics.service.AnalyticsService, cp =  }
            //I/System.Console( 1617): { i = 51, cn = com.google.android.gms.auth.trustagent.GoogleTrustAgent, cp =  }
            //I/System.Console( 1617): { i = 86, cn = com.google.android.gms.backup.BackupTransportService, cp =  }
            //I/System.Console( 1617): { i = 4, cn = com.google.android.gms.car.CarService, cp =  }
            //I/System.Console( 1617): { i = 76, cn = com.google.android.gms.clearcut.service.ClearcutLoggerService, cp =  }
            //I/System.Console( 1617): { i = 75, cn = com.google.android.gms.common.stats.GmsCoreStatsService, cp =  }
            //I/System.Console( 1617): { i = 67, cn = com.google.android.gms.deviceconnection.service.DeviceConnectionServiceBroker, cp =  }
            //I/System.Console( 1617): { i = 19, cn = com.google.android.gms.gcm.GcmService, cp =  }
            //I/System.Console( 1617): { i = 38, cn = com.google.android.gms.gcm.http.GoogleHttpService, cp =  }
            //I/System.Console( 1617): { i = 74, cn = com.google.android.gms.playlog.service.PlayLogBrokerService, cp =  }
            //I/System.Console( 1617): { i = 18, cn = com.google.android.gms.trustagent.api.trustagent.GoogleTrustAgentService, cp =  }
            //I/System.Console( 1617): { i = 25, cn = com.google.android.gms.usagereporting.service.UsageReportingService, cp =  }
            //I/System.Console( 1617): { i = 82, cn = com.google.android.gms.wearable.service.WearableService, cp =  }
            //I/System.Console( 1617): { i = 40, cn = com.google.android.hotword.service.HotwordService, cp =  }
            //I/System.Console( 1617): { i = 60, cn = com.google.android.libraries.hangouts.video.VideoChatService, cp =  }
            //I/System.Console( 1617): { i = 30, cn = com.google.android.location.fused.FusedLocationService, cp =  }
            //I/System.Console( 1617): { i = 16, cn = com.google.android.location.geocode.GeocodeService, cp =  }
            //I/System.Console( 1617): { i = 39, cn = com.google.android.location.geofencer.service.GeofenceProviderService, cp =  }
            //I/System.Console( 1617): { i = 63, cn = com.google.android.location.internal.GoogleLocationManagerService, cp =  }
            //I/System.Console( 1617): { i = 54, cn = com.google.android.location.internal.PendingIntentCallbackService, cp =  }
            //I/System.Console( 1617): { i = 58, cn = com.google.android.location.internal.server.GoogleLocationService, cp =  }
            //I/System.Console( 1617): { i = 61, cn = com.google.android.location.network.NetworkLocationService, cp =  }
            //I/System.Console( 1617): { i = 3, cn = com.google.android.music.dial.DialMediaRouteProviderService, cp =  }
            //I/System.Console( 1617): { i = 6, cn = com.google.android.search.core.service.BroadcastListenerService, cp =  }
            //I/System.Console( 1617): { i = 35, cn = com.google.android.search.core.service.SearchService, cp =  }
            //I/System.Console( 1617): { i = 69, cn = com.google.android.voiceinteraction.GsaVoiceInteractionService, cp =  }
            //I/System.Console( 1617): { i = 85, cn = com.ime.framework.spellcheckservice.SamsungIMESpellCheckerService, cp =  }
            //I/System.Console( 1617): { i = 49, cn = com.samsung.android.MtpApplication.MtpService, cp =  }
            //I/System.Console( 1617): { i = 78, cn = com.samsung.android.app.catchfavorites.catchnotifications.CatchNotificationsService, cp = PendingIntent{1f770943: android.os.BinderProxy@6924ca9} }
            //I/System.Console( 1617): { i = 56, cn = com.samsung.android.app.edge.nightclock.NightClockService, cp =  }
            //I/System.Console( 1617): { i = 59, cn = com.samsung.android.app.galaxyfinder.recommended.RecommendedService, cp =  }
            //I/System.Console( 1617): { i = 53, cn = com.samsung.android.app.galaxyfinder.tag.TagReadyService, cp =  }
            //I/System.Console( 1617): { i = 72, cn = com.samsung.android.app.shealth.tracker.pedometer.service.PedometerService, cp =  }
            //I/System.Console( 1617): { i = 32, cn = com.samsung.android.app.shealth.tracker.sport.livetracker.LiveTrackerService, cp =  }
            //I/System.Console( 1617): { i = 79, cn = com.samsung.android.beaconmanager.BeaconService, cp =  }
            //I/System.Console( 1617): { i = 42, cn = com.samsung.android.health.wearable.service.WearableService, cp =  }
            //I/System.Console( 1617): { i = 70, cn = com.samsung.android.providers.context.ContextService, cp =  }
            //I/System.Console( 1617): { i = 24, cn = com.samsung.android.scloud.auth.RelayService, cp =  }
            //I/System.Console( 1617): { i = 26, cn = com.samsung.android.sconnect.periph.PeriphService, cp =  }
            //I/System.Console( 1617): { i = 29, cn = com.samsung.android.sensor.framework.SensorService, cp =  }
            //I/System.Console( 1617): { i = 64, cn = com.samsung.android.service.health.HealthService, cp =  }
            //I/System.Console( 1617): { i = 14, cn = com.samsung.android.service.peoplestripe.PeopleNotiListenerService, cp = PendingIntent{17538bc0: android.os.BinderProxy@6924ca9} }
            //I/System.Console( 1617): { i = 77, cn = com.samsung.android.service.peoplestripe.PeopleStripeService, cp =  }
            //I/System.Console( 1617): { i = 28, cn = com.samsung.android.sm.widgetapp.SMWidgetService, cp =  }
            //I/System.Console( 1617): { i = 47, cn = com.samsung.android.thememanager.ThemeManagerService, cp =  }
            //I/System.Console( 1617): { i = 52, cn = com.samsung.appcessory.server.SAPService, cp =  }
            //I/System.Console( 1617): { i = 5, cn = com.samsung.hs20settings.WifiHs20UtilityService, cp =  }
            //I/System.Console( 1617): { i = 41, cn = com.samsung.sec.android.application.csc.CscUpdateService, cp =  }
            //I/System.Console( 1617): { i = 2, cn = com.sec.android.app.bluetoothtest.BluetoothBDTestService, cp =  }
            //I/System.Console( 1617): { i = 31, cn = com.sec.android.app.launcher.services.LauncherService, cp =  }
            //I/System.Console( 1617): { i = 10, cn = com.sec.android.daemonapp.ap.accuweather.WeatherClockService, cp =  }
            //I/System.Console( 1617): { i = 8, cn = com.sec.android.inputmethod.SamsungKeypad, cp = PendingIntent{39a730f9: android.os.BinderProxy@2b45775c} }
            //I/System.Console( 1617): { i = 46, cn = com.sec.android.pagebuddynotisvc.PageBuddyNotiSvc, cp =  }
            //I/System.Console( 1617): { i = 1, cn = com.sec.android.sensor.framework.SensorService, cp =  }
            //I/System.Console( 1617): { i = 83, cn = com.sec.android.service.sm.service.SecurityManagerService, cp =  }
            //I/System.Console( 1617): { i = 7, cn = com.sec.android.widgetapp.ap.weather.common.appservice.WeatherScreenService, cp =  }
            //I/System.Console( 1617): { i = 11, cn = com.sec.android.widgetapp.ap.weather.common.appservice.WeatherService, cp =  }
            //I/System.Console( 1617): { i = 36, cn = com.sec.android.widgetapp.ap.weather.widget.surfacewidget.WeatherSurfaceWidget, cp =  }
            //I/System.Console( 1617): { i = 33, cn = com.sec.android.widgetapp.digitalclockeasy.DigitalClockEasyService, cp =  }
            //I/System.Console( 1617): { i = 9, cn = com.sec.bcservice.BroadcastService, cp =  }
            //I/System.Console( 1617): { i = 20, cn = com.sec.enterprise.mdm.services.simpin.EnterpriseSimPin, cp =  }
            //I/System.Console( 1617): { i = 87, cn = com.sec.phone.SecPhoneService, cp =  }
            //I/System.Console( 1617): { i = 43, cn = com.sec.spp.push.PushClientService, cp =  }
            //I/System.Console( 1617): { i = 27, cn = org.simalliance.openmobileapi.service.SmartcardService, cp =  }

            //I/System.Console( 5883): { i = 85, cn = com.google.android.gms.backup.BackupTransportService, process = com.google.android.gms.persistent }
            //I/System.Console( 5883): { i = 86, cn = com.sec.phone.SecPhoneService, process = com.sec.phone }
            //I/System.Console( 5883): { i = 7, cn = com.sec.android.inputmethod.SamsungKeypad, process = com.sec.android.inputmethod, cp = PendingIntent{e6c79e2: android.os.BinderProxy@181ef173}, describeContents = 0 }
            //I/System.Console( 5883): { i = 13, cn = com.samsung.android.service.peoplestripe.PeopleNotiListenerService, process = com.samsung.android.service.peoplestripe, cp = PendingIntent{24b00830: android.os.BinderProxy@6924ca9}, describeContents = 0 }
            //I/System.Console( 5883): { i = 14, cn = com.android.systemui.ImageWallpaper, process = com.android.systemui.imagewallpaper, cp = PendingIntent{135c522e: android.os.BinderProxy@1ced31cf}, describeContents = 0 }
            //I/System.Console( 5883): { i = 77, cn = com.samsung.android.app.catchfavorites.catchnotifications.CatchNotificationsService, process = com.samsung.android.app.catchfavorites, cp = PendingIntent{2b45775c: android.os.BinderProxy@6924ca9}, describeContents = 0 }

            // http://stackoverflow.com/questions/7170730/how-to-set-a-control-panel-for-my-service-in-android
            // The service's description and configuration intent can be set during a service binding
            foreach (var ss in se)
            {


                var cn = ss.cn;

                PendingIntent cp = ss.cp;

                // whats a ControlPanel ?

                //  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.app.PendingIntent.describeContents()' on a null object reference

                if (cp == null)
                    Console.WriteLine(new { ss.i, cn, ss.rsi.process });
                else
                    Console.WriteLine(new { ss.i, cn, ss.rsi.process, cp, describeContents = cp.describeContents() });

                // I/System.Console(17713): { cn = AndroidBootServiceNotificationActivity.Activities.NotifyService }
                if (cn == typeof(NotifyService).FullName)
                {
                    // cannot find ourself? unless its running

                    startservice.setEnabled(false);
                    stopservice.setEnabled(true);

                    // its running

                    // http://stackoverflow.com/questions/7170730/how-to-set-a-control-panel-for-my-service-in-android
                    // http://www.techques.com/question/1-7170730/How-to-set-a-control-panel-for-my-Service-in-Android
                    // http://alvinalexander.com/java/jwarehouse/android/core/java/android/app/ActivityManagerNative.java.shtml
                }


                #region cp
                if (cp != null)
                {
                    // could we not infer activity from code from application?

                    new Button(this).WithText(
                        cn
                    ).AtClick(
                        delegate
                        {
                            // http://codetheory.in/android-pending-intents/
                            try
                            {
                                cp.send();
                            }
                            catch
                            {
                            }

                            //this.startActivity(
                            //    cp
                            //);
                        }
                    ).AttachTo(ll);
                }
                #endregion


            }

            this.setContentView(sv);

            //this.ShowToast("http://jsc-solutions.net");


            new Button(this).WithText("exit").AttachTo(ll).AtClick(
                delegate
                {

                    // will it be logged?
                    System.Environment.Exit(13);

                    // application still visible in tasks?
                }
            );

            new Button(this).WithText("finish").AttachTo(ll).AtClick(
               delegate
               {
                   //this.finishAndRemoveTask();
                   this.finish();

                   // will it be logged?
                   //System.Environment.Exit(13);

                   // application still visible in tasks?
               }
           );

            new Button(this).WithText("finishAndRemoveTask").AttachTo(ll).AtClick(
             delegate
             {
                 this.finishAndRemoveTask();
                 //this.finish();

                 // will it be logged?
                 //System.Environment.Exit(13);

                 // application still visible in tasks?
             }
         );
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);

            var goo = new foo.Goo();

            //Activator.CreateInstance<

            //var goo = (foo.Goo)Activator.CreateInstance(
            //    typeof(foo.Goo)
            //);

            //E/AndroidRuntime(32112): Caused by: java.lang.RuntimeException
            //E/AndroidRuntime(32112):        at foo.Bar.GetBarString(Bar.java:29)
            //E/AndroidRuntime(32112):        at foo.Goo.GetString(Goo.java:9)
            //E/AndroidRuntime(32112):        at TestJavaNativesOverride.Activities.ApplicationActivity.onCreate(ApplicationActivity.java:69)

            b.WithText(goo.GetString());
            b.AtClick(
                v =>
                {
                    b.setText(
                         new assets::foo.Bar().GetBarString()
                    );
                }
            );


            this.setContentView(sv);



        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            var activity = this;
            // http://stackoverflow.com/questions/11425020/actionbar-in-a-dialogfragment
            //To show activity as dialog and dim the background, you need to declare android:theme="@style/PopupTheme" on for the chosen activity on the manifest
            //activity.requestWindowFeature(Window.FEATURE_ACTION_BAR);
            //activity.getWindow().setFlags(WindowManager_LayoutParams.FLAG_DIM_BEHIND, WindowManager_LayoutParams.FLAG_DIM_BEHIND);
            //activity.getWindow().setFlags(WindowManager_LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager_LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //var @params = activity.getWindow().getAttributes();
            ////@params.height = WindowManager_LayoutParams.FILL_PARENT;
            ////@params.width = 850; //fixed width
            ////@params.height = 450; //fixed width
            //@params.alpha = 1.0f;
            //@params.dimAmount = 0.5f;
            //activity.getWindow().setAttributes(@params);
            //activity.getWindow().setLayout(850, 850);
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);

            var b = new Button(this).AttachTo(ll);



            b.WithText("before AtClick");
            b.AtClick(
                v =>
                {
                    b.setText("AtClick");
                }
            );


            AtPrepareOptions +=
                value =>
                {
                    value.clear();

                    var item1 = value.add(
                         (java.lang.CharSequence)(object)"http://abstractatech.com"
                    );



                    item1.setIcon(android.R.drawable.ic_menu_view);

                    var item2 = value.add(
                        (java.lang.CharSequence)(object)"http://jsc-solutions.net"
                    );

                    //item2.setIcon(android.R.drawable.ic_menu_edit);
                    item2.setIcon(android.R.drawable.ic_menu_view);

                    var i = new Intent(Intent.ACTION_VIEW,
                        android.net.Uri.parse("http://jsc-solutions.net")
                    );

                    // http://vaibhavsarode.wordpress.com/2012/05/14/creating-our-own-activity-launcher-chooser-dialog-android-launcher-selection-dialog/
                    var ic = Intent.createChooser(i, "http://jsc-solutions.net");


                    item2.setIntent(
                        ic
                    );
                };

            AtOption +=
                item =>
                {

                    //b.WithText("menu was clicked!" + (string)(object)item.getTitle());
                    b.WithText("menu was clicked!" + new { item });
                };

            var b2 = new Button(this);
            b2.setText("The other button!");
            ll.addView(b2);

            this.setContentView(sv);
        }
        protected override void onCreate(Bundle savedInstanceState)
        {
            // http://www.mkyong.com/android/android-activity-from-one-screen-to-another-screen/

            base.onCreate(savedInstanceState);

            //this.getWindow().getDecorView()
            //this.getWindow().setTitle("secondary " + new { ApplicationActivity.foo});
            //this.getWindow().setTitleColor(0xff0000);

            // Set the IMMERSIVE flag.
            // Set the content to appear under the system bars so that the content
            // doesn't resize when the system bars hide and show.
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);
            this.setContentView(sv);

            var b = new Button(this).AttachTo(ll);



            b.WithText(" secondary " + new { ApplicationActivity.foo });
            b.AtClick(
                v =>
                {
                    this.finish();
                }
            );

            //this.AtPause += delegate
            //{
            //    this.finish();
            //};

            //this.AtWindowFocusChanged += e =>
            //    {
            //        if (!e)
            //            this.finish();


            //    };

            //this.AtUserLeaveHint += delegate { this.finish(); };

            //this.onfo
            //this.onWindowFocusChanged
            //public void onWindowFocusChanged (boolean hasFocus)
        }
        static __InitializeAndroidActivity()
        {
            Console.WriteLine("StaticInvoke");

            //  Exception Ljava/lang/RuntimeException; thrown while initializing LTryHideActionbarExperiment/StaticInvoke;
            try
            {


                // https://groups.google.com/forum/?fromgroups=#!topic/android-developers/suLMCWiG0D8
                var c = ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext;


                (ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext as ScriptCoreLib.Android.CoreAndroidWebServiceActivity).runOnUiThread(
                    a =>
                    {
                        //var c = ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext;



                        // http://stackoverflow.com/questions/4451641/change-android-layout-programatically

                        var sv = new ScrollView(a);
                        var ll = new LinearLayout(a);
                        //ll.setOrientation(LinearLayout.VERTICAL);
                        sv.addView(ll);

                        var b = new Button(a).AttachTo(ll);



                        b.WithText("before AtClick");
                        b.AtClick(
                            v =>
                            {
                                b.setText("AtClick");
                            }
                        );

                        var b2 = new Button(a);
                        b2.setText("The other button!");
                        ll.addView(b2);


                        //Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f050002
                        //       at android.content.res.Resources.getText(Resources.java:230)
                        //       at android.content.res.Resources.getString(Resources.java:314)
                        //       at com.facebook.widget.LoginButton.setButtonText(LoginButton.java:532)
                        //       at com.facebook.widget.LoginButton.finishInit(LoginButton.java:472)
                        //       at com.facebook.widget.LoginButton.<init>(LoginButton.java:189)

                        var login = new LoginButton(a);

                        // You have disabled Facebook Login in your app, but you must still specify Package Name or Key Hashes.
                        //login.loginText = "loginText";
                        login.setApplicationId("625051627510580");

                        //                        FATAL EXCEPTION: main
                        //java.lang.NullPointerException: Argument 'applicationId' cannot be null
                        //       at com.facebook.internal.Validate.notNull(Validate.java:29)
                        //       at com.facebook.Session.<init>(Session.java:224)
                        //       at com.facebook.Session.<init>(Session.java:213)
                        //       at com.facebook.Session$Builder.build(Session.java:1454)
                        //       at com.facebook.widget.LoginButton$LoginClickListener.onClick(LoginButton.java:621)


                        //                        FATAL EXCEPTION: main
                        //com.facebook.FacebookException: Cannot use SessionLoginBehavior SSO_WITH_FALLBACK when com.facebook.LoginActivity is not declared as an activity in AndroidManifest.xml
                        //       at com.facebook.Session.validateLoginBehavior(Session.java:992)
                        //       at com.facebook.Session.open(Session.java:915)
                        //       at com.facebook.Session.openForRead(Session.java:385)
                        //       at com.facebook.widget.LoginButton$LoginClickListener.onClick(LoginButton.java:641)

                        //                 Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f030001
                        //at android.content.res.Resources.getValue(Resources.java:1014)
                        //at android.content.res.Resources.loadXmlResourceParser(Resources.java:2139)
                        //at android.content.res.Resources.getLayout(Resources.java:853)
                        //at android.view.LayoutInflater.inflate(LayoutInflater.java:394)
                        //at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                        //at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
                        //at android.app.Activity.setContentView(Activity.java:1881)
                        //at com.facebook.LoginActivity.onCreate(LoginActivity.java:55)

                        login.setSessionStatusCallback(
                            new XStatusCallback
                            {
                                yield = (arg0, arg1, arg2) =>
                                {
                                    var AccessToken = arg0.getAccessToken();
                                    Console.WriteLine(new { AccessToken, arg0, arg1, arg2 });

                                }
                            }
                        );

                        login.setUserInfoChangedCallback(
                            new XUserInfoChangedCallback
                            {

                                yield = u =>
                                {
                                    var id = u.getId();
                                    var name = u.getName();

                                    Console.WriteLine(new { name, id });

                                    b2.WithText(new { name, id }.ToString());
                                }

                            }
                        );

                        login.AttachTo(ll);

                        a.setContentView(sv);
                    }
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + new { ex.Message, ex.StackTrace });
            }
        }
		public ApplicationSurface(RenderingContextView v, Button button_set_min_filter, Button button_set_mag_filter, Activity OwnerActivity)
		{
			v.onsurface +=
			 gl =>
			 {
				 //var __gl = (ScriptCoreLib.Android.__WebGLRenderingContext)(object)gl;

				 #region fields
				 /**
                     * Store the model matrix. This matrix is used to move models from object space (where each model can be thought
                     * of being located at the center of the universe) to world space.
                     */
				 float[] mModelMatrix = new float[16];

				 /**
                  * Store the view matrix. This can be thought of as our camera. This matrix transforms world space to eye space;
                  * it positions things relative to our eye.
                  */
				 float[] mViewMatrix = new float[16];

				 /** Store the projection matrix. This is used to project the scene onto a 2D viewport. */
				 float[] mProjectionMatrix = new float[16];

				 /** Allocate storage for the final combined matrix. This will be passed into the shader program. */
				 float[] mMVPMatrix = new float[16];

				 /** Store the accumulated rotation. */
				 float[] mAccumulatedRotation = new float[16];

				 /** Store the current rotation. */
				 float[] mCurrentRotation = new float[16];

				 /** A temporary matrix. */
				 float[] mTemporaryMatrix = new float[16];

				 /** 
                  * Stores a copy of the model matrix specifically for the light position.
                  */
				 float[] mLightModelMatrix = new float[16];

				 /** Store our model data in a float buffer. */
				 FloatBuffer mCubePositions;
				 FloatBuffer mCubeNormals;
				 FloatBuffer mCubeTextureCoordinates;
				 FloatBuffer mCubeTextureCoordinatesForPlane;

				 /** This will be used to pass in the transformation matrix. */
				 ScriptCoreLib.JavaScript.WebGL.WebGLUniformLocation mMVPMatrixHandle;

				 /** This will be used to pass in the modelview matrix. */
				 ScriptCoreLib.JavaScript.WebGL.WebGLUniformLocation mMVMatrixHandle;

				 /** This will be used to pass in the light position. */
				 ScriptCoreLib.JavaScript.WebGL.WebGLUniformLocation mLightPosHandle;

				 /** This will be used to pass in the texture. */
				 ScriptCoreLib.JavaScript.WebGL.WebGLUniformLocation mTextureUniformHandle;

				 /** This will be used to pass in model position information. */
				 int mPositionHandle;

				 /** This will be used to pass in model normal information. */
				 int mNormalHandle;

				 /** This will be used to pass in model texture coordinate information. */
				 int mTextureCoordinateHandle;

				 /** How many bytes per float. */
				 int mBytesPerFloat = 4;

				 /** Size of the position data in elements. */
				 int mPositionDataSize = 3;

				 /** Size of the normal data in elements. */
				 int mNormalDataSize = 3;

				 /** Size of the texture coordinate data in elements. */
				 int mTextureCoordinateDataSize = 2;

				 /** Used to hold a light centered on the origin in model space. We need a 4th coordinate so we can get translations to work when
                  *  we multiply this by our transformation matrices. */
				 float[] mLightPosInModelSpace = new float[] { 0.0f, 0.0f, 0.0f, 1.0f };

				 /** Used to hold the current position of the light in world space (after transformation via model matrix). */
				 float[] mLightPosInWorldSpace = new float[4];

				 /** Used to hold the transformed position of the light in eye space (after transformation via modelview matrix) */
				 float[] mLightPosInEyeSpace = new float[4];

				 /** This is a handle to our cube shading program. */
				 ScriptCoreLib.JavaScript.WebGL.WebGLProgram mProgramHandle;

				 /** This is a handle to our light point program. */
				 ScriptCoreLib.JavaScript.WebGL.WebGLProgram mPointProgramHandle;

				 /** These are handles to our texture data. */
				 ScriptCoreLib.JavaScript.WebGL.WebGLTexture mBrickDataHandle;
				 ScriptCoreLib.JavaScript.WebGL.WebGLTexture mGrassDataHandle;

				 #endregion

				 #region ontouchmove
				 // These still work without volatile, but refreshes are not guaranteed to happen.					
				 /* volatile */
				 float mDeltaX = 0;
				 /* volatile */
				 float mDeltaY = 0;

				 v.ontouchmove +=
					 (x, y) =>
					 {
						 mDeltaX += x;
						 mDeltaY += y;
					 };
				 #endregion

				 #region Define points for a cube.

				 // X, Y, Z
				 float[] cubePositionData =
			{
					 // In OpenGL counter-clockwise winding is default. This means that when we look at a triangle, 
					 // if the points are counter-clockwise we are looking at the "front". If not we are looking at
					 // the back. OpenGL has an optimization where all back-facing triangles are culled, since they
					 // usually represent the backside of an object and aren't visible anyways.

					 // Front face
					 -1.0f, 1.0f, 1.0f,
					-1.0f, -1.0f, 1.0f,
					1.0f, 1.0f, 1.0f,
					-1.0f, -1.0f, 1.0f,
					1.0f, -1.0f, 1.0f,
					1.0f, 1.0f, 1.0f,

					 // Right face
					 1.0f, 1.0f, 1.0f,
					1.0f, -1.0f, 1.0f,
					1.0f, 1.0f, -1.0f,
					1.0f, -1.0f, 1.0f,
					1.0f, -1.0f, -1.0f,
					1.0f, 1.0f, -1.0f,

					 // Back face
					 1.0f, 1.0f, -1.0f,
					1.0f, -1.0f, -1.0f,
					-1.0f, 1.0f, -1.0f,
					1.0f, -1.0f, -1.0f,
					-1.0f, -1.0f, -1.0f,
					-1.0f, 1.0f, -1.0f,

					 // Left face
					 -1.0f, 1.0f, -1.0f,
					-1.0f, -1.0f, -1.0f,
					-1.0f, 1.0f, 1.0f,
					-1.0f, -1.0f, -1.0f,
					-1.0f, -1.0f, 1.0f,
					-1.0f, 1.0f, 1.0f,

					 // Top face
					 -1.0f, 1.0f, -1.0f,
					-1.0f, 1.0f, 1.0f,
					1.0f, 1.0f, -1.0f,
					-1.0f, 1.0f, 1.0f,
					1.0f, 1.0f, 1.0f,
					1.0f, 1.0f, -1.0f,

					 // Bottom face
					 1.0f, -1.0f, -1.0f,
					1.0f, -1.0f, 1.0f,
					-1.0f, -1.0f, -1.0f,
					1.0f, -1.0f, 1.0f,
					-1.0f, -1.0f, 1.0f,
					-1.0f, -1.0f, -1.0f,
			};

				 // X, Y, Z
				 // The normal is used in light calculations and is a vector which points
				 // orthogonal to the plane of the surface. For a cube model, the normals
				 // should be orthogonal to the points of each face.
				 float[] cubeNormalData =
			{
					 // Front face
					 0.0f, 0.0f, 1.0f,
					0.0f, 0.0f, 1.0f,
					0.0f, 0.0f, 1.0f,
					0.0f, 0.0f, 1.0f,
					0.0f, 0.0f, 1.0f,
					0.0f, 0.0f, 1.0f,

					 // Right face 
					 1.0f, 0.0f, 0.0f,
					1.0f, 0.0f, 0.0f,
					1.0f, 0.0f, 0.0f,
					1.0f, 0.0f, 0.0f,
					1.0f, 0.0f, 0.0f,
					1.0f, 0.0f, 0.0f,

					 // Back face 
					 0.0f, 0.0f, -1.0f,
					0.0f, 0.0f, -1.0f,
					0.0f, 0.0f, -1.0f,
					0.0f, 0.0f, -1.0f,
					0.0f, 0.0f, -1.0f,
					0.0f, 0.0f, -1.0f,

					 // Left face 
					 -1.0f, 0.0f, 0.0f,
					-1.0f, 0.0f, 0.0f,
					-1.0f, 0.0f, 0.0f,
					-1.0f, 0.0f, 0.0f,
					-1.0f, 0.0f, 0.0f,
					-1.0f, 0.0f, 0.0f,

					 // Top face 
					 0.0f, 1.0f, 0.0f,
					0.0f, 1.0f, 0.0f,
					0.0f, 1.0f, 0.0f,
					0.0f, 1.0f, 0.0f,
					0.0f, 1.0f, 0.0f,
					0.0f, 1.0f, 0.0f,

					 // Bottom face 
					 0.0f, -1.0f, 0.0f,
					0.0f, -1.0f, 0.0f,
					0.0f, -1.0f, 0.0f,
					0.0f, -1.0f, 0.0f,
					0.0f, -1.0f, 0.0f,
					0.0f, -1.0f, 0.0f
			};

				 // S, T (or X, Y)
				 // Texture coordinate data.
				 // Because images have a Y axis pointing downward (values increase as you move down the image) while
				 // OpenGL has a Y axis pointing upward, we adjust for that here by flipping the Y axis.
				 // What's more is that the texture coordinates are the same for every face.
				 float[] cubeTextureCoordinateData =
			{
					 // Front face
					 0.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 1.0f,
					1.0f, 0.0f,

					 // Right face 
					 0.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 1.0f,
					1.0f, 0.0f,

					 // Back face 
					 0.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 1.0f,
					1.0f, 0.0f,

					 // Left face 
					 0.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 1.0f,
					1.0f, 0.0f,

					 // Top face 
					 0.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 1.0f,
					1.0f, 0.0f,

					 // Bottom face 
					 0.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 0.0f,
					0.0f, 1.0f,
					1.0f, 1.0f,
					1.0f, 0.0f
			};

				 // S, T (or X, Y)
				 // Texture coordinate data.
				 // Because images have a Y axis pointing downward (values increase as you move down the image) while
				 // OpenGL has a Y axis pointing upward, we adjust for that here by flipping the Y axis.
				 // What's more is that the texture coordinates are the same for every face.
				 float[] cubeTextureCoordinateDataForPlane =
			{
					 // Front face
					 0.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 25.0f,
					25.0f, 0.0f,

					 // Right face 
					 0.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 25.0f,
					25.0f, 0.0f,

					 // Back face 
					 0.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 25.0f,
					25.0f, 0.0f,

					 // Left face 
					 0.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 25.0f,
					25.0f, 0.0f,

					 // Top face 
					 0.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 25.0f,
					25.0f, 0.0f,

					 // Bottom face 
					 0.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 0.0f,
					0.0f, 25.0f,
					25.0f, 25.0f,
					25.0f, 0.0f
			};
				 #endregion

				 #region  Initialize the buffers.
				 mCubePositions = ByteBuffer.allocateDirect(cubePositionData.Length * mBytesPerFloat)
				 .order(ByteOrder.nativeOrder()).asFloatBuffer();
				 mCubePositions.put(cubePositionData).position(0);

				 mCubeNormals = ByteBuffer.allocateDirect(cubeNormalData.Length * mBytesPerFloat)
				 .order(ByteOrder.nativeOrder()).asFloatBuffer();
				 mCubeNormals.put(cubeNormalData).position(0);

				 mCubeTextureCoordinates = ByteBuffer.allocateDirect(cubeTextureCoordinateData.Length * mBytesPerFloat)
				 .order(ByteOrder.nativeOrder()).asFloatBuffer();
				 mCubeTextureCoordinates.put(cubeTextureCoordinateData).position(0);

				 mCubeTextureCoordinatesForPlane = ByteBuffer.allocateDirect(cubeTextureCoordinateDataForPlane.Length * mBytesPerFloat)
				 .order(ByteOrder.nativeOrder()).asFloatBuffer();
				 mCubeTextureCoordinatesForPlane.put(cubeTextureCoordinateDataForPlane).position(0);
				 #endregion


				 // Set the background clear color to black.
				 gl.clearColor(0.0f, 0.0f, 0.0f, 0.0f);

				 // Use culling to remove back faces.
				 gl.enable(gl.CULL_FACE);

				 // Enable depth testing
				 gl.enable(gl.DEPTH_TEST);

				 // Enable texture mapping
				 gl.enable(gl.TEXTURE_2D);

				 #region setLookAtM
				 // Position the eye in front of the origin.
				 float eyeX = 0.0f;
				 float eyeY = 0.0f;
				 float eyeZ = -0.5f;

				 // We are looking toward the distance
				 float lookX = 0.0f;
				 float lookY = 0.0f;
				 float lookZ = -5.0f;

				 // Set our up vector. This is where our head would be pointing were we holding the camera.
				 float upX = 0.0f;
				 float upY = 1.0f;
				 float upZ = 0.0f;

				 // Set the view matrix. This matrix can be said to represent the camera position.
				 // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and
				 // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose.
				 Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);
				 #endregion


				 #region mProgramHandle
				 mProgramHandle = gl.createProgram(
				  new Shaders.per_pixel_tex_and_lightVertexShader(),
				  new Shaders.per_pixel_tex_and_lightFragmentShader()
				 );

				 gl.bindAttribLocation(mProgramHandle, 0, "a_Position");
				 gl.bindAttribLocation(mProgramHandle, 1, "a_Color");
				 gl.bindAttribLocation(mProgramHandle, 2, "a_TexCoordinate");

				 gl.linkProgram(mProgramHandle);
				 #endregion

				 // Define a simple shader program for our point.

				 #region mPointProgramHandle
				 mPointProgramHandle = gl.createProgram(
					 new Shaders.pointVertexShader(),
					 new Shaders.pointFragmentShader()
				 );

				 gl.bindAttribLocation(mPointProgramHandle, 0, "a_Position");

				 gl.linkProgram(mPointProgramHandle);
				 #endregion


				 #region loadTexture
				 Func<android.graphics.Bitmap, ScriptCoreLib.JavaScript.WebGL.WebGLTexture> loadTexture = (bitmap) =>
				 {
					 var textureHandle = gl.createTexture();

					 // Bind to the texture in OpenGL
					 gl.bindTexture(gl.TEXTURE_2D, textureHandle);

					 // Set filtering
					 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, (int)gl.NEAREST);
					 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, (int)gl.NEAREST);

					 // Load the bitmap into the bound texture.
					 GLUtils.texImage2D((int)gl.TEXTURE_2D, 0, bitmap, 0);

					 // Recycle the bitmap, since its data has been loaded into OpenGL.
					 bitmap.recycle();


					 return textureHandle;
				 };
				 #endregion

				 #region openFileFromAssets
				 Func<string, InputStream> openFileFromAssets = (string spath) =>
				 {
					 InputStream value = null;
					 try
					 {
						 value = OwnerActivity.getResources().getAssets().open(spath);
					 }
					 catch
					 {

					 }
					 return value;

				 };
				 #endregion


				 // cant we use knownAssets yet?
				 var stone_wall_public_domain = android.graphics.BitmapFactory.decodeStream(
					 openFileFromAssets("assets/AndroidOpenGLESLesson6Activity/stone_wall_public_domain.png")
				 );


				 var noisy_grass_public_domain = android.graphics.BitmapFactory.decodeStream(
					 openFileFromAssets("assets/AndroidOpenGLESLesson6Activity/noisy_grass_public_domain.png")
				 );

				 // Load the texture
				 mBrickDataHandle = loadTexture(
					 stone_wall_public_domain
				 );

				 gl.generateMipmap(gl.TEXTURE_2D);


				 mGrassDataHandle = loadTexture(
				   noisy_grass_public_domain
				 );

				 gl.generateMipmap(gl.TEXTURE_2D);



				 // Initialize the accumulated rotation matrix
				 Matrix.setIdentityM(mAccumulatedRotation, 0);

				 #region onresize
				 v.onresize +=
					 (width, height) =>
					 {
						 // Set the OpenGL viewport to the same size as the surface.
						 gl.viewport(0, 0, width, height);

						 // Create a new perspective projection matrix. The height will stay the same
						 // while the width will vary as per aspect ratio.
						 float ratio = (float)width / height;
						 float left = -ratio;
						 float right = ratio;
						 float bottom = -1.0f;
						 float top = 1.0f;
						 float near = 1.0f;
						 float far = 1000.0f;

						 Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
					 };
				 #endregion


				 #region TEXTURE_MIN_FILTER
				 button_set_min_filter.AtClick(
					 delegate
					 {
						 var builder = new AlertDialog.Builder(OwnerActivity);


						 builder.setTitle("Set TEXTURE_MIN_FILTER!");
						 builder.setItems(
							 new[] {
									"NEAREST",
									"LINEAR",
									"NEAREST_MIPMAP_NEAREST",
									"NEAREST_MIPMAP_LINEAR",
									"LINEAR_MIPMAP_NEAREST",
									"LINEAR_MIPMAP_LINEAR",
								},
							 item =>
							 {

								 v.queueEvent(
									 delegate
									 {
										 int filter;

										 if (item == 0)
										 {
											 filter = (int)gl.NEAREST;
										 }
										 else if (item == 1)
										 {
											 filter = (int)gl.LINEAR;
										 }
										 else if (item == 2)
										 {
											 filter = (int)gl.NEAREST_MIPMAP_NEAREST;
										 }
										 else if (item == 3)
										 {
											 filter = (int)gl.NEAREST_MIPMAP_LINEAR;
										 }
										 else if (item == 4)
										 {
											 filter = (int)gl.LINEAR_MIPMAP_NEAREST;
										 }
										 else // if (item == 5)
										 {
											 filter = (int)gl.LINEAR_MIPMAP_LINEAR;
										 }

										 if (mBrickDataHandle != null)
											 if (mGrassDataHandle != null)
											 {
												 gl.bindTexture(gl.TEXTURE_2D, mBrickDataHandle);
												 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
												 gl.bindTexture(gl.TEXTURE_2D, mGrassDataHandle);
												 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);

											 }
									 }
								 );
							 }
						 );


						 var dialog = builder.create();

						 dialog.setOwnerActivity(OwnerActivity);
						 dialog.show();


					 }
					 );
				 #endregion

				 #region TEXTURE_MAG_FILTER
				 button_set_mag_filter.AtClick(
					 delegate
					 {
						 var builder = new AlertDialog.Builder(OwnerActivity);

						 builder.setTitle("Set TEXTURE_MAG_FILTER");
						 builder.setItems(
							 new[]{
									"GL_NEAREST",
									"GL_LINEAR"
								},
							 item =>
							 {


								 v.queueEvent(
									 delegate
									 {
										 int filter;

										 if (item == 0)
										 {
											 filter = (int)gl.NEAREST;
										 }
										 else // if (item == 1)
										 {
											 filter = (int)gl.LINEAR;
										 }

										 if (mBrickDataHandle != null)
											 if (mGrassDataHandle != null)
											 {
												 gl.bindTexture(gl.TEXTURE_2D, mBrickDataHandle);
												 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
												 gl.bindTexture(gl.TEXTURE_2D, mGrassDataHandle);
												 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
											 }

									 }
								 );
							 }
						 );

						 var dialog = builder.create();

						 dialog.setOwnerActivity(OwnerActivity);
						 dialog.show();
					 }
				 );
				 #endregion




				 #region onframe
				 v.onframe +=
					 delegate
					 {
						 var sw = Stopwatch.StartNew();

						 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

						 // Do a complete rotation every 10 seconds.
						 long time = SystemClock.uptimeMillis() % 10000L;
						 long slowTime = SystemClock.uptimeMillis() % 100000L;
						 float angleInDegrees = (360.0f / 10000.0f) * ((int)time);
						 float slowAngleInDegrees = (360.0f / 100000.0f) * ((int)slowTime);

						 var program = mProgramHandle;
						 // Set our per-vertex lighting program.
						 gl.useProgram(program);

						 var uniforms = program.Uniforms(gl);

						 // Set program handles for cube drawing.
						 mMVPMatrixHandle = gl.getUniformLocation(program, "u_MVPMatrix");
						 mMVMatrixHandle = gl.getUniformLocation(program, "u_MVMatrix");
						 mLightPosHandle = gl.getUniformLocation(program, "u_LightPos");
						 mTextureUniformHandle = gl.getUniformLocation(program, "u_Texture");

						 mPositionHandle = gl.getAttribLocation(program, "a_Position");
						 mNormalHandle = gl.getAttribLocation(program, "a_Normal");
						 mTextureCoordinateHandle = gl.getAttribLocation(program, "a_TexCoordinate");

						 // Calculate position of the light. Rotate and then push into the distance.
						 Matrix.setIdentityM(mLightModelMatrix, 0);
						 Matrix.translateM(mLightModelMatrix, 0, 0.0f, 0.0f, -2.0f);
						 Matrix.rotateM(mLightModelMatrix, 0, angleInDegrees, 0.0f, 1.0f, 0.0f);
						 Matrix.translateM(mLightModelMatrix, 0, 0.0f, 0.0f, 3.5f);

						 Matrix.multiplyMV(mLightPosInWorldSpace, 0, mLightModelMatrix, 0, mLightPosInModelSpace, 0);
						 Matrix.multiplyMV(mLightPosInEyeSpace, 0, mViewMatrix, 0, mLightPosInWorldSpace, 0);

						 // Draw a cube.
						 // Translate the cube into the screen.
						 Matrix.setIdentityM(mModelMatrix, 0);
						 Matrix.translateM(mModelMatrix, 0, 0.0f, 0.8f, -3.5f);

						 // Set a matrix that contains the current rotation.
						 Matrix.setIdentityM(mCurrentRotation, 0);
						 Matrix.rotateM(mCurrentRotation, 0, mDeltaX, 0.0f, 1.0f, 0.0f);
						 Matrix.rotateM(mCurrentRotation, 0, mDeltaY, 1.0f, 0.0f, 0.0f);
						 mDeltaX = 0.1f;
						 mDeltaY = 0.1f;

						 // Multiply the current rotation by the accumulated rotation, and then set the accumulated rotation to the result.
						 Matrix.multiplyMM(mTemporaryMatrix, 0, mCurrentRotation, 0, mAccumulatedRotation, 0);
						 java.lang.System.arraycopy(mTemporaryMatrix, 0, mAccumulatedRotation, 0, 16);

						 // Rotate the cube taking the overall rotation into account.     	
						 Matrix.multiplyMM(mTemporaryMatrix, 0, mModelMatrix, 0, mAccumulatedRotation, 0);
						 java.lang.System.arraycopy(mTemporaryMatrix, 0, mModelMatrix, 0, 16);

						 // Set the active texture unit to texture unit 0.
						 gl.activeTexture(gl.TEXTURE0);

						 // Bind the texture to this unit.
						 gl.bindTexture(gl.TEXTURE_2D, mBrickDataHandle);

						 // Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0.
						 gl.uniform1i(mTextureUniformHandle, 0);

						 // Pass in the texture coordinate information
						 mCubeTextureCoordinates.position(0);

						 opengl.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, (int)gl.FLOAT, false,
								 0, mCubeTextureCoordinates);

						 #region drawCube
						 Action drawCube =
							 delegate
							 {
								 // Pass in the position information
								 mCubePositions.position(0);
								 opengl.glVertexAttribPointer(mPositionHandle, mPositionDataSize, (int)gl.FLOAT, false,
										 0, mCubePositions);

								 gl.enableVertexAttribArray((uint)mPositionHandle);

								 // Pass in the normal information
								 mCubeNormals.position(0);
								 opengl.glVertexAttribPointer(mNormalHandle, mNormalDataSize, (int)gl.FLOAT, false,
										 0, mCubeNormals);

								 gl.enableVertexAttribArray((uint)mNormalHandle);

								 // This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix
								 // (which currently contains model * view).
								 Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

								 // Pass in the modelview matrix.
								 gl.uniformMatrix4fv(mMVMatrixHandle, false, mMVPMatrix);

								 // This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix
								 // (which now contains model * view * projection).        
								 Matrix.multiplyMM(mTemporaryMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);
								 java.lang.System.arraycopy(mTemporaryMatrix, 0, mMVPMatrix, 0, 16);

								 // Pass in the combined matrix.
								 gl.uniformMatrix4fv(mMVPMatrixHandle, false, mMVPMatrix);

								 // Pass in the light position in eye space.        
								 gl.uniform3f(mLightPosHandle, mLightPosInEyeSpace[0], mLightPosInEyeSpace[1], mLightPosInEyeSpace[2]);

								 // Draw the cube.k
								 gl.drawArrays(gl.TRIANGLES, 0, 36);
							 };
						 #endregion

						 drawCube();

						 // Draw a plane
						 Matrix.setIdentityM(mModelMatrix, 0);
						 Matrix.translateM(mModelMatrix, 0, 0.0f, -2.0f, -5.0f);
						 Matrix.scaleM(mModelMatrix, 0, 25.0f, 1.0f, 25.0f);
						 Matrix.rotateM(mModelMatrix, 0, slowAngleInDegrees, 0.0f, 1.0f, 0.0f);

						 // Set the active texture unit to texture unit 0.
						 gl.activeTexture(gl.TEXTURE0);

						 // Bind the texture to this unit.
						 gl.bindTexture(gl.TEXTURE_2D, mGrassDataHandle);

						 // Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0.
						 gl.uniform1i(mTextureUniformHandle, 0);

						 // Pass in the texture coordinate information
						 mCubeTextureCoordinatesForPlane.position(0);
						 opengl.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, (int)gl.FLOAT, false,
								 0, mCubeTextureCoordinatesForPlane);

						 gl.enableVertexAttribArray((uint)mTextureCoordinateHandle);

						 drawCube();


						 #region drawLight
						 Action drawLight =
							 delegate
							 {
								 var pointMVPMatrixHandle = gl.getUniformLocation(mPointProgramHandle, "u_MVPMatrix");
								 var pointPositionHandle = gl.getAttribLocation(mPointProgramHandle, "a_Position");

								 // Pass in the position.
								 gl.vertexAttrib3f((uint)pointPositionHandle, mLightPosInModelSpace[0], mLightPosInModelSpace[1], mLightPosInModelSpace[2]);

								 // Since we are not using a buffer object, disable vertex arrays for this attribute.
								 gl.disableVertexAttribArray((uint)pointPositionHandle);

								 // Pass in the transformation matrix.
								 Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mLightModelMatrix, 0);
								 Matrix.multiplyMM(mTemporaryMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);
								 java.lang.System.arraycopy(mTemporaryMatrix, 0, mMVPMatrix, 0, 16);

								 gl.uniformMatrix4fv(pointMVPMatrixHandle, false, mMVPMatrix);

								 // Draw the point.
								 gl.drawArrays(gl.POINTS, 0, 1);
							 };
						 #endregion

						 // Draw a point to indicate the light.
						 gl.useProgram(mPointProgramHandle);
						 drawLight();

						 sw.Stop();
						 OwnerActivity.runOnUiThread(
							 delegate
							 {
								 // Caused by: java.lang.ArithmeticException: divide by zero
								 // at AndroidOpenGLESLesson6Activity.Shaders.ApplicationSurface___c__DisplayClass0_4.__ctor_b__14(ApplicationSurface___c__DisplayClass0_4.java:28)
								 // ... 20 more
								 //Force finishing activity AndroidOpenGLESLesson6Activity.Activities /.AndroidOpenGLESLesson6Activity

								 OwnerActivity.setTitle(
									 "" + new { sw.ElapsedMilliseconds, fps = 1000.0 / sw.ElapsedMilliseconds });

							 }
						 );

					 };
				 #endregion

			 };

		}
        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            //ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            var b = new Button(this);
            ll.addView(b);

            var p = new Preview(this);

            b.WithText("take a picture");

            p.oncamera =
                camera =>
                    b.AtClick(
                        v =>
                        {
                            camera.takePicture(null, null,
                                new takePicture_handler
                                {
                                    handler =
                                        data =>
                                        {
                                            b.WithText("at click");
                                            try
                                            {
                                                // http://stackoverflow.com/questions/11874273/android-nexus-7-jelly-bean-startpreview-takepicture-calling-getcamerastereomode

                                                //E/NvOmxCamera(  126): OMX_ERRORTYPE android::NvOmxCamera::getCameraStereoMode(NvxComponent*, NvOmxCameraUserStereoMode&): Error: invalid NVX mode 0.
                                                //E/NvOmxCamera(  126): OMX_ERRORTYPE android::NvOmxCamera::getCameraStereoModeAndCaptureInfo(NvxComponent*, NvOmxCameraUserStereoMode&, NVX_STEREOCAPTUREINFO&): getCameraStereoMode failed with 0x00000000
                                                //D/NvOsDebugPrintf(  126): NvMMLiteJPEGEncSetAttribute: Incorrect value 0 for stereo capture type
                                                //E/NvOmxCameraSettings(  126): OMX_ERRORTYPE android::programStereoInfo(OMX_HANDLETYPE, const NVX_STEREOCAPTUREINFO&, android::NvxWrappers*): pNvxWrappers->OMX_SetConfigIL failed with 0x80001005
                                                //D/NvOsDebugPrintf(  126): Tryproc: INBuffer-Values of Width and Height 1280 960
                                                //D/dalvikvm(29535): GC_FOR_ALLOC freed 6686K, 52% free 7716K/15943K, paused 25ms, total 27ms


                                                var SAVE_PATH = android.os.Environment.getExternalStoragePublicDirectory(
                                                    android.os.Environment.DIRECTORY_PICTURES
                                                    );


                                                SAVE_PATH.mkdirs();

                                                var bmp = android.graphics.BitmapFactory.decodeByteArray(data, 0, data.Length);

                                                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                                                bmp.compress(android.graphics.Bitmap.CompressFormat.JPEG, 100, bytes);

                                                File f = new File(SAVE_PATH.ToString() + "/hello2.jpg");



                                                f.createNewFile();

                                                FileOutputStream fo = new FileOutputStream(f);
                                                fo.write(bytes.toByteArray());

                                                Intent intent = new Intent();
                                                intent.setAction(android.content.Intent.ACTION_VIEW);

                                                var imgUri = android.net.Uri.fromFile(f);

                                                intent.setDataAndType(imgUri, "image/*");

                                                b.WithText("done!");

                                                startActivity(intent);

                                            }
                                            // Error	1	The type caught or thrown must be derived from System.Exception	y:\jsc.svn\examples\java\android\AndroidCameraActivity\AndroidCameraActivity\ApplicationActivity.cs	154	52	AndroidCameraActivity
                                            catch (Exception ex)
                                            {
                                                b.WithText("saving.. error! " + ex.Message);

                                                //throw;
                                            }


                                        }
                                }
                            );

                        }
                    );


            this.setContentView(p);
            this.addContentView(sv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }