Autor Beitrag
Hippi
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Di 08.02.11 20:57 
Hallo liebes Forum,
Da ich noch Anfänger bin und in vielen Foren gesucht/gefragt habe und auch gegoogelt habe jedoch gute Antwort bekamm versuche ich es mal hier!

So ich habe eine externe MySql DatenbankVerbindung in meiner Konsolenanwendung angelegt. Jetzt hab ich vor so ein Lizenzsystem zu machen, so dass die Käufer/User den Lizenzkey in der Config-Datei einsetzt und die Konsolenanwendung fragt ab ob es in der externen Datenbank in der Tabelle ein Key gibt der in der Config eingegeben wurde! Wenn ja sollte das Programm weiterlaufen wenn nicht dann soll sich das ganze schliessen!

Hier mein Fortschritt im Code:

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
string myConnectionString = "SERVER=db4free.net;" + 
                            "DATABASE=DATENBANK;" + 
                            "UID=NAME;" + 
                            "PASSWORD=PASS;"

                MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString); 
                MySql.Data.MySqlClient.MySqlCommand command = connection.CreateCommand();
command.CommandText = ""// Hier zwischen sollte dann die If Abfrage sein doch ich komme nicht weiter!


Hier mein Code von dem Lizenz Abrage aus der Config-Datei
ausblenden C#-Quelltext
1:
int.Parse(UberEnvironment.GetConfig().data["lizenz"]);					


Ich brauche unbedingt hilfe! Danke

Moderiert von user profile iconChristian S.: Code- durch C#-Tags ersetzt
Trashkid2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 561
Erhaltene Danke: 137



BeitragVerfasst: Di 08.02.11 22:06 
Hallo und ein herzliches :welcome:

Also es kommt halt darauf an, was Du aus der Datenbank abfragen willst... wenn es Dir nur reicht zu wissen, dass der RegKey in der Tabelle vorkommt (ob nun 1x oder öfters) reicht ja ein ExecuteScalar hin. Also als Sql-Query einfach ein
ausblenden SQL-Anweisung
1:
Select COUNT(*) from <LicenceTabelle> WHERE <Spalte mit den Key> = requestedKey;					
Weil die ganze Abfrage aber per Parameter einfach mal sicher ist (SqlInjection) das Ganze nochmal unter Verwendung von Parametern:
ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
using (MySqlConnection connection = new MySqlConnection(connString))
{
  connection.Open();
  using (MySqlCommand command = new MySqlCommand("SELECT COUNT(*) FROM <LicenceTabelle> WHERE <Spalte mit den Key> = @regKey;", connection))
  {
    command.Parameters.AddWithValue("@regKey"int.Parse(UberEnvironment.GetConfig().data["lizenz"]););
    if ((Int64)command.ExecuteScalar() > 0)
    { 
      //key existiert                    
    }
  }
}

LG, Marko

Für diesen Beitrag haben gedankt: Hippi
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Di 08.02.11 22:35 
Vielen Dank! Ich werde mir das Morgen anschauen, da ich nicht am PC bin! Aufjedenfall danke, für die gute Antwort ;)
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Mi 09.02.11 16:20 
Hmm Leider funktionnert es nicht ganz!!
Christian S.
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 20451
Erhaltene Danke: 2264

Win 10
C# (VS 2019)
BeitragVerfasst: Mi 09.02.11 16:23 
Ich glaube, wenn Du nicht genauer beschreibst, was funktioniert und was nicht, wird Dir niemand helfen können ;-)

_________________
Zwei Worte werden Dir im Leben viele Türen öffnen - "ziehen" und "drücken".
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Mi 09.02.11 16:32 
Hallo!
Hier ist mein ganzer Code:

(ab Zeile 55-72 ist der gegebene Code von dem netten User eingetragen!)
ausblenden volle Höhe C#-Quelltext
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:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

using Uber.Core;
using Uber.Storage;
using Uber.Net;
using Uber.HabboHotel;


namespace Uber
{
    class UberEnvironment
    {
        private static Logging Logging;
        private static ConfigurationData Configuration;
        private static DatabaseManager DatabaseManager;
        private static Encoding DefaultEncoding;
        private static TcpConnectionManager ConnectionManager;
        private static MusSocket MusSocket;
        private static Game Game;

        public static String PrettyVersion
        {
            get
            {
                return "NexusEmu v3! Siempre revulucionando!";
            }
        }

        public static void Initialize()
        {
            Console.Title = PrettyVersion;

            DefaultEncoding = Encoding.Default;

            Logging = new Logging();
            Logging.MinimumLogLevel = LogLevel.Debug;

            UberEnvironment.GetLogging().WriteLine("           __  ___  ______                 Fixes Sacados de KM i ragezone    ");
            UberEnvironment.GetLogging().WriteLine("           ¡ ¡ ¡    ¡       ");
            UberEnvironment.GetLogging().WriteLine("           ¡ ¡ ¡    ¡       ");
            UberEnvironment.GetLogging().WriteLine("           ¡ ¡ ¡    ¡----       ");
            UberEnvironment.GetLogging().WriteLine("           ¡ ¡ ¡    ¡       ");
            UberEnvironment.GetLogging().WriteLine("           ¡ ¡_¡    ¡_____                                                        ");
            UberEnvironment.GetLogging().WriteLine("                                                NexusEmu v3! by x.a.n.a.99! La gran revulucion!");
            UberEnvironment.GetLogging().WriteLine("                                                                      ");
            UberEnvironment.GetLogging().WriteLine("       ------------------------------------------------------------------");
            UberEnvironment.GetLogging().WriteLine("                                                                      ");

            UberEnvironment.GetLogging().WriteLine("Vamos a pulsar el Boton de Encendido *Plip*");
           
            // Connection
            string myConnectionString = "SERVER=db4free.net;" +
                            "DATABASE=DATA;" +
                            "UID=ROOT;" +
                            "PASSWORD=PASS;";

            using (MySqlConnection connection = new MySqlConnection(myConnectionString))
            {
                connection.Open();
                using (MySqlCommand command = new MySqlCommand("SELECT COUNT(*) FROM lizensen WHERE key = @regKey;", connection))
                {
                    command.Parameters.AddWithValue("@regKey"int.Parse(UberEnvironment.GetConfig().data["lizenz"]));
                    if ((Int64)command.ExecuteScalar() > 0)
                    {
                        return;
                    }
                }
            }

                        try
                        {
                            Configuration = new ConfigurationData("Nexus-config.conf");

                            if (UberEnvironment.GetConfig().data["db.password"].Length == 0)
                            {
                                throw new Exception("For security reasons, your MySQL password cannot be left blank. Please change your password to start the server.");
                            }

                            if (UberEnvironment.GetConfig().data["db.password"] == "changeme")
                            {
                                throw new Exception("Your MySQL password may not be 'changeme'.\nPlease change your password to start the server.");
                            }
                            if (UberEnvironment.GetConfig().data["lizenz"].Length == 0)
                            {
                                throw new Exception("Bitte gebe in der Config einen Lizenzkey ein!");
                            }


                            DatabaseServer dbServer = new DatabaseServer(
                                UberEnvironment.GetConfig().data["db.hostname"],
                                uint.Parse(UberEnvironment.GetConfig().data["db.port"]),
                                UberEnvironment.GetConfig().data["db.username"],
                                UberEnvironment.GetConfig().data["db.password"]);

                            Database db = new Database(
                                UberEnvironment.GetConfig().data["db.name"],
                                uint.Parse(UberEnvironment.GetConfig().data["db.pool.minsize"]),
                                uint.Parse(UberEnvironment.GetConfig().data["db.pool.maxsize"]));

                            DatabaseManager = new DatabaseManager(dbServer, db);

                            MusSocket = new MusSocket(UberEnvironment.GetConfig().data["mus.tcp.bindip"],
                                int.Parse(UberEnvironment.GetConfig().data["mus.tcp.port"]),
                                UberEnvironment.GetConfig().data["mus.tcp.allowedaddr"].Split(';'), 20);

                            Game = new Game();

                            ConnectionManager = new TcpConnectionManager(
                                UberEnvironment.GetConfig().data["game.tcp.bindip"],
                                int.Parse(UberEnvironment.GetConfig().data["game.tcp.port"]),
                                int.Parse(UberEnvironment.GetConfig().data["game.tcp.conlimit"]));
                            ConnectionManager.GetListener().Start();

                            UberEnvironment.GetLogging().WriteLine("NexusEmu v3 by x.a.n.a.99,Se encemdio correctamente ya puedes entrar a Chutar Balones i Hablar con Los amigos!");

                        }

                        catch (KeyNotFoundException)
                        {
                            Logging.WriteLine("Please check your configuration file - some values appear to be missing.", LogLevel.Error);
                            Logging.WriteLine("Press any key to shut down ...", LogLevel.Error);

                            Console.ReadKey(true);
                            UberEnvironment.Destroy();

                            return;
                        }

                        catch (InvalidOperationException e)
                        {
                            Logging.WriteLine("Failed to initialize NexusEmu v3: " + e.Message, LogLevel.Error);
                            Logging.WriteLine("Pulsa una tecla para cerrar NexusEmu v3!", LogLevel.Error);

                            Console.ReadKey(true);
                            UberEnvironment.Destroy();

                            return;
                        }
                    }
                
            
        

        public static bool EnumToBool(string Enum)
        {
            if (Enum == "1")
            {
                return true;
            }

            return false;
        }

        public static string BoolToEnum(bool Bool)
        {
            if (Bool)
            {
                return "1";
            }

            return "0";
        }

        public static int GetRandomNumber(int Min, int Max)
        {
            RandomBase Quick = new Quick();
            return Quick.Next(Min, Max);
        }

        public static Double GetUnixTimestamp()
        {
            TimeSpan ts = (DateTime.UtcNow - new DateTime(197011000));
            return ts.TotalSeconds;
        }

        public static string FilterInjectionChars(string Input)
        {
            return FilterInjectionChars(Input, false);
        }

        public static string FilterInjectionChars(string Input, bool AllowLinebreaks)
        {
            Input = Input.Replace(Convert.ToChar(1), ' ');
            Input = Input.Replace(Convert.ToChar(2), ' ');
            //Input = Input.Replace(Convert.ToChar(3), ' ');
            Input = Input.Replace(Convert.ToChar(9), ' ');

            if (!AllowLinebreaks)
            {
                Input = Input.Replace(Convert.ToChar(13), ' ');
            }

            return Input;
        }

        public static bool IsValidAlphaNumeric(string inputStr)
        {
            if (string.IsNullOrEmpty(inputStr))
            {
                return false;
            }

            for (int i = 0; i < inputStr.Length; i++)
            {
                if (!(char.IsLetter(inputStr[i])) && (!(char.IsNumber(inputStr[i]))))
                {
                    return false;
                }
            }

            return true;
        }

        public static ConfigurationData GetConfig()
        {
            return Configuration;
        }

        public static Logging GetLogging()
        {
            return Logging;
        }

        public static DatabaseManager GetDatabase()
        {
            return DatabaseManager;
        }

        public static Encoding GetDefaultEncoding()
        {
            return DefaultEncoding;
        }

        public static TcpConnectionManager GetConnectionManager()
        {
            return ConnectionManager;
        }

        public static Game GetGame()
        {
            return Game;
        }

        public static void Destroy()
        {
            UberEnvironment.GetLogging().WriteLine("Destroying NexusEmu v3 environment...");

            if (GetGame() != null)
            {
                GetGame().Destroy();
                Game = null;
            }

            if (GetConnectionManager() != null)
            {
                UberEnvironment.GetLogging().WriteLine("Destroying connection manager.");
                GetConnectionManager().GetListener().Stop();
                GetConnectionManager().GetListener().Destroy();
                GetConnectionManager().DestroyManager();
                ConnectionManager = null;
            }

            if (GetDatabase() != null)
            {
                UberEnvironment.GetLogging().WriteLine("Destroying database manager.");
                GetDatabase().StopClientMonitor();
                GetDatabase().DestroyClients();
                GetDatabase().DestroyDatabaseManager();
                DatabaseManager = null;
            }

            Logging.WriteLine("Uninitialized successfully. Closing.");

            Environment.Exit(0);
        }
    }
}


Da mein Problem wenn ich die Konsolenanwendung öffne kommt!:

Object reference not set to an instance of an object.

Moderiert von user profile iconChristian S.: Code- durch C#-Tags ersetzt
Trashkid2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 561
Erhaltene Danke: 137



BeitragVerfasst: Mi 09.02.11 17:53 
So, wenn Du uns dann noch sagst, an welcher Stelle die NullReferenceException autritt, wäre es für alle, die helfen wollen sehr hilfreich!
Dazu ist der Code nämlich einfach mal zu lang.
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Mi 09.02.11 17:56 
An gar keiner Stelle hab durchsucht es ist nicht aufzufinden! Haben sie vielleicht TeamViewer für eine kleine Hilfe! Bitte ist mir sehr wichtig!
Trashkid2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 561
Erhaltene Danke: 137



BeitragVerfasst: Mi 09.02.11 18:04 
Wie jetzt? Wenn Du das Programm startest, wird die Exception geworfen, aber an keiner Stelle im Programm??
Wie soll denn das gehen.
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Mi 09.02.11 18:20 
Ja ist aber so warte ich schicke Ihnen das Projekt mal! Ich hoffe, dass du das ganze durchsuchst und mir weiterhelfen kannst und sagen wo der Fehler liegt!

Download:
www.mediafire.com/?kv0p520duib4cbv

Bitte D:

Wie gesagt bin totaler Anfänger und hab das Programm nicht geschrieben ich hab es nur gefixxt!
Trashkid2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 561
Erhaltene Danke: 137



BeitragVerfasst: Mi 09.02.11 20:02 
Hallo,

also habe mir das Projekt mal angeschaut.
Konnte den Fehler reproduzieren, was schonmal gut ist.
1. Also, die fehlende Referenz kam dadurch zustande, dass Du versuchst, aus der Configuration zu lesen, sie aber erst nach dem Versuch des Verbindungsaufbaus initialisiert wird.
Also müsste es so aussehen:
ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
Configuration = new ConfigurationData("Nexus-config.conf"); 
if (UberEnvironment.GetConfig().data.ContainsKey("lizenz"))
{
  using (MySqlConnection connection = new MySqlConnection(myConnectionString))
  {
    connection.Open();
    using (MySqlCommand command = new MySqlCommand("SELECT COUNT(*) FROM lizensen WHERE 'key' = @regKey;", connection))
    {
      command.Parameters.AddWithValue("@regKey", UberEnvironment.GetConfig().data["lizenz"]);
      if ((Int64)command.ExecuteScalar() > 0)
      {
        return;
      }
    }
  }
}

2. Im Command muss der Spaltenbezeichner in Hochkommas eingeschlossen sein. Das wusste ich aber auch nicht.
3. Ansonsten hast Du auch noch versucht, den RegKey in ein int zu konvertieren, aber da es eine Zeichenkette ist, wäre das auch gescheitert.
4. Du solltest abfragen, ob sich der Eintrag "lizenz" im Dictionary befindet (deshalb hier das ContainsKey)
5. Der Key in der Datenbank ist Latin1-Codiert. Deshalb klappt es mit dem Vergleich nicht. Also solltest Du entweder in der DB alles auf UTF-8 umstellen, oder musst es im Programm umkodieren.

So, hoffe, ich konnte helfen.
Spiel Spaß damit!
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Mi 09.02.11 20:30 
Ok! Danke das heißt ich muss nur diesen Code ersetzen und dann die Datenbank auf utf-8 setzen..?
Trashkid2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 561
Erhaltene Danke: 137



BeitragVerfasst: Mi 09.02.11 23:05 
Genau so läuft es. Mit der Umstellung auf UTF-8 muss ich mich nochmal verbessern:
Lag eher an dem Statement: der Spaltenbezeichner muss nicht in Hochkomma ('), sondern in (`) gekapselt werden. Somit ergibt sich folgendes Statement:
ausblenden SQL-Anweisung
1:
SELECT COUNT(*) FROM lizensen WHERE `key` = @regKey;					
Sorry, MySql ist da manchmal sehr eigensinnig. Damit ist also eine Umstellung nicht unbeding nötig. Aber besser wäre es, da auch das erste Feld auf UTF-8 gestellt ist. Ob das mit dem return hinhaut, wenn der Key gefunden wurde, kann ich nicht beurteilen, da ich nicht weiß, was dann passieren soll...aber für mich sieht das irgendwie falsch aus.

Ansonsten solltest Du nicht die Zugangsdaten der Datenbank so offenlegen!! Habe nicht probiert, welche Commands man ausführen kann, auch wenn es mir in den Fingern gekribbelt hat. Aber ein Insert konnte ich mir nicht verkneifen!

LG, Marko
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Mi 09.02.11 23:25 
Na vielen Dank! Ich wollte mit return; erzeugen, dass das Programm so weiterläuft bzw wieder zurück auf die "richtige" Bahn läuft oder sollte ich das anders anlegen...
Trashkid2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 561
Erhaltene Danke: 137



BeitragVerfasst: Do 10.02.11 07:39 
Definiere mal die "richtige Bahn" des Programms. Im Moment ist es so, dass, wenn der Key in der DB (vorrausgesetzt, es befindet sich einer in der Config) gefunden wurde, per return aus der Initialize()-Methode rausspringt. Was für mich keinen Sinn macht.

Also für mich steht der Code zur Abfrage des Keys in der DB einfach mal an der falschen Stelle. Zumal danach erstmal die Verbindungsdaten ausgelesen werden (also müsste der Connstring doch gar nicht hart reingecoded werden, wenn sich die Daten in der Config befinden, oder).

user profile iconHippi hat folgendes geschrieben Zum zitierten Posting springen:
hab das Programm nicht geschrieben ich hab es nur gefixxt!
Dann solltest Du eigentlich wissen, wie der Programmablauf sein sollte.
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Do 10.02.11 14:16 
Hallo,
Kannst "Du" bitte den Code bzw das Programm so bearbeiten, dass es klappt und dann das ganze auf mediafire.com hochladen! Ich versteh momentan nichts! Du hast ja Datenbank zugriff xP
Währe nett!
Trashkid2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 561
Erhaltene Danke: 137



BeitragVerfasst: Do 10.02.11 15:07 
Ich bin ja gerne hilfsbereit, aber das ist nun doch etwas viel verlangt!
Also nein.
Du hast gesagt, dass Du das Programm gefixt hast. Ich frage mich nur, ob das so geklappt hat.
Ich denke, ich habe schon viel geholfen und habe Dir gesagt, wie Du die Fehler fixen kannst. Wenn Du die Anleitung nicht in die Tat umsetzen kannst, tut es mir leid!
Marko
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Do 10.02.11 15:15 
Naja Trotzdem Danke! Werde das ganze jetzt ausprobieren ;)
Hippi Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 16



BeitragVerfasst: Do 10.02.11 16:03 
Okay Danke es funktionniert! Aufjedenfall würde ich gerne eine MessageBox ausgeben, wenn der Key falsch ist und nicht nür einfach, dass das Programm nicht weiterläuft!