XML Help to C#, Please convert this to c# - xml-serialization

<data1>
<ClosedDates>
<ClosedDate>2011-01-09</ClosedDate>
<ClosedDate>2011-01-10</ClosedDate>
<ClosedDate>2011-01-16</ClosedDate>
</ClosedDates>
</data1>
Guys, please help me to convert this XML in to C# class.

If you run the xsd.exe utility (docs here) twice on your data file, you'll get:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4952
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class data1 {
private data1ClosedDates[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ClosedDates", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public data1ClosedDates[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class data1ClosedDates {
private data1ClosedDatesClosedDate[] closedDateField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ClosedDate", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public data1ClosedDatesClosedDate[] ClosedDate {
get {
return this.closedDateField;
}
set {
this.closedDateField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class data1ClosedDatesClosedDate {
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
The xsd.exe utility is part of the Microsoft Windows SDK currently at v7.1 which you can download for free from here: http://msdn.microsoft.com/en-us/windows/bb980924
Now with this class in hand, you should be able to write something like:
XmlSerializer ser = new XmlSerializer(typeof(data1));
var result = ser.Deserialize(#"C:\test.xml");

Have a look at XmlSerializer.Deserialize Method (hope will help you)

Related

How do I fix this error when trying to use the Watson SDK for Unity?

thanks for taking a look at this. I'm new to Unity and struggling to understand how to fix this error.
Assets/Watson/Scripts/Logging/Logger.cs(115,53): error CS0311: The type IBM.Watson.DeveloperCloud.Logging.LogSystem' cannot be used as type parameter T in the generic type or method Singleton. There is no implicit reference conversion from IBM.Watson.DeveloperCloud.Logging.LogSystem' to `UnityEngine.MonoBehaviour
This is the line causing the error:
public static LogSystem Instance { get { return Singleton<LogSystem>.Instance; } }
And this is it in context:
/// <summary>
/// This singleton class maintains the of list of installed reactors and handles all LogRecord
/// objects. See the static class Log for functions the end user of this system should actually
/// be calling. This class is thread safe.
/// </summary>
public class LogSystem
{
#region Public Properties
/// <summary>
/// Returns the singleton instance of the Logger object.
/// </summary>
**public static LogSystem Instance { get { return Singleton<LogSystem>.Instance; } }**
#endregion
#region Private Data
private static bool sm_bInstalledDefaultReactors = false;
List<ILogReactor> m_Reactors = new List<ILogReactor>();
#endregion
#region Public Functions
public static List<ILogReactor> ReactorsInstalled
{
get
{
return LogSystem.Instance.m_Reactors;
}
}
/// <summary>
/// Install a default debug and file reactor.
/// </summary>
public static void InstallDefaultReactors(int logHistory = 2, LogLevel logLevelFileReactor = LogLevel.STATUS)
{
if (!sm_bInstalledDefaultReactors)
{
// install the default reactors...
sm_bInstalledDefaultReactors = true;
#if UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID
LogSystem.Instance.InstallReactor(new DebugReactor());
#endif
if (!string.IsNullOrEmpty(Constants.Path.LOG_FOLDER) && !System.IO.Directory.Exists(Application.persistentDataPath + Constants.Path.LOG_FOLDER))
System.IO.Directory.CreateDirectory(Application.persistentDataPath + Constants.Path.LOG_FOLDER);
LogSystem.Instance.InstallReactor(new FileReactor(Application.persistentDataPath + Constants.Path.LOG_FOLDER + "/" + Application.productName + ".log", logLevelFileReactor, logHistory));
Application.logMessageReceived += UnityLogCallback;
}
}
static void UnityLogCallback(string condition, string stacktrace, LogType type)
{
if (type == LogType.Exception)
Log.Critical("Unity", "Unity Exception {0} : {1}", condition, stacktrace);
}
/// <summary>
/// Installs a reactor into this Logger.
/// </summary>
/// <param name="reactor">The reactor object.</param>
public void InstallReactor(ILogReactor reactor)
{
lock (m_Reactors)
{
m_Reactors.Add(reactor);
}
// set our default reactor flag to true if the user installs their own reactors.
sm_bInstalledDefaultReactors = true;
}
/// <summary>
/// Removes a reactor from this Logger.
/// </summary>
/// <param name="reactor">The reactor to remove.</param>
/// <returns>Returns true on success.</returns>
public bool RemoveReactor(ILogReactor reactor)
{
lock (m_Reactors)
{
return m_Reactors.Remove(reactor);
}
}
/// <summary>
/// Send the given LogRecord to all installed reactors.
/// </summary>
/// <param name="log">The LogRecord to pass to all reactors.</param>
public void ProcessLog(LogRecord log)
{
lock (m_Reactors)
{
foreach (var reactor in m_Reactors)
reactor.ProcessLog(log);
}
}
#endregion
}
public static LogSystem Instance
{
get
{
return instance;
}
}
private static LogSystem instance;
// Ctor of the class
public LogSystem()
{
if(instance == null) { instance = this;}
}
This is a very basic singleton pattern implementation. You can find more advanced ones online.

Error : Cannot find Facebook SDK Version

the SDK 7.x is not working on Unity 5.1.0f3 , i always got the error version not found .
does someone have see this error ?
Actually, it's just a warning. But you can fix it.
There are several places where facebook plugin calls
FBBuildVersionAttribute.GetVersionAttributeOfType(typeof(AbstractFacebook));
So first, you need to modify FBBuildVersionAttribute to this:
// we are going to apply this attribute to Class
// instead of Assembly
// also make it inheritable for all implementations
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class FBBuildVersionAttribute : Attribute
{
private DateTime buildDate;
private string buildHash;
private string buildVersion;
private string sdkVersion;
public DateTime Date { get { return buildDate; } }
public string Hash { get { return buildHash; } }
public string SdkVersion { get { return sdkVersion; } }
public string BuildVersion { get { return buildVersion; } }
public FBBuildVersionAttribute(string sdkVersion, string buildVersion)
{
this.buildVersion = buildVersion;
var parts = buildVersion.Split('.');
buildDate = DateTime.ParseExact(parts[0], "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);
buildHash = parts[1];
this.sdkVersion = sdkVersion;
}
public override string ToString()
{
return buildVersion;
}
public static FBBuildVersionAttribute GetVersionAttributeOfType(Type type)
{
foreach (FBBuildVersionAttribute attribute in getAttributes(type))
{
return attribute;
}
return null;
}
private static FBBuildVersionAttribute[] getAttributes(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
// we want to get attributes from type instead of assmebly
return (FBBuildVersionAttribute[])(type.GetCustomAttributes(typeof(FBBuildVersionAttribute), false));
}
}
No you just need to add this attribute to AbstractFacebook:
[FBBuildVersionAttribute("7.0.1", "150604.98558e55096475c")]
public abstract class AbstractFacebook : MonoBehaviour
{
// ...
}
Note that 98558e55096475c part is trash string. It's not actual build hash, cause I don't have one.
Get the latest version of the FB Unity SDK. Change log says it's fixed now.
https://developers.facebook.com/docs/unity/change-log

Why is my Type not being Serialized correctly by the XmlSerializer

The intial problem was that when I called a webservice ( asmx) methos with a type the type was always going through as null . Inspecting the Soap confirmed that the type was going as an empty element. So I tried a simple test.
Here is my type which of course has been generated from WSDL
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.233")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://dto12.api.echosign")]
public partial class SendDocumentInteractiveOptions {
private bool authoringRequestedField;
private bool authoringRequestedFieldSpecified;
private bool autoLoginUserField;
private bool autoLoginUserFieldSpecified;
private bool noChromeField;
private bool noChromeFieldSpecified;
/// <remarks/>
public bool authoringRequested {
get {
return this.authoringRequestedField;
}
set {
this.authoringRequestedField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool authoringRequestedSpecified {
get {
return this.authoringRequestedFieldSpecified;
}
set {
this.authoringRequestedFieldSpecified = value;
}
}
/// <remarks/>
public bool autoLoginUser {
get {
return this.autoLoginUserField;
}
set {
this.autoLoginUserField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool autoLoginUserSpecified {
get {
return this.autoLoginUserFieldSpecified;
}
set {
this.autoLoginUserFieldSpecified = value;
}
}
/// <remarks/>
public bool noChrome {
get {
return this.noChromeField;
}
set {
this.noChromeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool noChromeSpecified {
get {
return this.noChromeFieldSpecified;
}
set {
this.noChromeFieldSpecified = value;
}
}
}
Now here is some simple code to serialize it.
SendDocumentInteractiveOptions sdio = new SendDocumentInteractiveOptions();
sdio.authoringRequested = true;
sdio.autoLoginUser = true;
sdio.noChrome = true;
XmlSerializer xmlSer = new XmlSerializer(typeof(SendDocumentInteractiveOptions));
XmlWriter xw = new XmlTextWriter(#"g:\test.xml", null);
xmlSer.Serialize(xw, sdio);
xw.Close();
And here is the resulting XML
<?xml version="1.0"?&gt
&ltSendDocumentInteractiveOptions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
So what am I missing here. Why are my public properties not getting serialized?
This is kind of an old question, but oh well. I think the solution might be in another question "Why isn't my public property serialized by the XmlSerializer?". Part of the answer lists reasons why an attribute would not be serialized and in that list is
it has a public bool FooSpecified {get;set;} property that returned false
In your code, you set the various Boolean values but set the related specified values. I was facing a similar issue and setting the specified value fixed it for me.

Error in Binding Custom Textbox Property

I have created custom Textbox in Silverlight 4, MVVM and PRISM 4. The custom text box has dynamic behavior link it dynamically set TextMode to either Password or Text.
This is working perfect. ( if i am bind TextMode static)
<control:PasswordTextBox x:Name="customTextBox2" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}" TextMode="Password"/>
This is giving me an error (if i am binding with dynamic)
<control:PasswordTextBox x:Name="customTextBox1" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}" TextMode="{Binding WritingMode}"/>
following is my ViewModel code
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class UserRightsViewModel : NotificationObject, IRegionMemberLifetime
{
private Mode _writingMode = Mode.Text;
public Mode WritingMode
{
get { return _writingMode; }
set
{
_writingMode = value; RaisePropertyChanged("WritingMode");
}
}
[ImportingConstructor]
public UserRightsViewModel(IEventAggregator eventAggregator, IRegionManager regionManager)
{
UserSecurity security = new UserSecurity();
FormSecurity formSecurity = security.GetSecurityList("Admin");
formSecurity.WritingMode = Mode.Password;
}
}
following is the enum
namespace QSys.Library.Enums
{
public enum Mode
{
Text,
Password
}
}
following code for Custom PasswordTextBox
namespace QSys.Library.Controls
{
public partial class PasswordTextBox : TextBox
{
#region Variables
private string _Text = string.Empty;
private string _PasswordChar = "*";
private Mode _TextMode = Mode.Text;
#endregion
#region Properties
/// <summary>
/// The text associated with the control.
/// </summary>
public new string Text
{
get { return _Text; }
set
{
_Text = value;
DisplayMaskedCharacters();
}
}
/// <summary>
/// Indicates the character to display for password input.
/// </summary>
public string PasswordChar
{
get { return _PasswordChar; }
set { _PasswordChar = value; }
}
/// <summary>
/// Indicates the input text mode to display for either text or password.
/// </summary>
public Mode TextMode
{
get { return _TextMode; }
set { _TextMode = value; }
}
#endregion
#region Constructors
public PasswordTextBox()
{
this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
this.KeyDown += new System.Windows.Input.KeyEventHandler(PasswordTextBox_KeyDown);
this.Loaded += new RoutedEventHandler(PasswordTextBox_Loaded);
}
#endregion
#region Event Handlers
void PasswordTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
//this.TextChanged += ImmediateTextBox_TextChanged;
}
public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (base.Text.Length >= _Text.Length) _Text += base.Text.Substring(_Text.Length);
DisplayMaskedCharacters();
}
public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int cursorPosition = this.SelectionStart;
int selectionLength = this.SelectionLength;
// Handle Delete and Backspace Keys Appropriately
if (e.Key == System.Windows.Input.Key.Back || e.Key == System.Windows.Input.Key.Delete)
{
if (cursorPosition < _Text.Length)
_Text = _Text.Remove(cursorPosition, (selectionLength > 0 ? selectionLength : 1));
}
base.Text = _Text;
this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
DisplayMaskedCharacters();
}
#endregion
#region Private Methods
private void DisplayMaskedCharacters()
{
int cursorPosition = this.SelectionStart;
// This changes the Text property of the base TextBox class to display all Asterisks in the control
base.Text = new string(_PasswordChar.ToCharArray()[0], _Text.Length);
this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
}
#endregion
#region Public Methods
#endregion
}
}
I am getting following error if i am binding with dynamically.
Set property 'QSys.Library.Controls.PasswordTextBox.TextMode' threw an exception. [Line: 40 Position: 144]
Your answer would be appreciated.
Thanks in advance.
Imdadhusen
Try to change in your PasswordTextBox class
public Mode TextMode
{
get { return _TextMode; }
set { _TextMode = value; }
}
to
public static readonly DependencyProperty TextModeProperty =
DependencyProperty.Register("TextMode", typeof(Mode), typeof(PasswordTextBox), new PropertyMetadata(default(Mode)));
public Mode TextMode
{
get { return (Mode) GetValue(TextModeProperty); }
set { SetValue(TextModeProperty, value); }
}
You can read more here:
Dependency Properties Overview
DependencyProperty Class
The main paragraph from the second link is:
A DependencyProperty supports the following capabilities in Windows
Presentation Foundation (WPF):
....
The property can be set through data binding. For more information about data binding dependency properties, see How to: Bind the
Properties of Two Controls.
I provide links for WPF, but basically for Silverlight it's the same

Refactoring two basic classes

How would you refactor these two classes to abstract out the similarities? An abstract class? Simple inheritance? What would the refactored class(es) look like?
public class LanguageCode
{
/// <summary>
/// Get the lowercase two-character ISO 639-1 language code.
/// </summary>
public readonly string Value;
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language)
{
if (language == null)
{
return null;
}
if (language.Length > 2)
{
language = language.Substring(0, 2);
}
try
{
return new LanguageCode(language);
}
catch (ArgumentException)
{
return null;
}
}
}
public class RegionCode
{
/// <summary>
/// Get the uppercase two-character ISO 3166 region/country code.
/// </summary>
public readonly string Value;
public RegionCode(string region)
{
this.Value = new RegionInfo(region).TwoLetterISORegionName;
}
public static RegionCode TryParse(string region)
{
if (region == null)
{
return null;
}
if (region.Length > 2)
{
region = region.Substring(0, 2);
}
try
{
return new RegionCode(region);
}
catch (ArgumentException)
{
return null;
}
}
}
It depends, if they are not going to do much more, then I would probably leave them as is - IMHO factoring out stuff is likely to be more complex, in this case.
Unless you have a strong reason for refactoring (because you are going to add more classes like those in near future) the penalty of changing the design for such a small and contrived example would overcome the gain in maintenance or overhead in this scenario. Anyhow here is a possible design based on generic and lambda expressions.
public class TwoLetterCode<T>
{
private readonly string value;
public TwoLetterCode(string value, Func<string, string> predicate)
{
this.value = predicate(value);
}
public static T TryParse(string value, Func<string, T> predicate)
{
if (value == null)
{
return default(T);
}
if (value.Length > 2)
{
value = value.Substring(0, 2);
}
try
{
return predicate(value);
}
catch (ArgumentException)
{
return default(T);
}
}
public string Value { get { return this.value; } }
}
public class LanguageCode : TwoLetterCode<LanguageCode> {
public LanguageCode(string language)
: base(language, v => new CultureInfo(v).TwoLetterISOLanguageName)
{
}
public static LanguageCode TryParse(string language)
{
return TwoLetterCode<LanguageCode>.TryParse(language, v => new LanguageCode(v));
}
}
public class RegionCode : TwoLetterCode<RegionCode>
{
public RegionCode(string language)
: base(language, v => new CultureInfo(v).TwoLetterISORegionName)
{
}
public static RegionCode TryParse(string language)
{
return TwoLetterCode<RegionCode>.TryParse(language, v => new RegionCode(v));
}
}
This is a rather simple question and to me smells awefully like a homework assignment.
You can obviously see the common bits in the code and I'm pretty sure you can make an attempt at it yourself by putting such things into a super-class.
You could maybe combine them into a Locale class, which stores both Language code and Region code, has accessors for Region and Language plus one parse function which also allows for strings like "en_gb"...
That's how I've seen locales be handled in various frameworks.
These two, as they stand, aren't going to refactor well because of the static methods.
You'd either end up with some kind of factory method on a base class that returns an a type of that base class (which would subsequently need casting) or you'd need some kind of additional helper class.
Given the amount of extra code and subsequent casting to the appropriate type, it's not worth it.
Create a generic base class (eg AbstractCode<T>)
add abstract methods like
protected T GetConstructor(string code);
override in base classes like
protected override RegionCode GetConstructor(string code)
{
return new RegionCode(code);
}
Finally, do the same with string GetIsoName(string code), eg
protected override GetIsoName(string code)
{
return new RegionCode(code).TowLetterISORegionName;
}
That will refactor the both. Chris Kimpton does raise the important question as to whether the effort is worth it.
I'm sure there is a better generics based solution. But still gave it a shot.
EDIT: As the comment says, static methods can't be overridden so one option would be to retain it and use TwoLetterCode objects around and cast them, but, as some other person has already pointed out, that is rather useless.
How about this?
public class TwoLetterCode {
public readonly string Value;
public static TwoLetterCode TryParseSt(string tlc) {
if (tlc == null)
{
return null;
}
if (tlc.Length > 2)
{
tlc = tlc.Substring(0, 2);
}
try
{
return new TwoLetterCode(tlc);
}
catch (ArgumentException)
{
return null;
}
}
}
//Likewise for Region
public class LanguageCode : TwoLetterCode {
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language) {
return (LanguageCode)TwoLetterCode.TryParseSt(language);
}
}