Hwo to put and get data to a mq queue through java

Hi All
I would like to know how to put and get messages into a mq series server which is residing on another machine through a java program.
I do not have a mq client installed in my machine..
I have WSAD in my machine.... Should i definitely use a JMS for the same?
PR.

The MQ client installation is free. You can download it from ibm.com, install it, and refer to the application development documentation that accompanies the installation. I believe there are even sample java programs included in the installation.
-Scott

Similar Messages

  • FTP put and get

    When using FTP put and get to transfer files, the program does not go into passive mode. My website requires the following sequence of commands: TYPE A, PORT, PASV, RETR or STOR filename.
    Please update Windows FTP for XP & Windows 7 and later or provide me with the means of using raw FTP commands in my programs.

    Hello ray.crwfrd,
    Please explain a bit about the requirement in case of misunderstanding.
    What do you mean about the sentence ‘update Windows FTP for XP & Windows 7’?
    The following article is about the means of raw FTP command.
    http://www.nsftools.com/tips/RawFTP.htm
    Please note: Since the website is not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
    Best regards,
    Fangzhou CHEN
    Fangzhou CHEN
    TechNet Community Support

  • Sending and getting data from external file.

    I'm running it in actionscript 1  and 2 since 3 wouldn't work when getting data from external media. I'm  trying to find out how to post data to a PHP file and getting from that  file I'm trying to make the flash for something that works like a game  but differently. Since I just found out how to make the HTML stuff show  up but a lot of times, some of my text will not appear so I don't know  what's going on.
    Does anyone know how to send and get data both at the same time from a sample file?
    The sample file is example.php
    It has to sent information like ID and NAME
    and it has to get information like Description and userID

    Ned Murphy wrote:
    The tutorial I pointed you to does provide the visuals you requested, both the AS code and sample PHP code, so I can't see where your learning by visuals aspect holds up.... your approach sounds more like you want someone to hand you a tailored solution that you won't need to learn from.  Visuals require reading and doing.  If that fails to get absorbed or you couldn't understand/revise it, what could anyone else prepare for you that would work better?
    I did the tutorial and everything but every time I press the button or even load it, it keeps on saying undefined. I like the have a sample FLA file so I can figure things out. I did everything from the site but it won't work out for me.
    I did step 5 too because it was almost all that I was looking for but it won't even work. keeps on saying undefined. I would show you but webcam max won't work and I can't show you an example.
    EDIT:
    You know it's frustrating when I don't know how the heck I'm supposed to do this stuff. I read the whole dang thing and I still can't get this dang thing working.
    I did everything. EVERYTHING. I just don't get this crap.

  • Read and Get Data from PDF

    Hi All,
    I am fairly new to programming macros in Excel VBA, and right now I need to write a macro that can open a PDF file and read it and get data from there and paste it into an excel spread sheet. Is this possible?  If so can you give me some sample code
    that would do that?

    I did this once many years ago.  I had to have Acrobat Professional installed ($$$).  There are free pdf parsers that you access from VBA using Win32 commands like:
    https://code.google.com/p/peepdf/
    Maybe something has changed since I did it

  • I've just upgraded to iPhone 4S and restored data from my old iPhone through iTunes.  I'm being asked for a password to get into my phone and the old password I had doesn't work.  I don't know what password it's looking for

    I've just upgraded to iPhone 4S and restored data from my old iPhone through iTunes.  I'm being asked for a password to get into my phone and the old password I had doesn't work.  I don't know what password it's looking for

    Thanks for replying, I'm a real techno-cretin.  What do you mean by not using the backup?  I'm busy trying to restore my new phone and it's doing a 6 hour download with updates.  Can I restore the data from my old phone backup onto the new iPhone 4S when the download is done?

  • PUT and GET Buttons disappeared?

    In the file panel the buttons for PUT and GET are not showing upp at all. What can I do?

    It sounds as though you set up a site selecting FTP & RDS Server. Select Site > New Site to define the site correctly.

  • Problem about put and get

    hi there,
    I met a problem, when i put the data, and get it.
    key data
    aaa aaaaaa
    bbb bbbbbb
    ccc cccccc
    I have put "aaa", "bbb" and "ccc" into db, but when I try to get the key for "aaa" , "bbb", it return the data "cccccc", how can I solve it?
    after that, when i get the key "ddd", "eee" , and all strings are length 3, the key does not in the DB, it also return the data "cccccc". Did I do something wrong on my code?
    void Set1(CString sKey)
    int ret;
    std::string sdb = "test.db";
    Db db(NULL, 0);
    ret = db.open(NULL,
         sdb.c_str(),
         NULL,
         DB_BTREE,
    DB_CREATE,
         0);
    std::string skey, sdata;
    skey = sKey;
    sdata.append(skey);
    sdata.append(skey);
    Dbt key(&skey, skey.length());
    Dbt data(&sdata, sdata.length());
    ret = db.put(NULL, &key, &data, 0);
    if(ret==0){
    TRACE("success\n");
    ret = db.close(0);
    void Get1(CString sKey)
    int ret;
    std::string sdb = "test.db";
    ret = db.open(NULL,
    sdb.c_str(),
         NULL,
         DB_BTREE,
         DB_CREATE,
         0);
    Dbc *cur;
    ret = db.cursor(NULL, &cur, 0);
    std::string skey, s2, a2;
    skey = sKey;
    Dbt key(&skey, skey.length());
    Dbt data;
    memset(&data, 0, sizeof(data));
    ret = cur->get(&key, &data, DB_SET);
    if(ret!=DB_NOTFOUND){
    a2 = (std::string*) data.get_data();
    s2 = (std::string*) key.get_data();
    TRACE("FOUND %s %s\n", s2->c_str(), a2->c_str());
    ret = cur->close();
    ret = db.close(0);
    }

    Hi,
    The problem seems to be with these lines:
    std::string skey, sdata;
    Dbt key(&skey, skey.length());
    Dbt data(&sdata, sdata.length());You are constructing a Dbt with data that is actually a pointer to a C++ std::string object. You want the value to be an actual c style string.
    An alternative would be to construct the Dbts like:
    Dbt key(skey.c_str(), skey.length());
    Dbt data(sdata.c_str(), sdata.length());You will need to create a new std::string out of any data retrieved from the database as well. Since it will now be just a C-style char * string.
    I hope this helps.
    Regards,
    Alex Gorrod, Oracle

  • !!! Storing and Getting data  from HashMap !!!

    Hi ,
    I have got a doubt if this is possible .. Please let me know if this can be implemented ..
    I have a Process1 running which stores data into HashMap one by one from the Users.
    Eg:
    Key Object
    1 ---> Karthik
    2 ---> Raaghav
    3 ---> Srikanth
    and so on ..
    Now what i internally do is i will wait for 5 min Duration (Session TimeOut).Once it is Over 5 min I will delete it from HashMap and Store it in a file ..
    Iam also using WebServer Eg:Iplanet .
    Now when i Shut down Iplanet all the data in the HashMap is Lost .
    My Requirement is to write another Process2 which will be invoked as soon as Iplanet is ShutDown and This process has to read the data from HashMap which is not Timed out .And write it into the File ..
    Q1)Please Let me know if this is can be Done ..
    Task Done :
    Process1 is already existing
    Doubts :
    Q2)If we write a Process2 will it spawn another VM or it will take the same VM that of the Process1.
    Becos if it spawns another VM then I will not be able to get the data from HashMap of the Process1..
    Thanks in Advance,
    [email protected]

    Thank You for the ..
    But my prblm is that the Process1 is already Existing which reads and writes in to HashMap ( Not a Servlets) ..Its a Pure Java Code ..
    And Now the requirement is another Process2 lets say which is put in thread (running in background )which gets the data from the HashMap of the Process1 or in other words Use the Same HashMap and not a different One ...
    Process1 ------------------>HashMap
    (write.java) (writes data ) /\
    |
    |
    |(get Data)
    |
    |
    |
    Process2
    I hope iam clear with my requirement ..
    If Any further explanation Required Iam perpared to give ..Please let me know
    thanks in advance ..

  • Xslt and getting data from a uri in xml file

    In my xml file, i have a node that conains a uri to another xml file
    Is it possible to use XSLT to open the hyperlink and get the content of that xml file?

    Possibly using the document() function.

  • Unexpected results getting data from two fact tables through conformed dim

    Hi all,
    We are getting an unexpected behaviour in our OBIEE 10.1.3.3.3. We have this scenario:
    We have {color:#0000ff}2 fact tables{color}{color:#000000} called F1 and F2. F1 has one measure, f1m1 and F2 has another one, f2m1.
    We have {color:#0000ff}4 conformed dimensions{color}, called D1, D2, D3, Date.
    When we are requesting for individual fact tables, we are getting:
    date d1 d2 d3 f1m1
    dt1 - x - y - z - m1
    dt1 - x - y - z' - m2
    date d1 d2 d3 f2m1
    dt1 - x - y - z - m3
    dt1 - x - y - z'' - m4
    But, trying to obtain a compare scenario, we are getting
    date d1 d2 d3 f1m1 f2m1
    dt1 x y z m1 m4
    Instead of
    date d1 d2 d3 f1m1 f2m1
    dt1 x y z m1 m3
    Looking at query log, we have catched the reason. That's why BI Server is using to solve this request using ROW_COUNT() to join SAWITH0 and SAWITH1 in SAWITH2 result set. So, the order may not be the same in the results sets in every fact table. More or less, generated query is like:
    WITH
    SAWITH0 AS
    (select ....
    from F1),
    SAWITH1 AS
    (select ...
    from F2),
    SAWITH2 AS
    select from (select ...
    ROW_NUMBER() OVER PARTITION (....) c10
    from SAWITH0.d1 full outer join SAWITH1.d1 ....) D1
    {color:#ff0000}where (D1.c10 = 1){color}
    select SAWITH2. ....
    from SAWITH2
    order by c1..c10
    The problems seems to be that BI server is ordering the result sets SAWITH0 and SAWITH1 and getting row number to join this results sets, but this is not getting the correct result.
    Any ideas?
    TIA
    Javier
    {color}
    Edited by: jirazazábal on Mar 13, 2009 2:46 PM

    I have done a logical fact table with two fact table source on it.
    The Sql performed against the database was this one.
    -------------------- Sending query to database named PRODS_AIX (id: <<153418>>):
    WITH
    SAWITH0 AS (select sum(T21296.CONSUMERS_SALES_EURO) as c1,
         T21309.DIVISION_CODE as c2
    from
         DIVISION T21309,
         C_CONSUMERS_SALES T21296
    where  ( T21296.DIVISION = T21309.DIMENSION_KEY )
    group by T21309.DIVISION_CODE),
    SAWITH1 AS (select sum(T21356.ORDER_VALUE) as c1,
         T21309.DIVISION_CODE as c2
    from
         DIVISION T21309,
         DWH_SALES_ORDER_OVERVIEW T21356
    where  ( T21309.DIMENSION_KEY = T21356.DIVISION_KEY )
    group by T21309.DIVISION_CODE)
    select distinct case  when SAWITH0.c2 is not null then SAWITH0.c2 when SAWITH1.c2 is not null then SAWITH1.c2 end  as c1,
         SAWITH0.c1 as c2,
         SAWITH1.c1 as c3
    from
         SAWITH0 full outer join SAWITH1 On nvl(SAWITH0.c2 , 'q') = nvl(SAWITH1.c2 , 'q') and nvl(SAWITH0.c2 , 'z') = nvl(SAWITH1.c2 , 'z')
    order by c1As you can see one select (SAWITH0) for the first fact table C_CONSUMERS_SALES and one select for the second fact table DWH_SALES_ORDER_OVERVIEW (SAWITH1 ) and the two statement are joined with a full outer join.
    I ask me why you have the three select (SAWITH0,SAWITH1 and SAWITH2). Can you please paste the complete SQL performed ?
    Can you tell us also which SQL is performed if you select only the columns from one fact table and not for the other ?
    Regards
    Nico
    http://gerardnico.com

  • Getting Data from C++ STL Vector into Java Vector

    Hi All,
    I have been involved in a project recently to port a lot of C++ code into Java. Testing the ported Java code has been done in isolation with JUnit and works fine, but we would like to test all the ported code. To do this we aim to call the ported (Java) methods from C++ using JNI.
    I have read a lot of the documentation from Sun on the JNI and can access and set Java methods that only contain primitive types without any problems. However what I cant seem to be able to achieve is passing aggregated C++ classes to Java.
    Java
    public void translation_unit_2( Vector v ) { \* code *\ }and somewhere in C++
    jobject actions;                  // Is initialized
    std::vector<Node> test ;   // Node class may contain other objects
    jmethodID tmp = env->GetMethodID(env->GetObjectClass(actions), "translation_unit_2", "(Ljava/util/Vector;)V");
    env->CallObjectMethod(actions, tmp, test);Now obviously what I have posted there doesnt work, but can anybody point me
    in the correct direction to pass the Vector and its Data in C++ to Java?
    None of the Java methods are native, because the eventually the whole system
    will be operating solely in Java, but the testing at this stage is quite important.
    If this is an impossible task then please say so also, any help will be appreciated !
    Thanks,
    Mark Hennessy

    Thanks for the reply and I understand that running an iterator
    over the vector would be the way the get the data out of the C++ Vector.
    However that still leaves me with the question of mapping an arbitrary
    C++ class ( which in the case of the example above would be a Node class which is
    composed of other aggregated classes ) to a jobject such that I can pass
    the data easily to Java throught JNI?
    Is this possible or would I have to decompose each and every class to its most
    primitive types and pass them over to Java and reconstruct them on the Java side?

  • Getting result from a telnet command through Java

    Hi,
    I've been using a set of classes found here: http://javatelnet.org/
    to do telnet through Java in a non-interactive mode.
    However I've got a problem when retrieving the result of a command sent to the remote host: the classes read the stream until the prompt is encountered; my problem is I must execute commands on several remote hosts, and the prompt is not necessarily the same on all hosts.
    Is there a simple means to establish a telnet connection through Java and retrieve the result of the commands?
    Any help would be appreciated.

    Thanks again, this is a very good article
    I see it is still the same strategy to get the result of a command : wait 'til the prompt is sent. Maybe there is just no other way to get it .
    But as I don't know the prompt on the different hosts I have to query, this won't do it.
    The article gave me an idea though : I only need to count the files in a directory on the remote host; until now I was trying to send the 'ls | wc -l' command by Telnet.
    Maybe I can simply do it by FTP (retrieve the list of files, and then count the lines with JAVA).

  • Getting the exace application page openning through java...

    Hi friends,
    I am able to open Ms word or Excel or any other application through java. Now I want to know in word or excel which pages the user has opened. How can I do this? that is....if user opnes abc.doc or abc.pdf through respective applications I should know that he has opned abc.pdf or abc.doc....
    Can anybody tell we what should I do?
    Thanks,
    BRS.

    Hi ,
    try my sample code and understand.
    import java.awt.BorderLayout;
    import java.awt.event.* ;
    import java.io.* ;
    import javax.swing.* ;
    import sun.awt.shell.ShellFolder;
    * @author Little Dany
    public class OtherApp
            extends JFrame {
        private JFileChooser fc ;
        private OtherApp() {
            super() ;
            setTitle( "Running Other Application" ) ;
            setDefaultCloseOperation( EXIT_ON_CLOSE ) ;
            init() ;
            setSize( 400 , 300 ) ;
            setVisible( true ) ;
        private void init() {
            fc = new JFileChooser() ;
            fc.setApproveButtonText( "Execute" ) ;
            getContentPane().add( new JButton( new ButAct() ) , BorderLayout.SOUTH ) ;
        public class ButAct extends AbstractAction {
            public ButAct() {
                super( "Button" ) ;
            public void actionPerformed ( ActionEvent actEvt ) {
                int r = fc.showOpenDialog( OtherApp.this ) ;
                if( r != JFileChooser.APPROVE_OPTION )
                    return ;
                openFile( fc.getSelectedFile() ) ;
            private void openFile( File file ) {
                Runtime r = Runtime.getRuntime() ;
                String cmd = getExecutable( file ) ;
                if( cmd == null )
                    cmd = file.getPath() ;
                else
                    cmd = cmd + " \"" + file.getPath() + "\"" ;
                try {
                    Process p = r.exec( cmd ) ;
                } catch ( IOException ioe ) {
                    ioe.printStackTrace() ;
            private String getExecutable( File file ) {
                try {
                    ShellFolder sf = ShellFolder.getShellFolder( file ) ;
                    String s = sf.getExecutableType() ;
                    if( s != null )
                        return s ;
                } catch ( FileNotFoundException fnfe ) {
                    fnfe.printStackTrace() ;
                String ext = getFileExtention( file ) ;
                if( ext == null || ext.equals( "txt" ) )
                    return "notepad" ;
                else if( ext.equals( "doc" ) || ext.equals( ".rtf" ) )
                    return "winword" ;
                else if( ext.equals( ".ppt" ) || ext.equals( ".pps" ) )
                    return "powerpnt" ;
                // Add more else if for handle more files like pdf
                // return value is the path of the executable
                // ex. return "C:\\program files\\notepad.exe" ;
                // ex. return "notepad" ; // if notepad.exe in the path variable.
                return null ;
            private String getFileExtention( File file ) {
                String name = file.getName() ;
                int id = name.lastIndexOf( '.' ) ;
                if( id == -1 || id == name.length() - 1 )
                    return null ;
                return name.substring( id + 1 ) ;
        public static void main ( String[] args ) {
            SwingUtilities.invokeLater( new Runnable() {
                public void run () {
                    new OtherApp() ;
    }

  • NIO Socket implementation - delay between select and get data from socket

    Hi all,
    I have implemented a internal CallAPI for RPC over a socket connection. It works fine but if there are more than five clients and some load I have the phenomena that the READ selector returns a SelectorKey but I did not get any data from the socket.
    My implementation is based on NIO has following components:
    + Accept-Thread
    Thread handles new clients.
    + Read-Thread
    Thread handles the data from the socket for the registered client. Each request is handled in an own Process-Thread. A Thread-Pool implementation is used for processing.
    + Process-Thread
    The Process-Thread reads the data from the socket and starts the processing of the logical request.
    In my tests I get the notification of data at the socket. The Process-Thread want to read the data for the socket, but no data are available. In some situations if have to read about 20 times and more to get the data. Between each read attempt I have inserted a sleep in the Process-Thread if no data was available. This have improved the problem, but it already exists. I tested the problem with several systems and jvm's but it seams that it is independent from the system.
    What can I to do improve the situation?
    I already include the read implementation from the grizzly-Framework. But it doesn't improve the situation.
    Socket - Init
         protected void openSocket( String host, int port ) throws IOException
              serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking( false );
              serverSocket = serverChannel.socket();
              serverSocket.setReuseAddress( true );
              this.serverhost = host;
              this.serverport = port;
              this.srvAcceptSelector = Selector.open();
              this.srvReadSelector = Selector.open();
              InetSocketAddress isa = null;
              if ( serverhost != null )
                   isa = new InetSocketAddress( this.serverhost, this.serverport );
              else
                   isa = new InetSocketAddress( this.serverport );
              serverSocket.bind( isa, 50 );
              serverChannel.register( this.srvAcceptSelector, SelectionKey.OP_ACCEPT );
         }New Client � Init
         // New Client
         if ( key.isAcceptable())
              keyCountConnect++;
              ServerSocketChannel actChannel =
                   (ServerSocketChannel) key.channel();
              // Socket akteptieren
              SocketChannel actSocket = actChannel.accept();
              if ( actSocket != null )
                   actSocket.finishConnect();
                   actSocket.configureBlocking( false );
                   actSocket.socket().setTcpNoDelay( true );
                   this.registerSocketList.add( actSocket );
                   this.srvReadSelector.wakeup();
         }Read Data from Socket
        protected int readDatafromSocket( ByteArrayOutputStream socketdata )
             throws IOException
             int readedChars = 0;
            int count = -1;
            Selector readSelector = null;
            SelectionKey tmpKey = null;
            if ( sc.isOpen())
                  ByteBuffer inputbuffer = null;
                 try
                      inputbuffer = bufferpool.getBuffer();
                      while (( count = sc.read( inputbuffer )) > 0 )
                           readedChars += count;
                          inputbuffer.flip();
                           byte[] tmparray=new byte[inputbuffer.remaining()];
                           inputbuffer.get( tmparray );
                           socketdata.write( tmparray );
                          inputbuffer.clear();
                      if ( count < 0 )
                           this.closeSocket();
                           if( readedChars == 0 )
                                readedChars = -1;
                           if ( log.isDebug())
                                  log.debug( "Socket is closed! " );
                      else if ( readedChars == 0 )
                           if ( log.isDebug())
                                  log.debug( "Reread with TmpSelector" );
                           // Glassfish/Grizzly-Implementation
                         readSelector = SelectorFactory.getSelector();
                         if ( readSelector == null )
                              return 0;
                          count = 1;
                          tmpKey = this.sc.register( readSelector, SelectionKey.OP_READ );
                         tmpKey.interestOps(
                              tmpKey.interestOps() | SelectionKey.OP_READ );
                         int code = readSelector.select( 500 );
                         tmpKey.interestOps(
                             tmpKey.interestOps() & ( ~SelectionKey.OP_READ ));
                         if ( code == 0 )
                             return 0;
                             // Return on the main Selector and try again.
                           while (( count = sc.read( inputbuffer )) > 0 )
                                readedChars += count;
                               inputbuffer.flip();
                                byte[] tmparray=new byte[inputbuffer.remaining()];
                                inputbuffer.get( tmparray );
                                socketdata.write( tmparray );
                               inputbuffer.clear();
                           if ( count < 0 )
                                this.closeSocket();
                                if( readedChars == 0 )
                                     readedChars =-1;
                           else if ( count == 0 )
                                  // No data
                 finally
                      if ( inputbuffer != null )
                           bufferpool.releaseBuffer( inputbuffer );
                           inputbuffer = null;
                      // Glassfish-Implementierung
                    if ( tmpKey != null )
                        tmpKey.cancel();
                    if ( readSelector != null)
                        // Bug 6403933
                         try
                            readSelector.selectNow();
                         catch (IOException ex)
                        SelectorFactory.returnSelector( readSelector );
            return readedChars;
        }Thanks for your time.

    I've commented on that blog before. It is rubbish:
    - what does 'overloading the main Selector' actually mean? if anything?
    - 'Although this not clearly stated inside the NIO API documentation': The API documentation doesn't say anything about which Selector you should register channels with. Why would it? Register it with any Selector you like ...
    - 'the cost of maintaining multiple Selectors can reduce scalability instead of improving it' Exactly. So what is the point again?
    - 'wrapping a ByteBuffer inside a ByteBufferInputStream:' Code is rubbish and redundant. java.nio.channels.Channels has methods for this.
    There is no a priori advantage to using multiple Selectors and threads unless you have multiple CPUs. And even then not much, as non-blocking reads and writes don't consume significant amounts of CPU. It's the processing of the data once you've got it that takes the CPU, and that should be done in a separate thread.
    So I would re-evaluate your strategy. I suspect you're getting the channel registered with more than one Selector at a time. Implement it the simple way first then see if you really have a problem with 'overloading the main Selector' ...

  • How to post and get data from server using Get Webrequest

    Hi:-)
    I'm trying to send a username and password argument my server and the server is suppose to send some string back. The following code, that I got of the web, just dies. I think this line:
    HttpWebRequestpreq = result.AsyncState
    asHttpWebRequest;
    is null. Can you kindly fix this for me? Thank you in advance:-)
    notes: I have a few textboxes with the values for the request params
    I'm targeting Windows Phone 8.0 and Windows Phone 8.1 devices
    privatevoidBtnSignUpSubmit_Tab(objectsender,
    RoutedEventArgse)
    //show error if Username == Username
    if(TbUN.Text.ToString() ==
    "Username")
    MessageBox.Show("You
    must fill in your Username in the Username textbox.\nThank you.");
    return;
    //make sure all fields are filled in
    if(TbUN.Text.ToString() ==
    ""|| TbPW.Text.ToString()
    == ""|| TbCPW.Text.ToString()
    == "")
    MessageBox.Show("All
    fields must be filled in.\nThank you.");
    return;
    //make sure Password is the same as Confirm Password
    if(TbPW.Text.CompareTo(TbCPW.Text) !=
    0)
    MessageBox.Show("Your
    Password should be the same as Confirm Password.\nThank you.");
    return;
    //make sure Username contains valid characters
    boolbValid = IsUsernameValid(TbUN.Text);
    if(bValid)
                    bSignUp =
    true;
    //disable textboxes
                    TbUN.IsEnabled =
    false;
                    TbPW.IsEnabled =
    false;
                    TbCPW.IsEnabled =
    false;
                    TbEmail.IsEnabled =
    false;
                    BtnSignUpSubmit.IsEnabled =
    false;
                    title.Text =
    "requesting...";
    //make Post request top-server
    //add parameters
    stringdata =
    "username="+TbUN.Text+"&Password="+TbPW.Text;
    if(TbEmail.Text.Contains("@")
    && TbEmail.Text.Contains("."))
                        data +=
    "&email="+ TbEmail.Text;
                    System.
    UriURL =
    newUri("http://www.iclips.co.za/RegisterUsernameAndPassword.php");
    WebRequestwebRequest =
    WebRequest.Create(URL);
                    webRequest.Method =
    "POST";
                    webRequest.ContentType =
    "application/x-www-form-urlencoded";
                    webRequest.ContentLength = data.Length;
    //we first obtain an input stream to which to write the body of the HTTP POST
                    webRequest.BeginGetRequestStream((
    IAsyncResultresult) =>
    HttpWebRequestpreq = result.AsyncState
    asHttpWebRequest;
    if(preq !=
    null)
    StreampostStream = preq.EndGetRequestStream(result);
    //guess one could just accept a byte[] [via function argument] for arbitrary data types - images, audio,...
    byte[] dataStream =
    Encoding.UTF8.GetBytes(data);
                            postStream.Write(dataStream, 0, dataStream.Length);
                            postStream.Close();
    //we can then finalize the request...
                            preq.BeginGetResponse((
    IAsyncResultfinal_result) =>
    HttpWebRequestreq = final_result.AsyncState
    asHttpWebRequest;
    if(req !=
    null)
    try
    //we call the success callback as long as we get a response stream
    WebResponseresponse = req.EndGetResponse(final_result);
                                        success_callback(response.GetResponseStream());
    catch(WebExceptionwe)
    //otherwise call the error/failure callback
                                        error_callback(we.Message);
    return;
                            }, preq);
                    }, URL);
    privatevoiderror_callback(stringp)
    if(bSignUp)
                    bSignUp =
    false;
    // Show error message
    MessageBox.Show("Connection
    Error!\n\n"+ p);
    //enable input
    //disable textboxes
                    TbUN.IsEnabled =
    true;
                    TbPW.IsEnabled =
    true;
                    TbCPW.IsEnabled =
    true;
                    TbEmail.IsEnabled =
    true;
                    BtnSignUpSubmit.IsEnabled =
    false;
                    title.Text =
    "try again";
    privatevoidsuccess_callback(Streamstream)
    if(bSignUp)
                    bSignUp =
    false;
    // Open the stream using a StreamReader for easy access.
    StreamReaderreader =
    newStreamReader(stream);
    // Read the content.
    stringresponse = reader.ReadToEnd();
    // Display the content.
    MessageBox.Show(response);
    // Clean up the streams.
                    reader.Close();

    // Directives
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using iClips.Resources;
    using System.ComponentModel;
    using System.Threading;
    using System.IO;
    using System.IO.IsolatedStorage;
    using Microsoft.Devices;
    using System.Windows.Media;
    using Microsoft.Xna.Framework.Media;
    using System.Windows.Media.Imaging;
    using System.Threading.Tasks;
    using System.Text;
    using Windows.Storage;
    using System.Windows.Threading;
    using System.Diagnostics;
    using System.Globalization;
    namespace iClips
    public partial class MainPage : PhoneApplicationPage
    Boolean bSignUp;
    HyperlinkButton BtnSignIn, BtnSignUp, BtnSignUpSubmit;
    TextBox TbUN, TbPW, TbCPW, TbEmail;
    TextBlock un, title;
    System.DateTime startTime;
    // Viewfinder for capturing video.
    private VideoBrush videoRecorderBrush;
    // Source and device for capturing video.
    private CaptureSource captureSource;
    private CaptureDevice vcDevice;
    double w, h;
    // File details for storing the recording.
    private IsolatedStorageFileStream isoVideoFile;
    private FileSink fileSink;
    private string isoVideoFileName = "CameraMovie.mp4";
    // For managing button and application state.
    private enum ButtonState { Initialized, Stopped, Ready, Recording, Playback, Paused, NoChange, CameraNotSupported };
    private ButtonState currentAppState;
    //create reference to SocketClient
    SocketClient sock = new SocketClient();
    // Constructor
    public MainPage()
    InitializeComponent();
    //setup recording
    // Prepare ApplicationBar and buttons.
    PhoneAppBar = (ApplicationBar)ApplicationBar;
    PhoneAppBar.IsVisible = true;
    StartRecording = ((ApplicationBarIconButton)ApplicationBar.Buttons[0]);
    StopPlaybackRecording = ((ApplicationBarIconButton)ApplicationBar.Buttons[1]);
    StartPlayback = ((ApplicationBarIconButton)ApplicationBar.Buttons[2]);
    PausePlayback = ((ApplicationBarIconButton)ApplicationBar.Buttons[3]);
    //display a welcome message
    txtDebug.Text = "Welcome to iClips.";
    string result = sock.Connect("197.189.214.116", 5000);
    txtOutput.Text = result;
    if(result.Contains("success")){
    sock.Send("#testing_");
    SetScreenResolution();
    //set image on load friends
    /*Uri uri = new Uri("/Assets/home_icons/myFriends.png", UriKind.Relative);
    BitmapImage imgSource = new BitmapImage(uri);
    Image image = new Image();
    image.Source = imgSource;
    load_friends.Content = image;*/
    SignIn();
    private void SignIn()
    // remove all elements inside sign grid
    for (int index = MyGrid.Children.Count - 1; index >= 0; index--)
    MyGrid.Children.RemoveAt(index);
    BtnSignIn = new HyperlinkButton();
    BtnSignIn.Content = "<< Sign In >>";
    BtnSignIn.Click += new RoutedEventHandler(SignIn_Tab);
    BtnSignIn.VerticalAlignment = VerticalAlignment.Bottom;
    BtnSignUp = new HyperlinkButton();
    BtnSignUp.Content = "<< I'm new here. Sign Up. >>";
    BtnSignUp.Click += new RoutedEventHandler(SignUp_Tab);
    BtnSignUp.VerticalAlignment = VerticalAlignment.Bottom;
    un = new TextBlock();
    un.Text = "Enter your Username:";
    un.VerticalAlignment = VerticalAlignment.Bottom;
    un.HorizontalAlignment = HorizontalAlignment.Center;
    TextBlock pw = new TextBlock();
    pw.Text = "Enter your Password:";
    pw.VerticalAlignment = VerticalAlignment.Bottom;
    pw.HorizontalAlignment = HorizontalAlignment.Center;
    //setup username textbox
    TbUN = new TextBox();
    TbUN.Opacity = 0.5;
    TbUN.Text = "";
    TbUN.FontSize = 16;
    TbUN.FontWeight = FontWeights.ExtraBold;
    TbUN.Foreground = new SolidColorBrush(Colors.Black);
    TbUN.Background = new SolidColorBrush(Colors.Transparent);
    TbUN.VerticalAlignment = VerticalAlignment.Top;
    TbUN.Height = 70;
    TbUN.Tap += TbUN_Tap;
    //setup password textbox
    TbPW = new TextBox();
    TbPW.Opacity = 0.5;
    TbPW.Text = "";
    TbPW.FontSize = 16;
    TbPW.FontWeight = FontWeights.ExtraBold;
    TbPW.Foreground = new SolidColorBrush(Colors.Black);
    TbPW.Background = new SolidColorBrush(Colors.Transparent);
    TbPW.VerticalAlignment = VerticalAlignment.Top;
    TbPW.Height = 70;
    TbPW.Tap += TbPW_Tap;
    //Show the background color of MyGrid
    MyGrid.Background = new SolidColorBrush(Colors.Blue);
    // Create Row for Username Textblock
    RowDefinition gridRow0 = new RowDefinition();
    gridRow0.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow0);
    // Create Row for Username
    RowDefinition gridRow1 = new RowDefinition();
    gridRow1.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow1);
    //create row for password Textblock
    RowDefinition gridRow2a = new RowDefinition();
    gridRow2a.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow2a);
    //create row for password
    RowDefinition gridRow2 = new RowDefinition();
    gridRow2.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow2);
    //create row for << Sign In >>
    RowDefinition gridRow3 = new RowDefinition();
    gridRow3.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow3);
    //create row for << Sign Up >>
    RowDefinition gridRow4 = new RowDefinition();
    gridRow4.Height = new GridLength(120);
    MyGrid.RowDefinitions.Add(gridRow4);
    Grid.SetRow(un, 0);
    Grid.SetColumn(un, 0);
    Grid.SetRow(TbUN, 1);
    Grid.SetColumn(TbUN, 0);
    Grid.SetRow(pw, 2);
    Grid.SetColumn(pw, 0);
    Grid.SetRow(TbPW, 3);
    Grid.SetColumn(TbPW, 0);
    Grid.SetRow(BtnSignIn, 4);
    Grid.SetColumn(BtnSignIn, 0);
    Grid.SetRow(BtnSignUp, 5);
    Grid.SetColumn(BtnSignUp, 0);
    MyGrid.Children.Add(un);
    MyGrid.Children.Add(TbUN);
    MyGrid.Children.Add(pw);
    MyGrid.Children.Add(TbPW);
    MyGrid.Children.Add(BtnSignIn);
    MyGrid.Children.Add(BtnSignUp);
    private void SignUp_Tab(object sender, RoutedEventArgs e)
    MessageBox.Show("Welcome to Sign up.\n\nYou need 3 things to create an account:\n1. A unique Case-Sensitive Username. ex 'iClips' is not the same as 'Iclips'\n2. A password to secure you account. \n3. A profile photo for easy recognition.\nThank you.");
    // remove all elements inside sign grid
    for (int index = MyGrid.Children.Count - 1; index >= 0; index--)
    MyGrid.Children.RemoveAt(index);
    //repopulate grid with Sign Up elements
    //create title
    title = new TextBlock();
    title.Text = "--- Sign Up 1/2 ---";
    title.VerticalAlignment = VerticalAlignment.Top;
    title.HorizontalAlignment = HorizontalAlignment.Center;
    //field for Username
    TbUN = new TextBox();
    TbUN.Opacity = 0.5;
    TbUN.Text = "Username";
    TbUN.FontSize = 16;
    TbUN.FontWeight = FontWeights.ExtraBold;
    TbUN.Foreground = new SolidColorBrush(Colors.Black);
    TbUN.Background = new SolidColorBrush(Colors.Transparent);
    TbUN.VerticalAlignment = VerticalAlignment.Top;
    TbUN.Height = 70;
    TbUN.Tap += TbUN_Tap;
    //field for Password
    TbPW = new TextBox();
    TbPW.Opacity = 0.5;
    TbPW.Text = "Password";
    TbPW.FontSize = 16;
    TbPW.FontWeight = FontWeights.ExtraBold;
    TbPW.Foreground = new SolidColorBrush(Colors.Black);
    TbPW.Background = new SolidColorBrush(Colors.Transparent);
    TbPW.VerticalAlignment = VerticalAlignment.Top;
    TbPW.Height = 70;
    TbPW.Tap += TbPW_Tap;
    //field Confirm for Password
    TbCPW = new TextBox();
    TbCPW.Opacity = 0.5;
    TbCPW.Text = "Confirm Password";
    TbCPW.FontSize = 16;
    TbCPW.FontWeight = FontWeights.ExtraBold;
    TbCPW.Foreground = new SolidColorBrush(Colors.Black);
    TbCPW.Background = new SolidColorBrush(Colors.Transparent);
    TbCPW.VerticalAlignment = VerticalAlignment.Top;
    TbCPW.Height = 70;
    TbCPW.Tap += TbCPW_Tap;
    //field for Optional Email
    TbEmail = new TextBox();
    TbEmail.Opacity = 0.5;
    TbEmail.Text = "Email (Optional)";
    TbEmail.FontSize = 16;
    TbEmail.FontWeight = FontWeights.ExtraBold;
    TbEmail.Foreground = new SolidColorBrush(Colors.Black);
    TbEmail.Background = new SolidColorBrush(Colors.Transparent);
    TbEmail.VerticalAlignment = VerticalAlignment.Top;
    TbEmail.Height = 70;
    TbEmail.Tap += TbEmail_Tap;
    HyperlinkButton BtnGoBack = new HyperlinkButton();
    BtnGoBack.Content = "<< Go Back ";
    BtnGoBack.Click += new RoutedEventHandler(BtnGoBack_Tab);
    BtnGoBack.VerticalAlignment = VerticalAlignment.Bottom;
    BtnSignUpSubmit = new HyperlinkButton();
    BtnSignUpSubmit.Content = "<< Sign Up >>";
    BtnSignUpSubmit.Click += new RoutedEventHandler(BtnSignUpSubmit_Tab);
    BtnSignUpSubmit.VerticalAlignment = VerticalAlignment.Bottom;
    // Create Row for title
    RowDefinition gridRow0 = new RowDefinition();
    gridRow0.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow0);
    // Create Row for Username
    RowDefinition gridRow1 = new RowDefinition();
    gridRow1.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow1);
    //create row for password Textblock
    RowDefinition gridRow2a = new RowDefinition();
    gridRow2a.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow2a);
    //create row for Confirm password
    RowDefinition gridRow2 = new RowDefinition();
    gridRow2.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow2);
    //create row for email
    RowDefinition gridRow3 = new RowDefinition();
    gridRow3.Height = new GridLength(60);
    MyGrid.RowDefinitions.Add(gridRow3);
    //create row for << Sign Up >>
    RowDefinition gridRow4 = new RowDefinition();
    gridRow4.Height = new GridLength(120);
    MyGrid.RowDefinitions.Add(gridRow4);
    //create row for << Go Back >>
    RowDefinition gridRow5 = new RowDefinition();
    gridRow5.Height = new GridLength(120);
    MyGrid.RowDefinitions.Add(gridRow5);
    Grid.SetRow(title, 0);
    Grid.SetColumn(title, 0);
    Grid.SetRow(TbUN, 1);
    Grid.SetColumn(TbUN, 0);
    Grid.SetRow(TbPW, 2);
    Grid.SetColumn(TbPW, 0);
    Grid.SetRow(TbCPW, 3);
    Grid.SetColumn(TbCPW, 0);
    Grid.SetRow(TbEmail, 4);
    Grid.SetColumn(TbEmail, 0);
    Grid.SetRow(BtnSignUpSubmit, 5);
    Grid.SetColumn(BtnSignUpSubmit, 0);
    Grid.SetRow(BtnGoBack, 6);
    Grid.SetColumn(BtnGoBack, 0);
    MyGrid.Children.Add(title);
    MyGrid.Children.Add(TbUN);
    MyGrid.Children.Add(TbPW);
    MyGrid.Children.Add(TbCPW);
    MyGrid.Children.Add(TbEmail);
    MyGrid.Children.Add(BtnSignUpSubmit);
    MyGrid.Children.Add(BtnGoBack);
    BtnSignUp.Content = "<< Sign Up >>";
    private bool IsUsernameValid(string str)
    int d;
    if (str.Length > 30)
    MessageBox.Show("You may only use a maximum of 30 characters for your Username.\nThank you.");
    return false;
    for (d = 0; d < str.Length; d++)
    if (str.Contains("~") || str.Contains("!") || str.Contains("@") || str.Contains("$")
    || str.Contains("#") || str.Contains("%") || str.Contains("|") || str.Contains("_"))
    MessageBox.Show("Your Username may not contain any of the follwing characters: \n~ ! @ # $ % | _\nThank you.");
    return false;
    return true;
    private void BtnSignUpSubmit_Tab(object sender, RoutedEventArgs e)
    //show error if Username == Username
    if (TbUN.Text.ToString() == "Username")
    MessageBox.Show("You must fill in your Username in the Username textbox.\nThank you.");
    return;
    //make sure all fields are filled in
    if (TbUN.Text.ToString() == "" || TbPW.Text.ToString() == "" || TbCPW.Text.ToString() == "")
    MessageBox.Show("All fields must be filled in.\nThank you.");
    return;
    //make sure Password is the same as Confirm Password
    if (TbPW.Text.CompareTo(TbCPW.Text) != 0)
    MessageBox.Show("Your Password should be the same as Confirm Password.\nThank you.");
    return;
    //make sure Username contains valid characters
    bool bValid = IsUsernameValid(TbUN.Text);
    if (bValid)
    bSignUp = true;
    //disable textboxes
    TbUN.IsEnabled = false;
    TbPW.IsEnabled = false;
    TbCPW.IsEnabled = false;
    TbEmail.IsEnabled = false;
    BtnSignUpSubmit.IsEnabled = false;
    title.Text = "requesting...";
    //make Post request top-server
    //add parameters
    string data = "username="+TbUN.Text+"&Password="+TbPW.Text;
    if(TbEmail.Text.Contains("@") && TbEmail.Text.Contains("."))
    data += "&email=" + TbEmail.Text;
    System.Uri URL = new Uri("http://www.iclips.co.za/RegisterUsernameAndPassword.php");
    WebRequest webRequest = WebRequest.Create(URL);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = data.Length;
    //we first obtain an input stream to which to write the body of the HTTP POST
    webRequest.BeginGetRequestStream((IAsyncResult result) =>
    HttpWebRequest preq = result.AsyncState as HttpWebRequest;
    if (preq != null)
    Stream postStream = preq.EndGetRequestStream(result);
    //guess one could just accept a byte[] [via function argument] for arbitrary data types - images, audio,...
    byte[] dataStream = Encoding.UTF8.GetBytes(data);
    postStream.Write(dataStream, 0, dataStream.Length);
    postStream.Close();
    //we can then finalize the request...
    preq.BeginGetResponse((IAsyncResult final_result) =>
    HttpWebRequest req = final_result.AsyncState as HttpWebRequest;
    if (req != null)
    try
    //we call the success callback as long as we get a response stream
    WebResponse response = req.EndGetResponse(final_result);
    success_callback(response.GetResponseStream());
    catch (WebException we)
    //otherwise call the error/failure callback
    error_callback(we.Message);
    return;
    }, preq);
    }, URL);
    private void error_callback(string p)
    if (bSignUp)
    bSignUp = false;
    // Show error message
    MessageBox.Show("Connection Error!\n\n" + p);
    //enable input
    //disable textboxes
    TbUN.IsEnabled = true;
    TbPW.IsEnabled = true;
    TbCPW.IsEnabled = true;
    TbEmail.IsEnabled = true;
    BtnSignUpSubmit.IsEnabled = false;
    title.Text = "try again";
    private void success_callback(Stream stream)
    if (bSignUp)
    bSignUp = false;
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(stream);
    // Read the content.
    string response = reader.ReadToEnd();
    // Display the content.
    MessageBox.Show(response);
    // Clean up the streams.
    reader.Close();
    private void BtnGoBack_Tab(object sender, RoutedEventArgs e)
    SignIn();
    private void TbEmail_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    TbEmail.SelectAll();
    private void TbCPW_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    TbCPW.SelectAll();
    private void SignIn_Tab(object sender, RoutedEventArgs e)
    if (TbUN.Text.ToString() == "" || TbPW.Text.ToString() == "")
    MessageBox.Show("Your Username or Password cannot be empty.\nThank you.");
    return;
    private void TbUN_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    TbUN.SelectAll();
    un.Text = "Usernames are Case-Sensitive.\n'Iclips' is not the same as 'iClips'.";
    private void TbPW_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    TbPW.SelectAll();
    protected override void OnNavigatedTo(NavigationEventArgs e)
    base.OnNavigatedTo(e);
    // Initialize the video recorder.
    InitializeVideoRecorder();
    CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;
    // The event is fired when the shutter button receives a full press.
    CameraButtons.ShutterKeyPressed += OnButtonFullPress;
    // The event is fired when the shutter button is released.
    CameraButtons.ShutterKeyReleased += OnButtonRelease;
    protected override void OnNavigatedFrom(NavigationEventArgs e)
    // Dispose of camera and media objects.
    DisposeVideoPlayer();
    DisposeVideoRecorder();
    base.OnNavigatedFrom(e);
    CameraButtons.ShutterKeyHalfPressed -= OnButtonHalfPress;
    CameraButtons.ShutterKeyPressed -= OnButtonFullPress;
    CameraButtons.ShutterKeyReleased -= OnButtonRelease;
    // Ensure that the viewfinder is upright in LandscapeRight.
    protected override void OnOrientationChanged(OrientationChangedEventArgs e)
    if (vcDevice != null)
    if (e.Orientation == PageOrientation.LandscapeLeft)
    txtDebug.Text = "LandscapeLeft";
    videoRecorderBrush.RelativeTransform =
    new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
    //rotate logo
    if (logo != null)
    RotateTransform rt = new RotateTransform();
    rt.Angle = 90;
    //default rotation is around top left corner of the control,
    //but you sometimes want to rotate around the center of the control
    //to do that, you need to set the RenderTransFormOrigin
    //of the item you're going to rotate
    //I did not test this approach, maybe You're going to need to use actual coordinates
    //so this bit is for information purposes only
    logo.RenderTransformOrigin = new Point(0.5, 0.5);
    logo.RenderTransform = rt;
    //rotate sign in link
    if (MyGrid != null)
    RotateTransform rt = new RotateTransform();
    rt.Angle = 90;
    //default rotation is around top left corner of the control,
    //but you sometimes want to rotate around the center of the control
    //to do that, you need to set the RenderTransFormOrigin
    //of the item you're going to rotate
    //I did not test this approach, maybe You're going to need to use actual coordinates
    //so this bit is for information purposes only
    MyGrid.RenderTransformOrigin = new Point(0.5, 0.5);
    MyGrid.RenderTransform = rt;
    if (e.Orientation == PageOrientation.PortraitUp)
    txtDebug.Text = "PortraitUp";
    videoRecorderBrush.RelativeTransform =
    new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 0 };
    //rotate logo
    if (logo != null)
    RotateTransform rt = new RotateTransform();
    rt.Angle = 0;
    //default rotation is around top left corner of the control,
    //but you sometimes want to rotate around the center of the control
    //to do that, you need to set the RenderTransFormOrigin
    //of the item you're going to rotate
    //I did not test this approach, maybe You're going to need to use actual coordinates
    //so this bit is for information purposes only
    logo.RenderTransformOrigin = new Point(0.5, 0.5);
    logo.RenderTransform = rt;
    //rotate sign in link
    if (MyGrid != null)
    RotateTransform rt = new RotateTransform();
    rt.Angle = 0;
    //default rotation is around top left corner of the control,
    //but you sometimes want to rotate around the center of the control
    //to do that, you need to set the RenderTransFormOrigin
    //of the item you're going to rotate
    //I did not test this approach, maybe You're going to need to use actual coordinates
    //so this bit is for information purposes only
    MyGrid.RenderTransformOrigin = new Point(0.5, 0.5);
    MyGrid.RenderTransform = rt;
    if (e.Orientation == PageOrientation.LandscapeRight)
    txtDebug.Text = "LandscapeRight";
    // Rotate for LandscapeRight orientation.
    //videoRecorderBrush.RelativeTransform =
    //new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 180 };
    //rotate logo
    if (logo != null)
    RotateTransform rt = new RotateTransform();
    rt.Angle = -90;
    //default rotation is around top left corner of the control,
    //but you sometimes want to rotate around the center of the control
    //to do that, you need to set the RenderTransFormOrigin
    //of the item you're going to rotate
    //I did not test this approach, maybe You're going to need to use actual coordinates
    //so this bit is for information purposes only
    logo.RenderTransformOrigin = new Point(0.5, 0.5);
    logo.RenderTransform = rt;
    //rotate sign in link
    if (MyGrid != null)
    RotateTransform rt = new RotateTransform();
    rt.Angle = -90;
    //default rotation is around top left corner of the control,
    //but you sometimes want to rotate around the center of the control
    //to do that, you need to set the RenderTransFormOrigin
    //of the item you're going to rotate
    //I did not test this approach, maybe You're going to need to use actual coordinates
    //so this bit is for information purposes only
    MyGrid.RenderTransformOrigin = new Point(0.5, 0.5);
    MyGrid.RenderTransform = rt;
    if (e.Orientation == PageOrientation.PortraitDown)
    txtDebug.Text = "PortraitDown";
    videoRecorderBrush.RelativeTransform =
    new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 270 };
    // Provide auto-focus with a half button press using the hardware shutter button.
    private void OnButtonHalfPress(object sender, EventArgs e)
    // Focus when a capture is not in progress.
    try
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = "Half Button Press: Auto Focus";
    catch (Exception focusError)
    // Cannot focus when a capture is in progress.
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = focusError.Message;
    // Capture the image with a full button press using the hardware shutter button.
    private void OnButtonFullPress(object sender, EventArgs e)
    // Focus when a capture is not in progress.
    try
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = "Full Button Press: Auto Focus";
    catch (Exception focusError)
    // Cannot focus when a capture is in progress.
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = focusError.Message;
    // Cancel the focus if the half button press is released using the hardware shutter button.
    private void OnButtonRelease(object sender, EventArgs e)
    try
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = "Shutter is released: Auto Focus";
    catch (Exception focusError)
    // Cannot focus when a capture is in progress.
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = focusError.Message;
    // Update the buttons and text on the UI thread based on app state.
    private void UpdateUI(ButtonState currentButtonState, string statusMessage)
    // Run code on the UI thread.
    Dispatcher.BeginInvoke(delegate
    switch (currentButtonState)
    // When the camera is not supported by the phone.
    case ButtonState.CameraNotSupported:
    StartRecording.IsEnabled = false;
    StopPlaybackRecording.IsEnabled = false;
    StartPlayback.IsEnabled = false;
    PausePlayback.IsEnabled = false;
    break;
    // First launch of the application, so no video is available.
    case ButtonState.Initialized:
    StartRecording.IsEnabled = true;
    StopPlaybackRecording.IsEnabled = false;
    StartPlayback.IsEnabled = false;
    PausePlayback.IsEnabled = false;
    break;
    // Ready to record, so video is available for viewing.
    case ButtonState.Ready:
    StartRecording.IsEnabled = true;
    StopPlaybackRecording.IsEnabled = false;
    StartPlayback.IsEnabled = true;
    PausePlayback.IsEnabled = false;
    break;
    // Video recording is in progress.
    case ButtonState.Recording:
    StartRecording.IsEnabled = false;
    StopPlaybackRecording.IsEnabled = true;
    StartPlayback.IsEnabled = false;
    PausePlayback.IsEnabled = false;
    break;
    // Video playback is in progress.
    case ButtonState.Playback:
    StartRecording.IsEnabled = false;
    StopPlaybackRecording.IsEnabled = true;
    StartPlayback.IsEnabled = false;
    PausePlayback.IsEnabled = true;
    break;
    // Video playback has been paused.
    case ButtonState.Paused:
    StartRecording.IsEnabled = false;
    StopPlaybackRecording.IsEnabled = true;
    StartPlayback.IsEnabled = true;
    PausePlayback.IsEnabled = false;
    break;
    default:
    break;
    // Display a message.
    txtDebug.Text = statusMessage;
    // Note the current application state.
    currentAppState = currentButtonState;
    public void InitializeVideoRecorder()
    if (captureSource == null)
    // Create the VideoRecorder objects.
    captureSource = new CaptureSource();
    fileSink = new FileSink();
    vcDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
    // Add eventhandlers for captureSource.
    captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed);
    // Initialize the camera if it exists on the phone.
    if (vcDevice != null)
    // Create the VideoBrush for the viewfinder.
    videoRecorderBrush = new VideoBrush();
    videoRecorderBrush.SetSource(captureSource);
    // Display the viewfinder image on the rectangle.
    viewfinderRectangle.Fill = videoRecorderBrush;
    // Start video capture and display it on the viewfinder.
    captureSource.Start();
    // Set the button state and the message.
    UpdateUI(ButtonState.Initialized, "Tap record to start recording...");
    else
    // Disable buttons when the camera is not supported by the phone.
    UpdateUI(ButtonState.CameraNotSupported, "A camera is not supported on this phone.");
    // Set recording state: start recording.
    private void StartVideoRecording()
    try
    // Connect fileSink to captureSource.
    if (captureSource.VideoCaptureDevice != null
    && captureSource.State == CaptureState.Started)
    captureSource.Stop();
    // Connect the input and output of fileSink.
    fileSink.CaptureSource = captureSource;
    fileSink.IsolatedStorageFileName = isoVideoFileName;
    // Begin recording.
    if (captureSource.VideoCaptureDevice != null
    && captureSource.State == CaptureState.Stopped)
    captureSource.Start();
    // Set the button states and the message.
    UpdateUI(ButtonState.Recording, "Recording...");
    StartTimer();
    // If recording fails, display an error.
    catch (Exception e)
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = "ERROR: " + e.Message.ToString();
    //start the timer
    private void StartTimer()
    dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    dispatcherTimer.Start();
    startTime = System.DateTime.Now;
    private void StopTimer()
    dispatcherTimer.Stop();
    private void dispatcherTimer_Tick(object sender, EventArgs e)
    System.DateTime now = System.DateTime.Now;
    txtRecTime.Text = now.Subtract(startTime).ToString();
    // Set the recording state: stop recording.
    private void StopVideoRecording()
    try
    // Stop recording.
    if (captureSource.VideoCaptureDevice != null
    && captureSource.State == CaptureState.Started)
    captureSource.Stop();
    // Disconnect fileSink.
    fileSink.CaptureSource = null;
    fileSink.IsolatedStorageFileName = null;
    // Set the button states and the message.
    UpdateUI(ButtonState.Stopped, "Preparing viewfinder...");
    StopTimer();
    StartVideoPreview();
    // If stop fails, display an error.
    catch (Exception e)
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = "ERROR: " + e.Message.ToString();
    // Set the recording state: display the video on the viewfinder.
    private void StartVideoPreview()
    try
    // Display the video on the viewfinder.
    if (captureSource.VideoCaptureDevice != null
    && captureSource.State == CaptureState.Stopped)
    // Add captureSource to videoBrush.
    videoRecorderBrush.SetSource(captureSource);
    // Add videoBrush to the visual tree.
    viewfinderRectangle.Fill = videoRecorderBrush;
    captureSource.Start();
    // Set the button states and the message.
    UpdateUI(ButtonState.Ready, "Ready to record.");
    // If preview fails, display an error.
    catch (Exception e)
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = "ERROR: " + e.Message.ToString();
    // Start the video recording.
    private void StartRecording_Click(object sender, EventArgs e)
    // Avoid duplicate taps.
    StartRecording.IsEnabled = false;
    StartVideoRecording();
    // Handle stop requests.
    private void StopPlaybackRecording_Click(object sender, EventArgs e)
    // Avoid duplicate taps.
    StopPlaybackRecording.IsEnabled = false;
    // Stop during video recording.
    if (currentAppState == ButtonState.Recording)
    StopVideoRecording();
    // Set the button state and the message.
    UpdateUI(ButtonState.NoChange, "Recording stopped.");
    // Stop during video playback.
    else
    // Remove playback objects.
    DisposeVideoPlayer();
    StartVideoPreview();
    // Set the button state and the message.
    UpdateUI(ButtonState.NoChange, "Playback stopped.");
    // Start video playback.
    private void StartPlayback_Click(object sender, EventArgs e)
    // Avoid duplicate taps.
    StartPlayback.IsEnabled = false;
    // Start video playback when the file stream exists.
    if (isoVideoFile != null)
    VideoPlayer.Play();
    // Start the video for the first time.
    else
    // Stop the capture source.
    captureSource.Stop();
    // Remove VideoBrush from the tree.
    viewfinderRectangle.Fill = null;
    // Create the file stream and attach it to the MediaElement.
    isoVideoFile = new IsolatedStorageFileStream(isoVideoFileName,
    FileMode.Open, FileAccess.Read,
    IsolatedStorageFile.GetUserStoreForApplication());
    VideoPlayer.SetSource(isoVideoFile);
    // Add an event handler for the end of playback.
    VideoPlayer.MediaEnded += new RoutedEventHandler(VideoPlayerMediaEnded);
    // Start video playback.
    VideoPlayer.Play();
    // Set the button state and the message.
    UpdateUI(ButtonState.Playback, "Playback started.");
    // Pause video playback.
    private void PausePlayback_Click(object sender, EventArgs e)
    // Avoid duplicate taps.
    PausePlayback.IsEnabled = false;
    // If mediaElement exists, pause playback.
    if (VideoPlayer != null)
    VideoPlayer.Pause();
    // Set the button state and the message.
    UpdateUI(ButtonState.Paused, "Playback paused.");
    private void DisposeVideoPlayer()
    if (VideoPlayer != null)
    // Stop the VideoPlayer MediaElement.
    VideoPlayer.Stop();
    // Remove playback objects.
    VideoPlayer.Source = null;
    isoVideoFile = null;
    // Remove the event handler.
    VideoPlayer.MediaEnded -= VideoPlayerMediaEnded;
    private void DisposeVideoRecorder()
    if (captureSource != null)
    // Stop captureSource if it is running.
    if (captureSource.VideoCaptureDevice != null
    && captureSource.State == CaptureState.Started)
    captureSource.Stop();
    // Remove the event handler for captureSource.
    captureSource.CaptureFailed -= OnCaptureFailed;
    // Remove the video recording objects.
    captureSource = null;
    vcDevice = null;
    fileSink = null;
    videoRecorderBrush = null;
    // If recording fails, display an error message.
    private void OnCaptureFailed(object sender, ExceptionRoutedEventArgs e)
    this.Dispatcher.BeginInvoke(delegate()
    txtDebug.Text = "ERROR: " + e.ErrorException.Message.ToString();
    // Display the viewfinder when playback ends.
    public void VideoPlayerMediaEnded(object sender, RoutedEventArgs e)
    // Remove the playback objects.
    DisposeVideoPlayer();
    StartVideoPreview();
    public void SetScreenResolution()
    w = Application.Current.Host.Content.ActualWidth;
    h = Application.Current.Host.Content.ActualHeight;
    setResViewF(w, h);
    public void setResViewF(double width, double height)
    viewfinderRectangle.Width = width;
    viewfinderRectangle.Height = height;
    resMI.Content = "resolution: " + width + "*" + height;
    private void resMI_Click(object sender, RoutedEventArgs e)
    switch (resMI.Content.ToString())
    case "resolution: 176*220":
    setResViewF(240, 320);
    break;
    case "resolution: 240*320":
    setResViewF(360, 480);
    break;
    case "resolution: 360*480":
    setResViewF(480, 800);
    break;
    case "resolution: 480*800":
    setResViewF(1440, 720);
    break;
    case "resolution: 1440*720":
    setResViewF(1920, 1080);
    break;
    case "resolution: 1920*1080":
    setResViewF(176, 220);
    break;
    default:
    setResViewF(176, 220);
    break;
    public void WriteToFile(string key, string value)
    var Iso_settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
    if (!Iso_settings.Contains(key))
    Iso_settings.Add(key, value);
    Iso_settings.Save();//This will save your data in isolated storage.
    public string ReadFromFile(string key)
    var Iso_settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
    if (Iso_settings.Contains(key))
    return (string)Iso_settings[key];
    else
    return null;
    public DispatcherTimer dispatcherTimer { get; set; }
    private void ToggleZoom(MediaElement media)
    if (media.Stretch != Stretch.UniformToFill)
    // zoom
    media.Stretch = Stretch.UniformToFill;
    else
    // unzoom
    media.Stretch = Stretch.Uniform;
    BtnSignUpSubmit_Tab is the HyperLinkButton that would trigger the web request process. I need this code to work perfectly because a lot of people will use this. If you can simplify the http web request that already feels so good. Thank you. 

Maybe you are looking for

  • Hide selection fields in SAP PS Report (TCode:S_ALR_87013533)

    Dear Friends, We are implementing EP. In that i have to take one report of PS which tcode is S_ALR_87013533. In this report having various selection parameters field in 1st screen.But i want only Project defination field to be displayed and remaing f

  • Scale in Charts

    Hi, I want to set the scale of X axis based min value of the fact.... Lets say i have an analysis where fact measure values are all in between 85 and 100. So for better visibility i wanted the scale to start from the same. This should be dynamic as g

  • HT4356 Can I use xerox printer with ipad?

    I just got a new ipad is it possible to scan and then print it on my xerox printer? Thank you in advance, cairnberger

  • Depreciation Run gone wrong for Manual Assets

    Hi All We ran the depreciation run for period 4 - and now we see that the 2 manual assets are wrong because after changing the depreciation key from LINS to MANU - I forgot to 'recalculate values'  of the asset again so now the depreciation posted fo

  • MSI Z87-G45 Stuck on A2 SSD problem

    Hi, So I have a new setup build with some parts from my old machine (SSD, HDD, CD/DVD and PSU). At first the system booted fine and I was installing Windows 8.1 to my SSD. I went to get a cup of coffee and when I came back it restarted and was stuck