Ошибка при создании документа xml

Здравствуйте, есть веб-сервис для доступа к БД, при попытке запустить метод LogPas() выдает ошибку

System.InvalidOperationException: Ошибка при создании документа XML. —> System.InvalidOperationException: Невозможно сериализовать System.Data.Common.DataRecordInternal, т.*к. он не имеет беспараметрического конструктора.

    [WebMethod]
    public ArrayList LogPas()
    {
        ArrayList allData = new ArrayList();  
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand com = new SqlCommand("SELECT *  FROM Student", con);

            con.Open();
            SqlDataReader dr = com.ExecuteReader();
            if (dr.HasRows)
            { foreach (DbDataRecord result in dr)         
                        allData.Add(result);

            return allData;
            }
        else return null;
   }

Deleted's user avatar

Deleted

3711 золотой знак5 серебряных знаков13 бронзовых знаков

задан 20 мая 2013 в 10:08

Verling's user avatar

Вам компилятор и так всё сказал. Передать объект с типом DataRecordInternal не получится, так как для сериализации требуется конструктор без параметров, коего нет у данного типа.
Самое простое решение — использовать другой класс.

ответ дан 20 мая 2013 в 10:13

Spawn's user avatar

SpawnSpawn

2,50811 серебряных знаков20 бронзовых знаков

7

DCNick3

4 / 4 / 6

Регистрация: 03.05.2014

Сообщений: 101

1

01.06.2015, 00:08. Показов 6770. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Пытаюсь сериализировать — Фиг

Exception

Необработанное исключение типа «System.InvalidOperationException» в System.Xml.dll

Дополнительные сведения: Ошибка при создании документа XML.

Привожу классы:

Class’ы

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
[Serializable()]
    public class Scene
    {
        public static Scene Load(string file)
        {
            Stream loadStream = File.Open(file, FileMode.Open);
            XmlSerializer serializer = new XmlSerializer(typeof(Scene));
            return (Scene)serializer.Deserialize(loadStream);
        }
 
        internal static void Save(string file, Scene obj)
        {
            Stream saveStream = File.Open(file, FileMode.Create);
            XmlSerializer serializer = new XmlSerializer(typeof(Scene));
            serializer.Serialize(saveStream, obj);
        }
 
        public void Draw(SpriteBatch spriteBatch)
        {
            foreach (var element in elements)
                element.Draw(spriteBatch);
        }
 
        public SceneElement[] elements = new SceneElement[] { };
    }
 
    [Serializable()]
    public abstract class SceneElement
    {
        public int posX;
        public int posY;
        public bool isDrawOriginInCenter;
        public Color color;
        public float rotation;
 
        public abstract void Draw(SpriteBatch spriteBatch);
    }
 
    [Serializable()]
    public class SceneElementImage : SceneElement
    {
        public string texture;
        public int targetHeight;
        public int targetWidth;
 
        public override void Draw(SpriteBatch spriteBatch)
        {
            Texture2D ttexture = ContentRegistry.textureRegistry[texture];
            Vector2 origin = Vector2.Zero;
            if (isDrawOriginInCenter)
                origin = new Vector2(targetWidth, targetHeight) / 2.0F;
 
            spriteBatch.Draw(ttexture, new Rectangle(posX, posY, targetWidth, targetHeight), null, color, rotation, origin, SpriteEffects.None, 0);
        }
    }
 
    [Serializable()]
    public class SceneElementLabel : SceneElement
    {
        public string text;
        public string font;
        
 
        public override void Draw(SpriteBatch spriteBatch)
        {
            SpriteFont sFont = ContentRegistry.spriteFontRegistry[font];
            Vector2 origin = Vector2.Zero;
            if (isDrawOriginInCenter)
                origin = sFont.MeasureString(text) / 2.0F;
 
            spriteBatch.DrawString(sFont, text, new Vector2(posX, posY), color, rotation, origin, 1, SpriteEffects.None, 0);
        }
    }

Может проблема в абстрактах… Кароч выручайте, как можно изменить.
На эти классы сильно ничего не завязано, т.ч. можно менять (без потери возможностей).
Вот.

P.S. BinaryFormatter не пойдёт, ибо фалы человеки писать будут (в основном будем их читать)



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

01.06.2015, 00:08

Ответы с готовыми решениями:

Сериализация в Xml в С#
Доброе всем время суток! Нужна помощь по сериализации.
Есть несколько проблем:
1) при попытке…

XML сериализация
Добрый день!

1. Как при сериализации

XmlSerializer xmlSerializer = new…

Сериализация в xml
Имеется несколько классов следующего вида (схематично):
public class A
{
public List<B> b =…

XML сериализация списка
По какой схеме нужно сериализовать однонаправленный упорядоченный список? Просмотр всех элементов,…

2

Someone007

Эксперт .NET

6403 / 3940 / 1578

Регистрация: 09.05.2015

Сообщений: 9,241

01.06.2015, 04:33

2

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    [Serializable]
    public class Scene
    {
        public static Scene Load(string file)
        {
            using (Stream loadStream = File.Open(file, FileMode.Open))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Scene));
                return (Scene)serializer.Deserialize(loadStream);
            }
        }
 
        internal static void Save(string file, Scene obj)
        {
            using (Stream saveStream = File.Open(file, FileMode.Create))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Scene));
                serializer.Serialize(saveStream, obj);
            }
        }
 
        public void Draw(SpriteBatch spriteBatch)
        {
            foreach (var element in elements)
                element.Draw(spriteBatch);
        }
 
        public List<SceneElement> elements = new List<SceneElement>();
    }
 
    [Serializable]
    [XmlInclude(typeof(SceneElementImage))]
    [XmlInclude(typeof(SceneElementLabel))]
    public abstract class SceneElement
    {
        public int posX;
        public int posY;
        public bool isDrawOriginInCenter;
        public Color color;
        public float rotation;
 
        public abstract void Draw(SpriteBatch spriteBatch);
    }
 
    [Serializable]
    public class SceneElementImage : SceneElement
    {
        public string texture;
        public int targetHeight;
        public int targetWidth;
 
        public override void Draw(SpriteBatch spriteBatch)
        {
            Texture2D ttexture = ContentRegistry.textureRegistry[texture];
            Vector2 origin = Vector2.Zero;
            if (isDrawOriginInCenter)
                origin = new Vector2(targetWidth, targetHeight) / 2.0F;
 
            spriteBatch.Draw(ttexture, new Rectangle(posX, posY, targetWidth, targetHeight), null, color, rotation, origin, SpriteEffects.None, 0);
        }
    }
 
    [Serializable]
    public class SceneElementLabel : SceneElement
    {
        public string text;
        public string font;
 
        public override void Draw(SpriteBatch spriteBatch)
        {
            SpriteFont sFont = ContentRegistry.spriteFontRegistry[font];
            Vector2 origin = Vector2.Zero;
            if (isDrawOriginInCenter)
                origin = sFont.MeasureString(text) / 2.0F;
 
            spriteBatch.DrawString(sFont, text, new Vector2(posX, posY), color, rotation, origin, 1, SpriteEffects.None, 0);
        }
    }
C#
1
2
3
4
5
6
7
8
                Scene s = new Scene();
 
                s.elements.Add(new SceneElementImage());
                s.elements.Add(new SceneElementLabel());
 
                Scene.Save("test.scene", s);
 
                var s2 = Scene.Load("test.scene");



0



DCNick3

4 / 4 / 6

Регистрация: 03.05.2014

Сообщений: 101

01.06.2015, 21:58

 [ТС]

3

Сериализую так:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
            SceneElementLabel label = new SceneElementLabel();
            label.text = "Загрузка ...";
            label.posX = 960;
            label.posY = 720;
            label.isDrawOriginInCenter = true;
            label.font = "verdana48";
            label.color = Color.White;
            loadingScene.elements.Add(label);
            Scene.Save("loadingScene.xml", loadingScene);
 
 
            //Где-то ранее
            Scene loadingScene = new Scene();

Добавлено через 3 минуты
Таааак! Раздобыл еще сведений об исключении:

More DATA

System.InvalidOperationException не обработано
HResult=-2146233079
Message=Ошибка при создании документа XML.
Source=System.Xml
StackTrace:
в System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
в System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
в System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
в MyVisualNovelLanguage.Scene.Save(String file, Scene obj) в C:UsersНикитаdocumentsvisual studio 2015ProjectsMVNLMVNLMVNLMVNLScene.cs:строка 26
в MyVisualNovelLanguage.Game1.Initialize() в C:UsersНикитаdocumentsvisual studio 2015ProjectsMVNLMVNLMVNLMVNLGame1.cs:строка 137
в Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
в Microsoft.Xna.Framework.Game.Run()
в MyVisualNovelLanguage.Program.Main(String[] args) в C:UsersНикитаdocumentsvisual studio 2015ProjectsMVNLMVNLMVNLMVNLProgram.cs:строка 20
InnerException:
HResult=-2146233079
Message=Тип MyVisualNovelLanguage.SceneElementLabel не ожидался. Используйте атрибут XmlInclude или SoapInclude для задания типов, которые не известны как статические.
Source=Microsoft.GeneratedCode
StackTrace:
в Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterScene.Write3 _SceneElement(String n, String ns, SceneElement o, Boolean isNullable, Boolean needType)
в Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterScene.Write4 _Scene(String n, String ns, Scene o, Boolean isNullable, Boolean needType)
в Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterScene.Write5 _Scene(Object o)
InnerException:

Добавлено через 15 минут
РЕШЕНО:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
[Serializable(), XmlInclude(typeof(SceneElementLabel)), XmlInclude(typeof(SceneElementImage))]
    public class Scene
    {
        public Scene() { }
 
        public static Scene Load(string file)
        {
            Stream loadStream = File.Open(file, FileMode.Open);
            XmlSerializer serializer = new XmlSerializer(typeof(Scene));
            return (Scene)serializer.Deserialize(loadStream);
        }
 
        internal static void Save(string file, Scene obj)
        {
            StreamWriter saveStream = new StreamWriter("scene.xml", false);
            XmlSerializer serializer = new XmlSerializer(typeof(Scene));
            serializer.Serialize(saveStream, obj);
        }
 
        public void Draw(SpriteBatch spriteBatch)
        {
            foreach (var element in elements)
                element.Draw(spriteBatch);
        }
 
        public List<SceneElement> elements = new List<SceneElement>();
    }
 
    [Serializable()]
    public abstract class SceneElement
    {
        public SceneElement() { }
        public int posX;
        public int posY;
        public bool isDrawOriginInCenter;
        public Color color;
        public float rotation;
 
        public abstract void Draw(SpriteBatch spriteBatch);
    }
 
    [Serializable()]
    public class SceneElementImage : SceneElement
    {
        public SceneElementImage() { }
        public string texture;
        public int targetHeight;
        public int targetWidth;
 
        public override void Draw(SpriteBatch spriteBatch)
        {
            Texture2D ttexture = ContentRegistry.textureRegistry[texture];
            Vector2 origin = Vector2.Zero;
            if (isDrawOriginInCenter)
                origin = new Vector2(targetWidth, targetHeight) / 2.0F;
 
            spriteBatch.Draw(ttexture, new Rectangle(posX, posY, targetWidth, targetHeight), null, color, rotation, origin, SpriteEffects.None, 0);
        }
    }
 
    [Serializable()]
    public class SceneElementLabel : SceneElement
    {
        public SceneElementLabel() { }
        public string text;
        public string font;
        
 
        public override void Draw(SpriteBatch spriteBatch)
        {
            SpriteFont sFont = ContentRegistry.spriteFontRegistry[font];
            Vector2 origin = Vector2.Zero;
            if (isDrawOriginInCenter)
                origin = sFont.MeasureString(text) / 2.0F;
 
            spriteBatch.DrawString(sFont, text, new Vector2(posX, posY), color, rotation, origin, 1, SpriteEffects.None, 0);
        }
    }



1



hi i have the following code to perform xml serialization:

private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            string savepath;
            SaveFileDialog DialogSave = new SaveFileDialog();
            // Default file extension
            DialogSave.DefaultExt = "txt";
            // Available file extensions
            DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
            // Adds a extension if the user does not
            DialogSave.AddExtension = true;
            // Restores the selected directory, next time
            DialogSave.RestoreDirectory = true;
            // Dialog title
            DialogSave.Title = "Where do you want to save the file?";
            // Startup directory
            DialogSave.InitialDirectory = @"C:/";
            DialogSave.ShowDialog();
            savepath = DialogSave.FileName;
            DialogSave.Dispose();
            DialogSave = null;

            FormSaving abc = new FormSaving();
            if (MajorversionresultLabel != null && MajorversionresultLabel.Content != null && MajorversionLabel.Content.ToString() != string.Empty)
            abc.Majorversion = MajorversionresultLabel.Content.ToString();
            //abc.Minorversion = MinorversionresultLabel.Content.ToString();
            //abc.Projectnumber = ProjectnumberresultLabel.Content.ToString();
            //abc.Buildnumber = BuildnumberresultLabel.Content.ToString();
            //abc.Previousbuildversion = PreviousbuildversionresultLabel.Content.ToString();
            abc.Startzbuildfrom = StartzbuildfromcomboBox.SelectedItem;

            using (Stream savestream = new FileStream(savepath, FileMode.Create))
            {

                    XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
                    serializer.Serialize(savestream, abc);
            }



        }

the error «There was an error generating the XML document» occurs at serializer.Serialize(savestream, abc);

my form saving class:

public class FormSaving
        {

            public string Majorversion
            {
                get;

                set;

            }
            public string Minorversion
            {
                get;

                set;

            }
            public string Projectnumber
            {
                get;

                set;

            }
            public string Buildnumber
            {
                get;

                set;

            }
            public string Previousbuildversion
            {
                get;

                set;

            }
            public object Startzbuildfrom
            {
                get;

                set;
            }
    }

can anyone help me fix this?

EDIT:

i tried this but it doesnt work as well:

under «save button»

abc.Startzbuildfrom = StartzbuildfromcomboBox.SelectedItem.ToString();

under «load button»

StartzbuildfromcomboBox.SelectedItem = abc.Startzbuildfrom;

here is how i populate my combobox items:

<ComboBox Height="23" Margin="577,72,497,0" Name="StartzbuildfromcomboBox" VerticalAlignment="Top"><ComboBoxItem>library</ComboBoxItem></ComboBox>

Error:

TITLE: SQL Server Setup failure.
------------------------------

SQL Server Setup has encountered the following error:

There was an error generating the XML document.

Error code 0x84B10001.

For help, click: http://go.microsoft.com/fwlink?LinkID=20476&ProdName=Microsoft%20SQL%20Server&EvtSrc=setup.rll&EvtID=50000&EvtType=0xE0C083E6%25400xB2215DAC

C:Program FilesMicrosoft SQL Server100Setup BootstrapLogSummary.txt

Exception summary:
The following is an exception stack listing the exceptions in outermost to innermost order
Inner exceptions are being indented

Exception type: Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException
Message: 
There was an error generating the XML document.
HResult : 0x84b10001
FacilityCode : 1201 (4b1)
ErrorCode : 1 (0001)
Data: 
HelpLink.EvtType = 0xE0C083E6@0xB2215DAC
DisableWatson = true
Stack: 
at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.FlushCache(Boolean removeAllCachedObj)
at Microsoft.SqlServer.Configuration.InstallWizard.SummaryController.SaveData()
at Microsoft.SqlServer.Configuration.InstallWizardFramework.InstallWizardPageHost.PageLeaving(PageChangeReason reason)
at Microsoft.SqlServer.Configuration.WizardFramework.UIHost.set_SelectedPageIndex(Int32 value)
at Microsoft.SqlServer.Configuration.WizardFramework.NavigationButtons.nextButton_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Inner exception type: System.InvalidOperationException
Message: 
There was an error generating the XML document.
HResult : 0x80131509
Stack: 
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
Inner exception type: System.Security.Cryptography.CryptographicException
Message: 
The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.

HResult : 0x80090345
Stack: 
at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData, Byte[] optionalEntropy, DataProtectionScope scope)
at Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)
at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterSqlEngineSetupPublic.Write7_SqlEngineSetupPublic(String n, String ns, SqlEngineSetupPublic o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterSqlEngineSetupPublic.Write8_SqlEngineSetupPublic(Object o)

If we look at the start place of the error, it says System.Security.Cryptography.CryptographicException. This means that there are some issues while encryption of the data. And the real error message is “The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.”

When I searched with above two, then I found that this can happen when there is Read Only Domain Controller (RODC).

WORKAROUND/SOLUTION

To solve this, we created the registry entry DWORD “ProtectionPolicy” and set to 1 to enable local backup of the MasterKey instead of requiring a RWDC in the following registry subkey:

HKEY_LOCAL_MACHINESoftwareMicrosoftCryptographyProtectProvidersdf9d8cd0-1501-11d1-8c7a-00c04fc297eb

We need to create the following key:

  • Path : HKLMSoftwareMicrosoftCryptographyProtectProvidersdf9d8cd0-1501-11d1-8c7a-00c04fc297eb
  • Name: ProtectionPolicy
  • Value : 1 (DWORD and Hexadecimal)

Setting this value to 1 causes DPAPI master keys to be backed up locally rather than using a domain backup. For more information about DPAPI you can read https://support.microsoft.com/en-us/kb/309408

This workaround is documented in https://support.microsoft.com/en-in/help/3000850/november-2014-update-rollup-for-windows-rt-8.1,-windows-8.1,-and-windows-server-2012-r2

Sources:

https://support.microsoft.com/en-in/help/3000850/november-2014-update-rollup-for-windows-rt-8-1-windows-8-1-and-windows

SQL Server Setup has encountered the following error:
There was an error generating the XML document.
Error code 0x84B10001.

Error Code 0x84B10001, 0x84B10001 sql server 2008, 0x84B10001 sql server 2008 r2, 0x84B10001 sql server 2012, 0x84B10001 sql server 2014, 0x84B10001 sql server 2016, 0x84B10001 sql server 2017

This issue occurs when SQL Server(2008,  2012, 2014, 2016, 2017) Setup fails.

Cause of this Error:

There are many possible scenarios that may initiate this issue. For example, a failure of a previous installation of SQL server may corrupt the registry, and this registry corruption may initiate this issue.

Solution-1:

From Control Panel, uninstall existing Microsoft SQL Server Setup installation and start again with fresh installation.

Solution-2:

1. Create a new windows user on your machine and add this user to local Administrator group.

2. Log in with new user and start the SQL Server installation again.

На этой неделе мы обсудим одно из самых распространенных сообщений об ошибках, которые мы получаем при установке SQL Server 2008 R2 в системах Windows . Это пятая статья серии «Устранение неполадок SQL», которую мы начали несколько недель назад В последние пару недель мы обсуждали различные сообщения об ошибках при установке SQL. На этой неделе мы обсудим большинство распространенных ошибок; «Системе конфигурации не удалось инициализировать 0x84B10001».

Системе конфигурации не удалось инициализировать 0x84B10001

Когда я впервые получил эту ошибку, мне пришлось провести много исследований, чтобы выяснить причину. После долгих поисков выяснилось, что эта ошибка происходит из-за Microsoft .NET.

В папке C: Windows Microsoft.NET Framework64 v2.0.50727 CONFIG находится файл machine.config , вызывающий эту ошибку.

Файл Machine. config содержит параметры, которые применяются ко всему компьютеру. Этот файл находится в каталоге C: Windows Microsoft.NET Framework64 v2.0.50727 CONFIG . Machine.config содержит параметры конфигурации для привязки сборки на уровне машины, встроенных каналов удаленного взаимодействия и ASP.NET. Система конфигурации сначала просматривает файл конфигурации машины и другие разделы конфигурации, когда может позвонить разработчик. Этот файл содержит, помимо многих других элементов XML, элемент browserCaps . Внутри этого элемента находится ряд других элементов, которые определяют правила синтаксического анализа для различных пользовательских агентов и какие свойства поддерживает каждый из этих синтаксических анализаторов.

Чтобы исправить эту ошибку, мы должны изменить файл Machine.config. Нам нужно удалить раздел конфигурации, который содержит все элементы конфигурации Windows Communication Foundation (WCF) ServiceModel . Я все еще не понимаю, почему нам нужно удалить этот раздел, чтобы это сообщение об ошибке исчезло.

Есть два метода, которые вы можете попытаться решить эту проблему.

Метод первый

В этом методе мы изменим файл Machine.config.

  • Перейдите в C: Windows Microsoft.NET Framework64 v2.0.50727 CONFIG .
  • Найдите файл Machine.config и создайте копию этого файла в качестве резервной копии.
  • Щелкните правой кнопкой мыши файл Machine.config и выберите команду «Изменить» (лучше всего использовать Notepad ++ для изменения этого файла).
  • Найдите следующий раздел (найдите )

  • Удалите всю конфигурацию, т. Е. С на
  • Сохраните файл Machine.config .

Теперь попробуйте установить Microsoft SQL Server 2008 R2 и посмотреть, если вы получаете ту же ошибку.

Метод второй

В этом методе вы можете попытаться загрузить последний серверный пакет Microsoft SQL Server 2008 R2 и попытаться установить его. Потому что, по мнению Microsoft, эта ошибка исправлена ​​в пакете обновления 1 (SP1) для Microsoft SQL Server 2008 R2. Но я не уверен, сколько случаев это действительно решило проблему, поэтому я упомянул первый метод.

Эти методы должны помочь вам в устранении этой ошибки.

So i have been trying to install SQL Server 2012 Express edition But it give me an error code 0x84B10001 Error generating XML Document, This error pops up as it starts the process «ConfigEvent_SQL_WRITER_sqlwriter_Cpu64_Install_GetDefaultConfig_validation»
 a few seconds into installation.

Going through many forums i haven’t found anything that helped me solve this, 

Having Gone through numerous forums to try and solve this, i saw that a lot of people refereed to the to the summary log file to find the exact issue. 

Below is the Summary for the latest log file. 

I Hope this is enough information.

Overall summary:
  Final result:                  Failed: see details below
  Exit code (Decimal):           -2068774911
  Exit facility code:            1201
  Exit error code:               1
  Exit message:                  There was an error generating the XML document.
  Start time:                    2017-04-25 08:00:21
  End time:                      2017-04-25 08:04:14
  Requested action:              Install
  Exception help link:           http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3128.0&EvtType=0xE0C083E6%400xB2215DAC&EvtType=0xE0C083E6%400xB2215DAC

Setup completed with required actions for features.
Troubleshooting information for those features:
  Next step for SQLEngine:       SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for Replication:     SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for SNAC:            SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for SNAC_SDK:        SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for Writer:          SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for Browser:         SQL Server Setup was canceled before completing the operation. Try the setup process again.

Machine Properties:
  Machine name:                  DESKTOP-RAKCKMR
  Machine processor count:       8
  OS version:                    Future Windows Version
  OS service pack:               
  OS region:                     United States
  OS language:                   English (United Kingdom)
  OS architecture:               x64
  Process architecture:          64 Bit
  OS clustered:                  No

Product features discovered:
  Product              Instance             Instance ID                    Feature                
                 Language             Edition              Version         Clustered 

Package properties:
  Description:                   Microsoft SQL Server 2012 Service Pack 1
  ProductName:                   SQL Server 2012
  Type:                          RTM
  Version:                       11
  SPLevel:                       0
  Installation location:         c:cadbbb88a0c1ab687c313ex64setup
  Installation edition:          Express

Product Update Status:
  None discovered.

User Input Settings:
  ACTION:                        Install
  ADDCURRENTUSERASSQLADMIN:      true
  AGTSVCACCOUNT:                 NT AUTHORITYNETWORK SERVICE
  AGTSVCPASSWORD:                *****
  AGTSVCSTARTUPTYPE:             Disabled
  ASBACKUPDIR:                   Backup
  ASCOLLATION:                   Latin1_General_CI_AS
  ASCONFIGDIR:                   Config
  ASDATADIR:                     Data
  ASLOGDIR:                      Log
  ASPROVIDERMSOLAP:              1
  ASSERVERMODE:                  MULTIDIMENSIONAL
  ASSVCACCOUNT:                  <empty>
  ASSVCPASSWORD:                 <empty>
  ASSVCSTARTUPTYPE:              Automatic
  ASSYSADMINACCOUNTS:            <empty>
  ASTEMPDIR:                     Temp
  BROWSERSVCSTARTUPTYPE:         Automatic
  CLTCTLRNAME:                   <empty>
  CLTRESULTDIR:                  <empty>
  CLTSTARTUPTYPE:                0
  CLTSVCACCOUNT:                 <empty>
  CLTSVCPASSWORD:                <empty>
  CLTWORKINGDIR:                 <empty>
  COMMFABRICENCRYPTION:          0
  COMMFABRICNETWORKLEVEL:        0
  COMMFABRICPORT:                0
  CONFIGURATIONFILE:             
  CTLRSTARTUPTYPE:               0
  CTLRSVCACCOUNT:                <empty>
  CTLRSVCPASSWORD:               <empty>
  CTLRUSERS:                     <empty>
  ENABLERANU:                    true
  ENU:                           true
  ERRORREPORTING:                false
  FEATURES:                      SQLENGINE, REPLICATION, SNAC_SDK
  FILESTREAMLEVEL:               0
  FILESTREAMSHARENAME:           <empty>
  FTSVCACCOUNT:                  <empty>
  FTSVCPASSWORD:                 <empty>
  HELP:                          false
  IACCEPTSQLSERVERLICENSETERMS:  true
  INDICATEPROGRESS:              false
  INSTALLSHAREDDIR:              C:Program FilesMicrosoft SQL Server
  INSTALLSHAREDWOWDIR:           C:Program Files (x86)Microsoft SQL Server
  INSTALLSQLDATADIR:             <empty>
  INSTANCEDIR:                   C:Program FilesMicrosoft SQL Server
  INSTANCEID:                    SHIPWEIGHT
  INSTANCENAME:                  SHIPWEIGHT
  ISSVCACCOUNT:                  NT AUTHORITYNetwork Service
  ISSVCPASSWORD:                 <empty>
  ISSVCSTARTUPTYPE:              Automatic
  MATRIXCMBRICKCOMMPORT:         0
  MATRIXCMSERVERNAME:            <empty>
  MATRIXNAME:                    <empty>
  NPENABLED:                     0
  PID:                           *****
  QUIET:                         false
  QUIETSIMPLE:                   false
  ROLE:                          AllFeatures_WithDefaults
  RSINSTALLMODE:                 DefaultNativeMode
  RSSHPINSTALLMODE:              DefaultSharePointMode
  RSSVCACCOUNT:                  <empty>
  RSSVCPASSWORD:                 <empty>
  RSSVCSTARTUPTYPE:              Automatic
  SAPWD:                         <empty>
  SECURITYMODE:                  <empty>
  SQLBACKUPDIR:                  <empty>
  SQLCOLLATION:                  Latin1_General_CI_AS
  SQLSVCACCOUNT:                 NT ServiceMSSQL$SHIPWEIGHT
  SQLSVCPASSWORD:                <empty>
  SQLSVCSTARTUPTYPE:             Automatic
  SQLSYSADMINACCOUNTS:           SIGMAjoshua
  SQLTEMPDBDIR:                  <empty>
  SQLTEMPDBLOGDIR:               <empty>
  SQLUSERDBDIR:                  <empty>
  SQLUSERDBLOGDIR:               <empty>
  SQMREPORTING:                  false
  TCPENABLED:                    0
  UIMODE:                        AutoAdvance
  UpdateEnabled:                 true
  UpdateSource:                  MU
  X86:                           false

  Configuration file:            C:Program FilesMicrosoft SQL Server110Setup BootstrapLog20170425_075926ConfigurationFile.ini

Detailed results:
  Feature:                       Database Engine Services
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Server Replication
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Client Connectivity
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Client Connectivity SDK
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Writer
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Browser
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

Rules with failures:

Global rules:

Scenario specific rules:

Rules report file:               C:Program FilesMicrosoft SQL Server110Setup BootstrapLog20170425_075926SystemConfigurationCheck_Report.htm

Exception summary:
The following is an exception stack listing the exceptions in outermost to innermost order
Inner exceptions are being indented

Exception type: Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException
    Message: 
        There was an error generating the XML document.
    HResult : 0x84b10001
        FacilityCode : 1201 (4b1)
        ErrorCode : 1 (0001)
    Data: 
      HelpLink.EvtType = 0xE0C083E6@0xB2215DAC
      DisableWatson = true
    Stack: 
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.FlushCache(Boolean removeAllCachedObj)
        at Microsoft.SqlServer.Configuration.SetupExtension.DatastoreCacheFeatureConfigEventHandler.InConfigurationActionExecutionEventHandler(Object sender, FeatureConfigScenarioEventArgs eventArgs)
        at Microsoft.SqlServer.Chainer.Infrastructure.NotificationHandler.Invoke(Object notification, Object[] objectArray)
        at Microsoft.SqlServer.Configuration.ConfigExtension.ConfigFeatureActionListener.InConfigurationActionExecutionEventHandler(ActionKey key, TextWriter loggingStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionMetadata.NotifyInExecution(ActionKey actionRunning, TextWriter loggingStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.InvokeAction(WorkflowObject metabase, TextWriter statusStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.PendingActions.InvokeActions(WorkflowObject metaDb, TextWriter loggingStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionEngine.RunActionQueue()
        at Microsoft.SqlServer.Chainer.TimingConfigAction.Execute(String actionId, TextWriter errorStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.ExecuteActionHelper(TextWriter statusStream, ISequencedAction actionToRun, ServiceContainer context)
    Inner exception type: System.InvalidOperationException
        Message: 
                There was an error generating the XML document.
        HResult : 0x80131509
        Stack: 
                at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
                at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
                at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        Inner exception type: System.Security.Cryptography.CryptographicException
            Message: 
                        The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.

                        
            HResult : 0x80090345
            Stack: 
                        at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData, Byte[] optionalEntropy, DataProtectionScope scope)
                        at Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)
                        at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write6_AgentConfigurationPublic(String n, String ns, AgentConfigurationPublic
o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write7_AgentConfigurationPublic(Object o)

So i have been trying to install SQL Server 2012 Express edition But it give me an error code 0x84B10001 Error generating XML Document, This error pops up as it starts the process «ConfigEvent_SQL_WRITER_sqlwriter_Cpu64_Install_GetDefaultConfig_validation»
 a few seconds into installation.

Going through many forums i haven’t found anything that helped me solve this, 

Having Gone through numerous forums to try and solve this, i saw that a lot of people refereed to the to the summary log file to find the exact issue. 

Below is the Summary for the latest log file. 

I Hope this is enough information.

Overall summary:
  Final result:                  Failed: see details below
  Exit code (Decimal):           -2068774911
  Exit facility code:            1201
  Exit error code:               1
  Exit message:                  There was an error generating the XML document.
  Start time:                    2017-04-25 08:00:21
  End time:                      2017-04-25 08:04:14
  Requested action:              Install
  Exception help link:           http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3128.0&EvtType=0xE0C083E6%400xB2215DAC&EvtType=0xE0C083E6%400xB2215DAC

Setup completed with required actions for features.
Troubleshooting information for those features:
  Next step for SQLEngine:       SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for Replication:     SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for SNAC:            SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for SNAC_SDK:        SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for Writer:          SQL Server Setup was canceled before completing the operation. Try the setup process again.
  Next step for Browser:         SQL Server Setup was canceled before completing the operation. Try the setup process again.

Machine Properties:
  Machine name:                  DESKTOP-RAKCKMR
  Machine processor count:       8
  OS version:                    Future Windows Version
  OS service pack:               
  OS region:                     United States
  OS language:                   English (United Kingdom)
  OS architecture:               x64
  Process architecture:          64 Bit
  OS clustered:                  No

Product features discovered:
  Product              Instance             Instance ID                    Feature                
                 Language             Edition              Version         Clustered 

Package properties:
  Description:                   Microsoft SQL Server 2012 Service Pack 1
  ProductName:                   SQL Server 2012
  Type:                          RTM
  Version:                       11
  SPLevel:                       0
  Installation location:         c:cadbbb88a0c1ab687c313ex64setup
  Installation edition:          Express

Product Update Status:
  None discovered.

User Input Settings:
  ACTION:                        Install
  ADDCURRENTUSERASSQLADMIN:      true
  AGTSVCACCOUNT:                 NT AUTHORITYNETWORK SERVICE
  AGTSVCPASSWORD:                *****
  AGTSVCSTARTUPTYPE:             Disabled
  ASBACKUPDIR:                   Backup
  ASCOLLATION:                   Latin1_General_CI_AS
  ASCONFIGDIR:                   Config
  ASDATADIR:                     Data
  ASLOGDIR:                      Log
  ASPROVIDERMSOLAP:              1
  ASSERVERMODE:                  MULTIDIMENSIONAL
  ASSVCACCOUNT:                  <empty>
  ASSVCPASSWORD:                 <empty>
  ASSVCSTARTUPTYPE:              Automatic
  ASSYSADMINACCOUNTS:            <empty>
  ASTEMPDIR:                     Temp
  BROWSERSVCSTARTUPTYPE:         Automatic
  CLTCTLRNAME:                   <empty>
  CLTRESULTDIR:                  <empty>
  CLTSTARTUPTYPE:                0
  CLTSVCACCOUNT:                 <empty>
  CLTSVCPASSWORD:                <empty>
  CLTWORKINGDIR:                 <empty>
  COMMFABRICENCRYPTION:          0
  COMMFABRICNETWORKLEVEL:        0
  COMMFABRICPORT:                0
  CONFIGURATIONFILE:             
  CTLRSTARTUPTYPE:               0
  CTLRSVCACCOUNT:                <empty>
  CTLRSVCPASSWORD:               <empty>
  CTLRUSERS:                     <empty>
  ENABLERANU:                    true
  ENU:                           true
  ERRORREPORTING:                false
  FEATURES:                      SQLENGINE, REPLICATION, SNAC_SDK
  FILESTREAMLEVEL:               0
  FILESTREAMSHARENAME:           <empty>
  FTSVCACCOUNT:                  <empty>
  FTSVCPASSWORD:                 <empty>
  HELP:                          false
  IACCEPTSQLSERVERLICENSETERMS:  true
  INDICATEPROGRESS:              false
  INSTALLSHAREDDIR:              C:Program FilesMicrosoft SQL Server
  INSTALLSHAREDWOWDIR:           C:Program Files (x86)Microsoft SQL Server
  INSTALLSQLDATADIR:             <empty>
  INSTANCEDIR:                   C:Program FilesMicrosoft SQL Server
  INSTANCEID:                    SHIPWEIGHT
  INSTANCENAME:                  SHIPWEIGHT
  ISSVCACCOUNT:                  NT AUTHORITYNetwork Service
  ISSVCPASSWORD:                 <empty>
  ISSVCSTARTUPTYPE:              Automatic
  MATRIXCMBRICKCOMMPORT:         0
  MATRIXCMSERVERNAME:            <empty>
  MATRIXNAME:                    <empty>
  NPENABLED:                     0
  PID:                           *****
  QUIET:                         false
  QUIETSIMPLE:                   false
  ROLE:                          AllFeatures_WithDefaults
  RSINSTALLMODE:                 DefaultNativeMode
  RSSHPINSTALLMODE:              DefaultSharePointMode
  RSSVCACCOUNT:                  <empty>
  RSSVCPASSWORD:                 <empty>
  RSSVCSTARTUPTYPE:              Automatic
  SAPWD:                         <empty>
  SECURITYMODE:                  <empty>
  SQLBACKUPDIR:                  <empty>
  SQLCOLLATION:                  Latin1_General_CI_AS
  SQLSVCACCOUNT:                 NT ServiceMSSQL$SHIPWEIGHT
  SQLSVCPASSWORD:                <empty>
  SQLSVCSTARTUPTYPE:             Automatic
  SQLSYSADMINACCOUNTS:           SIGMAjoshua
  SQLTEMPDBDIR:                  <empty>
  SQLTEMPDBLOGDIR:               <empty>
  SQLUSERDBDIR:                  <empty>
  SQLUSERDBLOGDIR:               <empty>
  SQMREPORTING:                  false
  TCPENABLED:                    0
  UIMODE:                        AutoAdvance
  UpdateEnabled:                 true
  UpdateSource:                  MU
  X86:                           false

  Configuration file:            C:Program FilesMicrosoft SQL Server110Setup BootstrapLog20170425_075926ConfigurationFile.ini

Detailed results:
  Feature:                       Database Engine Services
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Server Replication
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Client Connectivity
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Client Connectivity SDK
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Writer
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

  Feature:                       SQL Browser
  Status:                        Failed: see logs for details
  Reason for failure:            Setup was canceled for the feature.
  Next Step:                     SQL Server Setup was canceled before completing the operation. Try the setup process again.

Rules with failures:

Global rules:

Scenario specific rules:

Rules report file:               C:Program FilesMicrosoft SQL Server110Setup BootstrapLog20170425_075926SystemConfigurationCheck_Report.htm

Exception summary:
The following is an exception stack listing the exceptions in outermost to innermost order
Inner exceptions are being indented

Exception type: Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException
    Message: 
        There was an error generating the XML document.
    HResult : 0x84b10001
        FacilityCode : 1201 (4b1)
        ErrorCode : 1 (0001)
    Data: 
      HelpLink.EvtType = 0xE0C083E6@0xB2215DAC
      DisableWatson = true
    Stack: 
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.FlushCache(Boolean removeAllCachedObj)
        at Microsoft.SqlServer.Configuration.SetupExtension.DatastoreCacheFeatureConfigEventHandler.InConfigurationActionExecutionEventHandler(Object sender, FeatureConfigScenarioEventArgs eventArgs)
        at Microsoft.SqlServer.Chainer.Infrastructure.NotificationHandler.Invoke(Object notification, Object[] objectArray)
        at Microsoft.SqlServer.Configuration.ConfigExtension.ConfigFeatureActionListener.InConfigurationActionExecutionEventHandler(ActionKey key, TextWriter loggingStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionMetadata.NotifyInExecution(ActionKey actionRunning, TextWriter loggingStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.InvokeAction(WorkflowObject metabase, TextWriter statusStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.PendingActions.InvokeActions(WorkflowObject metaDb, TextWriter loggingStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionEngine.RunActionQueue()
        at Microsoft.SqlServer.Chainer.TimingConfigAction.Execute(String actionId, TextWriter errorStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.ExecuteActionHelper(TextWriter statusStream, ISequencedAction actionToRun, ServiceContainer context)
    Inner exception type: System.InvalidOperationException
        Message: 
                There was an error generating the XML document.
        HResult : 0x80131509
        Stack: 
                at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
                at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
                at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        Inner exception type: System.Security.Cryptography.CryptographicException
            Message: 
                        The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation.

                        
            HResult : 0x80090345
            Stack: 
                        at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData, Byte[] optionalEntropy, DataProtectionScope scope)
                        at Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)
                        at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write6_AgentConfigurationPublic(String n, String ns, AgentConfigurationPublic
o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write7_AgentConfigurationPublic(Object o)

Я пишу веб-приложение с использованием MVC3, но при попытке передать объект контроллеру и показать его, похоже, он не распознает тип или что-то еще.

У меня есть объект Job, a JobService возвращает a Job следующим образом:

public Job View(int jobId)
{
    Job job=_jobRepository.Jobs.Where(x => x.Id == jobId).FirstOrDefault();
    return job;
}

В WebService я вызываю View следующим образом:

[WebMethod]
public Job GetJob(GetJobRequest getJobRequest)
{
    var getJobResponse = new GetJobResponse();
    getJobResponse.Job = _jobService.View(getJobRequest.Id);
    return getJobResponse.Job;
}

Затем контроллер вызывает это:

public class JobsController : Controller
{
    public ActionResult Index()
    {
        var jobModel = new JobModel();

        using (var webServiceSoapClient = new WebServiceSoapClient())
        {
            var getJobRequest = new GetJobRequest();
            getJobRequest.Id = 26038;
            jobModel.Job = webServiceSoapClient.GetJob(getJobRequest);
        }
        return View(jobModel);
    }
}

И он бросает эту ошибку:

System.Web.Services.Protocols.SoapException: сервер не смог обработать запрос. — > System.InvalidOperationException: произошла ошибка генерации XML-документа. — > System.InvalidOperationException: Тип System.Data.Entity.DynamicProxies.Job_55765AEC3BD02AFD7E0527408ED5746E1054965A59B82A127B5A688C19C61D5B не ожидался. Используйте атрибут XmlInclude или SoapInclude, чтобы указать типы, которые не известны статически.    в Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write9_Job (String n, String ns, Job o, Boolean isNullable, Boolean needType)    в Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write18_GetJobResponse (Object [] p)    в Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer13.Serialize(Object objectToSerialize, XmlSerializationWriter writer)    в System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces пространства имен, String encodingStyle, String id)    — Конец внутренней проверки стека исключений —    в System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces пространства имен, String encodingStyle, String id)    в System.Web.Services.Protocols.SoapServerProtocol.WriteReturns(Object [] returnValues, Stream outputStream)    в System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object [] returnValues)    в System.Web.Services.Protocols.WebServiceHandler.Invoke()    — Конец внутренней трассировки стека исключений —

Сначала я передавал GetJobResponse службе, но я попытался сделать ее как можно более простой, чтобы заставить ее работать, и я все еще не могу понять это. Я видел, что есть другие вопросы, предлагающие использование XmlInclude и прочее, но это все еще не работает.

Применяя это:

public string SerializeObjectToXMLString(object theObject)
{
    // Exceptions are handled by the caller

    using (System.IO.MemoryStream oStream = new System.IO.MemoryStream())
    {
        System.Xml.Serialization.XmlSerializer oSerializer = new System.Xml.Serialization.XmlSerializer(theObject.GetType());

        oSerializer.Serialize(oStream, theObject);

        return Encoding.Default.GetString(oStream.ToArray());
    }
}

К заданию, возвращенному View в тесте, проходит тест, поэтому я думаю, что проблема исходит из моего веб-сервиса.

Пожалуйста, помогите meeee: ‘(

  • Ошибка при создании диска при установке виндовс
  • Ошибка при создании диска восстановления windows 10
  • Ошибка при создании гугл таблицы
  • Ошибка при создании временного файла необходимого для завершения установки компас
  • Ошибка при создании временного файла ксс