System typeinitializationexception ошибка

private static void Main(string[] args)
{
    string str = null;
    Logger.InitUserLogWithRotation();            // <--- error occur
    ...
}

When I build project, it has no error. But When I execute it, it always aborted.

I tried to debug project , but System.TypeInitializationException error occurred at first line.

I’ve already tried to googling , yet found no solution.

It seems like any variable initialize code is wrong , but can’t find it.

Please help me. I’m new to C#.

Thanks.

※ Here is Logger Class Code

public class Logger
{
    private static int HDLOG_PRIORITY_DEBUG = 4;
    private static int HDLOG_PRIORITY_ERROR = 1;
    private static int HDLOG_PRIORITY_FATAL = 0;
    private static int HDLOG_PRIORITY_INFO = 3;
    private static int HDLOG_PRIORITY_WARNING = 2;
    public static int LOG_LEVEL_DEBUG = 4;
    public static int LOG_LEVEL_ERROR = 2;
    public static int LOG_LEVEL_FATAL = 1;
    public static int LOG_LEVEL_INFO = 5;
    public static int LOG_LEVEL_WARNING = 3;
    private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
    private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
    private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
    private static bool s_consoleLogging = false;
    private static FileStream s_fileStream;
    public static HdLoggerCallback s_HdLoggerCallback;
    private static string s_logDir = null;
    private static string s_logFileName = "XXXX";
    private static string s_logFilePath = null;
    public static int s_logFileSize = 0xa00000;
    private static bool s_loggerInited = false;
    private static string s_logLevels = null;
    private static int s_logRotationTime = 0x7530;
    private static string s_logStringDebug = "DEBUG";
    private static string s_logStringError = "ERROR";
    private static string s_logStringFatal = "FATAL";
    private static string s_logStringInfo = "INFO";
    private static string s_logStringWarning = "WARNING";
    private static int s_processId = -1;
    private static string s_processName = "Unknown";
    private static object s_sync = new object();
    public static int s_totalLogFileNum = 5;
    private static TextWriter writer = Console.Error;

    private static void Close()
    {
        if (!s_consoleLogging)
        {
            writer.Close();
            s_fileStream.Dispose();
            writer.Dispose();
        }
    }

    public static void Debug(string msg)
    {
        Debug("{0}", new object[] { msg });
    }

    public static void Debug(string fmt, params object[] args)
    {
        Print(LOG_LEVEL_DEBUG, s_processName, fmt, args);
    }

    private static void DoLogRotation()
    {
    Label_0000:
        Thread.Sleep(s_logRotationTime);
        try
        {
            lock (s_sync)
            {
                FileInfo info = new FileInfo(s_logFilePath);
                if (info.Length >= s_logFileSize)
                {
                    string destFileName = s_logFilePath + ".1";
                    string path = s_logFilePath + "." + s_totalLogFileNum;
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    for (int i = s_totalLogFileNum - 1; i >= 1; i--)
                    {
                        string str3 = s_logFilePath + "." + i;
                        string str4 = s_logFilePath + "." + (i + 1);
                        if (File.Exists(str3))
                        {
                            File.Move(str3, str4);
                        }
                    }
                    File.Move(s_logFilePath, destFileName);
                }
            }
            goto Label_0000;
        }
        catch (Exception)
        {
            goto Label_0000;
        }
    }

    public static void Error(string msg)
    {
        Error("{0}", new object[] { msg });
    }

    public static void Error(string fmt, params object[] args)
    {
        Print(LOG_LEVEL_ERROR, s_processName, fmt, args);
    }

    public static void Fatal(string msg)
    {
        Fatal("{0}", new object[] { msg });
    }

    public static void Fatal(string fmt, params object[] args)
    {
        Print(LOG_LEVEL_FATAL, s_processName, fmt, args);
    }

    private static string GetLogDir(bool userSpecificLog)
    {
        string str;
        if (s_logDir != null)
        {
            return s_logDir;
        }
        try
        {
            if (userSpecificLog)
            {
                str = Path.Combine(s_bstUserDataDir, "Logs");
            }
            else
            {
                str = (string) Registry.LocalMachine.OpenSubKey(@"Software\XXXX").GetValue("LogDir");
            }
        }
        catch (Exception)
        {
            str = Path.Combine(s_bstUserDataDir, "Logs");
        }
        s_logDir = str;
        return str;
    }

    private static string GetPrefix(string tag, string logLevel)
    {
        int managedThreadId = Thread.CurrentThread.ManagedThreadId;
        DateTime now = DateTime.Now;
        return string.Format("{0:D4}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}.{6:D3} {7}:{8:X8} ({9}). {10}: ", new object[] { now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond, s_processId, managedThreadId, tag, logLevel });
    }

    public static TextWriter GetWriter()
    {
        return new Writer(delegate (string msg) {
            Print(msg);
        });
    }

    private static void HdLogger(int prio, uint tid, string tag, string msg)
    {
        int level = 0;
        if (prio == HDLOG_PRIORITY_FATAL)
        {
            level = LOG_LEVEL_FATAL;
        }
        else if (prio == HDLOG_PRIORITY_ERROR)
        {
            level = LOG_LEVEL_ERROR;
        }
        else if (prio == HDLOG_PRIORITY_WARNING)
        {
            level = LOG_LEVEL_WARNING;
        }
        else if (prio == HDLOG_PRIORITY_INFO)
        {
            level = LOG_LEVEL_INFO;
        }
        else if (prio == HDLOG_PRIORITY_DEBUG)
        {
            level = LOG_LEVEL_DEBUG;
        }
        Print(level, tag, "{0:X8}: {1}", new object[] { tid, msg });
    }

    public static void Info(string msg)
    {
        Info("{0}", new object[] { msg });
    }

    public static void Info(string fmt, params object[] args)
    {
        Print(LOG_LEVEL_INFO, s_processName, fmt, args);
    }

    public static void InitConsoleLog()
    {
        InitLog("-", true, false);
    }

    public static void InitLog(string logFileName, bool userSpecificLog, bool doLogRotation)
    {
        s_loggerInited = true;
        s_HdLoggerCallback = new HdLoggerCallback(Logger.HdLogger);
        s_processId = Process.GetCurrentProcess().Id;
        s_processName = Process.GetCurrentProcess().ProcessName;
        if (logFileName == "-")
        {
            writer = Console.Error;
            s_consoleLogging = true;
        }
        else
        {
            if (logFileName == null)
            {
                logFileName = s_logFileName;
            }
            if (userSpecificLog)
            {
                logFileName = logFileName + "Users";
            }
            string logDir = GetLogDir(userSpecificLog);
            string str2 = string.Format(@"{0}\{1}.log", logDir, logFileName);
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            s_logFilePath = str2;
            LogLevelsInit();
            lock (s_sync)
            {
                Open();
            }
            if (doLogRotation)
            {
                new Thread(() => DoLogRotation()) { IsBackground = true }.Start();
            }
        }
    }

    public static void InitSystemLog()
    {
        InitLog(null, false, false);
    }

    public static void InitSystemLogWithRotation()
    {
        InitLog(null, false, true);
    }

    public static void InitUserLog()
    {
        InitLog(null, true, false);
    }

    public static void InitUserLogWithRotation()
    {
        InitLog(null, true, true);
    }

    private static bool IsLogLevelEnabled(string tag, string level)
    {
        if (s_logLevels == null)
        {
            return false;
        }
        return (s_logLevels.StartsWith("ALL") || s_logLevels.Contains((tag + ":" + level).ToUpper()));
    }

    private static void LogLevelsInit()
    {
        string name = @"Software\XXXX\Config";
        try
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(name))
            {
                s_logLevels = (string) key.GetValue("DebugLogs");
            }
        }
        catch (Exception)
        {
            return;
        }
        if (s_logLevels != null)
        {
            s_logLevels = s_logLevels.ToUpper();
        }
    }

    private static void Open()
    {
        if (!s_consoleLogging)
        {
            if (!s_loggerInited)
            {
                InitLog("-", false, false);
                s_loggerInited = true;
            }
            else
            {
                s_fileStream = new FileStream(s_logFilePath, FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite);
                writer = new StreamWriter(s_fileStream, Encoding.UTF8);
            }
        }
    }

    public static void Print(string msg)
    {
        Print("{0}", new object[] { msg });
    }

    public static void Print(string fmt, params object[] args)
    {
        Print(LOG_LEVEL_INFO, s_processName, fmt, args);
    }

    public static void Print(int level, string tag, string fmt, params object[] args)
    {
        string str = "UNKNOWN";
        if (level == LOG_LEVEL_FATAL)
        {
            str = s_logStringFatal;
        }
        else if (level == LOG_LEVEL_ERROR)
        {
            str = s_logStringError;
        }
        else if (level == LOG_LEVEL_WARNING)
        {
            str = s_logStringWarning;
        }
        else if (level == LOG_LEVEL_INFO)
        {
            str = s_logStringInfo;
        }
        else if (level == LOG_LEVEL_DEBUG)
        {
            str = s_logStringDebug;
        }
        if ((level != LOG_LEVEL_DEBUG) || IsLogLevelEnabled(tag, str))
        {
            lock (s_sync)
            {
                Open();
                writer.WriteLine(GetPrefix(tag, str) + fmt, args);
                writer.Flush();
                Close();
            }
        }
    }

    public static void SetLogDir(string logDir)
    {
        s_logDir = logDir;
    }

    public static void Warning(string msg)
    {
        Warning("{0}", new object[] { msg });
    }

    public static void Warning(string fmt, params object[] args)
    {
        Print(LOG_LEVEL_WARNING, s_processName, fmt, args);
    }

    public delegate void HdLoggerCallback(int prio, uint tid, string tag, string msg);

    public class Writer : TextWriter
    {
        private WriteFunc writeFunc;

        public Writer(WriteFunc writeFunc)
        {
            this.writeFunc = writeFunc;
        }

        public override void WriteLine(string msg)
        {
            this.writeFunc(msg);
        }

        public override void WriteLine(string fmt, object obj)
        {
            this.writeFunc(string.Format(fmt, obj));
        }

        public override void WriteLine(string fmt, object[] objs)
        {
            this.writeFunc(string.Format(fmt, objs));
        }

        public override System.Text.Encoding Encoding
        {
            get
            {
                return System.Text.Encoding.UTF8;
            }
        }

        public delegate void WriteFunc(string msg);
    }
}

1 / 1 / 0

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

Сообщений: 19

1

15.01.2013, 15:26. Показов 29630. Ответов 18


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

Добрый день! Не могу понять, как исправить исключение System.TypeInitializationException! Помогите с решением!
Скрин прилагается:

Заранее очень благодарен за помощь!

Миниатюры

Как исправить исключение System.TypeInitializationException
 



0



Администратор

Эксперт .NET

9410 / 4696 / 759

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

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

Записей в блоге: 14

15.01.2013, 15:35

2

Код в студию. По одной строке кода не могу сказать, в чём проблема.
Плюс вам подсказка:

MSDN
Если инициализация типа инициализатором класса завершилась сбоем, то будет создан объект TypeInitializationException, которому будет передана ссылка на исключение, созданное инициализатором класса этого типа.Базовое исключение хранится в свойстве InnerException объекта TypeInitializationException.



0



Yorie

1 / 1 / 0

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

Сообщений: 19

15.01.2013, 15:44

 [ТС]

3

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
using System;
using System.Net.Sockets;
using c_game.controllers;
using c_game.crypt;
using c_game.db;
using c_game.logger;
using c_game.managers;
using c_game.model.events;
using c_game.model.items;
using c_game.model.npcs.ai;
using c_game.model.quests;
using c_game.model.skills2;
using c_game.network;
using c_game.network.loginauth;
using c_game.network.loginauth.send;
using c_game.staticf;
using c_game.tables;
using c_game.tables.multisell;
using c_game.world;
using c_game.geo;
 
namespace c_game
{
    class GameServer
    {
        public static GameServer gs = new GameServer();
        public string GameServergetInstance;
        public static GameServer getInstance()
        {
            return gs;
        }
 
        protected TcpListener _listener;
 
        public GameServer()
        {
            Console.Title = "Старт Игрового Сервера";
 
            CLogger.form();
            Cfg.init("all");
 
         //   DateTime next = DateTime.Now.AddMinutes(4000);
 
         //   TimeSpan ts = next - DateTime.Now;
 
         //   Console.WriteLine("hrs " + (int)ts.TotalHours + " total " + (int)(ts.Minutes)+" " + (int)(ts.TotalMinutes%60));
         //   return;
 
 
            PClassess.getInstance();
          //  return;
            //shop_conv.test();
           // Console.Write("end");
          //  return;
          //  double x = 100.01;
        //    x += -23;
         //   Console.WriteLine("res " + x);
          //  DateTime time1 = DateTime.Now;   //Точка начала отсчета времени 
        //    Console.ReadKey();               //Пауза до нажатия клавиши
         //   DateTime time2 = DateTime.Now;   //Точка окончания отсчета времени 
         //   long elapsedTicks = time2.Ticks - time1.Ticks;       // подсчитываем число тактов, один такт соответствует 100 наносекундам
         //   Console.WriteLine(elapsedTicks * 1E-7);  // делим на 10^7 для отображения времени в секундах
          //  Console.ReadKey();
            NetworkBlock.getInstance();
            GameTime.getInstance();
 
            IdFactory.getInstance().init();
 
            L2World.getInstance();
            MapRegionTable.getInstance();
            ZoneTable.getInstance();
 
            NpcTable.getInstance();
            NpcData.getInstance();
            SpawnTable.getInstance();
            StaticObjTable.getInstance().read();
            StructureTable.getInstance().read();
            TSkillTable.getInstance();
            ItemTable.getInstance();
            ItemHandler.getInstance();
            MultiSell.getInstance();
            Capsule.getInstance();
            RecipeTable.getInstance();
 
            MonsterRace.getInstance();
            
            AIManager.getInstance();
 
 
            BlowFishKeygen.genKey();
            CLogger.info("generated 20 blowfish keys");
 
            SQLjec.getInstance();
            ClassIdContainer.init();
            
 
            
            
 
            AdminAccess.getInstance();
 
            QuestManager.getInstance();
 
            AnnounceManager.getInstance();
 
            AllianceTable.getInstance();
            ClanTable.getInstance();
            
            CLogger.info("NpcServer: ");
            StaticObjTable.getInstance().Spawn();
            MonsterRace.getInstance().Spawn();
            SpawnTable.getInstance().Spawn();
            StructureTable.getInstance().init();
 
            HtmCache.getInstance();
 
            AuthThread.getInstance();
 
         //   GeoData.getInstance();
 
            CLogger.extra_info("listening game clients on port " + Cfg.SERVER_PORT);
            _listener = new TcpListener(Cfg.SERVER_PORT);
            _listener.Start();
 
            TcpClient clientSocket = default(TcpClient);
            while (true)
            {
                clientSocket = _listener.AcceptTcpClient();
                accept(clientSocket);
            }
        }
 
        private void accept(TcpClient clientSocket)
        {
            ClientManager.getInstance().addClient(clientSocket);
        }
    }
}

и сам код где выдает исключение!

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
using System.Diagnostics;
using c_game._test;
using c_game.tools;
using System;
using c_game.geo;
 
namespace c_game
{
    class Program
    {
        static void Main()
        {
           // test2.ss();
           // Cfg.init("all");
           // drop_l2j_to_rcs.ss();
 
            //short spdx = 300;
            //for (long s1 = 1; s1 < int.MaxValue; s1++)
            //{
            //    double x = 6000 * spdx;
            //}
            //double dx = (14107 - 12107), dy = 0, dz = 0;
            //double distance = Math.Sqrt(dx * dx + dy * dy);
 
            //int ticks = 1 + (int)(10 * distance / 300); ;
 
            //Console.WriteLine("ticks " + ticks);
 
 
            //int spd = 200;
            //double formula = (14400 * spd) / (11148.38709677421 * (spd / 4));
           //Console.WriteLine("result " + spd + " >> " + (formula == 5.16666666666666 ? "yes" : "no") + " " + formula);
 
 
            GameServer.getInstance();
          //  new GeoData().loadGeo();
          //  Console.WriteLine("end.");
          //  Console.ReadLine();
            Process.GetCurrentProcess().WaitForExit();
        }
    }
}



0



tezaurismosis

Администратор

Эксперт .NET

9410 / 4696 / 759

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

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

Записей в блоге: 14

15.01.2013, 15:55

4

К сожалению, я не могу сам отладить этот код, т.к. это «верхушка айсберга». Запустите отладку и отпишитесь о свойстве InnerException в исключении или запустите обработку ошибки и напишите результат.

C#
1
2
3
4
5
try {
    GameServer.getInstance();
} catch (TypeInitializationException ex) {
    Console.WriteLine(ex.InnerException);
}



1



1 / 1 / 0

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

Сообщений: 19

15.01.2013, 16:15

 [ТС]

5

Код

System.TypeInitializationException: Инициализатор типа "c_game.tables.PClassess"
 выдал исключение. ---> System.FormatException: Входная строка имела неверный фо
рмат.
   в System.Number.ParseDouble(String value, NumberStyles options, NumberFormatI
nfo numfmt)
   в System.Double.Parse(String s)
   в c_game.tables.PClassess..ctor() в C:\Users\Sergey\Desktop\l2game\l2game\c_g
ame\tables\PClassess.cs:строка 86
   в c_game.tables.PClassess..cctor() в C:\Users\Sergey\Desktop\l2game\l2game\c_
game\tables\PClassess.cs:строка 14
   --- Конец трассировки внутреннего стека исключений ---
   в c_game.tables.PClassess.getInstance()
   в c_game.GameServer..ctor() в C:\Users\Sergey\Desktop\l2game\l2game\c_game\Ga
meServer.cs:строка 50
   в c_game.GameServer..cctor() в C:\Users\Sergey\Desktop\l2game\l2game\c_game\G
ameServer.cs:строка 26

Добавлено через 8 минут

Код

System.TypeInitializationException: Инициализатор типа "c_game.tables.MapRegionT
able" выдал исключение. ---> MySql.Data.MySqlClient.MySqlException: Table 'rabbi
t_cgame.world_mapregion' doesn't exist
   в MySql.Data.MySqlClient.MySqlStream.ReadPacket()
   в MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& in
sertedId)
   в MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedR
ows, Int32& insertedId)
   в MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
   в MySql.Data.MySqlClient.MySqlDataReader.NextResult()
   в MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)

   в MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
   в c_game.tables.MapRegionTable..ctor() в C:\Users\Sergey\Desktop\l2game\l2gam
e\c_game\tables\MapRegionTable.cs:строка 37
   в c_game.tables.MapRegionTable..cctor() в C:\Users\Sergey\Desktop\l2game\l2ga
me\c_game\tables\MapRegionTable.cs:строка 13
   --- Конец трассировки внутреннего стека исключений ---
   в c_game.tables.MapRegionTable.getInstance()
   в c_game.GameServer..ctor() в C:\Users\Sergey\Desktop\l2game\l2game\c_game\Ga
meServer.cs:строка 70
   в c_game.GameServer..cctor() в C:\Users\Sergey\Desktop\l2game\l2game\c_game\G
ameServer.cs:строка 26



0



tezaurismosis

Администратор

Эксперт .NET

9410 / 4696 / 759

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

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

Записей в блоге: 14

15.01.2013, 16:32

6

C#
1
PClassess.getInstance();

видимо вы неправильно используете метод, первое исключение говорит об этом (System.FormatException: Входная строка имела неверный формат), возможно вам необходимо изменить какое-то свойство.

rabbit_cgame.world_mapregion — этой таблицы нет в базе данных, об этом говорит второе исключение. Проверьте базу данных или имя таблицы.

Не по теме:

Не хочется никого обидеть, и судя по всему, это обращено не к вам, но этот интерфейс для линейки (как я понял из кода) — убожество. Может он хорош на языке, на котором написан оригинальный код, но на C# выглядит отвратно. IMHO



0



1452 / 845 / 150

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

Сообщений: 2,370

15.01.2013, 16:42

7

Цитата
Сообщение от tezaurismosis
Посмотреть сообщение

Не хочется никого обидеть, и судя по всему, это обращено не к вам, но этот интерфейс для линейки (как я понял из кода) — убожество. Может он хорош на языке, на котором написан оригинальный код, но на C# выглядит отвратно. IMHO

Зайдите в раздел Java на этом форуме! Посмотрите примеры кода!



0



Yorie

1 / 1 / 0

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

Сообщений: 19

15.01.2013, 17:02

 [ТС]

8

мдеее)))

C#
1
2
3
4
5
6
7
8
9
System.TypeInitializationException: Инициализатор типа "c_game.tables.SpawnTable
" выдал исключение. ---> System.NullReferenceException: Ссылка на объект не указ
ывает на экземпляр объекта.
   в c_game.tables.SpawnTable.read(String path) в C:\Users\Sergey\Desktop\l2game
\l2game\c_game\tables\SpawnTable.cs:строка 86
   в c_game.tables.SpawnTable..ctor() в C:\Users\Sergey\Desktop\l2game\l2game\c_
game\tables\SpawnTable.cs:строка 24
   в c_game.tables.SpawnTable..cctor() в C:\Users\Sergey\Desktop\l2game\l2game\c
_game\tables\SpawnTable.cs:строка 13



0



Администратор

Эксперт .NET

9410 / 4696 / 759

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

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

Записей в блоге: 14

15.01.2013, 17:34

9

Цитата
Сообщение от LeniumSoft
Посмотреть сообщение

Зайдите в раздел Java на этом форуме!

Ах, это Java. Как-то изучал, она сильно схожа с C#, но скажу честно, мне с непривычки больно читать этот код.
В таком случае стоит написать код для выполнения этих задач на Java, перевести его с C# не составляет проблем, как мне кажется. И ещё: обращение кода на C# — не самом быстром языке по части скорости выполнения к так же нерасторопной Java будет довольно медленным, это удар по производительности.
По поводу отладки

Код

System.NullReferenceException: Ссылка на объект не указ
ывает на экземпляр объекта.
   в c_game.tables.SpawnTable.read(String path) в C:\Users\Sergey\Desktop\l2game
\l2game\c_game\tables\SpawnTable.cs:строка 86

возможно path = null, попробуйте изменить его значение. И ещё раз задумайтесь о разумности использования этого API.



0



Yorie

1 / 1 / 0

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

Сообщений: 19

15.01.2013, 17:38

 [ТС]

10

вот 86 строка!

C#
1
 spawns.Add(new L2Spawn(Convert.ToInt32(stp.Attribute("id").Value), value, stp.Attribute("pos").Value.Split(' ')));

Код

возможно path = null, попробуйте изменить его значение. И ещё раз задумайтесь о разумности использования этого API.

я просто хочу попытаться запустить этот серв, и посмотреть что там вообще!!! За то что ты помагаеш, я те очень сильно благодарен!



0



Администратор

Эксперт .NET

9410 / 4696 / 759

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

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

Записей в блоге: 14

15.01.2013, 17:48

11

В строке, которую вы привели c_game.tables.SpawnTable.read(String path) не используется, вы точно ту строку написали? Нужно из файла SpawnTable.cs



0



Yorie

1 / 1 / 0

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

Сообщений: 19

15.01.2013, 17:52

 [ТС]

12

Цитата
Сообщение от tezaurismosis
Посмотреть сообщение

В строке, которую вы привели c_game.tables.SpawnTable.read(String path) не используется, вы точно ту строку написали? Нужно из файла SpawnTable.cs

да точно от туда!
Вот весь код:

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using c_game.logger;
using c_game.model.npcs;
using c_game.world;
 
namespace c_game.tables
{
    public class SpawnTable
    {
        private static SpawnTable instance = new SpawnTable();
        public static SpawnTable getInstance()
        {
            return instance;
        }
 
        public readonly SortedList<string, L2Territory> territorries = new SortedList<string, L2Territory>();
        public readonly List<L2Spawn> spawns = new List<L2Spawn>();
        public SpawnTable()
        {
            foreach (string path in Directory.EnumerateFiles(@"scripts\spawn\", "*.xml"))
                read(path);
 
            CLogger.info("SpawnTable: Created " + territorries.Count+" territories with "+npcs+" monsters.");
        }
 
        private long npcs = 0;
        public void read(string path)
        {
            XElement xml = XElement.Parse(File.ReadAllText(path));
            XElement ex = xml.Element("list");
            foreach (var m in ex.Elements())
            {
                if (m.Name == "territory")
                {
                    L2Territory zone = new L2Territory();
                    zone.name = m.Attribute("name").Value;
                    zone.controller = m.Attribute("controller").Value;
                    zone.start_active = bool.Parse(m.Attribute("start_active").Value);
 
                    foreach (var stp in m.Elements())
                    {
                        switch (stp.Name.LocalName)
                        {
                            case "npc":
                                int cnt = Convert.ToInt32(stp.Attribute("count").Value);
                                string pos = null;
                                if (stp.Attribute("pos") != null)
                                    pos = stp.Attribute("pos").Value;
                                zone.AddNpc(Convert.ToInt32(stp.Attribute("id").Value), cnt, stp.Attribute("respawn").Value, pos);
                                npcs += cnt;
                                break;
                            case "zone":
                                zone.AddPoint(stp.Attribute("loc").Value.Split(' '));
                                break;
                        }
                    }
 
                    zone.InitZone(); //создаем зону
                    if (territorries.ContainsKey(zone.name))
                        Console.WriteLine("dublicate zone name " + zone.name);
                    else
                        territorries.Add(zone.name, zone);
                }
                else if (m.Name == "spawn")
                {
                    foreach (var stp in m.Elements())
                    {
                        switch (stp.Name.LocalName)
                        {
                            case "npc":
                                {
                                    string respawn = stp.Attribute("respawn").Value;
                                    long value = Convert.ToInt32(respawn.Remove(respawn.Length - 1));
                                    if (respawn.Contains("s"))
                                        value *= 1000;
                                    else if (respawn.Contains("m"))
                                        value *= 60000;
                                    else if (respawn.Contains("h"))
                                        value *= 3600000;
                                    else if (respawn.Contains("d"))
                                        value *= 86400000;
 
                                    spawns.Add(new L2Spawn(Convert.ToInt32(stp.Attribute("id").Value), value, stp.Attribute("pos").Value.Split(' ')));
                                }
                                npcs++;
                                break;
 
                        }
                    }
                }
            }
        }
 
        bool nospawn = true;
        public void Spawn()
        {
            CLogger.extra_info("NpcServer spawn init.");
            if (nospawn)
            {
                CLogger.extra_info("NpcServer spawn done (blocked).");
                return;
            }
            long sp = 0;
            foreach (L2Territory t in territorries.Values)
            {
                sp += t.spawns.Count;
                t.Spawn();
            }
 
            sp += spawns.Count;
            foreach (L2Spawn s in spawns)
                s.init();
 
            CLogger.extra_info("NpcServer spawn done, #"+sp+" npcs.");
        }
 
        public void SunRise(bool y)
        {
            foreach (L2Territory t in territorries.Values)
                t.SunRise(y);
 
            foreach (L2Spawn s in spawns)
                s.SunRise(y);
        }
 
        public L2Object spawnOne(int id, int x, int y, int z, int h)
        {
            NpcTemplate template = NpcTable.getInstance().getNpcTemplate(id);
 
            L2Warrior o = new L2Warrior();
            o.setTemplate(template);
            //switch (template._type)
            //{
            //    case NpcTemplate.L2NpcType.warrior:
            //    case NpcTemplate.L2NpcType.zzoldagu:
            //    case NpcTemplate.L2NpcType.herb_warrior:
            //    case NpcTemplate.L2NpcType.boss:
            //        o = new L2Warrior();
            //        ((L2Warrior)o).setTemplate(template);
            //        break;
 
            //    default:
            //        o = new L2Citizen();
            //        ((L2Citizen)o).setTemplate(template);
            //        break;
            //}
            o.X = x;
            o.Y = y;
            o.Z = z;
            o.Heading = h;
 
            o.SpawnX = x;
            o.SpawnY = y;
            o.SpawnZ = z;
 
            L2World.getInstance().realiseEntry(o, null, true);
            o.onSpawn();
 
            return o;
        }
    }
}



0



tezaurismosis

Администратор

Эксперт .NET

9410 / 4696 / 759

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

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

Записей в блоге: 14

15.01.2013, 18:34

13

Не вижу очевидных ошибок, проверь аргументы метода Add, может один из них null

C#
1
spawns.Add(new L2Spawn(Convert.ToInt32(stp.Attribute("id").Value), value, stp.Attribute("pos").Value.Split(' ')));



0



1 / 1 / 0

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

Сообщений: 19

16.01.2013, 11:30

 [ТС]

14

проверил, но вроде все норм….!!!! Я уже хз чо делать!!!

Добавлено через 11 часов 42 минуты
есть еше какие нить предложения?)



0



76 / 66 / 1

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

Сообщений: 175

17.01.2013, 12:28

15

http://rghost.ru/43084446

Добавлено через 14 часов 27 минут
у него ошибка при билде этого сервера, по ссылке эта ошибка исправлена, пусть сделает себе *.diff и исправит у себя ошибку или использует выложенный мною по ссылке исходник.



1



1 / 1 / 0

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

Сообщений: 19

17.01.2013, 15:13

 [ТС]

16

благадарю! А можно узнать, что там еше исправленно?



0



76 / 66 / 1

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

Сообщений: 175

17.01.2013, 15:30

17

исправлены все ошибки для успешного запуска сервера: добавлены таблицы в бд(от балды, можно сказать, чтоб сервер загружался), исправлено немного код и spawn-файл.
в мир я не заходил.

как я писал выше, сделай диф и посмотри различия

Миниатюры

Как исправить исключение System.TypeInitializationException
 



1



1 / 1 / 0

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

Сообщений: 19

17.01.2013, 15:32

 [ТС]

18

спс, ша проверю!



0



0 / 0 / 0

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

Сообщений: 2

24.07.2014, 11:07

19

Здравствуйте, кто нибудь пожалуйста выложите файл fixedCSFreya.zip, спасибо.



0



I’ve a simple class MyClass with a method defined in a DLL, now I refer to this DLL in another code and try to initialise object like this Myclass obj = new MyClass(). I’m not sure why compiler is throwing NullReferenceException. Please assist

DLL:

public class MyClass
{
    public MyClass(){}
    public void method()
    {
         //some code
    }
}

Other code:

void main()
{
    MyClass obj=new MyClass(); //This is where I get NullReferenceException error
}

Tamir Vered's user avatar

Tamir Vered

10.2k5 gold badges45 silver badges57 bronze badges

asked Sep 10, 2017 at 10:39

Aniruddha's user avatar

10

For posterity, since we found the answer in the comments:

TypeInitializationException is usually caused by an error in static field initialization or static constructor execution.

Indeed we found that the inner exception stack trace pointed to :

SqlConStr = ConfigurationManager.ConnectionStrings["RMDB.Database"].Conn‌​ectionString

This error is caused by the fact that the connection string RMDB.Database was not specified in the app.config for the application. Connection strings (event those used from dlls) must be specified in the app.config of the application using the connection.

answered Sep 10, 2017 at 11:47

Titian Cernicova-Dragomir's user avatar

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Closed

THammond9 opened this issue

Sep 23, 2019

· 42 comments

Comments

@THammond9

Hi, I am encountering an issue while trying to use Microsoft.Data.SqlClient with EF Core v2.2.6. I am using this for Always Encrypted and it implemented based on this comment: #11 (comment).
My scenario might be a little unique since we have some old code with a custom ORM that is using the old library System.Data.SqlClient. This old code is not using any columns that are encrypted so it is my understanding that nothing needs to change there. EF Core is the only ORM that is reading/updating the encrypted column.

I tested Always Encrypted on my local machine and there were no problems. It was only after the code was merged and deployed to the dev environment did the error below occur. It is important to note that the exception is only thrown when viewing any pages in the application that use EF Core. If the page uses the custom ORM there is no problem. I briefly had the error occur on my local machine but after doing a clean/rebuild in VS the error disappeared. I then went to the server for the dev and deleted everything in the bin folder (hopefully mimicking the clean process) and redeployed but that did not resolve the issue for us.

I did find this issue: https://github.com/dotnet/corefx/issues/30518 but since the server is Windows Server 2016 and System.Data.SqlClient is v4.6.1 I do not believe that the issue is the same even if the exception appears to be similar.

I am not really sure where to go from here.
Info:
App: Asp.Net MVC 5, .Net Framework 4.6.1
EF Core v2.2.6 is in a .Net Standard 2.0 project
SQL Server Enterprise 64 bit 13.0.5426.0
Server: Windows Server 2016 version 1607

System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.TdsParser' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNILoadHandle' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNINativeMethodWrapper' threw an exception. ---> System.ComponentModel.Win32Exception: Failed to load C:\inetpub\wwwroot\Simplifyed\bin\x64\SNI.dll
   at Microsoft.Data.SqlClient.SNINativeMethodWrapper..cctor() in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\Interop\SNINativeMethodWrapper.cs:line 66
   --- End of inner exception stack trace ---
   at Microsoft.Data.SqlClient.SNINativeMethodWrapper.SNIInitialize()
   at Microsoft.Data.SqlClient.SNILoadHandle..ctor() in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParserSafeHandles.cs:line 31
   at Microsoft.Data.SqlClient.SNILoadHandle..cctor() in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParserSafeHandles.cs:line 16
   --- End of inner exception stack trace ---
   at Microsoft.Data.SqlClient.TdsParser..cctor() in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 156
   --- End of inner exception stack trace ---
   at Microsoft.Data.SqlClient.TdsParser..ctor(Boolean MARS, Boolean fAsynchronous) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 32
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1548
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1442
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, ServerCertificateValidationCallback serverCallback, ClientCertificateRetrievalCallback clientCallback, DbConnectionPool pool, String accessToken, SqlClientOriginalNetworkAddressInfo originalNetworkAddressInfo, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 425
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnectionFactory.cs:line 123
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 143
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 870
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1807
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1293
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1190
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 302
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionInternal.cs:line 683
   at Microsoft.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1618
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1599
   at Microsoft.Data.SqlClient.SqlConnection.Open() in E:\agent1\_work\31\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1250
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__17`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
....

@Wraith2

The important part is:

Win32Exception: Failed to load C:\__source_code\repo1\Simplified\bin\x86\SNI.dll

So it’s trying to load the 32 bit version of sni.dll and it isn’t present.

That makes me suspect that you build it on a 64 bit system and then just transferred the files to the other machine. You need to publish the project for an x86 target to get the right native dependency resolved. Give it a try.

@THammond9

Sorry, I took the exception from my local machine. I update my comment to the one from the Dev environment.

@Wraith2

Essentially the same thing I’m afraid, the important bit is:

.Win32Exception: Failed to load C:\inetpub\wwwroot\Simplifyed\bin\x64\SNI.dll

@THammond9

I am using Azure DevOps for build and deployment with BuildPlatform set to any cpu. The SNI.dll file exists in both \bin\x64 and \bin\x86 at the IIS site path on the server.

EDIT: I was looking at the file information and it appears that the date modified is 9/23/2019 6:44 PM. The current server time is 9/23/2019 5:19 PM. I remember that modified file times in the future caused an issue when I was testing time zone related changes. Does this sound like a likely culprit?

@cheenamalhotra

@THammond9
What is the Microsoft.Data.SqlClient version in use? We had the issue before in previews. Please confirm if the issue occurs with Stable v1.0.19249.1?

If yes, can you wrap up a repro app and provide us to reproduce error? A basic architecture app with just a connection object should be good starting point to look into.

@THammond9

I can confirm that I am using v1.0.19249.1. I will try to repro the error but I am going to have to rewrite my Always Encrypted quires to use ADO.Net before I can work on the repro app.

@cheenamalhotra

@THammond9

Curious to know if the timezone issue was the root cause, did you happen to test again in next days?

@THammond9

@cheenamalhotra I don’t think that was the issue. When I took a closer look that the server I noticed that all files deployed by Azure DevOps have a modified date in the future, which is likely UTC (I am EST). The site does not seem to have a problem with this for all of the other files so it seems unlikely that this would be the issue for only this library. Unfortunately I had to revert the changes so that dev could move forward, so I am unable to test further at the moment. I am still planning on trying to get a repro app but the earliest I could work on it would be next week.

@David-Engel

That makes me suspect that you build it on a 64 bit system and then just transferred the files to the other machine. You need to publish the project for an x86 target to get the right native dependency resolved. Give it a try.

Just to clarify the above, It shouldn’t matter whether the app is targeting x86 or x64. When building/deploying a .NET Framework target with a M.D.SqlClient dependency, both x86\SNI.dll and x64\SNI.dll files should be written to the output path (done by a targets file in the SqlClient NuGet package). This enables Microsoft.Data.SqlClient.dll to support AnyCPU by dynamically loading the appropriate native SNI.dll at runtime.

It looks like SqlClient could do a better job of reporting the underlying error about why it failed to load the dll.

@cheenamalhotra

Hi @THammond9

Let us know if you can provide us a repro app for this issue that can inspect further.

Also to add, as per @David-Engel ‘s comment above, PR #225 has been merged and released in latest driver version 1.1.0-preview1. Please give it a try if you can gather more info on why the SNI.dll is failing to load.

@THammond9

I haven’t forgotten about this, just been a little busy. I will try this today with 1.1.0-preview1 and see if there is more information when the exception throws.

@THammond9

Here is the updated exception. Does not seem that much different to me. I verified that the Microsoft.Data.SqlClient.dll was the preview version and that the SNI.dll file exists in both folders. It was deployed with Azure DevOps:

System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.TdsParser' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNILoadHandle' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNINativeMethodWrapper' threw an exception. ---> System.ComponentModel.Win32Exception: Failed to load C:\inetpub\wwwroot\dev2.verityiq.com\bin\x64\SNI.dll ---> System.ComponentModel.Win32Exception: The specified module could not be found
   --- End of inner exception stack trace ---
   at Microsoft.Data.SqlClient.SNINativeMethodWrapper..cctor() in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\Interop\SNINativeMethodWrapper.cs:line 67
   --- End of inner exception stack trace ---
   at Microsoft.Data.SqlClient.SNINativeMethodWrapper.SNIInitialize()
   at Microsoft.Data.SqlClient.SNILoadHandle..ctor() in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParserSafeHandles.cs:line 36
   at Microsoft.Data.SqlClient.SNILoadHandle..cctor() in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParserSafeHandles.cs:line 17
   --- End of inner exception stack trace ---
   at Microsoft.Data.SqlClient.TdsParser..cctor() in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 166
   --- End of inner exception stack trace ---
   at Microsoft.Data.SqlClient.TdsParser..ctor(Boolean MARS, Boolean fAsynchronous) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:line 33
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1743
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1628
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, ServerCertificateValidationCallback serverCallback, ClientCertificateRetrievalCallback clientCallback, DbConnectionPool pool, String accessToken, SqlClientOriginalNetworkAddressInfo originalNetworkAddressInfo, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 465
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnectionFactory.cs:line 145
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 167
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 955
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 2024
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1427
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1309
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 357
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\ProviderBase\DbConnectionInternal.cs:line 773
   at Microsoft.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1880
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1857
   at Microsoft.Data.SqlClient.SqlConnection.Open() in E:\agent1\_work\28\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1425
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

@cheenamalhotra

\bin\x64\SNI.dll —> System.ComponentModel.Win32Exception: The specified module could not be found

This would mean a dependency dll is not found in your OS for SNI.dll to load.
Could you take a look which dependent dll is not available in your host OS of Azure DevOps Server?
Or if the issue is something else!

Dependency list is here:
image

@THammond9

Is there an easy way to locate all of these dlls or do I just search the windows folder for the names? Also does it matter what the location of these dlls are?

@THammond9

Did a search in the windows folder and api-ms-win-crt-* and vcRunTime140.dll are missing

@cheenamalhotra

Try installing/fixing Microsoft Visual C++ 2015 Redistributable

@THammond9

I let the network team know to install Microsoft Visual C++ 2015 Redistributable on the server. After it is updated I will try again.

@THammond9

Sorry it took so long with an update; the missing Microsoft Visual C++ 2015 Redistributable was the issue. Not sure how these kinds of issues are usually handled but it might be useful to list this prerequisite somewhere (NuGet, here?) and a link or set of instructions on how to validate if this package is installed. Anyway, thank you every one for your help with this issue 😄

@corner22

I am getting a very similar issue when running unit tests on our CI server, but the Microsoft Visual C++ 2015 Redistributable solution does not work for me.

Some of the unit test projects have a packagereference to one of our own nuget packages that has a dependency on Microsoft.Data.SqlClient 1.0.19269.1. When these unit tests run they fail with the same TypeInitializationException error. I can see that the bin folder of the unit test project contains Microsoft.Data.SqlClient.dll but the corresponding x86 and x64 sub folders are missing. The CI server has «Microsoft Visual C++ 2015-2019 Redistributable» x86 and x64 versions installed.

The CI server builds the VS Projects with MSBuild. If I log onto the CI Server and manually build the same projects with VS 2019 Community Edition then the x86 and x64 folders are created, and the unit tests run successfully.

Why doesn’t MSBuild create the x86/x64 folders whereas VS 2019 does create them?

Thanks in advance.

@cheenamalhotra

Hi @corner22

Please provide us detail stack trace for the «TypeInitializationException» you’re facing. Also a repro if possible.

@corner22

Hi @corner22

Please provide us detail stack trace for the «TypeInitializationException» you’re facing. Also a repro if possible.

I have resolved the problem. It wasn’t an issue with your nuget package. When building with MSBuild, our CI server was using an out-dated version of nuget (4.8.1). After upgrading it to use the latest (5.3.0) then MSBuild correctly built the package.

Sorry to trouble you with this, but hopefully sharing my experience will be useful to others who may get a similar issue.

@ErikEJ

@Wraith2

I’d be interested to know what difference between the versions caused the issue as well.

@ErikEJ

@Wraith2

Looks likely, and in that case the nuspec update would be a good move.

@yukiwongky

Closing since fix in PR #274 is merged.

@yukiwongky

Hi everyone, we had to revert the change since NuGet.org gallery does not support <metadata minClientVersion="5.0.0"> at the moment. We’ve filed a bug #7674 on their end. Additionally, we realized having this change may impact users with older version of Visual Studio / NuGet. Therefore we won’t be introducing this change.

@Poolitzer80

We are currently facing the same issue on our azure nodes when upgrading to Microsoft.Data.SqlClient.
We have installed the VC++ Redistributable 2017 but not 2015.
Are the redistributable not backwards compatible?

The api-ms-win-crt files are all missing on our node. The vcruntime140.dll is available in the system32 directory

@Wraith2

Are the redistributable not backwards compatible?

No. There is a specific redistributable for each major version of the c++ runtime and you need to have the correct one installed. This only applied on windows. On Linux the implementation is entirely managed code and doesn’t require a c++ runtime.

@Poolitzer80

I tried to install the redistributable 2015-2019 now
image

But the error is still occuring

@cheenamalhotra

@Poolitzer80

Do you have Nuget.exe version > v5.0 installed on your client machine as shared here: #211 (comment)?

If not, please try upgrading and let us know.

@Poolitzer80

Hi Cheena

Yeah i already saw, that in your bugfix.
We tried already to upgrade our nuget task, but everthing newer than 4.7.1
Does not restore our own repository nuget packages ☹

Do you have an idea what we have to do that the new nuget updater works with our pipeline?

Viele Grüße
Jakob Schönfeld

root-nine GmbH
Eduard-Rüber-Str. 7
83022 Rosenheim
Geschäftsführer: Rupert Maier – Georg Huber
Registergericht Traunstein HRB 26248
Telefon: 08031 / 581797-5
E-Mail: info@root-nine.de<mailto:info@root-nine.de>
Homepage: www.root-nine.de<http://www.root-nine.de/>

Von: Cheena Malhotra <notifications@github.com>
Gesendet: Freitag, 6. Dezember 2019 16:43
An: dotnet/SqlClient <SqlClient@noreply.github.com>
Cc: Jakob Schönfeld <jakob.schoenfeld@root-nine.de>; Mention <mention@noreply.github.com>
Betreff: Re: [dotnet/SqlClient] System.TypeInitializationException: The type initializer for ‘Microsoft.Data.SqlClient.TdsParser’ threw an exception. (#211)

@Poolitzer80<https://github.com/Poolitzer80>

Do you have Nuget.exe version > v5.0 installed on your client machine as shared here: #211 (comment)<#211 (comment)>?

If not, please try upgrading and let us know.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<#211?email_source=notifications&email_token=ANDSDHEMGJ4XDWL6DOY3NM3QXJXH7A5CNFSM4IZOOBZ2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEGEPIJY#issuecomment-562623527>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/ANDSDHACPZGXXNGDO7BDSA3QXJXH7ANCNFSM4IZOOBZQ>.

@cheenamalhotra

From NuGet documentation:

NuGet.exe 5.0 and later require .NET Framework 4.7.2 or later to execute.

That might be the source of problem. You could try upgrading to 4.7.2 and investigating packages not being restored.

If you’re not willing to upgrade, you can also add Microsoft.Data.SqlClient.SNI NuGet package to your references to load SNI.dll manually.

@Poolitzer80

Thank you! We will try to upgrade to 4.7.2! Have a nice weekend!

Viele Grüße
Jakob Schönfeld

root-nine GmbH
Eduard-Rüber-Str. 7
83022 Rosenheim
Geschäftsführer: Rupert Maier – Georg Huber
Registergericht Traunstein HRB 26248
Telefon: 08031 / 581797-5
E-Mail: info@root-nine.de<mailto:info@root-nine.de>
Homepage: www.root-nine.de<http://www.root-nine.de/>

Von: Cheena Malhotra <notifications@github.com>
Gesendet: Freitag, 6. Dezember 2019 17:11
An: dotnet/SqlClient <SqlClient@noreply.github.com>
Cc: Jakob Schönfeld <jakob.schoenfeld@root-nine.de>; Mention <mention@noreply.github.com>
Betreff: Re: [dotnet/SqlClient] System.TypeInitializationException: The type initializer for ‘Microsoft.Data.SqlClient.TdsParser’ threw an exception. (#211)

From NuGet documentation<https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools#windows>:

NuGet.exe 5.0 and later require .NET Framework 4.7.2 or later to execute.

That might be the source of problem. You could try upgrading to 4.7.2 and investigating packages not being restored.

If you’re not willing to upgrade, you can also add Microsoft.Data.SqlClient.SNI<https://www.nuget.org/packages/Microsoft.Data.SqlClient.SNI/> NuGet package to your references to load SNI.dll manually.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<#211?email_source=notifications&email_token=ANDSDHHIXHJJSMZ5ITDQOTTQXJ2QVA5CNFSM4IZOOBZ2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEGESFDI#issuecomment-562635405>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/ANDSDHC3OB3EE2WELAOJY6DQXJ2QVANCNFSM4IZOOBZQ>.

@David-Engel

Are the redistributable not backwards compatible?

No. There is a specific redistributable for each major version of the c++ runtime and you need to have the correct one installed. This only applied on windows.

@Wraith2 I think this has changed a bit since 2015. From https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads :

Note Visual C++ 2015, 2017 and 2019 all share the same redistributable files.

For example, installing the Visual C++ 2019 redistributable will affect programs built with Visual C++ 2015 and 2017 also. However, installing the Visual C++ 2015 redistributable will not replace the newer versions of the files installed by the Visual C++ 2017 and 2019 redistributables.

This is different from all previous Visual C++ versions, as they each had their own distinct runtime files, not shared with other versions.

@Poolitzer80 The 2017 ones should be correct. But is your application 32-bit? If so, you will need to install the x86 redistributable package (even if you are running it on an x64 system), which will put the libraries in the SysWOW64 folder.

@SteveDunn

I had this error and it was fixed by updating
image

… to version 4.8.0

When installing, it’ll say (in the license box):

image

@jssmotta

Hello, I’d tried all options above, and I fixed uninstalling and reinstalling again with dependency behavior Highest using the Options on NuGet.

I’m using:
Net Framework 4.8
C# 7.3
Visual Studio 2019 Updated
ASP.NET App

I make this post because I had this issue last year but I did abandon, today I look for a solution.

#JeffersonMotta2020 #TdsParserError

FIX_SYSTEM_DATA_SQLCLIENT

@cheenamalhotra

@jssmotta

Could you please upload a sample app to reproduce the issue?

Since the application architectures differ a lot and sometimes other dependencies have role to play, we’d like to know more about your specific use case, before making assumptions. Please open a new ticket with your repro, that would be ideal.

@kgreed

I seem to be having related problems reported here

Seems to be that EF Core 3 uses a different version of Microsoft..Extensions.DependencyInjection.Abstractions than MSTest

@ryanriv

We ran into this with a console app that was targeting .NET Framework 4.8. Installing the Microsoft.Data.SqlClient.SNI package manually fixed the problem. The only difference I can see is that NuGet is using 1.1.0 without the explicit reference, and Microsoft.Data.SqlClient.SNI 1.1.1 fixes the problem.

Note: the app runs fine from my machine, but if I build the app and try to run the exe on one of our servers, it throws the TdsParser error unless the SNI package is installed.

The only dependency in my sample app is Microsoft.Data.SqlClient 1.1.2.

@patrick-steele

Thanks @ryanriv — that fixed it for me too. I had Microsoft.Data.SqlClient.SNI version 1.1.0 and was getting this error (with Microsoft.Data.SqlClient 1.1.2). I updated the SNI package to 1.1.1 and that fixed the The specified module could not be found error.

@emmanuelcaamal

the following issue fix it giving execute permission to /x64/SNI.dll. I don´t know if it´s the correct soluction but it worked for me

System.TypeInitializationException: The type initializer for ‘Microsoft.Data.SqlClient.TdsParser’ threw an exception. —> System.TypeInitializationException: The type initializer for ‘Microsoft.Data.SqlClient.SNILoadHandle’ threw an exception. —> System.TypeInitializationException: The type initializer for ‘Microsoft.Data.SqlClient.SNINativeMethodWrapper’ threw an exception. —> System.ComponentModel.Win32Exception: Failed to load C:\websites\wwwroot\bin\x64\SNI.dll

<< Back to C-SHARP

Understand the TypeInitializationException, which indicates a static constructor error.

TypeInitializationException occurs when a static constructor has an error. It is thrown from static constructors. It actually wraps the errors from static constructors. It cannot be reliably trapped outside of the static constructor.StaticException

Example. We test this exception in an example program. This program shows that this exception in the .NET Framework is raised when any exception is thrown inside a type initializer, also called a static constructor.

Info: The runtime wraps any exception raised in the static constructor inside a TypeInitializationException.

And: The InnerException is the original cause of the problem. The TypeInitializationException is only raised from type initializers.

C# program that throws TypeInitializationException

using System;

class Program
{
static Program()
{
//
// Static constructor for the program class.
// … Also called a type initializer.
// … It throws an exception in runtime.
//
int number = 100;
int denominator = int.Parse(«0»);
int result = number / denominator;
Console.WriteLine(result);
}

static void Main()
{
// Entry point.
}
}

Output

Unhandled Exception:

System.TypeInitializationException

: The type initializer for
‘Program’ threw an exception. —>
System.DivideByZeroException: Attempted to divide by zero.
at Program..cctor….
— End of inner exception stack trace —
at Program.Main()

Notes, program. When Main is reached, the static Program constructor is executed. The code in the static constructor attempts to divide by zero. This causes a DivideByZeroException to be thrown.

And: The runtime then wraps this exception inside a TypeInitializationException.

Fix. To fix this error, you can add try-catch blocks around the body of the static constructor that throws it. If you try to catch the exception inside the Main method, you will not capture it in this program.TryCatch

However: If you wrap the body of the static constructor in a try-catch block, you will capture it.

Summary. TypeInitializationException is used to wrap exceptions inside type initializers, also called static constructors. This is a special-purpose exception. Often these errors will be fatal to the program’s correct execution.

Sometimes: Programs will use static constructors to ensure certain constraints are met at startup.

And: The TypeInitializationException then is thrown when the constraints are not met.

Related Links:

  • C# ContainsValue Method (Value Exists in Dictionary)
  • C# ContextMenuStrip Example
  • C# Normalize, IsNormalized Methods
  • C# continue Keyword
  • C# Control: Windows Forms
  • C# File.Open Examples
  • C# Null String Example
  • C# null Keyword
  • C# Windows Forms Controls
  • C# File.ReadAllBytes, Get Byte Array From File
  • C# Nullable Examples
  • C# NullReferenceException and Null Parameter
  • C# File.ReadAllLines, Get String Array From File
  • C# Object Array
  • C# Color Table
  • C# Convert Char Array to String
  • C# File.ReadAllText, Get String From File
  • C# Obsolete Attribute
  • C# Color Examples: FromKnownColor, FromName
  • C# ColorDialog Example
  • C# Comment: Single Line and Multiline
  • C# Concat Extension: Combine Lists and Arrays
  • C# Conditional Attribute
  • C# Console Color, Text and BackgroundColor
  • C# String Clone() method
  • C# Convert Char to String
  • C# Convert Days to Months
  • C# File.ReadLines, Use foreach Over Strings
  • C# File.Replace Method
  • C# FileInfo Length, Get File Size
  • C# FileInfo Examples
  • C# StreamReader ReadLine, ReadLineAsync Examples
  • C# readonly Keyword
  • C# Aggregate: Use Lambda to Accumulate Value
  • C# AggressiveInlining: MethodImpl Attribute
  • C# Multidimensional Array
  • C# MultiMap Class (Dictionary of Lists)
  • C# Anagram Method
  • C# Recursion Example
  • C# And Bitwise Operator
  • C# Regex, Read and Match File Lines
  • C# Regex Groups, Named Group Example
  • C# Anonymous Function (Delegate With No Name)
  • C# Any Method, Returns True If Match Exists
  • C# Regex.Matches Quote Example
  • C# StringBuilder Append and AppendLine
  • C# Optimization
  • C# StringBuilder AppendFormat
  • ASP.NET appSettings Example
  • C# ArgumentException: Invalid Arguments
  • C# Regex.Matches Method: foreach Match, Capture
  • C# File Handling
  • C# Filename With Date Example (DateTime.Now)
  • C# FileNotFoundException (catch Example)
  • C# FileStream Length, Get Byte Count From File
  • C# Convert String to Byte Array
  • C# FileStream Example, File.Create
  • C# FileSystemWatcher Tutorial (Changed, e.Name)
  • C# finally Keyword
  • C# String Format
  • C# String Replace() method
  • C# Sum Method: Add up All Numbers
  • C# Switch Char, Test Chars With Cases
  • C# Switch Enum
  • C# String Split() method
  • C# String StartsWith() method
  • C# String SubString() method
  • C# System (using System namespace)
  • C# Partial Types
  • C# Tag Property: Windows Forms
  • C# Iterators
  • C# TextInfo Examples
  • C# TextReader, Returned by File.OpenText
  • C# Delegate Covariance
  • C# Delegate Inference
  • C# Array.ConvertAll, Change Type of Elements
  • HelpProvider Control Use
  • C# SplitContainer: Windows Forms
  • C# SqlClient Tutorial: SqlConnection, SqlCommand
  • C# SqlCommand Example: SELECT TOP, ORDER BY
  • C# SqlCommandBuilder Example: GetInsertCommand
  • C# SqlConnection Example: Using, SqlCommand
  • C# SqlDataAdapter Example
  • C# SqlDataReader: GetInt32, GetString
  • C# SqlParameter Example: Constructor, Add
  • C# Array.Copy Examples
  • C# Array.CreateInstance Method
  • C# HTML and XML Handling
  • C# HtmlEncode and HtmlDecode
  • C# HtmlTextWriter Example
  • C# Array and Dictionary Test, Integer Lookups
  • C# HttpUtility.HtmlEncode Methods
  • C# HybridDictionary
  • C# String ToCharArray() method
  • C# Array.Exists Method, Search Arrays
  • C# default Operator
  • C# Func Object (Lambda That Returns a Value)
  • C# GC.Collect Examples: CollectionCount, GetTotalMemory
  • C# Path.GetDirectoryName (Remove File From Path)
  • C# goto Examples
  • C# Array.Find Examples, Search Array With Lambda
  • C# Array.ForEach: Use Lambda on Every Element
  • C# DefaultIfEmpty Method
  • C# HttpClient Example: System.Net.Http
  • C# Array Versus List Memory Usage
  • C# Define and Undef Directives
  • ASP.NET HttpContext Request Property
  • C# Stack Collection: Push, Pop
  • C# Static List: Global List Variable
  • C# Static Regex
  • C# Array Property, Return Empty Array
  • C# Destructor
  • C# Constructor Examples
  • C# Contains Extension Method
  • C# String GetTypeCode() method
  • C# String ToLowerInvariant() method
  • C# Customized Dialog Box
  • C# DataColumn Example: Columns.Add
  • C# DataGridView Add Rows
  • DataGridView Columns, Edit Columns Dialog
  • C# DataGridView Row Colors (Alternating)
  • C# DataGridView Tutorial
  • C# DataGridView
  • C# DataRow Examples
  • C# DataSet Examples
  • C# DataSource Example
  • C# DataTable Compare Rows
  • C# DataTable foreach Loop
  • C# DataTable RowChanged Example: AcceptChanges
  • C# DataTable Select Example
  • C# DataTable Examples
  • C# DataView Examples
  • C# OfType Examples
  • C# OpenFileDialog Example
  • C# operator Keyword
  • C# Odd and Even Numbers
  • C# BaseStream Property
  • C# Console.Beep Example
  • C# Bitwise Or
  • C# orderby Query Keyword
  • C# Benchmark
  • C# String ToUpperInvariant() method
  • C# String Trim() method
  • C# out Parameter
  • C# BinaryReader Example (Use ReadInt32)
  • C# OutOfMemoryException
  • C# BinaryWriter Type
  • C# BitArray Examples
  • C# BitConverter Examples
  • C# Bitcount Examples
  • C# OverflowException
  • C# Overload Method
  • C# Static String
  • C# First Sentence
  • C# Regex.Replace, Matching End of String
  • C# Regex.Replace, Remove Numbers From String
  • C# Anonymous Types
  • C# FirstOrDefault (Get First Element If It Exists)
  • C# Fisher Yates Shuffle: Generic Method
  • C# fixed Keyword (unsafe)
  • C# Flatten Array (Convert 2D to 1D)
  • C# Regex.Replace, Merge Multiple Spaces
  • C# Regex.Replace Examples: MatchEvaluator
  • C# Extension Methods
  • C# Query Expression
  • C# First Words in String
  • C# First (Get Matching Element With Lambda)
  • C# Regex.Split, Get Numbers From String
  • C# Partial Method
  • C# ContainsKey Method (Key Exists in Dictionary)
  • C# Regex.Split Examples
  • C# Regex Trim, Remove Start and End Spaces
  • C# Implicitly Typed Local Variable
  • C# Object and Collection Initializer
  • C# RegexOptions.Compiled
  • C# Auto Implemented Properties
  • C# Dynamic Binding
  • C# Named and Optional Arguments
  • C# Asynchronous Methods
  • C# Convert ArrayList to Array (Use ToArray)
  • C# RegexOptions.IgnoreCase Example
  • C# New Features | C# Version Features
  • C# Programs
  • C# Caller Info Attributes
  • C# Convert ArrayList to List
  • C# Convert Bool to Int
  • C# RegexOptions.Multiline
  • C# Using Static Directive
  • C# Convert Bytes to Megabytes
  • C# Region and endregion
  • C# Remove Char From String at Index
  • C# Exception Filters
  • C# DialogResult: Windows Forms
  • C# Dictionary, Read and Write Binary File
  • C# Array Examples, String Arrays
  • C# ArrayList Examples
  • C# ArraySegment: Get Array Range, Offset and Count
  • C# break Statement
  • C# Buffer BlockCopy Example
  • C# BufferedStream: Optimize Read and Write
  • IL Disassembler Tutorial
  • C# Intermediate Language (IL)
  • C# new Keyword
  • C# NotifyIcon: Windows Forms
  • C# NotImplementedException
  • C# Null Array
  • C# static Keyword
  • C# StatusStrip Example: Windows Forms
  • C# Dictionary Memory
  • C# Dictionary Optimization, Increase Capacity
  • 404 Not Found
  • C# 24 Hour Time Formats
  • C# Dictionary Optimization, Test With ContainsKey
  • C# String Chars (Get Char at Index)
  • C# DictionaryEntry Example (Hashtable)
  • C# Directives
  • C# String GetType() method
  • C# Directory.CreateDirectory, Create New Folder
  • C# Directory.GetFiles Example (Get List of Files)
  • C# DivideByZeroException
  • C# DllImport Attribute
  • C# Do While Loop Example
  • C# CharEnumerator
  • C# Chart, Windows Forms (Series and Points)
  • C# CheckBox: Windows Forms
  • C# Await in Catch Finally Blocks
  • C# Increment String That Contains a Number
  • C# Increment, Preincrement and Decrement Ints
  • C# String ToString() method
  • C# String ToUpper() method
  • C# class Examples
  • Dot Net Perls
  • C# Indexer Examples (This Keyword, get and set)
  • C# Default Values for Getter Only Properties
  • C# Digit Separator
  • C# Clear Dictionary: Remove All Keys
  • C# Clone Examples: ICloneable Interface
  • C# Closest Date (Find Dates Nearest in Time)
  • C# Expression Bodied Members
  • C# DateTime.MinValue (Null DateTime)
  • C# DateTime.Month Property
  • C# Combine Arrays: List, Array.Copy and Buffer.BlockCopy
  • C# Combine Dictionary Keys
  • C# ComboBox: Windows Forms
  • C# IndexOutOfRangeException
  • C# Inheritance
  • C# Null Propagator
  • C# CompareTo Int Method
  • C# Comparison Object, Used With Array.Sort
  • C# Insert String Examples
  • C# int Array
  • C# String Interpolation
  • C# nameof operator
  • C# DateTime.Parse: Convert String to DateTime
  • C# DateTime Subtract Method
  • C# Compress Data: GZIP
  • C# Interface Examples
  • C# Interlocked Examples: Add, CompareExchange
  • C# Dictionary Initializer
  • C# 2D Array Examples
  • 7 Zip Command Line Examples
  • C# 7 Zip Executable (Process.Start)
  • C# Decompress GZIP
  • C# Remove Duplicates From List
  • C# dynamic Keyword
  • C# Null Coalescing and Null Conditional Operators
  • C# Null List (NullReferenceException)
  • C# DayOfWeek
  • C# Remove Element
  • C# Pattern Matching
  • C# Tuples
  • C# Enum.Format Method (typeof Enum)
  • C# Enum.GetName, GetNames: Get String Array From Enum
  • C# Enum.Parse, TryParse: Convert String to Enum
  • C# stackalloc Operator
  • C# Deconstruction
  • C# Remove HTML Tags
  • C# Local Functions
  • C# ElementAt, ElementAtOrDefault Use
  • C# Error and Warning Directives
  • C# ErrorProvider Control: Windows Forms
  • C# Remove String
  • C# StackOverflowException
  • C# Program to swap numbers without third variable
  • C# Binary Literals
  • C# event Examples
  • C# Program to convert Decimal to Binary
  • C# Ref Returns and Locals
  • C# Encapsulate Field
  • C# Enum Array Example, Use Enum as Array Index
  • C# enum Flags Attribute Examples
  • C# IndexOf Examples
  • C# IndexOfAny Examples
  • C# Initialize Array
  • C# Get Every Nth Element From List (Modulo)
  • C# Excel Interop Example
  • C# StartsWith and EndsWith String Methods
  • C# Static Array
  • C# Program to Convert Number in Characters
  • C# Expression Bodied Constructors and Finalizers
  • C# Initialize List
  • C# InitializeComponent Method: Windows Forms
  • C# Numeric Casts
  • C# NumericUpDown Control: Windows Forms
  • C# object.ReferenceEquals Method
  • C# Object Examples
  • C# Optional Parameters
  • C# Except (Remove Elements From Collection)
  • C# Static Dictionary
  • C# Program to Print Alphabet Triangle
  • C# Expression Bodied Getters and Setters
  • C# Prime Number
  • C# Reserved Filenames
  • C# Program to print Number Triangle
  • C# Async Main
  • C# Default Expression
  • C# Inline Optimization
  • C# Override Method
  • C# Enum ToString: Convert Enum to String
  • C# enum Examples
  • C# Enumerable.Range, Repeat and Empty
  • C# Dictionary Equals: If Contents Are the Same
  • C# Dictionary Versus List Loop
  • C# Dictionary Order, Use Keys Added Last
  • C# Dictionary Size and Performance
  • C# Dictionary Versus List Lookup Time
  • C# Dictionary Examples
  • C# Get Directory Size (Total Bytes in All Files)
  • C# Directory Type
  • C# Distinct Method, Get Unique Elements Only
  • C# Divide by Powers of Two (Bitwise Shift)
  • C# Divide Numbers (Cast Ints)
  • C# DomainUpDown Control Example
  • C# Double Type: double.MaxValue, double.Parse
  • C# Environment Type
  • C# Main args Examples
  • C# All Method: All Elements Match a Condition
  • C# Alphabetize String
  • C# Alphanumeric Sorting
  • C# EventLog Example
  • C# PadRight and PadLeft: String Columns
  • C# Arithmetic Expression Optimization
  • C# Array.AsReadOnly Method (ObjectModel)
  • C# Array.BinarySearch Method
  • C# Map Example
  • ASP.NET MapPath: Virtual and Physical Paths
  • C# Get Paragraph From HTML With Regex
  • C# Array.Clear Examples
  • C# Exception Handling
  • C# explicit and implicit Keywords
  • C# Factory Design Pattern
  • C# File.Copy Examples
  • C# typeof and nameof Operators
  • C# string.Concat Examples
  • C# String Interpolation Examples
  • C# string.Join Examples
  • C# String Performance, Memory Usage Info
  • C# String Property
  • C# String Slice, Get Substring Between Indexes
  • C# String Switch Examples
  • C# String
  • C# StringBuilder Append Performance
  • C# Mask Optimization
  • C# MaskedTextBox Example
  • C# Parallel.For Example (Benchmark)
  • C# StringBuilder Cache
  • C# Math.Abs: Absolute Value
  • C# Parallel.Invoke: Run Methods on Separate Threads
  • C# Array.IndexOf, LastIndexOf: Search Arrays
  • C# Remove Duplicate Chars
  • C# IEqualityComparer
  • C# If Preprocessing Directive: Elif and Endif
  • C# If Versus Switch Performance
  • C# if Statement
  • C# Parameter Optimization
  • C# Parameter Passing, ref and out
  • C# params Keyword
  • C# int.Parse: Convert Strings to Integers
  • C# TextWriter, Returned by File.CreateText
  • C# this Keyword
  • C# ThreadPool
  • C# OrderBy, OrderByDescending Examples
  • C# Process Examples (Process.Start)
  • C# Thread Join Method (Join Array of Threads)
  • C# ThreadPool.SetMinThreads Method
  • C# TimeZone Examples
  • Panel, Windows Forms (Create Group of Controls)
  • C# Path Examples
  • C# Get Percentage From Number With Format String
  • ASP.NET PhysicalApplicationPath
  • C# PictureBox: Windows Forms
  • C# PNG Optimization
  • C# Position Windows: Use WorkingArea and Location
  • Visual Studio Post Build, Pre Build Macros
  • C# Get Title From HTML With Regex
  • C# ToArray Extension Method
  • C# ProfileOptimization
  • C# ProgressBar Example
  • C# ToCharArray: Convert String to Array
  • C# ToDictionary Method
  • C# Bool Methods, Return True and False
  • C# bool Sort Examples (True to False)
  • C# Stopwatch Examples
  • C# Stream
  • C# StreamReader ReadToEnd Example (Read Entire File)
  • C# StreamReader ReadToEndAsync Example (Performance)
  • C# StreamReader Examples
  • C# StreamWriter Examples
  • C# String Append (Add Strings)
  • C# Caesar Cipher
  • C# String Compare and CompareTo Methods
  • C# Cast Extension: System.Linq
  • C# Cast to Int (Convert Double to Int)
  • C# Cast Examples
  • C# catch Examples
  • C# String Constructor (new string)
  • C# Math.Ceiling Usage
  • C# return Keyword
  • C# Math.Floor Method
  • C# Program to generate Fibonacci Triangle
  • C# String TrimEnd() method
  • C# Math.Max and Math.Min Examples
  • C# String Compare() method
  • C# var Examples
  • C# virtual Keyword
  • C# void Method, Return No Value
  • C# volatile Example
  • C# WebBrowser Control (Navigate Method)
  • C# WebClient: DownloadData, Headers
  • C# Where Method and Keyword
  • C# Math.Pow Method, Exponents
  • C# String CompareOrdinal() method
  • C# String TrimStart() method
  • C# Math.Round Examples: MidpointRounding
  • C# String CompareTo() method
  • C# Math Type
  • C# Reverse String
  • C# String Concat() method
  • C# Max and Min: Get Highest or Lowest Element
  • C# Reverse Words
  • C# Reverse Extension Method
  • C# RichTextBox Example
  • C# String Contains() method
  • C# MemoryFailPoint and InsufficientMemoryException
  • C# String CopyTo() method
  • C# partial Keyword
  • C# ToBase64String (Data URI Image)
  • C# Path.ChangeExtension
  • C# Struct Versus Class
  • C# struct Examples
  • C# Path Exists Example
  • C# Path.GetExtension: File Extension
  • C# Path.GetRandomFileName Method
  • C# Pragma Directive
  • C# Predicate (Lambda That Returns True or False)
  • C# Pretty Date Format (Hours or Minutes Ago)
  • C# PreviewKeyDown Event
  • C# Substring Examples
  • C# Numeric Suffix Examples
  • C# switch Examples
  • C# Convert Degrees Celsius to Fahrenheit
  • C# Convert Dictionary to List
  • C# Convert Dictionary to String (Write to File)
  • C# Convert List to Array
  • C# Convert List to DataTable (DataGridView)
  • C# Convert List to String
  • C# Convert Miles to Kilometers
  • C# Convert Milliseconds, Seconds, Minutes
  • C# Convert Nanoseconds, Microseconds, Milliseconds
  • C# Console.Read Method
  • C# Console.ReadKey Example
  • C# Console.ReadLine Example (While Loop)
  • C# Console.SetOut and Console.SetIn
  • C# Intersect: Get Common Elements
  • C# InvalidCastException
  • C# InvalidOperationException: Collection Was Modified
  • C# Console.WindowHeight
  • C# DriveInfo Examples
  • C# IOException Type: File, Directory Not Found
  • C# Right String Part
  • C# RNGCryptoServiceProvider Example
  • C# Property Examples
  • C# PropertyGrid: Windows Forms
  • C# Protected and internal Keywords
  • C# Public and private Methods
  • C# Console.Write, Append With No Newline
  • C# Console.WriteLine (Print)
  • C# DropDownItems Control
  • C# IOrderedEnumerable (Query Expression With orderby)
  • C# is: Cast Examples
  • C# Remove Punctuation From String
  • C# Query Windows Forms (Controls.OfType)
  • C# Queryable: IQueryable Interface and AsQueryable
  • ASP.NET QueryString Examples
  • C# Queue Collection: Enqueue
  • C# const Example
  • C# Constraint Puzzle Solver
  • C# IComparable Example, CompareTo: Sort Objects
  • C# RadioButton Use: Windows Forms
  • C# ReadOnlyCollection Use (ObjectModel)
  • C# Recursion Optimization
  • C# Recursive File List: GetFiles With AllDirectories
  • C# ref Keyword
  • C# Reflection Examples
  • C# Regex.Escape and Unescape Methods
  • C# Count Characters in String
  • C# Count, Dictionary (Get Number of Keys)
  • C# IDictionary Generic Interface
  • C# IEnumerable Examples
  • C# IsFixedSize, IsReadOnly and IsSynchronized Arrays
  • C# Count Letter Frequencies
  • C# IList Generic Interface: List and Array
  • C# string.IsNullOrEmpty, IsNullOrWhiteSpace
  • C# IsSorted Method: If Array Is Already Sorted
  • C# ROT13 Method, Char Lookup Table
  • C# StringBuilder Examples
  • C# StringComparison and StringComparer
  • C# StringReader Class (Get Parts of Strings)
  • C# Count Extension Method: Use Lambda to Count
  • C# Image Type
  • C# ImageList Use: Windows Forms
  • C# string.Copy Method
  • C# CopyTo String Method: Put Chars in Array
  • C# value Keyword
  • C# Empty String Examples
  • C# ValueTuple Examples (System.ValueTuple, ToTuple)
  • C# ValueType Examples
  • C# String Equals Examples
  • C# String For Loop, Count Spaces in String
  • C# string.Intern and IsInterned
  • C# Variable Initializer for Class Field
  • C# String IsUpper, IsLower
  • C# String Length Property: Get Character Count
  • C# Token
  • C# String EndsWith() method
  • C# ToList Extension Method
  • C# String Equals() method
  • C# String IsNormalized() method
  • C# ToLookup Method (Get ILookup)
  • C# String Format() method
  • C# ToLower and ToUpper: Uppercase and Lowercase Strings
  • C# String IndexOf() method
  • C# TabControl: Windows Forms
  • TableLayoutPanel: Windows Forms
  • ToolStripContainer Control: Dock, Properties
  • C# ToolTip: Windows Forms
  • C# ToString Integer Optimization
  • C# String Insert() method
  • C# Take and TakeWhile Examples
  • C# Task Examples (Task.Run, ContinueWith and Wait)
  • C# Ternary Operator
  • C# Text Property: Windows Forms
  • C# TextBox.AppendText Method
  • C# TextBox Example
  • C# TextChanged Event
  • C# TextFieldParser Examples: Read CSV
  • C# ToString: Get String From Object
  • C# String Intern(String str) method
  • C# String IsInterned() method
  • C# ToTitleCase Method
  • C# TrackBar: Windows Forms
  • C# Tree and Nodes Example: Directed Acyclic Word Graph
  • C# TreeView Tutorial
  • C# String Normalize() method
  • C# Convert String Array to String
  • C# Jagged Array Examples
  • C# MemoryStream: Use Stream on Byte Array
  • C# MenuStrip: Windows Forms
  • C# int.MaxValue, MinValue (Get Lowest Number)
  • C# Program to reverse number
  • C# Modulo Operator: Get Remainder From Division
  • C# MonthCalendar Control: Windows Forms
  • C# Int and uint Types
  • C# Integer Append Optimization
  • C# Keywords
  • C# Label Example: Windows Forms
  • C# Lambda Expressions
  • C# LastIndexOf Examples
  • C# Last, LastOrDefault Methods
  • C# Convert TimeSpan to Long
  • C# Convert Types
  • C# join Examples (LINQ)
  • C# Multiple Return Values
  • C# Multiply Numbers
  • C# Mutex Example (OpenExisting)
  • C# Named Parameters
  • C# String GetEnumerator() method
  • C# String GetHashCode() method
  • C# KeyCode Property and KeyDown
  • C# namespace Keyword
  • C# NameValueCollection Usage
  • C# Nested Lists: Create 2D List or Jagged List
  • C# Nested Switch Statement
  • C# Copy Dictionary
  • C# KeyNotFoundException: Key Not Present in Dictionary
  • C# KeyValuePair Examples
  • C# Environment.NewLine
  • C# Let Keyword (Use Variable in Query Expression)
  • C# Levenshtein Distance
  • C# Regex Versus Loop: Use For Loop Instead of Regex
  • C# Regex.Match Examples: Regular Expressions
  • C# RemoveAll: Use Lambda to Delete From List
  • C# Replace String Examples
  • ASP.NET Response.BinaryWrite
  • ASP.NET Response.Write
  • C# Return Optimization: out Performance
  • C# Count Elements in Array and List
  • C# SelectMany Example: LINQ
  • C# Sentinel Optimization
  • C# SequenceEqual Method (If Two Arrays Are Equal)
  • C# Shift Operators (Bitwise)
  • C# Short and ushort Types
  • C# Single Method: Get Element If Only One Matches
  • C# SingleOrDefault
  • C# Singleton Pattern Versus Static Class
  • C# Singleton Class
  • C# sizeof Keyword
  • C# Skip and SkipWhile Examples
  • C# Sleep Method (Pause)
  • C# Sort Dictionary: Keys and Values
  • C# String Literal: Newline and Quote Examples
  • C# LinkLabel Example: Windows Forms
  • C# LINQ
  • C# List Add Method, Append Element to List
  • C# List AddRange, InsertRange (Append Array to List)
  • C# List Clear Example
  • C# List Contains Method
  • C# List Remove Examples
  • C# List Examples
  • C# ListBox Tutorial (DataSource, SelectedIndex)
  • C# ListView Tutorial: Windows Forms
  • C# SaveFileDialog: Use ShowDialog and FileName
  • C# Scraping HTML Links
  • C# sealed Keyword
  • C# Seek File Examples: ReadBytes
  • C# select new Example: LINQ
  • C# ThreadStart and ParameterizedThreadStart
  • C# Extension Method
  • C# StringBuilder Capacity
  • C# extern alias Example
  • C# StringBuilder Clear (Set Length to Zero)
  • C# StringBuilder Data Types
  • C# StringBuilder Performance
  • C# Select Method (Use Lambda to Modify Elements)
  • C# StringBuilder Equals (If Chars Are Equal)
  • C# StringBuilder Memory
  • C# Convert Feet, Inches
  • C# StringBuilder ToString: Get String From StringBuilder
  • C# Serialize List (Write to File With BinaryFormatter)
  • C# Maze Pathfinding Algorithm
  • C# Memoization
  • C# Memory Usage for Arrays of Objects
  • C# MessageBox.Show Examples
  • C# Method Call Depth Performance
  • C# Method Parameter Performance
  • C# Method Size Optimization
  • C# throw Keyword Examples
  • C# Timer Examples
  • C# TimeSpan Examples
  • C# StringWriter Class
  • C# async, await Examples
  • C# Attribute Examples
  • C# Average Method
  • C# BackgroundWorker
  • C# base Keyword
  • C# String Between, Before, After
  • C# Binary Representation int (Convert, toBase 2)
  • C# BinarySearch List
  • C# bool Array (Memory Usage, One Byte Per Element)
  • C# bool.Parse, TryParse: Convert String to Bool
  • C# bool Type
  • C# Change Characters in String (ToCharArray, For Loop)
  • C# FromOADate and Excel Dates
  • C# Char Combine: Get String From Chars
  • C# Generic Class, Generic Method Examples
  • C# char.IsDigit (If Char Is Between 0 and 9)
  • C# CSV Methods (Parse and Segment)
  • C# GetEnumerator: While MoveNext, Get Current
  • C# GetHashCode (String Method)
  • C# Thumbnail Image With GetThumbnailImage
  • C# char.IsLower and IsUpper
  • C# Character Literal (const char)
  • C# DataRow Field Method: Cast DataTable Cell
  • C# GetType Method
  • C# Global Variable Examples (Public Static Property)
  • ASP.NET Global Variables Example
  • C# Char Lowercase Optimization
  • C# Char Test (If Char in String Equals a Value)
  • C# char.ToLower and ToUpper
  • C# Get Day Count Elapsed From DateTime
  • C# DateTime Format
  • C# Group By Operator: LINQ
  • GroupBox: Windows Forms
  • C# char Examples
  • C# DateTime.Now (Current Time)
  • C# GroupBy Method: LINQ
  • C# GroupJoin Method
  • C# Array Length Property, Get Size of Array
  • C# GZipStream Example (DeflateStream)
  • C# abstract Keyword
  • C# Action Object (Lambda That Returns Void)
  • C# DateTime.Today (Current Day With Zero Time)
  • C# DateTime.TryParse and TryParseExact
  • C# DateTime Examples
  • C# DateTimePicker Example
  • C# Debug.Write Examples
  • C# Visual Studio Debugging Tutorial
  • C# decimal Examples
  • C# HashSet Examples
  • C# Hashtable Examples
  • C# delegate Keyword
  • C# descending, ascending Keywords
  • C# while Loop Examples
  • C# Whitespace Methods: Convert UNIX, Windows Newlines
  • C# XmlReader, Parse XML File
  • C# XmlTextReader
  • C# XmlTextWriter
  • C# XmlWriter, Create XML File
  • C# XOR Operator (Bitwise)
  • C# yield Example
  • C# File.Delete
  • C# File Equals: Compare Files
  • C# File.Exists Method
  • C# TrimEnd and TrimStart
  • C# True and False
  • C# Truncate String
  • C# String ToLower() method
  • C# History
  • C# Features
  • C# Variables
  • C# Data Types
  • C# float Numbers
  • C# Settings.settings in Visual Studio
  • C# Shuffle Array: KeyValuePair and List
  • C# Single and Double Types
  • C# try Keyword
  • C# TryGetValue (Get Value From Dictionary)
  • C# Tuple Examples
  • C# Trim Strings
  • C# String IsNullOrEmpty() method
  • C# Type Class: Returned by typeof, GetType
  • C# Word Count
  • C# Thread Methods
  • C# String IsNullOrWhiteSpace() method
  • C# Single Instance Windows Form
  • C# TypeInitializationException
  • C# String Join() method
  • C# Word Interop: Microsoft.Office.Interop.Word
  • C# String LastIndexOf() method
  • FlowLayoutPanel Control
  • C# Focused Property
  • C# FolderBrowserDialog Control
  • C# Font Type: FontFamily and FontStyle
  • C# FontDialog Example
  • C# for Loop Examples
  • C# foreach Loop Examples
  • ForeColor, BackColor: Windows Forms
  • C# Form: Event Handlers
  • C# Contains String Method
  • C# Union: Combine and Remove Duplicate Elements
  • C# XElement Example (XElement.Load, XName)
  • C# String LastIndexOfAny() method
  • C# Snippet Examples
  • C# Sort DateTime List
  • C# Sort List With Lambda, Comparison Method
  • C# Sort Number Strings
  • C# Sort Examples: Arrays and Lists
  • C# SortedDictionary
  • C# SortedList
  • C# SortedSet Examples
  • C# Unreachable Code Detected
  • C# Unsafe Keyword: Fixed, Pointers
  • C# Uppercase First Letter
  • C# Uri and UriBuilder Classes
  • C# String PadLeft() method
  • C# Split String Examples
  • C# Zip Method (Use Lambda on Two Collections)
  • C# String PadRight() method
  • C# Nullable
  • C# String Copy() method
  • C# Using Alias Example
  • C# using Statement: Dispose and IDisposable
  • C# File.Move Method, Rename File
  • C# String Remove() method
  • C# Array.Resize Examples
  • C# Array.Sort: Keys, Values and Ranges
  • C# Operators
  • C# Keywords
  • C# Button Example
  • C# Byte Array: Memory Usage, Read All Bytes
  • C# Byte and sbyte Types
  • C# Capacity for List, Dictionary
  • C# Case Insensitive Dictionary
  • C# case Example (Switch Case)
  • C# Char Array
  • C# Array.Reverse Example
  • C# Random Lowercase Letter
  • C# Random Paragraphs and Sentences
  • C# Array Slice, Get Elements Between Indexes
  • C# Array.TrueForAll: Use Lambda to Test All Elements
  • C# Random String
  • C# Checked and Unchecked Keywords
  • C# ArrayTypeMismatchException
  • C# as: Cast Examples
  • C# Random Number Examples
  • C# Assign Variables Optimization
  • C# ASCII Table
  • C# ASCII Transformation, Convert Char to Index
  • C# CheckedListBox: Windows Forms
  • C# AsEnumerable Method
  • C# AsParallel Example
  • ASP.NET AspLiteral
  • C# Line Count for File
  • C# Sort by File Size
  • C# Line Directive
  • C# Sort, Ignore Leading Chars
  • C# Sort KeyValuePair List: CompareTo
  • C# LinkedList
  • C# Sort Strings by Length
  • C# List CopyTo (Copy List Elements to Array)
  • C# List Equals (If Elements Are the Same)
  • C# List Find and Exists Examples
  • C# List Insert Performance
  • C# Thread.SpinWait Example
  • ASP.NET LiteralControl Example
  • C# Locality Optimizations (Memory Hierarchy)
  • C# lock Keyword
  • C# Long and ulong Types
  • C# Loop Over String Chars: Foreach, For
  • C# Loop Over String Array
  • C# Math.Sqrt Method

Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

Понравилась статья? Поделить с друзьями:
  • Sxstrace exe ошибка при запуске игры
  • Sweb ошибка 500
  • System sleep wake ошибка mac os
  • Sxstrace exe как устранить ошибку яндекс
  • Swat 4 вылетает критическая ошибка