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' ...

Similar Messages

  • ADF 11g can not select and copy data from cell of readonly table in IE

    hi,
    In ADF 11g, when render view object as readonly table with Single RowsSelection, using IE browser can not select and copy data from the cell, but it work in firefox.
    is it a bug?
    Edited by: kent2066 on 2009-5-18 上午8:46

    Hi Timo,
    Sorry forgot to mention versions.
    We are using 11.1.1.7 and IE 9.
    I tried in Google but could not get the solution.
    Kindly let me know solution for this.
    PavanKumar

  • Help get data from socket

    hi all
    i am trying to get data from socket www.yahoo.com site and try to write in file with following code
    NOTE:here netClient is the soccket object accepted by server
    File f=new File(finalpath);
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(netClient.getInputStream()));
    OutputStream fo=new FileOutputStream(f);
    String str;
    try{
    while((str=fromClient.readLine())!=null){
    byte buf[]=str.getBytes();
    fo.write(buf);
    }catch(Exception e){}
    finally{fo.close();}
    But i am not getiing data from socket
    please help
    regards krunal

    GeneralYerevan is absolutely right. Use URLConnection and you will get what you want. It seems to me that you do not know deeply how http works. The fact that you opened a connection to www.google.com doesn't mean that you will get data. The web server, after it accepts the socket object, waits for your request. In you case it is something like "GET / HTTP1.1", which you have to write to the stream. URLConnection does all this for you and all you have is to read the InputStream.

  • 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

  • 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.

  • !!! 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 ..

  • !!!! Storing and Getting Data from HashMap !!! VERY URGENT

    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]

    You need to consider the following
    -------Normal execution:
    Keep a list of all instances of the HashMap and a timestamp for each. Start a timer thread (or use the jdk api Timer class). Fire it every minute, or 5 minutes, or hour - the length depends on how your system runs - load, fail-safe, etc. When the timer fires, any instances with expired timestamps are written.
    -------Graceful Shutdown:
    If you have a way to exit your application gracefully then rbyrom suggestion is needed. Basically it writes all existing instances in the list on shutdown.
    -------Abnormal events
    What do you do if the disk drive is full and you can't write data?
    -------Abnormal shutdown
    What happens if someone pulls the plug on the server? How important is the data?

  • SSRS Expression to compare two values and get data from another dataset

    Hi,
    I have a requirement where in i need to compare a value of a dataset (not the one which table is poiting to)
    with the value of a text box, and return the count if it matches else 0, the expression is as below. Here 
    industryName and recCount are from the dataset ds_MedimOrLowImpactEntities.  whats wrong in this expression
    =Sum(IIF(Fields!industryName.Value = reportItems!hpapra_name.Value, Fields!RecCount.Value, 0), "ds_MediumOrLowImpactEntities")
    This is the error that i am getting:
    Any help on this is appreciated
    Kruthi Hegde

    Hi Kruthi,
    After testing the issue in my local environment, I can reproduce it. Just the error message said, “Aggregate function can be used only on report items contained in page headers and footers”. So the sum function that contains report items should be stayed
    at page headers or footers. Besides, you said the hpapra_name textbox contain a field from another dataset, not the ds_MedimOrLowImpactEntities dataset. While in Reporting Services, Report item expressions can only refer to other report items within the same
    grouping scope or a containing grouping scope. So consider the two issues, we should use some other expression to instead the “reportItems!hpapra_name.Value” expression.
    Take a look at the "Looking up values from another dataset" topic here:
    http://msdn.microsoft.com/en-us/library/ms159673.aspx#LookupFunctions
    Hope this helps.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • 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.

  • 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. 

  • Process Class:How to give and get data from an exe file continuously???

    hi,,,
    I am trying to run an executable file from my program to give it input and read its output....
    And i am having problems...
    The exe file takes one input and appends to it "1235" (ITS A TEST CASE).
    When it is only for a single input , the program rums perfectly.. but when it is within a loop it does not
    Pls help
    Here is the code for that EXE file. (its in C)
    #include<stdio.h>
    int main()
    char a[10];
    int i;
    int k=1235;
    while(1){
    scanf("%s",a);
    if(a[0]=='s')
    break;
    printf("%s%d\n",a,k);
    }Note that when i remove the loop here, my code is able to get and give it data.
    My JAVA program::
    import java.io.*;
    public class Main {
      public static void main(String[] args) throws IOException {
            try {
          String line;
          Process p = Runtime.getRuntime().exec
            ("C:\\users\\Untitled3.exe");
           BufferedWriter   out=new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
              out.write("dfgsfs\n");
              time= java.lang.System.nanoTime();
              out.flush();
          BufferedReader input =new BufferedReader(new InputStreamReader(p.getInputStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(input.readLine());
          input.close();
        catch (Exception err) {
          err.printStackTrace();
    }PLS HELP

    I see a problem in your C code. You're not flushing stdout after you printf and that usually means java is not seeing whats your C program is printing.
    removing the loop probably works because stdout is being flushed right before exit.
    I used a perl script to test your stuff and found that flushing made the trick
    #!/usr/bin/perl
    open(OUTFILE,">>./output.txt");
    $| = 1;
    while (<STDIN>) {
        if (m/.*error.*/) {
            print STDERR  $_;
        } else {
            print STDOUT  $_;
        print OUTFILE $_;
        if (m/exit/) {
            last;
    close(OUTFILE);
    exit;notice "$| =1;" that autoflushes in perl (just in case you were wondering where my flush call went)
    Enjoy!

  • Formula in Fields and get data from fields together

    Hi, I was trying to setup formula in fields as follows:
    U_Test & U_Test are numeric fields.
    SELECT ($[INV1.U_Test.Number]-$[INV1.U_Test3.Number])*0.1
    The outcome should be (U_Test-U_Test3)*0.1
    U_Test2 & U_Test5 are alphnumeric fields.
    SELECT $[INV1.U_Test2]+[INV1.U_Test5])
    The outcome should be U_Test2U_Test5
    I have been struggling in the syntax error. Can you help me out?
    Thanks.
    Raymond

    I think better u can create the UDF again.
    Test - Numeric - 10
    Test1 - Numeric - 10
    Then use this query
    Select $[$38.U_Test.number] + $[$38.U_Test2.number]
    I hope UDF can be case sensitive. It is working properly for me.
    Sample:
    Select case when ($[por1.U_x.number] *$[por1.U_y.number]) > 15 then 15 else ($[por1.U_x.number] *$[por1.U_y.number]) end
    here x,y are UDF created as numeric.
    SAGAR

  • How to build Hierarchy and get values from DAX Evaluation Query?

    i have create Calander Hierachy for Year,Quarter,Month... in this invisible tabuler model medata properties.
    any one give steps for create Hierachy and Get Data From DAX evaluation context ?.
    VenkadesanPerumal

    Venkadesan, is this still an issue?
    Thanks!
    Ed Price, Azure & Power BI Customer Program Manager (Blog,
    Small Basic,
    Wiki Ninjas,
    Wiki)
    Answer an interesting question?
    Create a wiki article about it!

  • How to get data from subsites list of SharePoint 2010 in ssrs

    Hi,
    Can someone help me on this issue.
    I want to create a report using ssrs, I have some of the data in SQL and some of the data in sharepoint list.
    First I need to go to SQL and get the data from the table which contains URL for the subsite in sharepoint.
    after that I need to go to all the subsites and go to perticulat list in the subsites and get data from that list.
    for example, their is a top level site "abc"
    it contains sub site "123", "456","567", etc.. All this sub sites contain a list by name "Sample List", Now I need to go to that sub site list(Sample List) and get list-item column say "created By" which
    is created on particular date. 
    in my report, I need to print the sub site "url/Title" which comes from SQL database and list-item column  "Created By" of that sub site list "Sample List".
    I tried using subreport inside a report by using "Microsoft SharePoint List" as a datasource, but when it comes to real time we don't know how many subsites will be created, so we can't create a datasource for each subsite site.
    I guess we need to be using XML as a datasource, but how can we go to particular subsite in query while using XML, since all subsites have list with the same name ?
    I appreciate your help.
    Thank you,
    Kishore 

    Hi Kishore,
    SQL Server Reporting Services(SSRS) supports expression-based connection strings. This will help us to achieve the goal you mentioned in this case:
    Create a new report
    Create a Data Source in the report with the connection string like this:
    http://server/_vti_bin/lists.asmx (We use static connection string instead of expression-based connection string now, as it is not supported to get fields based on expression-based connection string in design time. We will change it to be expression-based
    connection string later)
    Create the data set(as you have done using XML query language). Please use list name instead of GUID in the listName parameter.
    Design the report(e.g. Add controls to the report)
    Now, let's change the connection string to be expression-based. First, please add a parameter to the report, move this parameter to top. This parameter is used to store the sub site name.
    Open the Data Source editor, set the connection string to be: ="http://server/" & Parameters!parameterCreatedInStep5.value & "_vti_bin/lists.asmx"
    In the main report, pass the sub site name to the report we created above via the parameter created in step5
    That is all.
    Anyway, this is actually a SQL Server Reporting Service(SSRS) question. You can get better support on this question from:
    http://social.technet.microsoft.com/Forums/en/sqlreportingservices/threads
    For more information about Expression-Based connection string, please see:
    http://msdn.microsoft.com/en-us/library/ms156450.aspx#Expressions
    If there is anything unclear, please feel free to ask.
    Thanks,
    Jinchun Chen
    Jin Chen - MSFT

  • Any Function module to get data from ESS leave form

    Hi Friends,
    I have modified std workflow ws12300111.with 2 levels.
    I want to send mail to HOD. In that mail i have to mention details like start date , end date,leave type which is entered into ESS form. I want to retrive that data.
    Is there any Fm is available? which wil give ESS data as output.
    Plz let m know.
    Regards,
    Shital

    Have you thought about creating attachments in the WF so you can read the form and get data from it.
    There's plenty of standard WF examples around of attaching objects to WF's.
    Since the ESS action will initiate the relevant workflows you should easily be able to save this data.
    BTW If your other question on this WF was answered please close that thread.
    Cheers
    Jimbo

Maybe you are looking for

  • Pages 5.2 does not open Pages 2.0 files

    Just started using Pages in the last several months. The version of pages I had/have is 2.02. I created several documents and saved them with this version. Yesterday I down loaded Pages 5.2. This version indicates that the files I just created last w

  • Default directory for FIle Manager

    Hi, I am working on file manager for my final year project. I am using jsp, Tomcat and Linux as OS. The question is, "Is there any way to authenticate users from OS(linux or windows 2000) and how can i set user home directory(e.g. home/sahsan/) to my

  • I made menu but it plays the first video clip and no autostart

    Hi all, I created a dvd today with a menu, but instead of starting at the menu and letting you choose it automatically plays the first clip when you play the dvd. And when I put the dvd in a dvd player it doesn't automatically play the dvd menu or an

  • How to create a program that enable peer-to-peer connection

    I'm currently doing a college project which is a instant messenging system. The system will have the client-server network and peer-to-peer network. The client-server network part has been finished but i still facing the problem to write the code to

  • How make dynamic site with MUSE

    Howdy, i want ask how make dynamic site with muse, can it intergated with CMS like wordpress, joomla, drupal etc? Thanks, best regard, harles