Search Results

Search found 69 results on 3 pages for 'xmltextreader'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • How to Show detail section only with out any space in Active Report

    - by Sunil Naudiyal
    i have a active report without any Page Header , Report Header and no any Footer type section. for more detail see attached image. Now issue is that When we run this report we got space before report detail. for more detail see attached image Below is my code Assembly asm = Assembly.GetAssembly(this.GetType()); System.IO.Stream stre = asm.GetManifestResourceStream(asm.GetName().Name + ".CoverPage.rpx"); using (XmlTextReader xr = new XmlTextReader(stre)) { arCoverPage.LoadLayout(xr); } //Get detail for Cover Page AddingReportSection(report, HeaderType.CoverPage); arCoverPage.DataSource = lstCoverPage; arCoverPage.Run(); I want remove this space.so please give me any suggestion/idea I also tried to set height of page but i am not get sucess. arCoverPage.PageSettings.DefaultPaperSize = false; arCoverPage.PageSettings.Gutter = 3.0F; arCoverPage.PageSettings.Orientation = DataDynamics.ActiveReports.Document.PageOrientation.Portrait; arCoverPage.PageSettings.PaperHeight = 5.0F; this.viReport.Document = arCoverPage.Document;

    Read the article

  • Object reference not set to an instance of an object.

    - by Lambo
    I have the following code - private static void convert() { string csv = File.ReadAllText("test.csv"); string year = "2008"; XDocument doc = ConvertCsvToXML(csv, new[] { "," }); doc.Save("update.xml"); XmlTextReader reader = new XmlTextReader("update.xml"); XmlDocument testDoc = new XmlDocument(); testDoc.Load(@"update.xml"); XDocument turnip = XDocument.Load("update.xml"); webservice.singleSummary[] test = new webservice.singleSummary[1]; webservice.FinanceFeed CallWebService = new webservice.FinanceFeed(); foreach(XElement el in turnip.Descendants("row")) { test[0].account = el.Descendants("var").Where(x => (string)x.Attribute("name") == "account").SingleOrDefault().Attribute("value").Value; test[0].actual = System.Convert.ToInt32(el.Descendants("var").Where(x => (string)x.Attribute("name") == "actual").SingleOrDefault().Attribute("value").Value); test[0].commitment = System.Convert.ToInt32(el.Descendants("var").Where(x => (string)x.Attribute("name") == "commitment").SingleOrDefault().Attribute("value").Value); test[0].costCentre = el.Descendants("var").Where(x => (string)x.Attribute("name") == "costCentre").SingleOrDefault().Attribute("value").Value; test[0].internalCostCentre = el.Descendants("var").Where(x => (string)x.Attribute("name") == "internalCostCentre").SingleOrDefault().Attribute("value").Value; MessageBox.Show(test[0].account, "Account"); MessageBox.Show(System.Convert.ToString(test[0].actual), "Actual"); MessageBox.Show(System.Convert.ToString(test[0].commitment), "Commitment"); MessageBox.Show(test[0].costCentre, "Cost Centre"); MessageBox.Show(test[0].internalCostCentre, "Internal Cost Centre"); CallWebService.updateFeedStatus(test, year); } It is coming up with the error of - NullReferenceException was unhandled, saying that the object reference not set to an instance of an object. The error occurs on the first line test[0].account. How can I get past this?

    Read the article

  • Reading XML or objects from a Web service

    - by Shawn
    This is my first time working with webservices and I am a bit lost. I successfully called the functions, but I only can get one value from the service. I read that the easiest way is to read xml or create objects and then call their values. Currently I use functions that return the desired value but I need to call them 3 times to get all the data witch is a waste of time and resources. I tried to call the service with the URL and use it as a website or getting the service to work the same way without importing into the program. The thing is that i cant find a way to pass the values into the url, because of that i get only blank pages. What is the fastest way to get my data from the services? I need city name, temperature and a flag if the city is valid. I need to pass the zip code to the service. Thank you. My current code wetther.Weather wether = new wetther.Weather(); string farenhait = wether.GetCityWeatherByZIP(zip).Temperature; string city = wether.GetCityWeatherByZIP(zip).City; bool correct = wether.GetCityWeatherByZIP(zip).Success; I tried it that way // Retrieve XML document XmlTextReader reader = new XmlTextReader("http://xml.weather.yahoo.com/forecastrss?p=94704"); // Skip non-significant whitespace reader.WhitespaceHandling = WhitespaceHandling.Significant; // Read nodes one at a time while (reader.Read()) { // Print out info on node Console.WriteLine("{0}: {1}", reader.NodeType.ToString(), reader.Name); } This one works for the yahoo page but not for mine. I need to use this webservice - http://wsf.cdyne.com/WeatherWS/Weather.asmx

    Read the article

  • Help me convert .NET 1.1 Xml validation code to .NET 2.0 please.

    - by Hamish Grubijan
    It would be fantastic if you could help me rid of these warnings below. I have not been able to find a good document. Since the warnings are concentrated in just the private void ValidateConfiguration( XmlNode section ) section, hopefully this is not terribly hard to answer, if you have encountered this before. Thanks! 'System.Configuration.ConfigurationException.ConfigurationException(string)' is obsolete: 'This class is obsolete, to create a new exception create a System.Configuration!System.Configuration.ConfigurationErrorsException' 'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202' private void ValidateConfiguration( XmlNode section ) { // throw if there is no configuration node. if( null == section ) { throw new ConfigurationException("The configuration section passed within the ... class was null ... there must be a configuration file defined.", section ); } //Validate the document using a schema XmlValidatingReader vreader = new XmlValidatingReader( new XmlTextReader( new StringReader( section.OuterXml ) ) ); // open stream on Resources; the XSD is set as an "embedded resource" so Resource can open a stream on it using (Stream xsdFile = XYZ.GetStream("ABC.xsd")) using (StreamReader sr = new StreamReader(xsdFile)) { vreader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); vreader.Schemas.Add(XmlSchema.Read(new XmlTextReader(sr), null)); vreader.ValidationType = ValidationType.Schema; // Validate the document while (vreader.Read()) { } if (!_isValidDocument) { _schemaErrors = _sb.ToString(); throw new ConfigurationException("XML Document not valid"); } } } // Does not cause warnings. private void ValidationCallBack( object sender, ValidationEventArgs args ) { // check what KIND of problem the schema validation reader has; // on FX 1.0, it gives a warning for "<xs:any...skip" sections. Don't worry about those, only set validation false // for real errors if( args.Severity == XmlSeverityType.Error ) { _isValidDocument = false; _sb.Append( args.Message + Environment.NewLine ); } }

    Read the article

  • Subitems are not all added to a list view in C# using XmlNodeList

    - by tim
    I'm working on extracting data from an RSS feed. In my listview (rowNews), I've got two columns: Title and URL. When the button is clicked, all of the titles of the articles are showing up in the title column, but only one URL is added to the URL column. I switched them around so that the URLs would be added to the first column and all of the correct URLs appeared... leading me to think this is a problem with my listview source (it's my first time working with subitems). Here's the original, before I started experimenting with the order: private void button1_Click(object sender, EventArgs e) { XmlTextReader rssReader = new XmlTextReader(txtUrl.Text); XmlDocument rssDoc = new XmlDocument(); rssDoc.Load(rssReader); XmlNodeList titleList = rssDoc.GetElementsByTagName("title"); XmlNodeList urlList = rssDoc.GetElementsByTagName("link"); ListViewItem lvi = new ListViewItem(); for (int i = 0; i < titleList.Count; i++) { rowNews.Items.Add(titleList[i].InnerXml); } for (int i = 0; i < urlList.Count; i++) { lvi.SubItems.Add(urlList[i].InnerXml); } rowNews.Items.Add(lvi); }

    Read the article

  • How to pass XML from C# to a stored procedure in SQL Server 2008?

    - by Geetha
    I want to pass xml document to sql server stored procedure such as this: CREATE PROCEDURE BookDetails_Insert (@xml xml) I want compare some field data with other table data and if it is matching that records has to inserted in to the table. Requirements: How do I pass XML to the stored procedure? I tried this, but it doesn’t work:[Working] command.Parameters.Add( new SqlParameter("@xml", SqlDbType.Xml) { Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml, XmlNodeType.Document, null)) }); How do I access the XML data within the stored procedure? Edit: [Working] String sql = "BookDetails_Insert"; XmlDocument xmlToSave = new XmlDocument(); xmlToSave.Load("C:\\Documents and Settings\\Desktop\\XML_Report\\Books_1.xml"); SqlConnection sqlCon = new SqlConnection("..."); using (DbCommand command = sqlCon.CreateCommand()) { **command.CommandType = CommandType.StoredProcedure;** command.CommandText = sql; command.Parameters.Add( new SqlParameter("@xml", SqlDbType.Xml) { Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml , XmlNodeType.Document, null)) }); sqlCon.Open(); DbTransaction trans = sqlCon.BeginTransaction(); command.Transaction = trans; try { command.ExecuteNonQuery(); trans.Commit(); sqlCon.Close(); } catch (Exception) { trans.Rollback(); sqlCon.Close(); throw; } Edit 2: How to create a select query to select pages, description based on some conditions. <booksdetail> <isn_13>700001048</isbn_13> <isn_10>01048B</isbn_10> <Image_URL>http://www.landt.com/Books/large/00/7010000048.jpg</Image_URL> <title>QUICK AND FLUPKE</title> <Description> PRANKS AND JOKES QUICK AND FLUPKE </Description> </booksdetail>

    Read the article

  • Help me convert C# 1.1 Xml validation code to C# 2.0 please.

    - by Hamish Grubijan
    It would be fantastic if you could help me rid of these warnings below. I have not been able to find a good document. Since the warnings are concentrated in just the private void ValidateConfiguration( XmlNode section ) section, hopefully this is not terribly hard to answer, if you have encountered this before. Thanks! 'System.Configuration.ConfigurationException.ConfigurationException(string)' is obsolete: 'This class is obsolete, to create a new exception create a System.Configuration!System.Configuration.ConfigurationErrorsException' 'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202' private void ValidateConfiguration( XmlNode section ) { // throw if there is no configuration node. if( null == section ) { throw new ConfigurationException("The configuration section passed within the ... class was null ... there must be a configuration file defined.", section ); } //Validate the document using a schema XmlValidatingReader vreader = new XmlValidatingReader( new XmlTextReader( new StringReader( section.OuterXml ) ) ); // open stream on Resources; the XSD is set as an "embedded resource" so Resource can open a stream on it using (Stream xsdFile = XYZ.GetStream("ABC.xsd")) using (StreamReader sr = new StreamReader(xsdFile)) { vreader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); vreader.Schemas.Add(XmlSchema.Read(new XmlTextReader(sr), null)); vreader.ValidationType = ValidationType.Schema; // Validate the document while (vreader.Read()) { } if (!_isValidDocument) { _schemaErrors = _sb.ToString(); throw new ConfigurationException("XML Document not valid"); } } } // Does not cause warnings. private void ValidationCallBack( object sender, ValidationEventArgs args ) { // check what KIND of problem the schema validation reader has; // on FX 1.0, it gives a warning for "<xs:any...skip" sections. Don't worry about those, only set validation false // for real errors if( args.Severity == XmlSeverityType.Error ) { _isValidDocument = false; _sb.Append( args.Message + Environment.NewLine ); } }

    Read the article

  • Debugging XSLT with extension objects in Visual Studio 2010

    - by Alex Ciminian
    I'm currently working on a project that involves a lot of XSLT transformations and I really need a debugger (I have XSLTs that are 1000+ lines long and I didn't write them :-). The project is written in C# and makes use of extension objects: xslArg.AddExtensionObject("urn:<obj>", new <Obj>()); From my knowledge, in this situation Visual Studio is the only tool that can help me debug the transformations step-by-step. The static debugger is no use because of the extension objects (it throws an error when it reaches elements that reference their namespace). Fortunately, I've found this thread which gave me a starting point (at least I know it can be done). After searching MSDN, I found the criteria that makes stepping into the transform possible. They are listed here. In short: the XML and the XSLT must be loaded via a class that has the IXmlLineInfo interface (XmlReader & co.) the XML resolver used in the XSLTCompiledTransform constructor is file-based (XmlUriResolver should work). the stylesheet should be on the local machine or on the intranet (?) From what I can tell, I fit all these criteria, but it still doesn't work. The relevant code samples are posted below: // [...] xslTransform = new XslCompiledTransform(true); xslTransform.Load(XmlReader.Create(new StringReader(contents)), null, new BaseUriXmlResolver(xslLocalPath)); // [...] // I already had the xml loaded in an xmlDocument // so I have to convert to an XmlReader XmlTextReader r = new XmlTextReader(new StringReader(xmlDoc.OuterXml)); XsltArgumentList xslArg = new XsltArgumentList(); xslArg.AddExtensionObject("urn:[...]", new [...]()); xslTransform.Transform(r, xslArg, context.Response.Output); I really don't get what I'm doing wrong. I've checked the interfaces on both XmlReader objects and they implement the required one. Also, BaseUriXmlResolver inherits from XmlUriResolver and the stylesheet is stored locally. The screenshot below is what I get when stepping into the Transform function. First I can see the stylesheet code after stepping through the parameters (on template-match), I get this: If anyone has any idea why it doesn't work or has an alternative way of getting it to work I'd be much obliged :). Thanks, Alex

    Read the article

  • Using returned XML from an authorised HTTP request in vb.NET

    - by Nathan
    Hi, How can I use the returned XML from the reader in a xmltextreader? ' Create the web request request = DirectCast(WebRequest.Create("https://mobilevikings.com/api/1.0/rest/mobilevikings/sim_balance.xml"), HttpWebRequest) ' Add authentication to request request.Credentials = New NetworkCredential("username", "password") ' Get response response = DirectCast(request.GetResponse(), HttpWebResponse) ' Get the response stream into a reader reader = New StreamReader(response.GetResponseStream()) Thanks in advance, Nathan.

    Read the article

  • IXmlSerializable Dictionary

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • IXmlSerializable Dictionary problem

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • Regex slow on Windows Server 2008

    - by pjmyburg
    Hi I have a situation where my regular expressions compile extremely slowly on Windows Server 2008. I wrote a small console application to highlight this issue. The app generates its own input and builds up a Regex from words in an XML file. I built a release version of this app and ran it both on my personal laptop (running XP) and the Windows 2008 server. The regular expression took 0.21 seconds to compile on my laptop, but 23 seconds to compile on the server. Any ideas what could be causing this? The problem is only on first use of the Regex (when it is first compiled - thereafter it is fine) I have also found another problem - when using \s+ in the regular expression on the same Windows 2008 server, the memory balloons (uses 4GB+) and the compilation of the Regex never finishes. Is there a known issue with Regex and 64 bit .net? Is there a fix/patch available for this? I cannot really find any info on the net, but I have found a few articles about this same issues in Framework 2.0 - surely this has been fixed by now? More info: The server is running the 64 bit version of the .net framework (3.5 SP1) and on my laptop I have Visual Studio 2008 and the 3.5 framework installed. The regular expression is of the following pattern: ^word$|^word$|^word$ and is constructed with the following flags: RegexOptions.IgnoreCase | RegexOptions.Compiled Edit: Here is a code snippet: StringBuilder regexString = new StringBuilder(); if (!String.IsNullOrEmpty(fileLocation)) { XmlTextReader textReader = new XmlTextReader(fileLocation); textReader.Read(); while (textReader.Read()) { textReader.MoveToElement(); if (textReader.Name == "word") { regexString.Append("^" + textReader.GetAttribute(0) + "$|"); } } ProfanityFilter = new Regex(regexString.ToString(0, regexString.Length - 1), RegexOptions.IgnoreCase | RegexOptions.Compiled); } DateTime time = DateTime.Now; Console.WriteLine("\nIsProfane:\n" + ProfanityFilter.IsMatch("test")); Console.WriteLine("\nTime: " + (DateTime.Now - time).TotalSeconds); Console.ReadKey(); This results in a time of 0.21 seconds on my laptop and 23 seconds on the 2008 server. The XML file consists of 168 words in the following format: <word text="test" />

    Read the article

  • Serializing Class Derived from Generic Collection yet Deserializing the Generic Collection

    - by Stacey
    I have a Repository Class with the following method... public T Single<T>(Predicate<T> expression) { using (var list = (Models.Collectable<T>)System.Xml.Serializer.Deserialize(typeof(Models.Collectable<T>), FileName)) { return list.Find(expression); } } Where Collectable is defined.. [Serializable] public class Collectable<T> : List<T>, IDisposable { public Collectable() { } public void Dispose() { } } And an Item that uses it is defined.. [Serializable] [System.Xml.Serialization.XmlRoot("Titles")] public partial class Titles : Collectable<Title> { } The problem is when I call the method, it expects "Collectable" to be the XmlRoot, but the XmlRoot is "Titles" (all of object Title). I have several classes that are collected in .xml files like this, but it seems pointless to rewrite the basic methods for loading each up when the generic accessors do it - but how can I enforce the proper root name for each file without hard coding methods for each one? The [System.Xml.Serialization.XmlRoot] seems to be ignored. When called like this... var titles = Repository.List<Models.Title>(); I get the exception <Titlesxmlns=''> was not expected. The XML is formatted such as. .. <?xml version="1.0" encoding="utf-16"?> <Titles xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Title> <Id>442daf7d-193c-4da8-be0b-417cec9dc1c5</Id> </Title> </Titles> Here is the deserialization code. public static T Deserialize<T>(String xmlString) { System.Xml.Serialization.XmlSerializer XmlFormatSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); StreamReader XmlStringReader = new StreamReader(xmlString); //XmlTextReader XmlFormatReader = new XmlTextReader(XmlStringReader); try { return (T)XmlFormatSerializer.Deserialize(XmlStringReader); } catch (Exception e) { throw e; } finally { XmlStringReader.Close(); } }

    Read the article

  • Validate an Xml file against a DTD with a proxy. C# 2.0

    - by Chris Dunaway
    I have looked at many examples for validating an XML file against a DTD, but have not found one that allows me to use a proxy. I have a cXml file as follows (abbreviated for display) which I wish to validate: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.018/InvoiceDetail.dtd"> <cXML payloadID="123456" timestamp="2009-12-10T10:05:30-06:00"> <!-- content snipped --> </cXML> I am trying to create a simple C# program to validate the xml against the DTD. I have tried code such as the following but cannot figure out how to get it to use a proxy: private static bool isValid = false; static void Main(string[] args) { try { XmlTextReader r = new XmlTextReader(args[0]); XmlReaderSettings settings = new XmlReaderSettings(); XmlDocument doc = new XmlDocument(); settings.ProhibitDtd = false; settings.ValidationType = ValidationType.DTD; settings.ValidationEventHandler += new ValidationEventHandler(v_ValidationEventHandler); XmlReader validator = XmlReader.Create(r, settings); while (validator.Read()) ; validator.Close(); // Check whether the document is valid or invalid. if (isValid) Console.WriteLine("Document is valid"); else Console.WriteLine("Document is invalid"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } static void v_ValidationEventHandler(object sender, ValidationEventArgs e) { isValid = false; Console.WriteLine("Validation event\n" + e.Message); } The exception I receive is System.Net.WebException: The remote server returned an error: (407) Proxy Authentication Required. which occurs on the line while (validator.Read()) ; I know I can validate against a DTD locally, but I don't want to change the xml DOCTYPE since that is what the final form needs to be (this app is solely for diagnostic purposes). For more information about the cXML spec, you can go to cxml.org. I appreciate any assistance. Thanks

    Read the article

  • VB.NET looping through XML to store in singleton

    - by rockinthesixstring
    I'm having a problem with looping through an XML file and storing the value in a singleton My XML looks like this <values> <value></value> <value>$1</value> <value>$5,000</value> <value>$10,000</value> <value>$15,000</value> <value>$25,000</value> <value>$50,000</value> <value>$75,000</value> <value>$100,000</value> <value>$250,000</value> <value>$500,000</value> <value>$750,000</value> <value>$1,000,000</value> <value>$1,250,000</value> <value>$1,500,000</value> <value>$1,750,000</value> <value>$2,000,000</value> <value>$2,500,000</value> <value>$3,000,000</value> <value>$4,000,000</value> <value>$5,000,000</value> <value>$7,500,000</value> <value>$10,000,000</value> <value>$15,000,000</value> <value>$25,000,000</value> <value>$50,000,000</value> <value>$100,000,000</value> <value>$100,000,000+</value> </values> And my function looks like this Public Class LoadValues Private Shared SearchValuesInstance As List(Of SearchValues) = Nothing Public Shared ReadOnly Property LoadSearchValues As List(Of SearchValues) Get Dim sv As New List(Of SearchValues) If SearchValuesInstance Is Nothing Then Dim objDoc As XmlDocument = New XmlDataDocument Dim objRdr As XmlTextReader = New XmlTextReader(HttpContext.Current.Server.MapPath("~/App_Data/Search-Values.xml")) objRdr.Read() objDoc.Load(objRdr) Dim root As XmlElement = objDoc.DocumentElement Dim itemNodes As XmlNodeList = root.SelectNodes("/values") For Each n As XmlNode In itemNodes sv.Add(New SearchValues(n("@value").InnerText, n("@value").InnerText)) Next SearchValuesInstance = sv Else : sv = SearchValuesInstance End If Return sv End Get End Property End Class My problem is that I'm getting an object not set to an instance of an object on the sv.Add(New SearchValues(n("@value").InnerText, n("@value").InnerText)) line.

    Read the article

  • C#, how to create an XML document from an object?

    - by JL
    I have the following variable that accepts a file name: var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None }; var xd = new XmlDocument(); xd.Load(xtr); I would like to change it so that I can pass in an object. I don't want to have to serialize the object to file first. Is this possible?

    Read the article

  • Authenticating clients in the new WCF Http stack

    - by cibrax
    About this time last year, I wrote a couple of posts about how to use the “Interceptors” from the REST starker kit for implementing several authentication mechanisms like “SAML”, “Basic Authentication” or “OAuth” in the WCF Web programming model. The things have changed a lot since then, and Glenn finally put on our hands a new version of the Web programming model that deserves some attention and I believe will help us a lot to build more Http oriented services in the .NET stack. What you can get today from wcf.codeplex.com is a preview with some cool features like Http Processors (which I already discussed here), a new and improved version of the HttpClient library, Dependency injection and better TDD support among others. However, the framework still does not support an standard way of doing client authentication on the services (This is something planned for the upcoming releases I believe). For that reason, moving the existing authentication interceptors to this new programming model was one of the things I did in the last few days. In order to make authentication simple and easy to extend,  I first came up with a model based on what I called “Authentication Interceptors”. An authentication interceptor maps to an existing Http authentication mechanism and implements the following interface, public interface IAuthenticationInterceptor{ string Scheme { get; } bool DoAuthentication(HttpRequestMessage request, HttpResponseMessage response, out IPrincipal principal);} An authentication interceptors basically needs to returns the http authentication schema that implements in the property “Scheme”, and implements the authentication mechanism in the method “DoAuthentication”. As you can see, this last method “DoAuthentication” only relies on the HttpRequestMessage and HttpResponseMessage classes, making the testing of this interceptor very simple (There is no need to do some black magic with the WCF context or messages). After this, I implemented a couple of interceptors for supporting basic authentication and brokered authentication with SAML (using WIF) in my services. The following code illustrates how the basic authentication interceptors looks like. public class BasicAuthenticationInterceptor : IAuthenticationInterceptor{ Func<UsernameAndPassword, bool> userValidation; string realm;  public BasicAuthenticationInterceptor(Func<UsernameAndPassword, bool> userValidation, string realm) { if (userValidation == null) throw new ArgumentNullException("userValidation");  if (string.IsNullOrEmpty(realm)) throw new ArgumentNullException("realm");  this.userValidation = userValidation; this.realm = realm; }  public string Scheme { get { return "Basic"; } }  public bool DoAuthentication(HttpRequestMessage request, HttpResponseMessage response, out IPrincipal principal) { string[] credentials = ExtractCredentials(request); if (credentials.Length == 0 || !AuthenticateUser(credentials[0], credentials[1])) { response.StatusCode = HttpStatusCode.Unauthorized; response.Content = new StringContent("Access denied"); response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=" + this.realm));  principal = null;  return false; } else { principal = new GenericPrincipal(new GenericIdentity(credentials[0]), new string[] {});  return true; } }  private string[] ExtractCredentials(HttpRequestMessage request) { if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme.StartsWith("Basic")) { string encodedUserPass = request.Headers.Authorization.Parameter.Trim();  Encoding encoding = Encoding.GetEncoding("iso-8859-1"); string userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass)); int separator = userPass.IndexOf(':');  string[] credentials = new string[2]; credentials[0] = userPass.Substring(0, separator); credentials[1] = userPass.Substring(separator + 1);  return credentials; }  return new string[] { }; }  private bool AuthenticateUser(string username, string password) { var usernameAndPassword = new UsernameAndPassword { Username = username, Password = password };  if (this.userValidation(usernameAndPassword)) { return true; }  return false; }} This interceptor receives in the constructor a callback in the form of a Func delegate for authenticating the user and the “realm”, which is required as part of the implementation. The rest is a general implementation of the basic authentication mechanism using standard http request and response messages. I also implemented another interceptor for authenticating a SAML token with WIF. public class SamlAuthenticationInterceptor : IAuthenticationInterceptor{ SecurityTokenHandlerCollection handlers = null;  public SamlAuthenticationInterceptor(SecurityTokenHandlerCollection handlers) { if (handlers == null) throw new ArgumentNullException("handlers");  this.handlers = handlers; }  public string Scheme { get { return "saml"; } }  public bool DoAuthentication(HttpRequestMessage request, HttpResponseMessage response, out IPrincipal principal) { SecurityToken token = ExtractCredentials(request);  if (token != null) { ClaimsIdentityCollection claims = handlers.ValidateToken(token);  principal = new ClaimsPrincipal(claims);  return true; } else { response.StatusCode = HttpStatusCode.Unauthorized; response.Content = new StringContent("Access denied");  principal = null;  return false; } }  private SecurityToken ExtractCredentials(HttpRequestMessage request) { if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == "saml") { XmlTextReader xmlReader = new XmlTextReader(new StringReader(request.Headers.Authorization.Parameter));  var col = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); SecurityToken token = col.ReadToken(xmlReader);  return token; }  return null; }}This implementation receives a “SecurityTokenHandlerCollection” instance as part of the constructor. This class is part of WIF, and basically represents a collection of token managers to know how to handle specific xml authentication tokens (SAML is one of them). I also created a set of extension methods for injecting these interceptors as part of a service route when the service is initialized. var basicAuthentication = new BasicAuthenticationInterceptor((u) => true, "ContactManager");var samlAuthentication = new SamlAuthenticationInterceptor(serviceConfiguration.SecurityTokenHandlers); // use MEF for providing instancesvar catalog = new AssemblyCatalog(typeof(Global).Assembly);var container = new CompositionContainer(catalog);var configuration = new ContactManagerConfiguration(container); RouteTable.Routes.AddServiceRoute<ContactResource>("contact", configuration, basicAuthentication, samlAuthentication);RouteTable.Routes.AddServiceRoute<ContactsResource>("contacts", configuration, basicAuthentication, samlAuthentication); In the code above, I am injecting the basic authentication and saml authentication interceptors in the “contact” and “contacts” resource implementations that come as samples in the code preview. I will use another post to discuss more in detail how the brokered authentication with SAML model works with this new WCF Http bits. The code is available to download in this location.

    Read the article

  • Error Installing COM+ (Error Code: 80131501)

    - by Regina Foo
    I've written a class library that reads from an xml file and return the result as a string. But when I want to install it as a COM+ component, an error occurred (Error Code: 80131501). I checked the event log and the details of the error is: Installation of 'C:\Users\User\Documents\Visual Studio 2005\Projects\InteropSOA\InteropSOA\bin\Debug\InteropSOA.dll' into '{28E82165-AD74-4E16-90C9-0C5CE7DA97AA}' failed with an exception: System.EnterpriseServices.RegistrationException: FATAL: Could not find component 'InteropSOA.ConfigReader' we just installed. at System.EnterpriseServices.RegistrationDriver.InstallAssembly(RegistrationConfig regConfig, Object obSync) at System.EnterpriseServices.RegistrationHelper.InstallAssemblyFromConfig(RegistrationConfig& regConfig) at System.EnterpriseServices.RegistrationHelper.InstallAssembly(String assembly, String& application, String partition, String& tlb, InstallationFlags installFlags) at System.EnterpriseServices.Internal.ComManagedImportUtil.InstallAssembly(String asmpath, String parname, String appname) Below are the steps I've done while developing the class library: Added "System.EnterpriseServices" to Reference. Imported the reference to the class. Declared the class as "ServicedComponent". Set project properties ("Make assembly COM-visible" checked, "Register for COM Interop" checked, Signed the assembly with a strong key file name.) Here are my codes: using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.XPath; using System.EnterpriseServices; namespace InteropSOA { public class ConfigReader : ServicedComponent { // xml file name private string strFileName; // type of request private string strRequest = ""; // response string private string strResponse = ""; // declarations for xPath private XPathDocument doc; private XPathNavigator nav; private XPathExpression expr; private XPathNodeIterator iterator; private XmlTextReader reader; private XmlDocument xmlDoc; public ConfigReader(string strFile, string request) { this.strFileName = strFile; this.strRequest = request; } public ConfigReader() { //default contructor } // reader for console program public void ReadXML() { doc = new XPathDocument(strFileName); nav = doc.CreateNavigator(); // compile xPath expression expr = nav.Compile("/Msg/" + strRequest + "/*"); iterator = nav.Select(expr); // interate on the node set try { while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); strResponse += nav2.Value + "|"; } } catch (Exception ex) { Console.WriteLine(ex.Message); } strResponse = strResponse.Substring(0, strResponse.Length-1); Console.WriteLine("Response string = " + strResponse); } public void WriteXML(string strRequest, string strElement, string strValue) { reader = new XmlTextReader(strFileName); xmlDoc = new XmlDocument(); xmlDoc.Load(reader); reader.Close(); XmlNode node; XmlElement root = xmlDoc.DocumentElement; node = root.SelectSingleNode("/Msg/" + strRequest + "/" + strElement); node.InnerText = strValue; xmlDoc.Save(strFileName); } // reader for ASP.NET public string ReadXMLElement() { doc = new XPathDocument(strFileName); nav = doc.CreateNavigator(); // compile xPath expression expr = nav.Compile("/Msg/" + strRequest + "/*"); iterator = nav.Select(expr); // interate on the node set try { while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); strResponse += nav2.Value + "|"; } } catch (Exception ex) { Console.WriteLine(ex.Message); } strResponse = strResponse.Substring(0, strResponse.Length - 1); return strResponse; } } }

    Read the article

  • ASMX Web Services with SOAP Extension

    - by digitall
    I am in the process of setting up a web service for an external client to connect to my client's application and update some information. I went the ASMX route (the rest of the application runs on WCF) because I knew the external client could be very difficult to deal with and I was trying to keep everything as simple as possible. They also aren't a .Net shop which makes things worse. After getting the service setup for them I provided the ASMX URL for them to see how to format the SOAP headers/message content. They have since come back and told me their tool is unable to send them in the format required by .Net and I can either come up with a different way to accept messages or we have to go with FTP. Based on this I have been researching how to intercept their message, reformat it the way my service requires it (which means adding two lines), and then let it process. This path led me to SOAP Extensions which I have been trying to work with but can't seem to figure out. When I have my sample application call the web service from the generated code Add Web Reference provides everything works great until I add in my extension. All it currently does is override ChainStream setting an internal stream equal to the one being passed in and returning a new stream, like this: private Stream newStream = null; private Stream oldStream = null; public override Stream ChainStream(Stream stream) { this.oldStream = stream; this.newStream = new MemoryStream(); return newStream; } I also override ProcessMessage and in it take the contents of oldStream and set newStream equal to that and then write to a different stream with an XmlWriter. I take that new stream and using a StreamReader read it into a string, with the end goal being manipulating it here and setting newStream (which is being used by ChainStream) equal to the contents of this. Here is that piece: public override void ProcessMessage(SoapMessage message) { switch (message.Stage) { case SoapMessageStage.BeforeDeserialize: this.Process(); break; default: break; } } private void Process() { this.newStream.Position = 0L; XmlTextReader reader = new XmlTextReader(this.oldStream); MemoryStream outStream = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(outStream)) { do { writer.WriteNode(reader, true); } while (reader.Read()); writer.Flush(); } outStream.Seek(0, SeekOrigin.Begin); StreamReader streamReader = new StreamReader(outStream); string message = streamReader.ReadToEnd(); newStream = outStream; newStream.Seek(0, SeekOrigin.Begin); streamReader.Close(); } By running this, which seems to me like it would be fine, my test application gets a 400 Bad Request back from the service. If I either don't use the extension or I don't do anything in ProcessMessage everything seems fine. Any suggestions to this? As a side note, once I get this working with the generated code from the WSDL I will be moving to a WebRequest to try sending the message to the service. Currently that bombs out with a 415 Unsupported Media Type response. I'm trying to keep this post to one question but if anyone has any tips with using a WebRequest to connect to an ASMX service it would be much appreciated!

    Read the article

  • null reference expction in the code

    - by LifeH2O
    I am getting NullReferenceException error on "_attr.Append(xmlNode.Attributes["name"]);". namespace SMAS { class Profiles { private XmlTextReader _profReader; private XmlDocument _profDoc; private const string Url = "http://localhost/teamprofiles.xml"; private const string XPath = "/teams/team-profile"; public XmlNodeList Teams{ get; private set; } private XmlAttributeCollection _attr; public ArrayList Team { get; private set; } public void GetTeams() { _profReader = new XmlTextReader(Url); _profDoc = new XmlDocument(); _profDoc.Load(_profReader); Teams = _profDoc.SelectNodes(XPath); foreach (XmlNode xmlNode in Teams) { _attr.Append(xmlNode.Attributes["name"]); } } } } the teamprofiles.xml file looks like <teams> <team-profile name="Australia"> <stats type="Test"> <span>1877-2010</span> <matches>721</matches> <won>339</won> <lost>186</lost> <tied>2</tied> <draw>194</draw> <percentage>47.01</percentage> </stats> <stats type="Twenty20"> <span>2005-2010</span> <matches>32</matches> <won>18</won> <lost>12</lost> <tied>1</tied> <draw>1</draw> <percentage>59.67</percentage> </stats> </team-profile> <team-profile name="Bangladesh"> <stats type="Test"> <span>2000-2010</span> <matches>66</matches> <won>3</won> <lost>57</lost> <tied>0</tied> <draw>6</draw> <percentage>4.54</percentage> </stats> </team-profile> </teams> I am trying to extract names of all teams in an ArrayList. Then i'll extract all stats of all teams and display them in my application. Can you please help me about that null reference exception?

    Read the article

  • null reference exception in the code

    - by LifeH2O
    I am getting NullReferenceException error on "_attr.Append(xmlNode.Attributes["name"]);". namespace SMAS { class Profiles { private XmlTextReader _profReader; private XmlDocument _profDoc; private const string Url = "http://localhost/teamprofiles.xml"; private const string XPath = "/teams/team-profile"; public XmlNodeList Teams{ get; private set; } private XmlAttributeCollection _attr; public ArrayList Team { get; private set; } public void GetTeams() { _profReader = new XmlTextReader(Url); _profDoc = new XmlDocument(); _profDoc.Load(_profReader); Teams = _profDoc.SelectNodes(XPath); foreach (XmlNode xmlNode in Teams) { _attr.Append(xmlNode.Attributes["name"]); } } } } the teamprofiles.xml file looks like <teams> <team-profile name="Australia"> <stats type="Test"> <span>1877-2010</span> <matches>721</matches> <won>339</won> <lost>186</lost> <tied>2</tied> <draw>194</draw> <percentage>47.01</percentage> </stats> <stats type="Twenty20"> <span>2005-2010</span> <matches>32</matches> <won>18</won> <lost>12</lost> <tied>1</tied> <draw>1</draw> <percentage>59.67</percentage> </stats> </team-profile> <team-profile name="Bangladesh"> <stats type="Test"> <span>2000-2010</span> <matches>66</matches> <won>3</won> <lost>57</lost> <tied>0</tied> <draw>6</draw> <percentage>4.54</percentage> </stats> </team-profile> </teams> I am trying to extract names of all teams in an ArrayList. Then i'll extract all stats of all teams and display them in my application. Can you please help me about that null reference exception?

    Read the article

  • how to create text file in window service

    - by angel ansari
    Hi, I have an XML file <config> <ServiceName>autorunquery</ServiceName> <DBConnection> <server>servername</server> <user>xyz</user> <password>klM#2bs</password> <initialcatelog>TEST</initialcatelog> </DBConnection> <Log> <logfilename>d:\testlogfile.txt</logfilename> </Log> <Frequency> <value>10</value> <unit>minute</unit> </Frequency> <CheckQuery>select * from credit_debit1 where station='Corporate'</CheckQuery> <Queries total="3"> <Query id="1">Update credit_debit1 set station='xxx' where id=2</Query> <Query id="2">Update credit_debit1 set station='xxx' where id=4</Query> <Query id="3">Update credit_debit1 set station='xxx' where id=9</Query> </Queries> </config> using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.IO; using System.Xml; namespace Service1 { public partial class Service1 : ServiceBase { XmlTextReader reader = null; string path = null; FileStream fs = null; StreamWriter sw = null; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer1.Enabled = true; timer1.Interval = 10000; timer1.Start(); logfile("start service"); } protected override void OnStop() { timer1.Enabled = false; timer1.Stop(); logfile("stop service"); } private void logfile(string content) { try { reader = new XmlTextReader("queryconfig.xml");//xml file name which is in current directory if (reader.ReadToFollowing("logfilename")) { path = reader.ReadElementContentAsString(); } fs = new FileStream(path, FileMode.Append, FileAccess.Write); sw = new StreamWriter(fs); sw.Write(content); sw.WriteLine(DateTime.Now.ToString()); } catch (Exception ex) { sw.Write(ex.ToString()); throw; } finally { if (reader != null) reader.Close(); if (sw != null) sw.Close(); if (fs != null) fs.Close(); } } } } My problem is that the file is not created.

    Read the article

  • Integrating WIF with WCF Data Services

    - by cibrax
    A time ago I discussed how a custom REST Starter kit interceptor could be used to parse a SAML token in the Http Authorization header and wrap that into a ClaimsPrincipal that the WCF services could use. The thing is that code was initially created for Geneva framework, so it got deprecated quickly. I recently needed that piece of code for one of projects where I am currently working on so I decided to update it for WIF. As this interceptor can be injected in any host for WCF REST services, also represents an excellent solution for integrating claim-based security into WCF Data Services (previously known as ADO.NET Data Services). The interceptor basically expects a SAML token in the Authorization header. If a token is found, it is parsed and a new ClaimsPrincipal is initialized and injected in the WCF authorization context. public class SamlAuthenticationInterceptor : RequestInterceptor {   SecurityTokenHandlerCollection handlers;   public SamlAuthenticationInterceptor()     : base(false)   {     this.handlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;   }   public override void ProcessRequest(ref RequestContext requestContext)   {     SecurityToken token = ExtractCredentials(requestContext.RequestMessage);     if (token != null)     {       ClaimsIdentityCollection claims = handlers.ValidateToken(token);       var principal = new ClaimsPrincipal(claims);       InitializeSecurityContext(requestContext.RequestMessage, principal);     }     else     {       DenyAccess(ref requestContext);     }   }   private void DenyAccess(ref RequestContext requestContext)   {     Message reply = Message.CreateMessage(MessageVersion.None, null);     HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };     responseProperty.Headers.Add("WWW-Authenticate",           String.Format("Basic realm=\"{0}\"", ""));     reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;     requestContext.Reply(reply);     requestContext = null;   }   private SecurityToken ExtractCredentials(Message requestMessage)   {     HttpRequestMessageProperty request = (HttpRequestMessageProperty)  requestMessage.Properties[HttpRequestMessageProperty.Name];     string authHeader = request.Headers["Authorization"];     if (authHeader != null && authHeader.Contains("<saml"))     {       XmlTextReader xmlReader = new XmlTextReader(new StringReader(authHeader));       var col = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();       SecurityToken token = col.ReadToken(xmlReader);                                        return token;     }     return null;   }   private void InitializeSecurityContext(Message request, IPrincipal principal)   {     List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();     policies.Add(new PrincipalAuthorizationPolicy(principal));     ServiceSecurityContext securityContext = new ServiceSecurityContext(policies.AsReadOnly());     if (request.Properties.Security != null)     {       request.Properties.Security.ServiceSecurityContext = securityContext;     }     else     {       request.Properties.Security = new SecurityMessageProperty() { ServiceSecurityContext = securityContext };      }    }    class PrincipalAuthorizationPolicy : IAuthorizationPolicy    {      string id = Guid.NewGuid().ToString();      IPrincipal user;      public PrincipalAuthorizationPolicy(IPrincipal user)      {        this.user = user;      }      public ClaimSet Issuer      {        get { return ClaimSet.System; }      }      public string Id      {        get { return this.id; }      }      public bool Evaluate(EvaluationContext evaluationContext, ref object state)      {        evaluationContext.AddClaimSet(this, new DefaultClaimSet(System.IdentityModel.Claims.Claim.CreateNameClaim(user.Identity.Name)));        evaluationContext.Properties["Identities"] = new List<IIdentity>(new IIdentity[] { user.Identity });        evaluationContext.Properties["Principal"] = user;        return true;      }    } A WCF Data Service, as any other WCF Service, contains a service host where this interceptor can be injected. The following code illustrates how that can be done in the “svc” file. <%@ ServiceHost Language="C#" Debug="true" Service="ContactsDataService"                 Factory="AppServiceHostFactory" %> using System; using System.ServiceModel; using System.ServiceModel.Activation; using Microsoft.ServiceModel.Web; class AppServiceHostFactory : ServiceHostFactory {    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)   {     WebServiceHost2 result = new WebServiceHost2(serviceType, true, baseAddresses);     result.Interceptors.Add(new SamlAuthenticationInterceptor());                 return result;   } } WCF Data Services includes an specific WCF host of out the box (DataServiceHost). However, the service is not affected at all if you replace it with a custom one as I am doing in the code above (WebServiceHost2 is part of the REST Starter kit). Finally, the client application needs to pass the SAML token somehow to the data service. In case you are using any Http client library for consuming the data service, that’s easy to do, you only need to include the SAML token as part of the “Authorization” header. If you are using the auto-generated data service proxy, a little piece of code is needed to inject a SAML token into the DataServiceContext instance. That class provides an event “SendingRequest” that any client application can leverage to include custom code that modified the Http request before it is sent to the service. So, you can easily create an extension method for the DataServiceContext that negotiates the SAML token with an existing STS, and adds that token as part of the “Authorization” header. public static class DataServiceContextExtensions {        public static void ConfigureFederatedCredentials(this DataServiceContext context, string baseStsAddress, string realm)   {     string address = string.Format(STSAddressFormat, baseStsAddress, realm);                  string token = NegotiateSecurityToken(address);     context.SendingRequest += (source, args) =>     {       args.RequestHeaders.Add("Authorization", token);     };   } private string NegotiateSecurityToken(string address) { } } I left the NegociateSecurityToken method empty for this extension as it depends pretty much on how you are negotiating tokens from an existing STS. In case you want to end-to-end REST solution that involves an Http endpoint for the STS, you should definitely take a look at the Thinktecture starter STS project in codeplex.

    Read the article

  • HTML to XAML Conversion, Display HTML in RichTextBox

    - by Erika
    Hi, unfortunately im REALLY stuck on this and was wondering in anyone knows how to work around this. I have some html text which i want displayed in a WPF RichTextBox. At the moment, i'm using some helper APIs found http://blogs.msdn.com/wpfsdk/archive/2006/05/25/606317.aspx to convert HTML to XAML. So at the moment i have a xaml data string, but i cant see to find a way to display this correctly within the richtextbox :s i have been trying the following: string xamlData = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(sBody,true); FlowDocument result = XamlReader.Load(new System.Xml.XmlTextReader(new StringReader(xamlData))) as FlowDocument; but this is crashing on the XamlReader.. Any other way will do, i just need to display an HTML string in this RichTextBox or something else! Please Help!

    Read the article

  • c# xml string special characters

    - by sam
    Please help explain why the dataset cannot read the encoded xml? string xml = "<?xml version=\"1.0\" standalone=\"yes\" ?> <DataSet><node>it's my \"node\" & i like it</node></DataSet>"; string encodedXml = System.Security.SecurityElement.Escape(xml); DataSet ds = new DataSet(); ds.ReadXml(New XmlTextReader(new StringReader(encodedXml))); I have checked the link http://weblogs.sqlteam.com/mladenp/archive/2008/10/21/Different-ways-how-to-escape-an-XML-string-in-C.aspx What i want to do is to read a string with special characters into a dataset. But the code cannot locate the special characters in the string, c# added all the \ so the linenumber is not accurate generated by XmlException object. Anyone could provide the code to read a string with special characters into a dataset. thanks very much

    Read the article

< Previous Page | 1 2 3  | Next Page >