Translate the string source like java source

I need to calculate some user defined formulas in my application. I have this formula in string form (e.g. "operand1 * operand2 + operand3" ). I have gained operand values throught the reflection and pars this string throught the StringTokenizer. So I have parsed string with operand values and operators. Is it possible to calculate this string like java code ?

Mayba possible. But why you dont convert the Strings in primitve types? You have just using static methods in the Wrapper classes like: Integer.parseInt(String), Double.parseDouble(String) and so on. The operators you can convert in a charakter and use
switch (operatorChar):
case '+' : ...
case '-' : ...
Take a look at the java.lang.Compiler, if you still want create bytecode.

Similar Messages

  • Help me to sort out the strings.(novice java user)

    Hi,
    I was wondering if someone can help me out of this problem.
    My program :
    -> it has to create an array of strings.
    -> then create an aray of integers.
    -> then if there are similar strings then i need to group them under the same name and display the output.
    for example if the input is like try, try, hard,mad, try for strings and the corresponing int values are 1,2,3,4,5 .... then.... i need to giv ethe o/p as try = 8
    hard = 3
    mad = g.

    I don't post here often, but I attempted to solve your problem. I noticed you weren't using any Maps (assumed you didn't know what they were)
    I would probably recommend using Maps for a problem like this, but I attempted it by glancing at your code and trying to understand what you were doing.
    (Still unsure if I do understand what you are doing :P)
    //     Program
    //          Created
    //               By
    //                    Lethalwire
    import java.util.*;
    import java.io.*;
    public class Expenses {
         public static void main(String[] args) {
              Scanner in = new Scanner(System.in);     //Reads data from user
              **     -expenses = Number of Categories
              **     -myCats = Array of Category objects
              **     -keepGoing = if true, program keeps running
              int expenses;
              Category[] myCats;
              boolean keepGoing = true;;
              **     Ask user for the number of categories
              System.out.println("Enter Amt. of expenses:  ");
              expenses = in.nextInt();
              **     initialize the Category array to the correct number of Categories
              myCats = new Category[expenses];
              **     Iterate through the myCats array and get names for each of the objects.
              for(int i = 0; i < myCats.length; i++) {
                   String tempName;
                   System.out.println("Enter name of category: ");
                   tempName = in.next();
                   myCats[i] = new Category(tempName);
              **     while loop tests keepGoing
              **     creates temporary variables :
              **          -tempCatName = takes the user's selected category
              **          -myTempCost = takes the current cost that needs to be added to the selected Category
              **          -exists = Checks to see if tempCatName exists in our array
              **               if !exists, error println is displayed
              **          -tempChar = takes the value of 'y' or 'n' to determine if the program continues
              System.out.println("-----------------------");
              while(keepGoing) {
                   String tempCatName;
                   double myTempCost;
                   boolean exists = false;
                   String tempChar;
                   System.out.println("Type a category name to add a value to.");
                   tempCatName = in.next();
                   System.out.println("What is the value you would like to add?");
                   myTempCost = in.nextDouble();
                   **     Iterate through the array and try to find the correctly matched object's name.
                   **      If object isn't found, error println is displayed
                   for(int i = 0; i < myCats.length; i++)
                        if( myCats.getName().equalsIgnoreCase(tempCatName) ) {
                             myCats[i].addCost(myTempCost);
                             exists = true;
                        if (!exists)
                             System.out.println("Category doesn't exist. (mispelled?");
                   **     Prompts the user to continue or not
                   **     Stores value in tempChar
                   **     if tempChar is yes, then program continues
                   **      if tempChar is no, keepGoing is set to false, then the while loop terminates
                   System.out.println("Continue? Enter 'y' for yes, 'n' for no.");
                   tempChar = in.next();
                        if( !tempChar.equalsIgnoreCase("y") )
                             keepGoing = false;
              System.out.println("-----------------------");
              **     Iterates through the array and gathers the current object's name, and total.
              **     They are then displayed
              System.out.println("Totals");
              for(int i = 0; i < myCats.length; i++)
                   System.out.println( myCats[i].getName() + ":\t\t\t$" + myCats[i].getTotal() );
    **     Cateogry class
    **     Holds an objects name and an ArrayList of double values
    class Category {
         **     -name = variable that keeps track of the current object's name
         **     -prices = ArrayList that adds double values when called for
         private String name;
         private ArrayList<Double> prices;
         **     Constructor takes 1 parameter
         **     Initializes prices
         Category(String n) {
              name = n;
              prices = new ArrayList<Double>();
         **     Returns the current objects name;
         String getName() {
              return name;
         **     Adds val to prices.
         void addCost(double val) {
              prices.add(val);
         **     Iterates through the prices arraylist and adds the values up storing them in total
         **     Method returns the total price;
         double getTotal() {
              double total = 0.0;
              for(Double d: prices)
                   total += d;
              return total;

  • How to change the font size of the string by using java?

    I wish to change the font size of the text, read from a text file by using java. Please send me the sample codes. By using ActiveX component for word we can do it. Please give me any other solution to suit the platform independ. Thanks in advance.
    thanks,
    Karthik.

    Text is displayed in some kind of text component - JTextField, JTextArea, JTextPane....To change the font of the text you change the font associated with the text component:
    textComponent.setFont( .... );

  • Use Enum to Switch on Strings where one string is a java reserved word.

    Hi,
    I'm having problems switching on a string using enums, when one of the strings is a java reserved word. Any suggestions would be appreciated. Or maybe even a suggestion that I should just be stringing together if-else if and doing string compares rather than a switch.
    I've been using the following method to switch on strings.
    public enum MyEnum
    foo, bar, novalue;
    public static MyEnum stringValue(String string)
    try { return valueOf(string); }
    catch (Exception e) { return novalue; }
    Then I can switch like
    switch(MyEnum.stringValue( someString )
    case foo:
    break;
    case bar:
    break;
    default:
    break;
    Now I have run into the problem where one of the strings I need to use is "int", which is a reserved word in java, so I have to modify.
    What is the best way to handle this?
    I could just not add it to the Enum and handle it at the switch like this...
    switch(MyEnum.stringValue( someString )
    case foo:
    break;
    case bar:
    break;
    default:
    if(someString.equals("int") {  ... }
    break;
    OR...
    I could change the Enum, and return intx, by checking if the string is "int". I could check before the valueOf, or during the exception, but I know it's not good practice to use Exceptions in the normal execution of your code... as it's not really an exception.
    public enum MyEnum
    foo, bar, intx, novalue;
    public static MyEnum stringValue(String string)
    if(string.equals("int") { return intx; }
    try { return valueOf(string); }
    catch (Exception e) { return novalue; }
    OR...
    public enum MyEnum
    foo, bar, intx, novalue;
    public static MyEnum stringValue(String string)
    try { return valueOf(string); }
    catch (Exception e) {
    if(string.equals("int") { return intx; }
    else return novalue;
    }

    My advice is still to not name the enum the same as the value of the string you want to test for. That page I linked to shows how to have enums with parameters. Then you could have an enum whose name is (say) JavaInt and whose string value is "int".
    But frankly if I wanted to map Strings to actions I would just use a Map<String, Action> instead of trying to force my code into an antique construction like switch.

  • How can i extract using while the time from the string ?

    First time how can i extract the time as string ?
    And second how can i extract the time as DateTime.Now ?
    public static void ExtractDateTime()
    htmltoextract = new Uri("http://test.com");
    client = new WebClient();
    f = client.DownloadString(htmltoextract);
    client.Dispose();
    int index = 0;
    while (index != -1)
    int t = f.IndexOf(firstTag);
    int g = f.IndexOf(lastTag);
    a = f.Substring(t + firstTag.Length, g - t - 8);
    The string look like this: thisisateststring201309202145andthenextimeinthestringis201309202130andthelastofthisexampletimeinthisstringis201309202115
    What i need to do is first time to extract the time as string to a List<string> like this:
    index 0 201309202145
    index 1 201309202130
    index 2 201309202115
    The second time to extract the times as this time format: YYYYMMDDhhmm and also to add the times to a List.
    First time and second time i mean first example and second example. To use my code but first time to extract it as strings second example as the format of YYYYMMDDhhmm
    And i need to use the while and indexof and substring in this cases.

    Is the region always going to be "eu" or are you going to have more than one region.  Since you are reading a string DateTime from different timezone than the computer you are reading the data you have to convert to a different timezone. 
    It looks like you have at least 'is' and 'eu' for regions.  I don't know what offsets you need so try something like this.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Globalization;
    using System.IO;
    namespace ConsoleApplication1
    class Program
    static void Main(string[] args)
    string input = File.ReadAllText(@"c:\temp\test.txt");
    string pattern1 = @"imageUrls = \[[^\]]*\]";
    Regex ex1 = new Regex(pattern1, RegexOptions.Singleline);
    string pattern2 = @"region=(?'region'[^&]*)&time=(?'time'\d{12})";
    Match match1 = ex1.Match(input);
    Regex ex2 = new Regex(pattern2, RegexOptions.Singleline);
    MatchCollection matches2 = ex2.Matches(match1.Value);
    IFormatProvider provider = CultureInfo.InvariantCulture;
    List<DateTime> dateTime = new List<DateTime>();
    foreach (Match match2 in matches2)
    string region = match2.Groups["region"].Value;
    DateTime dt = DateTime.ParseExact(match2.Groups["time"].Value, "yyyyMMddHHmm", provider);
    switch (region)
    case "eu" :
    dt.AddHours(1);
    break;
    case "is":
    dt.AddHours(-1);
    break;
    dateTime.Add(dt);

  • Compile source string like java code

    I need to calculate some user defined formulas in my application. I have this formula in string form (e.g. "operand1 * operand2 + operand3" ). I have gained operand values throught the reflection and pars this string throught the StringTokenizer. So I have parsed string with operand values and operators. Is it possible to compile this string like java code ?
    Thanks for all hints

    Compile to what - a class file?
    Yes, it's possible if you don't mind using non-100% pure Java. You can compile them using the sun.tools.javac.Main class found from tools.jar in the lib directory of the jdk.
    But from what you say it would be easier to use an existing expression evaluator. Take a look at JEP (jep.sourceforge.net) and BeanShell (www.google.com) before you make any decision.

  • I have a large number of photos I'd like to delete from my ipad 2 however from reading previous comments it seems I have to unsync from the original source computer. I'm in another country now and don't have access to it.  Is there another way?

    I have a large number of photos I'd like to delete from my ipad 2 however from reading previous comments it seems I have to unsync from the original source computer. I'm in another country now and don't have access to it.  Is there another way?

    You should be able to do this via the iPad directly.  Open the Photos application and the forward arrow, then select all of the photos you want to delete and click the red delete button.

  • How to keep HTML code in the applet source (.java) file itself?

    Hi,
    How to keep HTML code (APPLET tag) in the applet source (.java) file itself?
    Please give an example?
    thank you,

    R6i wrote:
    ...What I mean is without writing external HTML file, how to run an applet (during practice)?'Practice'? What does that mean? During development? If that is what you are referring to, add an applet tag at the top of YourApplet.java inside a Java comment area. Then AppletViewer (in recent SDKs) can then run it with just..
    prompt:javac YourApplet.java
    prompt:// the '.java' extension is not a mistake
    prompt:appletviewer YourApplet.javaIf you do not mean 'during development', then that brings us back to +"What advantages do you see that is bringing to the end user?".+

  • Trying to get the string from javax.xml.transform.Source

    I have a SOAP client that will submit a string of data to a url and return an xml string back. It works ok besides that last part.
    I found on another site someone took the returned XML and printed it to the system print box. I want to just get the string out to a variable to pass back..
    This chunk works:
    TransformerFactory tff = TransformerFactory.newInstance();
    Transformer tf = tff.newTransformer();
    Source sc = rp.getSOAPPart().getContent();
    StreamResult result = new StreamResult(System.out);
    tf.transform(sc, result);
    System.out.println();Instead of this I just want to catch the XML string in a String variable. Thanks for the help.

    Instead of giving your StreamResult System.out, give it a StringWriter. You can then call toString on the StringWriter, and get what you're after
    StringWriter output = new StringWriter();
    TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(output));
    String xmlResult = output.toString();

  • How can I download the full source code for the Java 3D package

    how can I download the full source code for javax.media.j3d
    especially I need the Transform3D.java class.
    thanks a lot
    Meir

    thank you guys I'll try to do so, I suggest you to
    join me.From the one of the (ex-!)Java3D team:
    "I'm glad to see that Sun has decided to officially support an
    open source Java/OpenGL binding, JOGL. Perhaps they will
    eventually decide to make Java 3D open source. However, be
    careful what you wish for. The Java 3D source is huge and
    complex. There are native sections for Solaris, Windows/OpenGL,
    and Windows/Direct3D, plus common code. I don't know how you'd
    open source a build process that requires different pieces of
    the code be built on different machines running different
    operating systems."
    Sounds scary - I hope we're ready for it :)

  • Changing the Data source in Business Objects XI

    Hi,
      Is it possible to change the data source(not universe) in runtime to generate business objects reports. I am using BOXI 3.1.
    Below is the code I am using to change the universe in runtime. I would like to change this so that i can change the data source instead of changing the universe. My intention is to generate report from multipple database using same universe. Right now I am using multipple universes connected to multiple datasources to achieve this. I am using Report Engine SDK(Java).
               if("Webi".equals(mDocKind))
                   // Added for multiple database support
                   DataProviders dataProvs = documentInstance.getDataProviders();
                try{
                    //To support multiple queries in BO reports
                 for(int count=0;count<dataProvs.getCount(); count++){
                   DataProvider dp=dataProvs.getItem(count);
                   DataSource ds= dp.getDataSource();
                   infoUniverseObjects = getUniverseObject(infoStore,NewUniverseName);
                   infoUniverseObject = (IInfoObject)infoUniverseObjects.get(0);
                   String newDsCuid = infoUniverseObject.getCUID();
                   dataProvs.changeDataSource(ds.getID(), "UnivCUID=" + newDsCuid, true);
                   if(dataProvs.mustFillChangeDataSourceMapping())
                        // Re-map data source to target Universe objects
                        ChangeDataSourceMapping mapping = dataProvs.getChangeDataSourceMapping();
                        ChangeDataSourceObjectMapping[] maps = mapping.getAllMappings();
                        dataProvs.setChangeDataSourceMapping();
                    }//for dataProvs.getCount()
                }catch(Exception e)
                      mLogger.info("BOReportObject","createReport","Inside multiple data providers loop"+e.getMessage());
    Thanks in advance
    Shameer
    Edited by: Shameertaj on May 20, 2009 3:08 AM

    Hi Shameer,
    I think this is only possible with the Universe Designer SDK (which is only available in COM).
    Please kindly refer to the API reference for the Universe Designer SDK for more details:
    http://help.sap.com/businessobject/product_guides/boexir31/en/bodessdk.chm
    Also, please note that changing the universe connection when viewing a document on-demand is not recommended because this could lead to possible issues.
    For example:
    Two users trying to view documents that uses the same universe at approximately the same time.
    But user A wants to use connection X and user B wants to use connection Y.
    This could lead to an error while openning the document or while refreshing/retrieving the the data.
    Hope this helps.
    Regards,
    Dan

  • Question: map the whole source message into one field in the target.

    Hi Friends,
    Is there a way to populate the whole source message into one of the fields in the target message?
    I am trying to do this in message mapping. Guide if this could be done in any other way or is there a way to do it in message mapping.
    Waiting for your valuable guidance,
    Regards,
    Lakshmi

    Hi Friends,
    I tried to convert the source message into a string using XSLT mapping. It was successful, however i need to have the source message in XML format and not in any other format. This is because, I am mapping the source XML into a field in a WSDL. The webservice requires the entire source message be inside a field called "Request" in the WSDL (it is like XML inside another XML).
    Is there any way to do this? Please suggest.. (Im not good at java programming... may be i dont know)

  • Trying to change the data source for a Crystal Report.

    <p>The method below represents my best attempt to programatically change the data source of a Crystal Report. The goal is to have a routine that will update the data source for reports after they have been distributed to production servers. So far I have not been successful in saving the report back to the CMS. No exceptions are thrown, but when I view the Database Configuration of the report in the CMC nothing has changed.
    </p>
    <p>
    Am I missing a step, or is there another way to accomplish this?
    </p>
    <p>
    Thank you.
    </p>
    <hr />
    <pre>
    private void test(String reportName)
       throws SDKException, ReportSDKException, java.io.IOException
       IInfoObjects newInfoObjects;
       IInfoObject reportObj;
       ReportClientDocument clientDoc = new ReportClientDocument();
       DatabaseController dc;
       PropertyBag pBag;
       PropertyBag logonProps;
       ConnectionInfo newConInfo;
       ConnectionInfo oldConInfo;
       ConnectionInfos conInfos;
       int connOptions = DBOptions._ignoreCurrentTableQualifiers + DBOptions._doNotVerifyDB; //0;
       Fields connFields = null;
       String queryStr = "Select * From CI_INFOOBJECTS " +
          "Where SI_NAME='wfr.rpt' AND SI_KIND='CrystalReport' AND SI_INSTANCE=0";
       newInfoObjects = getCms().executeQuery(queryStr);
       if(newInfoObjects.size() > 0)
          reportObj = (IInfoObject)newInfoObjects.get(0);
          try
             clientDoc = getCms().getReportAppFactory().openDocument(
                reportObj
                , OpenReportOptions._refreshRepositoryObjects
                , java.util.Locale.US);
             dc = clientDoc.getDatabaseController();
             conInfos = dc.getConnectionInfos(null);
             for(int i = 0; i < conInfos.size(); ++i)
                oldConInfo = (ConnectionInfo)conInfos.getConnectionInfo(i);
                newConInfo = (ConnectionInfo)oldConInfo.clone(true);
                pBag = newConInfo.getAttributes();
                pBag.putStringValue("QE_ServerDescription", "alio");
                logonProps = new PropertyBag();
                logonProps.putStringValue("Trusted_Connection", "false");
                logonProps.putStringValue("Server", "alio");
                pBag.put("QE_LogonProperties", logonProps);
                newConInfo.setUserName("admin");
                newConInfo.setPassword("password");
                dc.replaceConnection(
                   oldConInfo
                   , newConInfo
                   , connFields
                   , connOptions);
          catch(ReportSDKServerException Ex)
             String msg = "A server error occured while processing the " + reportObj.getKind()
                + " object, " + reportObj.getTitle() + " (" + reportObj.getCUID() + "), from the CMS.";
             Utility.errorOut(msg, Ex);
          catch(Exception Ex)
             String msg = "An error occured while processing the " + reportObj.getKind()
                + " object, " + reportObj.getTitle() + " (" + reportObj.getCUID() + "), from the CMS.";
             Utility.errorOut(msg, Ex);
          finally
             clientDoc.save();
             getCms().commitToInfoStore(newInfoObjects);
             clientDoc.close();
    </pre>
    Edited by: Mark Young on Sep 10, 2009 2:16 PM

    <style type="text/css">
    /<![CDATA[/
        body
            font-size: 1.125em;
              font-family: helvetica,arial,"sans-serif";
          .code{font-family: "courier new",courier,mono,monospace}
          .bi{font-style: italic; font-weight: bold;}
    /]]>/
    </style>
    <p>Justin,</p>
    <p>
    Thank you for the reply. Time constraints have not allowed me to post back to this tread
    till now. I will try your suggestion. My assumption is that <i>Save the report back to the
    info store</i> refers to <span class="code">IInfoStore.commit(IInfoObjects)</span>.
    </p>
    <p>
    I'm afraid that I do not understand why I don't want to change the report client document,
    or why <i>successfully exporting the report with the new login/password</i> is not what I
    want to do. Any explanation on that statement would be appreciated.
    </p>
    <p>
    I did find a way to accomplish my goal. It involved adding the SSOKEY property to the
    logon property bag. Below you'll see my revised code which modifies the report logon and
    server. I have no idea what
    this does, and SAP support has not been able to tell me why it works. However, what I
    discovered is that if I changed the report option, <b>Database Configuration -> When
    viewing report:</b>, in the CMS to <span class="bi">Use same database logon as when report
    is run</span> from <span class="bi">Prompt the user for database logon</span>, then the
    SSOKEY property had been added to the logon property bag having an empty string as its
    value. This allowed me to successfullyupdate and save the modified logon back to the CMS.
    </p>
    <p>
    So I took a chance and added code to always add the SSOKEY property with an empty string
    as its value, and I could then successfully modify and save the report's logon info
    and server. Again, I don't know what this means, but it has worked so far. If anyone has
    some insight or comments, either are welcome. Thank you in advance.
    </p>
    <br />
    <hr />
    <pre>
    private void changeDataSourceOfAWFCrystalReports()
       throws SDKException, ReportSDKException, java.io.IOException
       IInfoObjects newInfoObjects = null;
       IInfoObject reportObj = null;
       IReport curReport = null;
       ReportClientDocument clientDoc = new ReportClientDocument();
       DatabaseController dbController;
       PropertyBag pBag;
       PropertyBag logonProps;
       ConnectionInfo newConInfo;
       ConnectionInfo oldConInfo;
       ConnectionInfos conInfos;
       int connOptions = DBOptions._ignoreCurrentTableQualifiers + DBOptions._doNotVerifyDB;
       Fields connFields = null;
       String outputStr;
       int numOfReports;
       int numOfQueryPages;
       double progressIncrementPerPage = 30;
       int progressIncrementPerReport = 0;
       // Path query to reports is in a .properties file.
       String queryStr = getAppSettingsFile().getWscAwfCrystalReportPathQuery();
       try
          // Executes IInfoStore.getPageingQuery() and generates a list of queries.
          getCms().setPathQueryQueries(queryStr, 100);
          numOfQueryPages = 0;
          // Gets a List&lt;String&gt; of the IPageResult returned from IInfoStore.getPageingQuery().
          if(getCms().getPathQueryQueries() != null)
             numOfQueryPages = getCms().getPathQueryQueries().size();
          if(numOfQueryPages &gt; 0)
             // Use 30% of progress bar for the following loop.
             progressIncrementPerPage = Math.floor(30.0/(double)numOfQueryPages);
          for(int queryPageIndex = 0; queryPageIndex &lt; numOfQueryPages; ++queryPageIndex)
             // Gets the IInfoObjects returned from the current page query
             newInfoObjects = getCms().getPathQueryResultSetPage(queryPageIndex);
             numOfReports = newInfoObjects.size();
             if(newInfoObjects != null && numOfReports &gt; 0)
                progressIncrementPerReport =
                   Math.round((float)Math.floor(progressIncrementPerPage/(double)numOfReports));
                for(int reportIndex = 0; reportIndex &lt; numOfReports; ++reportIndex)
                   reportObj = (IInfoObject)newInfoObjects.get(reportIndex);
                   curReport = (IReport)reportObj;
                   clientDoc = getCms().getReportAppFactory().openDocument(
                      reportObj
                      , OpenReportOptions._refreshRepositoryObjects
                      , java.util.Locale.US);
                   dbController = clientDoc.getDatabaseController();
                   conInfos = dbController.getConnectionInfos(null);
                   for(int conInfosIndex = 0; conInfosIndex &lt; conInfos.size(); ++conInfosIndex)
                      oldConInfo = (ConnectionInfo)conInfos.getConnectionInfo(conInfosIndex);
                      newConInfo = (ConnectionInfo)oldConInfo.clone(true);
                      pBag = newConInfo.getAttributes();
                      pBag.putStringValue(
                         "QE_ServerDescription"
                         ,getConfigFile().getDBDataSourceConnections());
                      logonProps = new PropertyBag();
                      logonProps.putStringValue("Trusted_Connection", "false");
                      <b>logonProps.putStringValue("SSOKEY", "");</b>
                      logonProps.putStringValue(
                         "Server"
                         ,getConfigFile().getDBDataSourceConnections());
                      pBag.put("QE_LogonProperties", logonProps);
                      newConInfo.setUserName(getConfigFile().getUNVConnectionUserName());
                      newConInfo.setPassword(getConfigFile().getUNVConnectionPasswordDecrypted());
                      dbController.replaceConnection(
                         oldConInfo
                         , newConInfo
                         , connFields
                         , connOptions);
                      newConInfo = (ConnectionInfo)conInfos.getConnectionInfo(conInfosIndex);
                   } // end for on conInfosIndex
                   clientDoc.save();
                } // end for on reportIndex
             } // end if on newInfoObjects
          } // end for on queryPageIndex
       } // end try
       catch(ReportSDKServerException Ex)
          // handle...
       catch(Exception Ex)
          // handle...
       finally
          getCms().commitToInfoStore(newInfoObjects);
          if(clientDoc != null)
             clientDoc.close();
    </pre>

  • How to stop the capture source of AudioVideoCaptureDevice

    Hi. I capture video with the AudioVideoCaptureDevice API and I'm not sure if I followed the right steps to implement it. If I record a video for the first time everything works in the emulator but when I tap the record button for the second
    time the app crash. I think it's because I have to disconnect the file stream from the capture source but I can't because passed an instance of  AudioVideoCaptureDevice as the source of the video recorder brush. Here's my code + - in the order of
    execution:
    private async Task InitializeVideoRecorder()
    try
    if (vcDevice != null)
    vcDevice = null;
    CameraSensorLocation location = CameraSensorLocation.Back;
    captureResolutions =
    AudioVideoCaptureDevice.GetAvailableCaptureResolutions(location);
    vcDevice = await AudioVideoCaptureDevice.OpenAsync(location, captureResolutions[0]);
    vcDevice.RecordingFailed += OnCaptureFailed;
    vcDevice.VideoEncodingFormat = CameraCaptureVideoFormat.H264;
    vcDevice.AudioEncodingFormat = CameraCaptureAudioFormat.Aac;
    // Initialize the camera if it exists on the phone.
    if (vcDevice != null)
    //initialize fileSink
    await InitializeFileSink();
    // Create the VideoBrush for the viewfinder.
    videoRecorderBrush = new VideoBrush();
    videoRecorderBrush.SetSource(vcDevice);
    // Display the viewfinder image on the rectangle.
    viewfinderRectangle.Fill = videoRecorderBrush;
    //_cs.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.");
    catch(Exception ex)
    MessageBox.Show("InitializeVideoRecorder Error:\n" + ex.Message);
    private void OnCaptureFailed(AudioVideoCaptureDevice sender, CaptureFailedEventArgs args)
    MessageBox.Show(args.ToString());
    //setup iClips video file creation
    private async Task InitializeFileSink()
    StorageFolder isoStore = await ApplicationData.Current.LocalFolder.GetFolderAsync("Shared");
    sfVideoFile = await isoStore.CreateFileAsync(
    isoVideoFileName+".mp4",
    CreationCollisionOption.ReplaceExisting);
    // Set the recording state: display the video on the viewfinder.
    private void StartVideoPreview()
    try
    // Display the video on the viewfinder.
    if (vcDevice != null)
    // Create the VideoBrush for the viewfinder.
    videoRecorderBrush = new VideoBrush();
    videoRecorderBrush.SetSource(vcDevice);
    // Display the viewfinder image on the rectangle.
    viewfinderRectangle.Fill = videoRecorderBrush;
    // Set the button states and the message.
    UpdateUI(ButtonState.Ready, "Ready to record.");
    txtRecTime.Visibility = Visibility.Collapsed;
    // If preview fails, display an error.
    catch (Exception e)
    MessageBox.Show("Start Video Preview Exception:\n " + e.Message.ToString());
    // Set recording state: start recording.
    private async void StartVideoRecording()
    try
    if (vcDevice != null)
    MessageBox.Show("1");
    s = await sfVideoFile.OpenAsync(FileAccessMode.ReadWrite);
    MessageBox.Show("2");
    await vcDevice.StartRecordingToStreamAsync(s);
    MessageBox.Show("3");
    rState = 1;
    logo.Opacity = 1.0; //brighten logo to indicate that the recording started
    StartTimer(); //show time ellapsed on UI
    // Set the button states and the message.
    UpdateUI(ButtonState.Recording, "Recording...");
    // If recording fails, display an error.
    catch (Exception e)
    MessageBox.Show("Start Video Recording Error:\n" + e.Message.ToString());
    // Set the recording state: stop recording.
    private async void StopVideoRecording()
    try
    await vcDevice.StopRecordingAsync();
    sfVideoFile = null;
    rState = 0;
    logo.Opacity = 0.1;
    StopTimer();
    // Set the button states and the message.
    UpdateUI(ButtonState.Stopped, "Preparing viewfinder...");
    StartVideoPreview();
    // If stop fails, display an error.
    catch (Exception e)
    MessageBox.Show("Stop Video Recording:\n " + e.Message.ToString());
    // Start the video recording.
    private void StartRecording_Click(object sender, EventArgs e)
    // Avoid duplicate taps.
    StartRecording.IsEnabled = false;
    StartVideoRecording();
    private void DisposeVideoRecorder()
    if (_cs != null)
    // Stop captureSource if it is running.
    if (_cs.VideoCaptureDevice != null
    && _cs.State == CaptureState.Started)
    _cs.Stop();
    // Remove the event handler for captureSource.
    _cs.CaptureFailed -= OnCaptureFailed;
    // Remove the video recording objects.
    _cs = null;
    vcDevice = null;
    //fileSink = null;
    videoRecorderBrush = null;
    InitializeVideoRecorder() is called in OnNavigatedTo the when I tap the record button StartVideoRecording() is then called like wise StopVideoRecording() and when I tap the record button( or call StartVideoRecording) for the second time an error
    is thrown. What am I missing? (I bet it's something to do with how I implemented the capture source.) Thaanks in advance.
     

    Thank you that answer is very helpful. I got the recording to work and it's playing the video back too, however, when I record for the second time and tries to playback that file the screen is just black. Can you kindly take a look at my methods
    and see where I'm missing up?
    // Constructor
    public MainPage()
    try
    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]);
    //SetScreenResolution();
    //Sign_Client();
    catch (Exception ex)
    MessageBox.Show("Constructor Error:\n"+ ex.Message);
    //Life Cycle
    protected async override void OnNavigatedTo(NavigationEventArgs e)
    base.OnNavigatedTo(e);
    // Initialize the video recorder.
    await InitializeVideoRecorder();
    //prepare shutter hot keys
    CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;
    CameraButtons.ShutterKeyPressed += OnButtonFullPress;
    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;
    // Update the buttons and text on the UI thread based on app state.
    private void UpdateUI(ButtonState currentButtonState, string statusMessage)
    try
    // 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 Recording Stopped.
    case ButtonState.Stopped:
    StartRecording.IsEnabled = true;
    StopPlaybackRecording.IsEnabled = false;
    StartPlayback.IsEnabled = true;
    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;
    catch (Exception ex)
    MessageBox.Show("UpdateUI Error:\n" + ex.Message.ToString());
    private async Task InitializeVideoRecorder()
    try
    CameraSensorLocation location = CameraSensorLocation.Back;
    captureResolutions =
    AudioVideoCaptureDevice.GetAvailableCaptureResolutions(location);
    vcDevice = await AudioVideoCaptureDevice.OpenAsync(location, captureResolutions[0]);
    vcDevice.RecordingFailed += OnCaptureFailed;
    vcDevice.VideoEncodingFormat = CameraCaptureVideoFormat.H264;
    vcDevice.AudioEncodingFormat = CameraCaptureAudioFormat.Aac;
    //Set a perfect orientation to capture with
    int encodedOrientation = 0;
    int sensorOrientation = (Int32)this.vcDevice.SensorRotationInDegrees;
    switch (this.Orientation)
    // Camera hardware shutter button up.
    case PageOrientation.LandscapeLeft:
    encodedOrientation = -90 + sensorOrientation;
    break;
    // Camera hardware shutter button down.
    case PageOrientation.LandscapeRight:
    encodedOrientation = 90 + sensorOrientation;
    break;
    // Camera hardware shutter button right.
    case PageOrientation.PortraitUp:
    encodedOrientation = 0 + sensorOrientation;
    break;
    // Camera hardware shutter button left.
    case PageOrientation.PortraitDown:
    encodedOrientation = 180 + sensorOrientation;
    break;
    vcDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, sensorOrientation + 90);
    // Initialize the camera if it exists on the phone.
    if (vcDevice != null)
    //initialize fileSink
    await CreateAndOpenNewVideoFile();
    // Create the VideoBrush for the viewfinder.
    videoRecorderBrush = new VideoBrush();
    videoRecorderBrush.SetSource(vcDevice);
    // Display the viewfinder image on the rectangle.
    viewfinderRectangle.Fill = videoRecorderBrush;
    //_cs.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.");
    catch(Exception ex)
    MessageBox.Show("InitializeVideoRecorder Error:\n" + ex.Message);
    private void OnCaptureFailed(AudioVideoCaptureDevice sender, CaptureFailedEventArgs args)
    MessageBox.Show(args.ToString());
    //setup iClips video file creation
    private async Task CreateAndOpenNewVideoFile()
    StorageFolder isoStore = await ApplicationData.Current.LocalFolder.GetFolderAsync("Shared");
    sfVideoFile = await isoStore.CreateFileAsync(isoVideoFileName+".mp4",
    CreationCollisionOption.ReplaceExisting);
    s = await sfVideoFile.OpenAsync(FileAccessMode.ReadWrite);
    // Set the recording state: display the video on the viewfinder.
    private void StartVideoPreview()
    try
    // Display the video on the viewfinder.
    if (vcDevice != null)
    // Create the VideoBrush for the viewfinder.
    videoRecorderBrush = new VideoBrush();
    videoRecorderBrush.SetSource(vcDevice);
    // Display the viewfinder image on the rectangle.
    viewfinderRectangle.Fill = videoRecorderBrush;
    // Set the button states and the message.
    UpdateUI(ButtonState.Ready, "Ready to record.");
    txtRecTime.Visibility = Visibility.Collapsed;
    // If preview fails, display an error.
    catch (Exception e)
    MessageBox.Show("Start Video Preview Exception:\n " + e.Message.ToString());
    // Set recording state: start recording.
    private async void StartVideoRecording()
    try
    if (vcDevice != null)
    await vcDevice.StartRecordingToStreamAsync(s);
    rState = 1;
    logo.Opacity = 1.0; //brighten logo to indicate that the recording started
    StartTimer(); //show time ellapsed on UI
    // Set the button states and the message.
    UpdateUI(ButtonState.Recording, "Recording...");
    // If recording fails, display an error.
    catch (Exception e)
    MessageBox.Show("Start Video Recording Error:\n" + e.Message.ToString());
    // Set the recording state: stop recording.
    private async void StopVideoRecording()
    try
    await vcDevice.StopRecordingAsync();
    //sfVideoFile = null;
    rState = 0;
    logo.Opacity = 0.1;
    StopTimer();
    // Set the button states and the message.
    UpdateUI(ButtonState.Stopped, "Preparing viewfinder...");
    //StartVideoPreview();
    // If stop fails, display an error.
    catch (Exception e)
    MessageBox.Show("Stop Video Recording:\n " + e.Message.ToString());
    // Start the video recording.
    private void StartRecording_Click(object sender, EventArgs e)
    // Avoid duplicate taps.
    StartRecording.IsEnabled = false;
    StartVideoRecording();
    private void DisposeVideoRecorder()
    if (vcDevice != null)
    // Remove the video recording objects.
    vcDevice = null;
    // Remove the event handler for captureSource.
    vcDevice.RecordingFailed -= OnCaptureFailed;
    s = null;
    sfVideoFile = null;
    videoRecorderBrush = null;
    private void OnCaptureFailed(object sender, ExceptionRoutedEventArgs e)
    MessageBox.Show("Recording Failed!");
    private void SaveThumbnail()
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    var w = (int)vcDevice.PreviewResolution.Width;
    var h = (int)vcDevice.PreviewResolution.Height;
    var argbPx = new Int32[w * h];
    vcDevice.GetPreviewBufferArgb(argbPx);
    var wb = new WriteableBitmap(w, h);
    argbPx.CopyTo(wb.Pixels, 0);
    wb.Invalidate();
    using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
    var fileName = isoVideoFileName + "_iThumb.jpg";
    if (isoStore.FileExists(fileName))
    isoStore.DeleteFile(fileName);
    var file = isoStore.CreateFile(fileName);
    wb.SaveJpeg(file, w, h, 0, 20);
    file.Close();
    //STOP WATCH
    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;
    this.Dispatcher.BeginInvoke(delegate()
    txtRecTime.Visibility = Visibility.Visible;
    txtRecTime.Text = now.Subtract(startTime).ToString().Substring(0, now.Subtract(startTime).ToString().LastIndexOf("."));
    // ICLIPS THEATRE - VIDEO PLAYER
    private void StopPlaybackRecording_Click(object sender, EventArgs e)
    try
    if (rState == 1)
    // Avoid duplicate taps.
    StopPlaybackRecording.IsEnabled = false;
    // Stop during video recording.
    StopVideoRecording();
    // Set the button state and the message.
    UpdateUI(ButtonState.NoChange, "Recording stopped.");
    if (rState == 0)
    // Stop during video playback.
    // Remove playback objects.
    DisposeVideoPlayer();
    StartVideoPreview();
    // Set the button state and the message.
    UpdateUI(ButtonState.NoChange, "Playback stopped.");
    catch (Exception ex)
    MessageBox.Show("Stop playback recording Exception:\n" + ex.Message.ToString());
    private void StartPlayback_Click(object sender, EventArgs e)
    PlayVideo();
    private async void PlayVideo()
    try
    // Avoid duplicate taps.
    StartPlayback.IsEnabled = false;
    // Start video playback when the file stream exists.
    if (VideoPlayer.Source != null)
    VideoPlayer.Play();
    // Start the video for the first time.
    else
    //vcDevice.Dispose();
    // Remove VideoBrush from the tree.
    viewfinderRectangle.Fill = null;
    //get the path of iClips-video
    StorageFolder isoStore = await ApplicationData.Current.LocalFolder.GetFolderAsync("Shared");
    iclip = await isoStore.GetFileAsync(isoVideoFileName + ".mp4");
    // Create the file stream and attach it to the MediaElement.
    VideoPlayer.Source = new Uri(iclip.Path);
    // 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.");
    catch (Exception ex)
    MessageBox.Show("Play Video Exception:\n" + ex.Message.ToString());
    private void PausePlayback_Click(object sender, EventArgs e)
    PauseVideo();
    private void PauseVideo()
    // 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;
    iclip = null;
    // Remove the event handler.
    VideoPlayer.MediaEnded -= VideoPlayerMediaEnded;
    // Display the viewfinder when playback ends.
    public void VideoPlayerMediaEnded(object sender, RoutedEventArgs e)
    // Remove the playback objects.
    DisposeVideoPlayer();
    StartVideoPreview();
    I'm using StorageFile to create the file to save the video to. I think my Stop and Start Video Recording logic is causing ether the video not to write to the file the second time or something else. If you can see something that's not right kindly tell me. Thank
    you in advance.

  • Using a string source to create a filestream

    is there any way 2 use a string source to create a filestream.
    eg string s= " JAVA ";
    now i want a filestream containg this string s.

    You could save the string to a file and then open it. However, that seems a stupid thing to need to do. Why do you need a FileStream rather than an InputStream?

Maybe you are looking for

  • How do I make a complaint with Verizon?

    On January 23, 2014, I contacted Verizon Wireless Customer Service because I was experiencing less than satisfactory performance with my HTC One. I purchased the device in September of 2013. Through the first few months I experienced no issues with t

  • Help required in Time mangement Rule writing

    Hi All, The requirement is as follows: The company is going to offer a new type of leave entitlement u2013 Employee Sick Leave.  This new leave entitlement should be given to the active employees in the following Personnel Areas: 1030 -  only Personn

  • "could not start print job" when printing to PDF from Lightroom

    Any body else had this problem and fixed it??  When I print from Lightroom to Adobe PDF I get "could not start print job" and the print job hangs. I have: Lightroom 2.5 64 bit Acrobat Standard 9 Windows 7 Ultimata 64bit but I had this problem with Vi

  • CVS not updating? [SOLVED]

    I'm trying to use the web interface to the CVS entries in some packages, but it seems that the files there are outdated. I've heard about migration to SVN, so maybe this is a known problem that will get solved soon. Just wanted to ask and make sure.

  • How to give page break in SSRS

    I am making a very simple report in SSRS (SQL Server 2012). I am trying to do the following: On page 1 display following text THIS IS PAGE 1 On page 2 display following text THIS IS PAGE 2 I added "Text" field in my report in which I have set the val