Search Results

Search found 105 results on 5 pages for 'stringreader'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Using Android SAXParser, one my my XML Elements is mysteriously breaking in half.

    - by Drennen
    And its not '&' Im using the SAXParser object do parse the actual XML. This is normally done by passing a URL to the XMLReader.Parse method. Because my XML is coming from a POST request to a webservice, I am saving that result as a String and then employing StringReader / InputSource to feed this string back to the XMLReader.Parse method. However, something strange is happening at the 2001st character of the XMLstring. The 'characters' method of the document handler is being called TWICE in between the startElement and endElement methods, effectively breaking my string (in this case a project title) into two pieces. Because I am instantiating objects in my characters method, I am getting two objects instead of one. This line, about 2000 chars into the string fires 'characters' two times, breaking between "Lower" and "Level" <title>SUMC-BOOKSTORE, LOWER LEVEL RENOVATIONS</title> When I bypass the StringReader / InputSource workaround and feed a flat XML file to XMLReader.Parse, it works absolutely fine. Something about StringReader and or InputSource is somehow screwing this up. Here is my method that takes and XML string and parses is through the SAXParser. public void parseXML(String XMLstring) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); // Something is happening in the StringReader or InputSource // That cuts the XML element in half at the 2001 character mark. StringReader sr = new StringReader(XMLstring); InputSource is = new InputSource(sr); xr.parse(is); } catch (IOException e) { Log.e("CMS1", e.toString()); } catch (SAXException e) { Log.e("CMS2", e.toString()); } catch (ParserConfigurationException e) { Log.e("CMS3", e.toString()); } } I would greatly appreciate any ideas on how to not have 'characters' firing off twice when I get to this point in the XML String. Or, show me how to use a POST request and still pass off the URL to the Parse function. THANK YOU.

    Read the article

  • How to string multiple TextReaders together?

    - by Ken
    I have 3 TextReaders -- a combination of StreamReaders and StringReaders. Conceptually, the concatenation of them is a single text document. I want to call a method (not under my control) that takes a single TextReader. Is there any built-in or easy way to make a concatenating TextReader from multiple TextReaders? (I could write my own TextReader subclass, but it looks like a fair amount of work. In that case, I'd just write them all out to a temp file and then open it with a single StreamReader.) Is there an easy solution to this that I'm missing?

    Read the article

  • C# xml serializer - Unable to generate a temporary class

    - by gosom
    I am trying to serialize an xml to a class with the following way: XmlSerializer ser = new XmlSerializer(typeof(PSW5ns.PSW5)); StringReader stringReader; stringReader = new StringReader(response_xml); XmlTextReader xmlReader; xmlReader = new XmlTextReader(stringReader); PSW5ns.PSW5 obj; obj = (PSW5ns.PSW5)ser.Deserialize(xmlReader); xmlReader.Close(); stringReader.Close(); the class PSW5 is generated automatically by xsd.exe using an PSW5.xsd file given to me. I have done the same for other classes and it works. Now i get the following error (during runtime) : {"Unable to generate a temporary class (result=1).\r\nerror CS0030: Cannot convert type 'PSW5ns.TAX_INF[]' to 'PSW5ns.TAX_INF'\r\nerror CS0029: Cannot implicitly convert type 'PSW5ns.TAX_INF' to 'PSW5ns.TAX_INF[]'\r\n"} I am confused because it works for other classes the same way. I would appreciate any suggestions. Thanks inadvance, Giorgos

    Read the article

  • Convert XAML to FlowDocument to display in RichTextBox in WPF

    - by Erika
    I have some HTML, which i am converting to XAML using the library provided by Microsoft string t = HtmlToXamlConverter.ConvertHtmlToXaml(mail.HtmlDataString,true); now, from http://stackoverflow.com/questions/1449121/how-to-insert-xaml-into-richtextbox i am using the following: private static FlowDocument SetRTF(string xamlString) { StringReader stringReader = new StringReader(xamlString); System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader); Section sec = XamlReader.Load(xmlReader) as Section; FlowDocument doc = new FlowDocument(); while (sec.Blocks.Count > 0) doc.Blocks.Add(sec.Blocks.FirstBlock); return doc; } This however keeps crashing unfortunately =/ Does anyone have any clue on how to display XAML text in a RichTextBox please?

    Read the article

  • DataGridView error when set DataSource

    - by user264464
    I got an error when run datagridview.DataSource = dataView; dataview is correct. I can see data inside it when I debug program. I got next error "Object reference not set to an instance of an object." Any Ideas? code: this.datagridview = new System.Windows.Forms.DataGridView(); ... DataSet ds = new DataSet(); XmlReaderSettings settings = new XmlReaderSettings(); StringReader stringReader = new StringReader(retString); XmlReader xmlReader = XmlReader.Create(stringReader, settings); ds.ReadXml(xmlReader); DataView dataView = ds.Tables[0].DefaultView; dataView is not null. I am able to view it when debug

    Read the article

  • New TabItem Content ActualHeight crashes Xaml Window

    - by Jack Navarro
    I am able to create new TabItems with Content dynamically to a new window by streaming the Xaml with XamlReader: NewWindow newWindow = new NewWindow(); newWindow.Show(); TabControl myTabCntrol = newWindow.FindName("GBtabControl") as TabControl; StringReader stringReader = new StringReader(XamlGrid); XmlReader xmlReader = XmlReader.Create(stringReader); TabItem myTabItem = new TabItem(); myTabItem.Header = qDealName; myTabItem.Content = (UIElement)XamlReader.Load(xmlReader); myTabCntrol.Items.Add(myTabItem); This works fine. It displays a new grid wrapped in a scrollviewer. The problem is access the TabItem content from the newWindow. TabItem ti = GBtabControl.SelectedItem as TabItem; string scrollvwnm = "scrollViewer" + ti.Header.ToString(); MessageBox.Show(ti.ActualHeight.ToString()); // returns 21.5 ScrollViewer scrlvwr = this.FindName(scrollvwnm) as ScrollViewer; MessageBox.Show(scrollvwnm); // Displays name double checked for accuracy MessageBox.Show(scrlvwr.ActualHeight.ToString()); //Crashes ScrollViewer scrlvwr = ti.FindName(scrollvwnm) as ScrollViewer; MessageBox.Show(scrollvwnm); // Displays name double checked for accuracy MessageBox.Show(scrlvwr.ActualHeight.ToString()); //Also Crashes Is there a method to refresh UI in XAML so the new window is able to access the newly loaded tab item content? Thanks

    Read the article

  • C# XAML get new width and height for Canvas

    - by Jack Navarro
    I have searched through many times but have not seen this before. Probably really simple question but can't wrap my head around it. Wrote a VSTO add-in for Excel that draws a Grid dynamically. Then launches a new window and replaces the contents of the Canvas with the generated Grid. The problem is with printing. When I call the print procedure the canvas.height and canvas.width returned is the old value prior to replacing it with the grid. Sample: string="<Grid Name=\"CanvasGrid\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">..Lots of stuff..</Grid>"; // Launch new window and replace the Canvas element WpfUserControl newWindow = new WpfUserControl(); newWindow.Show(); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 StringReader stringReader = new StringReader(LssAllcChrt); XmlReader xmlReader = XmlReader.Create(stringReader); Canvas myCanvas = newWindow.FindName("GrphCnvs") as Canvas; myCanvas.Children.Clear(); myCanvas.Children.Add((UIElement)XamlReader.Load(xmlReader)); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 but should be much larger the Grid spans all three of my screens Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens //Run code from WpfUserControl.cs after it loads from button click Grid testGrid = canvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens So basically I have no way of telling what my new width and height are Any Ideas

    Read the article

  • XAML get new width and height for Canvas

    - by Jack Navarro
    I have searched through many times but have not seen this before. Probably really simple question but can't wrap my head around it. Wrote a VSTO add-in for Excel that draws a Grid dynamically. Then launches a new window and replaces the contents of the Canvas with the generated Grid. The problem is with printing. When I call the print procedure the canvas.height and canvas.width returned is the old value prior to replacing it with the grid. Sample: string="<Grid Name=\"CanvasGrid\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">..Lots of stuff..</Grid>"; // Launch new window and replace the Canvas element WpfUserControl newWindow = new WpfUserControl(); newWindow.Show(); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 StringReader stringReader = new StringReader(LssAllcChrt); XmlReader xmlReader = XmlReader.Create(stringReader); Canvas myCanvas = newWindow.FindName("GrphCnvs") as Canvas; myCanvas.Children.Clear(); myCanvas.Children.Add((UIElement)XamlReader.Load(xmlReader)); //To test MessageBox.Show(myCanvas.ActualWidth.ToString()); //return 894 but should be much larger the Grid spans all three of my screens Grid testGrid = myCanvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens //Run code from WpfUserControl.cs after it loads from button click Grid testGrid = canvas.FindName("CanvasGrid") as Grid; MessageBox.Show("Grid " + testGrid.ActualWidth.ToString()); //return 234 but should be much larger the Grid spans all three of my screens So basically I have no way of telling what my new width and height are.

    Read the article

  • How to serialize a data of type string without using StringWriter as input

    - by starz26
    I want to serialize a input data of type string, but do not want to use StringWriter and StringReader for for serializing/Deserializing. The reason for this is when a escapse chars are sent as part of the Input string for serializing, it is serialized but some Spl chars are inserted in the xml(eg:"").I'm getting an XMl error while deserializing this serialized data. void M1() { string str = 23 + "AC"+(char)1; StringWriter sw = new StringWriter(); XmlSerializer serializer = new XmlSerializer(typeof(String)); serializer.Serialize(sw, str); System.Console.WriteLine("String encoded to XML = \n{0} \n", sw.ToString()); StringReader sr = new StringReader(sw.ToString()); String s2 = (String)serializer.Deserialize(sr); System.Console.WriteLine("String decoded from XML = \n {0}", s2); }

    Read the article

  • I have a custom type which i want to serialize, this custom type accepts input which might consists

    - by starz26
    I have a custom type which i want to serialize, this custom type accepts input which might consists of escape chars. M1_Serilizer(MyCustomType customTypeObj) {XmlSerializer serializer = new XmlSerializer(typeof(MyCustomType)); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); serializer.Serialize(sw, customTypeObj); string str= sw.ToString(); M2_Deserializer(str); } M2_Deserializer(string str) { XmlSerializer serializer = new XmlSerializer(typeof(MyCustomType)); StringReader sr = new StringReader(str); MyCustomType customTypeObj = (MyCustomType)serializer.Deserialize(sr); } when escape type chars are part of the CustomTypeObj, on deserialization it throws an exception. Q1)How do i overcome this?, Q2)I should use StringReader and StringWriter and not memorystream or other thing ways. StringWriter/reader will only serve my internal functionality Q3)How can these escape chars be handled?

    Read the article

  • "type not defined" exception with WF4 RC

    - by avi1234
    Hi, I`m gettin the following exception while invoking my workflow (dynamically): The following errors were encountered while processing the workflow tree: 'DynamicActivity': The private implementation of activity '1: DynamicActivity' has the following validation error: Compiler error(s) encountered processing expression "TryCast(simplerule_out,OutputBase2)". Type 'OutputBase2' is not defined. 'DynamicActivity': The private implementation of activity '1: DynamicActivity' has the following validation error: Compiler error(s) encountered processing expression "Res". Type 'OutputBase2' is not defined. 'DynamicActivity': The private implementation of activity '1: DynamicActivity' has the following validation error: Compiler error(s) encountered processing expression "Res". Type 'OutputBase2' is not defined. 'DynamicActivity': The private implementation of activity '1: DynamicActivity' has the following validation error: Compiler error(s) encountered processing expression "New List(Of OutputBase2)". Type 'OutputBase2' is not defined. The workflow is very simple and worked fine on VS 2010 beta 2! All I`m trying to do is to create new list of my abstract custom type "OutputBase2". public class OutputBase2 { public OutputBase2() { } public bool Succeeded { get; set; } } class Example { public void Exec() { ActivityBuilder builder = new ActivityBuilder(); builder.Name = "act1"; var res = new DynamicActivityProperty { Name = "Res", Type = typeof(OutArgument<List<OutputBase2>>), Value = new OutArgument<List<OutputBase2>>() }; builder.Properties.Add(res); builder.Implementation = new Sequence(); ((Sequence)builder.Implementation).Activities.Add(new Assign<List<OutputBase2>> { To = new VisualBasicReference<List<OutputBase2>> { ExpressionText = res.Name }, Value = new VisualBasicValue<List<OutputBase2>>("New List(Of OutputBase2)") }); Activity act = getActivity(builder); var res2 = WorkflowInvoker.Invoke(act); } string getXamlStringFromActivityBuilder(ActivityBuilder activityBuilder) { string xamlString; StringBuilder stringBuilder = new StringBuilder(); System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder); System.Xaml.XamlSchemaContext xamlSchemaContext = new System.Xaml.XamlSchemaContext(); System.Xaml.XamlXmlWriter xamlXmlWriter = new System.Xaml.XamlXmlWriter(stringWriter, xamlSchemaContext); System.Xaml.XamlWriter xamlWriter = System.Activities.XamlIntegration.ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter); System.Xaml.XamlServices.Save(xamlWriter, activityBuilder); xamlString = stringBuilder.ToString(); return xamlString; } public Activity getActivity(ActivityBuilder t) { string xamlString = getXamlStringFromActivityBuilder(t); System.IO.StringReader stringReader = new System.IO.StringReader(xamlString); Activity activity = System.Activities.XamlIntegration.ActivityXamlServices.Load(stringReader); return activity; } } Thanks!

    Read the article

  • WPF Reusing Xaml Effectively

    - by Steve
    Hi, I've recently been working on a project using WPF to produce a diagram. In this I must show text alongside symbols that illustrate information associated with the text. To draw the symbols I initially used some png images I had produced. Within my diagram these images appeared blurry and only looked worse when zoomed in on. To improve on this I decided I would use a vector rather than a rastor image format. Below is the method I used to get the rastor image from a file path: protected Image GetSymbolImage(string symbolPath, int symbolHeight) { Image symbol = new Image(); symbol.Height = symbolHeight; BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(symbolPath); bitmapImage.DecodePixelHeight = symbolHeight; bitmapImage.EndInit(); symbol.Source = bitmapImage; return symbol; } Unfortunately this does not recognise vector image formats. So instead I used a method like the following, where "path" is the file path to a vector image of the format .xaml: public static Canvas LoadXamlCanvas(string path) { //if a file exists at the specified path if (File.Exists(path)) { //store the text in the file string text = File.ReadAllText(path); //produce a canvas from the text StringReader stringReader = new StringReader(text); XmlReader xmlReader = XmlReader.Create(stringReader); Canvas c = (Canvas)XamlReader.Load(xmlReader); //return the canvas return c; } return null; } This worked but drastically killed performance when called repeatedly. I found the logic necessary for text to canvas conversion (see above) was the main cause of the performance problem therefore embedding the .xaml images would not alone resolve the performance issue. I tried using this method only on the initial load of my application and storing the resulting canvases in a dictionary that could later be accessed much quicker but I later realised when using the canvases within the dictionary I would have to make copies of them. All the logic I found online associated with making copies used a XamlWriter and XamlReader which would again just introduce a performance problem. The solution I used was to copy the contents of each .xaml image into its own user control and then make use of these user controls where appropriate. This means I now display vector graphics and performance is much better. However this solution to me seems pretty clumsy. I'm new to WPF and wonder if there is some built in way of storing and reusing xaml throughout an application? Apologies for the length of this question. I thought having a record of my attempts might help someone with any similar problem. Thanks.

    Read the article

  • How do you deserialize a collection with child collections?

    - by Stuart Helwig
    I have a collection of custom entity objects one property of which is an ArrayList of byte arrays. The custom entity is serializable and the collection property is marked with the following attributes: [XmlArray("Images"), XmlArrayItem("Image",typeof(byte[]))] So I serialize a collection of these custom entities and pass them to a web service, as a string. The web service receives the string and byte array in tact, The following code then attempts to deserialize the collection - back into custom entities for processing... XmlSerializer ser = new XmlSerializer(typeof(List<myCustomEntity>)); StringReader reader = new StringReader(xmlStringPassedToWS); List<myCustomEntity> entities = (List<myCustomEntity>)ser.Deserialize(reader); foreach (myCustomEntity e in entities) { // ...do some stuff... foreach (myChildCollection c in entities.ChildCollection { // .. do some more stuff.... } } I've checked the XML resulting from the initial serialization and it does contain byte array - the child collection, as does the StringReader built above. After the deserialization process, the resulting collection of custom entites is fine, except that each object in the collection does not contain any items in its child collection. (i.e. it doesn't get to "...do some more stuff..." above. Can someone please explain what I am doing wrong? Is it possible to serialize ArrayLists within a generic collection of custom entities?

    Read the article

  • Embedding swank-clojure in java program

    - by user237417
    Based on the Embedding section of http://github.com/technomancy/swank-clojure, I'm using the following to test it out. Is there a better way to do this that doesn't use Compiler? Is there a way to programmatically stop swank? It seems start-repl takes control of the thread. What would be a good way to spawn off another thread for it and be able to kill that thread programatically. import clojure.lang.Compiler; import java.io.StringReader; public class Embed { public static void main(String[] args) throws Exception { final String startSwankScript = "(ns my-app\n" + " (:use [swank.swank :as swank]))\n" + "(swank/start-repl) "; Compiler.load(new StringReader(startSwankScript)); } } Any help much appreciated, hhh

    Read the article

  • How to force javax xslt transformer to encode entities in utf-8?

    - by calavera.info
    I'm working on filter that should transform an output with some stylesheet. Important sections of code looks like this: PrintWriter out = response.getWriter(); ... StringReader sr = new StringReader(content); Source xmlSource = new StreamSource(sr, requestSystemId); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setParameter("encoding", "UTF-8"); //same result when using ByteArrayOutputStream xo = new java.io.ByteArrayOutputStream(); StringWriter xo = new StringWriter(); StreamResult result = new StreamResult(xo); transformer.transform(xmlSource, result); out.write(xo.toString()); The problem is that national characters are encoded as html entities and not by using UTF. Is there any way to force transformer to use UTF-8 instead of entities?

    Read the article

  • IsAuthenticated is false! weird behaviour + review question

    - by Naor
    This is the login function (after I validate user name and password, I load user data into "user" variable and call Login function: public static void Login(IUser user) { HttpResponse Response = HttpContext.Current.Response; HttpRequest Request = HttpContext.Current.Request; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserId.ToString(), DateTime.Now, DateTime.Now.AddHours(12), false, UserResolver.Serialize(user)); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); cookie.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(cookie); string redirectUrl = user.HomePage; Response.Redirect(redirectUrl, true); } UserResolver is the following class: public class UserResolver { public static IUser Current { get { IUser user = null; if (HttpContext.Current.User.Identity.IsAuthenticated) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; user = Desrialize(ticket.UserData); } return user; } } public static string Serialize(IUser user) { StringBuilder data = new StringBuilder(); StringWriter w = new StringWriter(data); string type = user.GetType().ToString(); //w.Write(type.Length); w.WriteLine(user.GetType().ToString()); StringBuilder userData = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(user.GetType()); serializer.Serialize(new StringWriter(userData), user); w.Write(userData.ToString()); w.Close(); return data.ToString(); } public static IUser Desrialize(string data) { StringReader r = new StringReader(data); string typeStr = r.ReadLine(); Type type=Type.GetType(typeStr); string userData = r.ReadToEnd(); XmlSerializer serializer = new XmlSerializer(type); return (IUser)serializer.Deserialize(new StringReader(userData)); } } And the global.asax implements the following: void Application_PostAuthenticateRequest(Object sender, EventArgs e) { IPrincipal p = HttpContext.Current.User; if (p.Identity.IsAuthenticated) { IUser user = UserResolver.Current; Role[] roles = user.GetUserRoles(); HttpContext.Current.User = Thread.CurrentPrincipal = new GenericPrincipal(p.Identity, Role.ToString(roles)); } } First question: Am I do it right? Second question - weird thing! The user variable I pass to Login has 4 members: UserName, Password, Name, Id. When UserResolver.Current executed, I got the user instance. I descided to change the user structure - I add an array of Warehouse object. Since that time, when UserResolver.Current executed (after Login), HttpContext.Current.User.Identity.IsAuthenticated was false and I couldn't get the user data. When I removed the Warehouse[] from user structure, it starts to be ok again and HttpContext.Current.User.Identity.IsAuthenticated become true after I Login. What is the reason to this weird behaviour?

    Read the article

  • Difference in DocumentBuilder.parse when using JRE 1.5 and JDK 1.6

    - by dhiller
    Recently at last we have switched our projects to Java 1.6. When executing the tests I found out that using 1.6 a SAXParseException is not thrown which has been thrown using 1.5. Below is my test code to demonstrate the problem. import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import org.junit.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; /** * Test class to demonstrate the difference between JDK 1.5 to JDK 1.6. * * Seen on Linux: * * <pre> * #java version "1.6.0_18" * Java(TM) SE Runtime Environment (build 1.6.0_18-b07) * Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode) * </pre> * * Seen on OSX: * * <pre> * java version "1.6.0_17" * Java(TM) SE Runtime Environment (build 1.6.0_17-b04-248-10M3025) * Java HotSpot(TM) 64-Bit Server VM (build 14.3-b01-101, mixed mode) * </pre> * * @author dhiller (creator) * @author $Author$ (last editor) * @version $Revision$ * @since 12.03.2010 11:32:31 */ public class TestXMLValidation { /** * Tests the schema validation of an XML against a simple schema. * * @throws Exception * Falls ein Fehler auftritt * @throws junit.framework.AssertionFailedError * Falls eine Unit-Test-Pruefung fehlschlaegt */ @Test(expected = SAXParseException.class) public void testValidate() throws Exception { final StreamSource schema = new StreamSource( new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" " + "elementFormDefault=\"qualified\" xmlns:xsd=\"undefined\">" + "<xs:element name=\"Test\"/>" + "</xs:schema>" ) ); final String xml = "<Test42/>"; final DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance(); newFactory.setSchema( SchemaFactory.newInstance( "http://www.w3.org/2001/XMLSchema" ).newSchema( schema ) ); final DocumentBuilder documentBuilder = newFactory.newDocumentBuilder(); documentBuilder.parse( new InputSource( new StringReader( xml ) ) ); } } When using a JVM 1.5 the test passes, on 1.6 it fails with "Expected exception SAXParseException". The Javadoc of the DocumentBuilderFactory.setSchema(Schema) Method says: When errors are found by the validator, the parser is responsible to report them to the user-specified ErrorHandler (or if the error handler is not set, ignore them or throw them), just like any other errors found by the parser itself. In other words, if the user-specified ErrorHandler is set, it must receive those errors, and if not, they must be treated according to the implementation specific default error handling rules. The Javadoc of the DocumentBuilder.parse(InputSource) method says: BTW: I tried setting an error handler via setErrorHandler, but there still is no exception. Now my question: What has changed to 1.6 that prevents the schema validation to throw a SAXParseException? Is it related to the schema or to the xml that I tried to parse?

    Read the article

  • The correct point in time to read an ASP .NET 1.1 control property in order to change page output

    - by RossMan
    Using ASP .NET 1.1 with CMS 2002 and C#. Trying to read the contents of a CMS HTML placeholder control into a string reader object so certain logic can be performed and the page output modified before it is displayed: StringReader srHtml = new StringReader(this.HtmlPlaceholderControl1.Html); The problem is that the Html property is empty during Page_Load, I've tried in a PreRender overload as well, but the property is still empty. The HtmlPlaceholder control does render html when the page load has completed. Which event should be handled in order to read the propery of the web control?

    Read the article

  • Java Cloud Service Integration to REST Service

    - by Jani Rautiainen
    Service (JCS) provides a platform to develop and deploy business applications in the cloud. In Fusion Applications Cloud deployments customers do not have the option to deploy custom applications developed with JDeveloper to ensure the integrity and supportability of the hosted application service. Instead the custom applications can be deployed to the JCS and integrated to the Fusion Application Cloud instance. This series of articles will go through the features of JCS, provide end-to-end examples on how to develop and deploy applications on JCS and how to integrate them with the Fusion Applications instance. In this article a custom application integrating with REST service will be implemented. We will use REST services provided by Taleo as an example; however the same approach will work with any REST service. In this example the data from the REST service is used to populate a dynamic table. Pre-requisites Access to Cloud instance In order to deploy the application access to a JCS instance is needed, a free trial JCS instance can be obtained from Oracle Cloud site. To register you will need a credit card even if the credit card will not be charged. To register simply click "Try it" and choose the "Java" option. The confirmation email will contain the connection details. See this video for example of the registration.Once the request is processed you will be assigned 2 service instances; Java and Database. Applications deployed to the JCS must use Oracle Database Cloud Service as their underlying database. So when JCS instance is created a database instance is associated with it using a JDBC data source.The cloud services can be monitored and managed through the web UI. For details refer to Getting Started with Oracle Cloud. JDeveloper JDeveloper contains Cloud specific features related to e.g. connection and deployment. To use these features download the JDeveloper from JDeveloper download site by clicking the "Download JDeveloper 11.1.1.7.1 for ADF deployment on Oracle Cloud" link, this version of JDeveloper will have the JCS integration features that will be used in this article. For versions that do not include the Cloud integration features the Oracle Java Cloud Service SDK or the JCS Java Console can be used for deployment. For details on installing and configuring the JDeveloper refer to the installation guideFor details on SDK refer to Using the Command-Line Interface to Monitor Oracle Java Cloud Service and Using the Command-Line Interface to Manage Oracle Java Cloud Service. Access to a local database The database associated with the JCS instance cannot be connected to with JDBC.  Since creating ADFbc business component requires a JDBC connection we will need access to a local database. 3rd party libraries This example will use some 3rd party libraries for implementing the REST service call and processing the input / output content. Other libraries may also be used, however these are tested to work. Jersey 1.x Jersey library will be used as a client to make the call to the REST service. JCS documentation for supported specifications states: Java API for RESTful Web Services (JAX-RS) 1.1 So Jersey 1.x will be used. Download the single-JAR Jersey bundle; in this example Jersey 1.18 JAR bundle is used. Json-simple Jjson-simple library will be used to process the json objects. Download the  JAR file; in this example json-simple-1.1.1.jar is used. Accessing data in Taleo Before implementing the application it is beneficial to familiarize oneself with the data in Taleo. Easiest way to do this is by using a RESTClient on your browser. Once added to the browser you can access the UI: The client can be used to call the REST services to test the URLs and data before adding them into the application. First derive the base URL for the service this can be done with: Method: GET URL: https://tbe.taleo.net/MANAGER/dispatcher/api/v1/serviceUrl/<company name> The response will contain the base URL to be used for the service calls for the company. Next obtain authentication token with: Method: POST URL: https://ch.tbe.taleo.net/CH07/ats/api/v1/login?orgCode=<company>&userName=<user name>&password=<password> The response includes an authentication token that can be used for few hours to authenticate with the service: {   "response": {     "authToken": "webapi26419680747505890557"   },   "status": {     "detail": {},     "success": true   } } To authenticate the service calls navigate to "Headers -> Custom Header": And add a new request header with: Name: Cookie Value: authToken=webapi26419680747505890557 Once authentication token is defined the tool can be used to invoke REST services; for example: Method: GET URL: https://ch.tbe.taleo.net/CH07/ats/api/v1/object/candidate/search.xml?status=16 This data will be used on the application to be created. For details on the Taleo REST services refer to the Taleo Business Edition REST API Guide. Create Application First Fusion Web Application is created and configured. Start JDeveloper and click "New Application": Application Name: JcsRestDemo Application Package Prefix: oracle.apps.jcs.test Application Template: Fusion Web Application (ADF) Configure Local Cloud Connection Follow the steps documented in the "Java Cloud Service ADF Web Application" article to configure a local database connection needed to create the ADFbc objects. Configure Libraries Add the 3rd party libraries into the class path. Create the following directory and copy the jar files into it: <JDEV_USER_HOME>/JcsRestDemo/lib  Select the "Model" project, navigate "Application -> Project Properties -> Libraries and Classpath -> Add JAR / Directory" and add the 2 3rd party libraries: Accessing Data from Taleo To access data from Taleo using the REST service the 3rd party libraries will be used. 2 Java classes are implemented, one representing the Candidate object and another for accessing the Taleo repository Candidate Candidate object is a POJO object used to represent the candidate data obtained from the Taleo repository. The data obtained will be used to populate the ADFbc object used to display the data on the UI. The candidate object contains simply the variables we obtain using the REST services and the getters / setters for them: Navigate "New -> General -> Java -> Java Class", enter "Candidate" as the name and create it in the package "oracle.apps.jcs.test.model".  Copy / paste the following as the content: import oracle.jbo.domain.Number; public class Candidate { private Number candId; private String firstName; private String lastName; public Candidate() { super(); } public Candidate(Number candId, String firstName, String lastName) { super(); this.candId = candId; this.firstName = firstName; this.lastName = lastName; } public void setCandId(Number candId) { this.candId = candId; } public Number getCandId() { return candId; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } } Taleo Repository Taleo repository class will interact with the Taleo REST services. The logic will query data from Taleo and populate Candidate objects with the data. The Candidate object will then be used to populate the ADFbc object used to display data on the UI. Navigate "New -> General -> Java -> Java Class", enter "TaleoRepository" as the name and create it in the package "oracle.apps.jcs.test.model".  Copy / paste the following as the content (for details of the implementation refer to the documentation in the code): import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import oracle.jbo.domain.Number; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * This class interacts with the Taleo REST services */ public class TaleoRepository { /** * Connection information needed to access the Taleo services */ String _company = null; String _userName = null; String _password = null; /** * Jersey client used to access the REST services */ Client _client = null; /** * Parser for processing the JSON objects used as * input / output for the services */ JSONParser _parser = null; /** * The base url for constructing the REST URLs. This is obtained * from Taleo with a service call */ String _baseUrl = null; /** * Authentication token obtained from Taleo using a service call. * The token can be used to authenticate on subsequent * service calls. The token will expire in 4 hours */ String _authToken = null; /** * Static url that can be used to obtain the url used to construct * service calls for a given company */ private static String _taleoUrl = "https://tbe.taleo.net/MANAGER/dispatcher/api/v1/serviceUrl/"; /** * Default constructor for the repository * Authentication details are passed as parameters and used to generate * authentication token. Note that each service call will * generate its own token. This is done to avoid dealing with the expiry * of the token. Also only 20 tokens are allowed per user simultaneously. * So instead for each call there is login / logout. * * @param company the company for which the service calls are made * @param userName the user name to authenticate with * @param password the password to authenticate with. */ public TaleoRepository(String company, String userName, String password) { super(); _company = company; _userName = userName; _password = password; _client = Client.create(); _parser = new JSONParser(); _baseUrl = getBaseUrl(); } /** * This obtains the base url for a company to be used * to construct the urls for service calls * @return base url for the service calls */ private String getBaseUrl() { String result = null; if (null != _baseUrl) { result = _baseUrl; } else { try { String company = _company; WebResource resource = _client.resource(_taleoUrl + company); ClientResponse response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class); String entity = response.getEntity(String.class); JSONObject jsonObject = (JSONObject)_parser.parse(new StringReader(entity)); JSONObject jsonResponse = (JSONObject)jsonObject.get("response"); result = (String)jsonResponse.get("URL"); } catch (Exception ex) { ex.printStackTrace(); } } return result; } /** * Generates authentication token, that can be used to authenticate on * subsequent service calls. Note that each service call will * generate its own token. This is done to avoid dealing with the expiry * of the token. Also only 20 tokens are allowed per user simultaneously. * So instead for each call there is login / logout. * @return authentication token that can be used to authenticate on * subsequent service calls */ private String login() { String result = null; try { MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("orgCode", _company); formData.add("userName", _userName); formData.add("password", _password); WebResource resource = _client.resource(_baseUrl + "login"); ClientResponse response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); String entity = response.getEntity(String.class); JSONObject jsonObject = (JSONObject)_parser.parse(new StringReader(entity)); JSONObject jsonResponse = (JSONObject)jsonObject.get("response"); result = (String)jsonResponse.get("authToken"); } catch (Exception ex) { throw new RuntimeException("Unable to login ", ex); } if (null == result) throw new RuntimeException("Unable to login "); return result; } /** * Releases a authentication token. Each call to login must be followed * by call to logout after the processing is done. This is required as * the tokens are limited to 20 per user and if not released the tokens * will only expire after 4 hours. * @param authToken */ private void logout(String authToken) { WebResource resource = _client.resource(_baseUrl + "logout"); resource.header("cookie", "authToken=" + authToken).post(ClientResponse.class); } /** * This method is used to obtain a list of candidates using a REST * service call. At this example the query is hard coded to query * based on status. The url constructed to access the service is: * <_baseUrl>/object/candidate/search.xml?status=16 * @return List of candidates obtained with the service call */ public List<Candidate> getCandidates() { List<Candidate> result = new ArrayList<Candidate>(); try { // First login, note that in finally block we must have logout _authToken = "authToken=" + login(); /** * Construct the URL, the resulting url will be: * <_baseUrl>/object/candidate/search.xml?status=16 */ MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("status", "16"); JSONArray searchResults = (JSONArray)getTaleoResource("object/candidate/search", "searchResults", formData); /** * Process the results, the resulting JSON object is something like * this (simplified for readability): * * { * "response": * { * "searchResults": * [ * { * "candidate": * { * "candId": 211, * "firstName": "Mary", * "lastName": "Stochi", * logic here will find the candidate object(s), obtain the desired * data from them, construct a Candidate object based on the data * and add it to the results. */ for (Object object : searchResults) { JSONObject temp = (JSONObject)object; JSONObject candidate = (JSONObject)findObject(temp, "candidate"); Long candIdTemp = (Long)candidate.get("candId"); Number candId = (null == candIdTemp ? null : new Number(candIdTemp)); String firstName = (String)candidate.get("firstName"); String lastName = (String)candidate.get("lastName"); result.add(new Candidate(candId, firstName, lastName)); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (null != _authToken) logout(_authToken); } return result; } /** * Convenience method to construct url for the service call, invoke the * service and obtain a resource from the response * @param path the path for the service to be invoked. This is combined * with the base url to construct a url for the service * @param resource the key for the object in the response that will be * obtained * @param parameters any parameters used for the service call. The call * is slightly different depending whether parameters exist or not. * @return the resource from the response for the service call */ private Object getTaleoResource(String path, String resource, MultivaluedMap<String, String> parameters) { Object result = null; try { WebResource webResource = _client.resource(_baseUrl + path); ClientResponse response = null; if (null == parameters) response = webResource.header("cookie", _authToken).get(ClientResponse.class); else response = webResource.queryParams(parameters).header("cookie", _authToken).get(ClientResponse.class); String entity = response.getEntity(String.class); JSONObject jsonObject = (JSONObject)_parser.parse(new StringReader(entity)); result = findObject(jsonObject, resource); } catch (Exception ex) { ex.printStackTrace(); } return result; } /** * Convenience method to recursively find a object with an key * traversing down from a given root object. This will traverse a * JSONObject / JSONArray recursively to find a matching key, if found * the object with the key is returned. * @param root root object which contains the key searched for * @param key the key for the object to search for * @return the object matching the key */ private Object findObject(Object root, String key) { Object result = null; if (root instanceof JSONObject) { JSONObject rootJSON = (JSONObject)root; if (rootJSON.containsKey(key)) { result = rootJSON.get(key); } else { Iterator children = rootJSON.entrySet().iterator(); while (children.hasNext()) { Map.Entry entry = (Map.Entry)children.next(); Object child = entry.getValue(); if (child instanceof JSONObject || child instanceof JSONArray) { result = findObject(child, key); if (null != result) break; } } } } else if (root instanceof JSONArray) { JSONArray rootJSON = (JSONArray)root; for (Object child : rootJSON) { if (child instanceof JSONObject || child instanceof JSONArray) { result = findObject(child, key); if (null != result) break; } } } return result; } }   Creating Business Objects While JCS application can be created without a local database, the local database is required when using ADFbc objects even if database objects are not referred. For this example we will create a "Transient" view object that will be programmatically populated based the data obtained from Taleo REST services. Creating ADFbc objects Choose the "Model" project and navigate "New -> Business Tier : ADF Business Components : View Object". On the "Initialize Business Components Project" choose the local database connection created in previous step. On Step 1 enter "JcsRestDemoVO" on the "Name" and choose "Rows populated programmatically, not based on query": On step 2 create the following attributes: CandId Type: Number Updatable: Always Key Attribute: checked Name Type: String Updatable: Always On steps 3 and 4 accept defaults and click "Next".  On step 5 check the "Application Module" checkbox and enter "JcsRestDemoAM" as the name: Click "Finish" to generate the objects. Populating the VO To display the data on the UI the "transient VO" is populated programmatically based on the data obtained from the Taleo REST services. Open the "JcsRestDemoVOImpl.java". Copy / paste the following as the content (for details of the implementation refer to the documentation in the code): import java.sql.ResultSet; import java.util.List; import java.util.ListIterator; import oracle.jbo.server.ViewObjectImpl; import oracle.jbo.server.ViewRowImpl; import oracle.jbo.server.ViewRowSetImpl; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Tue Feb 18 09:40:25 PST 2014 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class JcsRestDemoVOImpl extends ViewObjectImpl { /** * This is the default constructor (do not remove). */ public JcsRestDemoVOImpl() { } @Override public void executeQuery() { /** * For some reason we need to reset everything, otherwise * 2nd entry to the UI screen may fail with * "java.util.NoSuchElementException" in createRowFromResultSet * call to "candidates.next()". I am not sure why this is happening * as the Iterator is new and "hasNext" is true at the point * of the execution. My theory is that since the iterator object is * exactly the same the VO cache somehow reuses the iterator including * the pointer that has already exhausted the iterable elements on the * previous run. Working around the issue * here by cleaning out everything on the VO every time before query * is executed on the VO. */ getViewDef().setQuery(null); getViewDef().setSelectClause(null); setQuery(null); this.reset(); this.clearCache(); super.executeQuery(); } /** * executeQueryForCollection - overridden for custom java data source support. */ protected void executeQueryForCollection(Object qc, Object[] params, int noUserParams) { /** * Integrate with the Taleo REST services using TaleoRepository class. * A list of candidates matching a hard coded query is obtained. */ TaleoRepository repository = new TaleoRepository(<company>, <username>, <password>); List<Candidate> candidates = repository.getCandidates(); /** * Store iterator for the candidates as user data on the collection. * This will be used in createRowFromResultSet to create rows based on * the custom iterator. */ ListIterator<Candidate> candidatescIterator = candidates.listIterator(); setUserDataForCollection(qc, candidatescIterator); super.executeQueryForCollection(qc, params, noUserParams); } /** * hasNextForCollection - overridden for custom java data source support. */ protected boolean hasNextForCollection(Object qc) { boolean result = false; /** * Determines whether there are candidates for which to create a row */ ListIterator<Candidate> candidates = (ListIterator<Candidate>)getUserDataForCollection(qc); result = candidates.hasNext(); /** * If all candidates to be created indicate that processing is done */ if (!result) { setFetchCompleteForCollection(qc, true); } return result; } /** * createRowFromResultSet - overridden for custom java data source support. */ protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet resultSet) { /** * Obtain the next candidate from the collection and create a row * for it. */ ListIterator<Candidate> candidates = (ListIterator<Candidate>)getUserDataForCollection(qc); ViewRowImpl row = createNewRowForCollection(qc); try { Candidate candidate = candidates.next(); row.setAttribute("CandId", candidate.getCandId()); row.setAttribute("Name", candidate.getFirstName() + " " + candidate.getLastName()); } catch (Exception e) { e.printStackTrace(); } return row; } /** * getQueryHitCount - overridden for custom java data source support. */ public long getQueryHitCount(ViewRowSetImpl viewRowSet) { /** * For this example this is not implemented rather we always return 0. */ return 0; } } Creating UI Choose the "ViewController" project and navigate "New -> Web Tier : JSF : JSF Page". On the "Create JSF Page" enter "JcsRestDemo" as name and ensure that the "Create as XML document (*.jspx)" is checked.  Open "JcsRestDemo.jspx" and navigate to "Data Controls -> JcsRestDemoAMDataControl -> JcsRestDemoVO1" and drag & drop the VO to the "<af:form> " as a "ADF Read-only Table": Accept the defaults in "Edit Table Columns". To execute the query navigate to to "Data Controls -> JcsRestDemoAMDataControl -> JcsRestDemoVO1 -> Operations -> Execute" and drag & drop the operation to the "<af:form> " as a "Button": Deploying to JCS Follow the same steps as documented in previous article"Java Cloud Service ADF Web Application". Once deployed the application can be accessed with URL: https://java-[identity domain].java.[data center].oraclecloudapps.com/JcsRestDemo-ViewController-context-root/faces/JcsRestDemo.jspx The UI displays a list of candidates obtained from the Taleo REST Services: Summary In this article we learned how to integrate with REST services using Jersey library in JCS. In future articles various other integration techniques will be covered.

    Read the article

  • PHP/Java bridge problem

    - by Jack
    I am using tomcat 6 on windows. Here is the code I am testing. import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.StringReader; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /** * Create and run THREAD_COUNT PHP threads, concurrently accessing a * shared resource. * * Create 5 script engines, passing each a shared resource allocated * from Java. Each script engine has to implement Runnable. * * Java accesses the Runnable script engine using * scriptEngine.getInterface() and calls thread.start() to invoke each * PHP Runnable implementations concurrently. */ class PhpThreads { public static final String runnable = new String("<?php\n" + "function run() {\n" + " $out = java_context()->getAttribute('sharedResource', 100);\n" + " $nr = (string)java_context()->getAttribute('nr', 100);\n" + " echo \"started thread: $nr\n\";\n" + " for($i=0; $i<100; $i++) {\n" + " $out->write(ord($nr));\n" + " java('java.lang.Thread')->sleep(1);\n" + " }\n" + "}\n" + "?>\n"); static final int THREAD_COUNT = 5; public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); Thread threads[] = new Thread[THREAD_COUNT]; ScriptEngine engines[] = new ScriptEngine[THREAD_COUNT]; ByteArrayOutputStream sharedResource = new ByteArrayOutputStream(); StringReader runnableReader = new StringReader(runnable); // create THREAD_COUNT PHP threads for (int i=0; i<THREAD_COUNT; i++) { engines[i] = manager.getEngineByName("php-invocable"); if (engines[i] == null) throw new NullPointerException ("php script engine not found"); engines[i].put("nr", new Integer(i+1)); engines[i].put("sharedResource", sharedResource); engines[i].eval(runnableReader); runnableReader.reset(); // cast the whole script to Runnable; note also getInterface(specificClosure, type) Runnable r = (Runnable) ((Invocable)engines[i]).getInterface(Runnable.class); threads[i] = new Thread(r); } // run the THREAD_COUNT PHP threads for (int i=0; i<THREAD_COUNT; i++) { threads[i].start(); } // wait for the THREAD_COUNT PHP threads to finish for (int i=0; i<THREAD_COUNT; i++) { threads[i].join(); ((Closeable)engines[i]).close(); } // print the output generated by the THREAD_COUNT concurrent threads String result = sharedResource.toString(); System.out.println(result); // Check result Object res=manager.getEngineByName("php").eval( "<?php " + "exit((int)('10011002100310041005'!=" + "@system(\"echo -n "+result+"|sed 's/./&\\\n/g'|sort|uniq -c|tr -d ' \\\n'\")));" + "?>"); System.exit(((Number)res).intValue()); } } I have added all the libraries. When I run the file I get the following error - run: Exception in thread "main" javax.script.ScriptException: java.io.IOException: Cannot run program "php-cgi": CreateProcess error=2, The system cannot find the file specified at php.java.script.InvocablePhpScriptEngine.eval(InvocablePhpScriptEngine.java:209) at php.java.script.SimplePhpScriptEngine.eval(SimplePhpScriptEngine.java:178) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:232) at PhpThreads.main(NewClass.java:53) Caused by: java.io.IOException: Cannot run program "php-cgi": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start(ProcessBuilder.java:459) at java.lang.Runtime.exec(Runtime.java:593) at php.java.bridge.Util$Process.start(Util.java:1064) at php.java.bridge.Util$ProcessWithErrorHandler.start(Util.java:1166) at php.java.bridge.Util$ProcessWithErrorHandler.start(Util.java:1217) at php.java.script.CGIRunner.doRun(CGIRunner.java:126) at php.java.script.HttpProxy.doRun(HttpProxy.java:63) at php.java.script.CGIRunner.run(CGIRunner.java:111) at php.java.bridge.ThreadPool$Delegate.run(ThreadPool.java:60) Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.<init>(ProcessImpl.java:81) at java.lang.ProcessImpl.start(ProcessImpl.java:30) at java.lang.ProcessBuilder.start(ProcessBuilder.java:452) ... 8 more What am I missing?

    Read the article

  • ASP.NET/C# - Deserialize XML, XSD.exe created multiple classes

    - by Barryman9000
    I'm trying to deserialize some XML (returned from a web service) into an object that I created using XSD.exe. The XSD executable created a .CS file with a different partial class for each parent node in the XML. For Example, the beginning of the XML looks like this (why can't I post xml here? sorry, this is ugly): <disclaimer><notificationDescription>Additional charges will apply.</notificationDescription></disclaimer><quote><masterQuote></masterQuote></quote> And the Class generated by the XSD.exe has a partial class named disclaimer with a get; set; string for notificationDescription. And another partial class for quoteMasterQuote with the corresponding child nodes as public strings. How can I deserialize this XML file into multiple classes? I found this code, but it seems like it'll only work for one object. public static PricingResponse2 DeSerialize(string _xml) { PricingResponse2 _resp = new PricingResponse2(); StringReader _strReader = new StringReader(_xml); XmlSerializer _serializer = new XmlSerializer(_resp.GetType()); XmlReader _xmlReader = new XmlTextReader(_strReader); try { _resp = (PricingResponse2)_serializer.Deserialize(_xmlReader); return _resp; } catch (Exception ex) { string _error = ex.Message; throw; } finally { _xmlReader.Close(); _strReader.Close(); _strReader.Dispose(); } } This is the first time I've tried this, so I'm a little lost.

    Read the article

  • Render User Controls and call their Page_Load

    - by David Murdoch
    The following code will not work because the controls (page1, page2, page3) require that their "Page_Load" event gets called. using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using iTextSharp.text; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; public partial class utilities_getPDF : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // add user controls to the page AddContentControl("controls/page1"); AddContentControl("controls/page2"); AddContentControl("controls/page3"); // set up the response to download the rendered PDF... Response.ContentType = "application/pdf"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AddHeader("Content-Disposition", "attachment;filename=FileName.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); // get the rendered HTML of the page System.IO.StringWriter stringWrite = new StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); this.Render(htmlWrite); StringReader reader = new StringReader(stringWrite.ToString()); // write the PDF to the OutputStream... Document doc = new Document(PageSize.A4); HTMLWorker parser = new HTMLWorker(doc); PdfWriter.GetInstance(doc, Response.OutputStream); doc.Open(); parser.Parse(reader); doc.Close(); } // the parts are probably irrelevant to the question... private const string contentPage = "~/includes/{0}.ascx"; private void AddContentControl(string page) { content.Controls.Add(myLoadControl(page)); } private Control myLoadControl(string page) { return TemplateControl.LoadControl(string.Format(contentPage, page)); } } So my question is: How can I get the controls HTML?

    Read the article

  • C# .net Deserialization I get an exception.

    - by starz26
    namespace N1 { public class InputEntry { //FieldName is a class tht is generated from an XSD which has complex type Name and value private FieldName[] name; public FieldName[] Name { get { return this.Name; } set { this.Name = value; } } } public class B { public void Method1() { InputEntry inputEntry = new InputEntry(); inputEntry.Name = "abc"; } private void Method2(InputEntry inputEntry) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(InputEntry)); System.IO.StringWriter inputStr = new System.IO.StringWriter(CultureInfo.InvariantCulture); serializer.Serialize(inputStr, inputEntry); string ipEntry = inputStr.ToString(); Method3(ipEntry); } private void Method3(string ipEntry) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(InputEntry)); System.IO.StringReader inputStr = new System.IO.StringReader(ipEntry); InputEntry inputEntry = (InputEntry)serializer.Deserialize(inputStr); } } } I get an exception when deserialising the follwing data(when a client configues data as <FieldName>PRINTLINE00</FieldName> <FieldValue>DENIAL STATE</FieldValue> ) Exception is: Message: There is an error in XML document (6, 22). String: <?xml version="1.0" encoding="utf-16"?> <InputEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Fields> <Field> <FieldName>PRINTLINE00</FieldName> <FieldValue>&#x1B;DENIAL STATE 217</FieldValue> </Field> </InputEntry>

    Read the article

  • Using XmlSerializer deserialize complex type elements are null

    - by Jean Bastos
    I have the following schema: <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tipos="http://www.ginfes.com.br/tipos_v03.xsd" targetNamespace="http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_resposta_v03.xsd" xmlns="http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_resposta_v03.xsd" attributeFormDefault="unqualified" elementFormDefault="qualified"> <xsd:import schemaLocation="tipos_v03.xsd" namespace="http://www.ginfes.com.br/tipos_v03.xsd" /> <xsd:element name="ConsultarSituacaoLoteRpsResposta"> <xsd:complexType> <xsd:choice> <xsd:sequence> <xsd:element name="NumeroLote" type="tipos:tsNumeroLote" minOccurs="1" maxOccurs="1"/> <xsd:element name="Situacao" type="tipos:tsSituacaoLoteRps" minOccurs="1" maxOccurs="1"/> </xsd:sequence> <xsd:element ref="tipos:ListaMensagemRetorno" minOccurs="1" maxOccurs="1"/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> and the following class: [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_envio_v03.xsd")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_envio_v03.xsd", IsNullable = false)] public partial class ConsultarSituacaoLoteRpsEnvio { [System.Xml.Serialization.XmlElementAttribute(Order = 0)] public tcIdentificacaoPrestador Prestador { get; set; } [System.Xml.Serialization.XmlElementAttribute(Order = 1)] public string Protocolo { get; set; } } Use the following code to deserialize the object: XmlSerializer respSerializer = new XmlSerializer(typeof(ConsultarSituacaoLoteRpsResposta)); StringReader reader = new StringReader(resp); ConsultarSituacaoLoteRpsResposta respModel = (ConsultarSituacaoLoteRpsResposta)respSerializer.Deserialize(reader); does not occur any error but the properties of objects are null, anyone know what is happening?

    Read the article

  • Very interesting problem in Compact Framework

    - by Alexander
    Hi, i have a performance problem while inserting data to sqlce.I'm reading string and making inserts to My tables.In LU_MAM table,i insert 1000 records withing 8 seconds.After Mam tables i make some inserts but my largest table is CR_MUS.When i want to insert record into CR_MUS,it takes too much time.CR_MUS has 2000 records and insert takes 35 seconds.What can be reason?I use same logic in my insert functions.Do u have any idea?I use VS 2008 sp1. Dim reader As StringReader reader = New StringReader(data) cn = New SqlCeConnection(General.ConnString) cn.Open() If myTransfer.ClearTables(cn, cmd) = True Then progress = 0 '------------------------------------------ cmd = New SqlServerCe.SqlCeCommand Dim rs As SqlCeResultSet cmd.Connection = cn cmd.CommandType = CommandType.TableDirect Dim rec As SqlCeUpdatableRecord ' name of table While reader.Peek > -1 If strerr_col = "" Then satir = reader.ReadLine() ayrac = Split(satir, "|") If ayrac(0).ToString() = "LC" Then prgsbar.Maximum = Convert.ToInt32(ayrac(1)) ElseIf ayrac(0).ToString = "PPAR" Then . If ayrac(2).ToString <> General.PMVer Then ShowWaitCursor(False) txtDurum.Text = "Wrong Version" Exit Sub End If If p_POCKET_PARAMETERS = True Then cmd.CommandText = "POCKET_PARAMETERS" txtDurum.Text = "POCKET_PARAMETERS" rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable) rec = rs.CreateRecord() p_POCKET_PARAMETERS = False End If strerr_col = myVERI_AL.POCKET_PARAMETERS_I(ayrac, cmd, rs, rec) prgsbar.Value += 1 ElseIf ayrac(0).ToString() = "MAM" Then If p_LU_MAM = True Then txtDurum.Text = "LU_MAM " cmd.CommandText = "LU_MAM" rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable) rec = rs.CreateRecord() p_LU_MAM = False End If strerr_col = myVERI_AL.LU_MAM_I(ayrac, cmd, rs, rec) prgsbar.Value += 1 ElseIf ayrac(0).ToString = "KMUS" Then If p_CR_MUS = True Then cmd.CommandText = "CR_MUS" txtDurum.Text = "CR_MUS" rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable) rec = rs.CreateRecord() p_TR_KAMPANYA_MALZEME = False End If strerr_col = myVERI_AL.CR_MUS_I(ayrac, cmd, rs, rec) prgsbar.Value += 1 end while Public Function CR_KAMPANYA_MUSTERI_I(ByVal f_Line() As String, ByRef myComm As SqlCeCommand, ByRef rs As SqlCeResultSet, ByRef rec As SqlCeUpdatableRecord) As String Try rec.SetValue(0, If(f_Line(1) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(1))) rec.SetValue(1, If(f_Line(2) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(2))) rec.SetValue(2, If(f_Line(3) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(3))) rec.SetValue(3, If(f_Line(5) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(5))) rec.SetValue(4, If(f_Line(6) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(6))) rs.Insert(rec) Catch ex As Exception strerr_col = ex.Message End Try Return strerr_col End Function

    Read the article

1 2 3 4 5  | Next Page >