C# - connecting to SQL Server - c#

At the beginning of my journey with C#, I am developing this simple Flashcard app. It can be used for learning vocabulary in new language.
I have created Flashcard class, also have been able to create functions allowing users to enter new words, revise them and play simple guessing game.
When creating new words, program ask user how many one, would like to create. Then uses object of Flashcard function n times, filling list with them.
After every operation like this, I'd like to insert new words, and its translation into a SQL Server database, although I've encountered first problem.
Flashcard.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlashCardApp
{
class Flashcard
{
private string Word;
private string Translation;
private string Description;
public bool IsKnownTemporarly;
public Flashcard(string word, string translation, string description)
{
Description = description;
Word = word;
Translation = translation;
IsKnownTemporarly = false;
}
public Flashcard()
{
Description = "Default description";
Translation = "Defualt translation";
Word = "Default word";
IsKnownTemporarly = false;
}
public Flashcard(Flashcard flashcard)
{
Description = flashcard.Description;
Word = flashcard.Word;
Translation = flashcard.Translation;
IsKnownTemporarly = flashcard.IsKnownTemporarly;
}
public string returnWord()
{
return Word;
}
public string returnDescription()
{
return Description;
}
public string returnTranslation()
{
return Translation;
}
public void CreateNewFlashcard()
{
Console.Write ("Word => ");
Word = Console.ReadLine();
Word = Word.ToLower();
Console.Write("Description => ");
Description = Description = Console.ReadLine();
Description = Description.ToLower();
Console.Write("Translation => ");
Translation = Console.ReadLine();
Translation = Translation.ToLower();
IsKnownTemporarly = false;
Console.Clear();
}
public void DisplayFlaschard()
{
Console.WriteLine(Word + " means " + Translation + " [" + Description + "]");
Console.ReadKey();
}
public void GuessWord()
{
Console.WriteLine("Do you remember this one? [" + Word + "]");
string userInput = Console.ReadLine();
if (userInput.ToLower() == Translation)
{
this.IsKnownTemporarly = true;
Console.WriteLine("Indeed, that is correct!");
Console.ReadKey();
Console.Clear();
}
else
{
Console.WriteLine("I'll help you this time, try to memorize!");
Console.WriteLine(Word + " means " + Translation + " [" + Description + "]");
this.IsKnownTemporarly = false;
Console.ReadKey();
Console.Clear();
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace FlashCardApp
{
class Program
{
static void Main(string[] args)
{
List<Flashcard> FlashcardsList = new List<Flashcard>();
Flashcard flashcard1 = new Flashcard("Car", "auto" ,"it drives
through streets");
Flashcard flashcard2 = new Flashcard("street", "droga" , "Lead you
around cities");
Flashcard flashcard3 = new Flashcard("screen", "ekran", "It displays
info");
Flashcard flashcard4 = new Flashcard("stapler", "zszywacz",
"costam");
Flashcard flashcard5 = new Flashcard("paper", "papier", "costam");
Flashcard flashcard6 = new Flashcard("pen", "dlugopis", "dligpsfs");
FlashcardsList.Add(flashcard1);
FlashcardsList.Add(flashcard2);
FlashcardsList.Add(flashcard3);
FlashcardsList.Add(flashcard4);
FlashcardsList.Add(flashcard5);
FlashcardsList.Add(flashcard6);
ConnectDB();
}
public static void ConnectDB()
{
string connectionString;
SqlConnection conn;
connectionString = #"Data Source=DESKTOP-RDM63QN\SQLEXPRESS; Initial
Catalog=Fishcards; User ID=MyName ;Password=MyPassword" ;
conn = new SqlConnection(connectionString);
conn.Open();
Console.WriteLine("Done!");
conn.Close();
}
public static void AddNewFlaschards(List<Flashcard> FlashcardsList)
{
Console.WriteLine("ADD NEW FLASCHARDS!");
Console.WriteLine("How many would you like to add?");
int count = Convert.ToInt32(Console.ReadLine());
Console.Clear();
for (int i = 0; i < count; i++)
{
Flashcard flashcard = new Flashcard();
Console.WriteLine("No. " + (i+1));
flashcard.CreateNewFlashcard();
FlashcardsList.Add(new Flashcard(flashcard));
}
Console.Read();
Console.Clear();
}
public static void ReviseFlashcards(List<Flashcard> FlashcardsList)
{
Console.WriteLine("REVISE YOUR SAVED FLASHCARDS!");
FlashcardsList.ForEach(fl => fl.DisplayFlaschard());
Console.Read();
Console.Clear();
}
public static bool IsThereAnyUnknownLeft(List<Flashcard> FlashcardsList)
{
int var = FlashcardsList.Count; // Merging the size of FlashcardList
int i = 0;
int sum = 0;
int[] array = new int[var];
foreach (Flashcard flashcard in FlashcardsList)
{
if(flashcard.IsKnownTemporarly == false)
{
array[i] = 0;
}
else
{
array[i] = 1;
}
i++;
}
for(int a = 0; a<var; a++)
{
sum = sum + array[a];
}
if (sum == var)
return true;
else
return false;
}
public static void PlayGuessingGame(List<Flashcard> FlashcardsList)
{
while(!IsThereAnyUnknownLeft(FlashcardsList))
{
foreach (Flashcard flashcard in FlashcardsList.Where(flashcard
=> flashcard.IsKnownTemporarly == false))
{
flashcard.GuessWord();
}
}
Console.Read();
Console.Clear();
}
}
}
Problem is that Visual Studio returns an error on conn.Open() with this info:
System.Data.SqlClient.SqlException: Cannot open database "Fishcards" requested by the login. The login failed.
Login failed for user 'MyNameisHere'.

Related

RAVENDB The name "Store" doesn't exist in the current context

I've been working on getting this to work all day, and haven't had any success. I want to clean up my code and separate different chunks of code into different classes and functions. Here is a chunk of code that refuses to run.
using System;
using Raven.Client.Documents;
namespace RavendbTest
{
class Program
{
static void Main(string[] args)
{
var store = new DocumentStore
{
Urls = new[] { "http://localhost:8080" },
Database = "Tasks"
};
store.Initialize();
}
static void Checking()
{
Console.WriteLine("Login or Sign Up? (L/S)");
string userInput = Console.ReadLine();
if (userInput.ToLower() == "l")
{
Console.WriteLine("Logging you in");
}
else if (userInput.ToLower() == "s")
{
Console.WriteLine("Signing you up\n");
Console.Write("First Name: ");
string firstName = Console.ReadLine();
char firstNameInitial = firstName.ToLower()[0];
Console.WriteLine(firstNameInitial);
Console.Write("Last Name: ");
string lastName = Console.ReadLine();
char lastNameInitial = lastName.ToLower()[0];
Console.WriteLine(lastNameInitial);
Console.Write("Email: ");
string email = Console.ReadLine();
string combinedInitial = firstNameInitial.ToString() + lastNameInitial.ToString();
Console.WriteLine(combinedInitial);
// Checking if email has a '#' symbol in it. Determine validity
bool isVerified = false;
for (int i = 0; email.Length > i; i++)
{
if (email[i] != '#')
{
continue;
}
else if (email[i] == '#')
{
isVerified = true;
}
}
if (isVerified == true)
{
using (var session = Store.OpenSession())
{
var task = session.Load<Entity>(combinedInitial + email);
if (task == null)
{
Console.WriteLine("Creating your account");
var newUser = new Entity
{
Id = combinedInitial + email,
FirstName = firstName,
LastName = lastName,
Email = email
};
session.Store(newUser);
session.SaveChanges();
}
else
{
Console.WriteLine("This email is already in use... Would you like to login? (Y/N)");
string changeChoice = Console.ReadLine();
if (changeChoice.ToLower()[0] == 'y')
{
}
else
{
Console.WriteLine("Exiting Program");
}
}
using (var session = store.OpenSession())
{
var task = session.Load<Entity>(combinedInitial + email);
}
}
}
else
{
Console.WriteLine("Please enter a valid email address");
Console.WriteLine("Exiting Program");
}
}
else
{
Console.WriteLine("Error");
}
}
}
}
I thinking that I'm getting errors because my function checking can't see that I've already initialize a DocumentStore. Any help is greatly appreciated

WebRequests in C# are very CPU Intensive. Need something better

I have a program that needs to scan for other devices running my program on the network. The solution I came up with was to call each ipAddress to see if my program is running.
The code below is completely blocking the cpu:-
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FileWire
{
class SearchNearby
{
private bool pc_search_cancelled = false;
private SynchronizedCollection<Thread> PCSearchThreadList;
private ConcurrentDictionary<String, String> NearbyPCList;
public void NewPcFound(string s, string s1)
{
Console.WriteLine(string.Format("PC Found at: {0} PC Name: {1}", s, s1));
}
public SearchNearby()
{
startPCScan();
while (true)
{
bool isAnyAlive = false;
foreach(Thread t in PCSearchThreadList)
{
isAnyAlive |= t.IsAlive;
}
if (!isAnyAlive)
{
Console.WriteLine("Search Complete");
foreach (var a in NearbyPCList)
{
Console.WriteLine(a.Key + " ;; " + a.Value);
}
startPCScan();
}
Thread.Sleep(100);
}
}
private void startPCScan()
{
PCSearchThreadList = new SynchronizedCollection<Thread>();
NearbyPCList = new ConcurrentDictionary<String, String>();
pc_search_cancelled = false;
String add = "";
System.Net.IPAddress[] ad = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList;
foreach (System.Net.IPAddress ip in ad)
{
add += ip.ToString() + "\n";
}
bool connected;
if (add.Trim(' ').Length == 0)
{
connected = false;
}
else
{
connected = true;
}
if (connected)
{
try
{
String[] addresses = add.Split('\n');
foreach (String address in addresses)
{
int myIP = int.Parse(address.Substring(address.LastIndexOf(".") + 1));
for (int def = 0; def <= 10; def++)
{
int finalDef = def;
for (int j = 0; j < 10; j++)
{
string finalJ = j.ToString();
Thread thread = new Thread(new ThreadStart(() =>
{
if (!pc_search_cancelled)
{
for (int i = (finalDef * 25); i < (finalDef * 25) + 25 && i <= 255; i++)
{
if (!pc_search_cancelled)
{
if (i != myIP)
{
String callToAddress = "http://" + address.Substring(0, address.LastIndexOf(".")) + "." + i + ":" + (1234 + int.Parse(finalJ)).ToString();
String name = canGetNameAndAvatar(callToAddress);
if (name != null)
{
NearbyPCList[callToAddress] = name;
NewPcFound(callToAddress, name);
}
}
}
}
}
}));
PCSearchThreadList.Add(thread);
thread.Start();
}
}
}
} catch (Exception e) {
}
}
}
private String canGetNameAndAvatar(String connection)
{
String link = connection + "/getAvatarAndName";
link = link.Replace(" ", "%20");
try
{
var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(500);
var a = new Task<HttpResponseMessage>[1];
a[0] = client.GetAsync(link);
Task.WaitAll(a);
var b = a[0].Result.Content.ReadAsStringAsync();
Task.WaitAll(b);
Console.WriteLine(b.Result);
string result = b.Result;
result = result.Substring(result.IndexOf("<body>") + 6, result.IndexOf("</body>") - (result.IndexOf("<body>") + 6));
AvtarAndName json = JsonConvert.DeserializeObject<AvtarAndName>(result);
if (json != null)
{
return json.name;
}
}
catch
{
return null;
}
return null;
}
}
}
This is the exact C# version of the java code I was using in Java:-
import com.sun.istack.internal.Nullable;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class PCScan {
private static boolean pc_search_cancelled = false;
private static List<Thread> PCSearchThreadList;
private static HashMapWithListener<String, String> NearbyPCList;
public static void main(String[] args) {
start();
while (true) {
int numCompleted = 0;
for (Thread t : PCSearchThreadList) {
if (!t.isAlive()) {
numCompleted++;
}
}
if (numCompleted == PCSearchThreadList.size()) {
start();
}
}
}
private static void start() {
try {
startPCScan();
} catch (SocketException e) {
e.printStackTrace();
}
NearbyPCList.setPutListener(new HashMapWithListener.putListener() {
#Override
public void onPut(Object key, Object value) {
System.out.println(key.toString() + ";;" + value.toString());
}
});
}
private static void startPCScan() throws SocketException {
pc_search_cancelled = false;
PCSearchThreadList = new CopyOnWriteArrayList<>();
NearbyPCList = new HashMapWithListener<>();
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
boolean connected;
String add = "";
while (enumeration.hasMoreElements()) {
NetworkInterface interfacea = enumeration.nextElement();
if (!interfacea.isLoopback()) {
Enumeration<InetAddress> enumeration1 = interfacea.getInetAddresses();
while (enumeration1.hasMoreElements()) {
String address = enumeration1.nextElement().getHostAddress();
if (address.split("\\.").length == 4) {
add += address + "\n";
}
}
}
}
System.out.println(add);
connected = true;
if (connected) {
try {
String[] addresses = add.split("\n");
addresses = new HashSet<String>(Arrays.asList(addresses)).toArray(new String[0]);
for (String address : addresses) {
int myIP = Integer.parseInt(address.substring(address.lastIndexOf(".") + 1));
for (int def = 0; def <= 10; def++) {
int finalDef = def;
for (int j = 0; j < 10; j++) {
int finalJ = j;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
if (!pc_search_cancelled) {
for (int i = (finalDef * 25); i < (finalDef * 25) + 25 && i <= 255; i++) {
if (!pc_search_cancelled) {
if (i != myIP) {
String callToAddress = "http://" + address.substring(0, address.lastIndexOf(".")) + "." + i + ":" + String.valueOf(Integer.parseInt("1234") + finalJ);
String name = canGetNameAndAvatar(callToAddress);
if (name != null) {
NearbyPCList.put(callToAddress, name);
}
}
}
}
}
}
});
PCSearchThreadList.add(thread);
thread.start();
}
}
// }
// }).start();
}
} catch (Exception e) {
}
}
}
private static String canGetNameAndAvatar(String connection) {
String link = connection + "/getAvatarAndName";
link = link.replaceAll(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
httpParams.setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 500);
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
String result = sb.toString();
result = result.substring(result.indexOf("<body>") + 6, result.indexOf("</body>"));
JSONObject json = new JSONObject(result);
if (json != null) {
return json.getString("name");
}
}
catch (Exception ignored){
return null;
}
return null;
}
static class HashMapWithListener<K, V> extends HashMap<K, V> {
private putListener PutListener;
public void setPutListener(putListener PutListener) {
this.PutListener = PutListener;
}
#Nullable
#Override
public V put(K key, V value) {
PutListener.onPut(key, value);
return super.put(key, value);
}
interface putListener {
public void onPut(Object key, Object value);
}
}
}
The java code runs absolutely fine and only uses about 20 percent cpu while c# code absolutely locks the PC. I tried Webclient, webrequest, httpClient. All have literally the same performance.
I need the code to be in c# as I can't include whole JRE in my program since it is too large. The rest of my program and GUI is in WPF format.
Also, I need the code to take a maximum of 50seconds while scanning ports 1234-1243. This code also works absolutely fine even on a midrange android phone. So, I don't know what the problem is.
I would suggest something like this (I've simplified it for the sake of an example):
private static HttpClient _client = new HttpClient() { Timeout = TimeSpan.FromMilliseconds(500) };
private async Task<Something> GetSomething(string url)
{
using (HttpResponseMessage response = await _client.GetAsync(url))
{
string json = await response.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Something>(json);
}
}
private async Task<Something[]> GetSomethings(string[] urls)
{
IEnumerable<Task<Something>> requestTasks = urls.Select(u => GetSomething(u));
Something[] results = await Task.WhenAll<Something>(requestTasks);
return results;
}
You should also make the method calling GetSomethings async, and await it, and do the same all the way up the call chain.
async/await uses a thread pool to execute, and the thread is actually suspended while the IO part of the request occurs, meaning that no CPU time is used during this period. When then IO part is done, it resumes the code at the await.
Related information:
Asynchronous programming documentation
How and when to use 'async' and 'await'
You are using threads and multithreading completely wrong.
Because I cannot really understand what you are trying to do because everything is cramped into one function, I cannot provide you with a more detailed solution.
But let me suggest the following: I understand, you want to execute some operation in the background connecting to some other computer, try something like this
var taskList = new List<Task>();
foreach (var pc in computers)
{
var currentPcTask = Task.Run(() => DoYourWorkForSomePcHere(pc));
taskList.Add(currentPcTask);
}
Task.WaitAll(taskList.ToArray());
This will be very CPU efficient.

Implementing Overrides in Bloomberg C# API

In querying "YAS_YLD_SPREAD" for multiple securities, I am trying to assign a different override value for the "YAS_BOND_PX" override of each (as per Excel snapshot)
However, I am doing something wrong in assigning the overrides, as the output does not return a single "YAS_YLD_SPREAD" for each security (it also spuriously returns a "YAS_YLD_SPREAD 1") and the values returned are not the 100.21, 645.06 values I expect/need
Grateful for your help,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArrayList = System.Collections.ArrayList;
using Event = Bloomberglp.Blpapi.Event;
using Element = Bloomberglp.Blpapi.Element;
using Message = Bloomberglp.Blpapi.Message;
using Name = Bloomberglp.Blpapi.Name;
using Request = Bloomberglp.Blpapi.Request;
using Service = Bloomberglp.Blpapi.Service;
using Session = Bloomberglp.Blpapi.Session;
using SessionOptions = Bloomberglp.Blpapi.SessionOptions;
using InvalidRequestException =
Bloomberglp.Blpapi.InvalidRequestException;
using Subscription = Bloomberglp.Blpapi.Subscription;
namespace COATI
{
public class BloombergFetch
{
public string[] IsinArray;
private const String APIREFDATA_SVC = "//blp/refdata";
private static readonly Name SECURITY_DATA =
Name.GetName("securityData");
private static readonly Name SECURITY = Name.GetName("security");
private static readonly Name FIELD_DATA = Name.GetName("fieldData");
private static readonly Name RESPONSE_ERROR =
Name.GetName("responseError");
private static readonly Name SECURITY_ERROR =
Name.GetName("securityError");
private static readonly Name FIELD_EXCEPTIONS =
Name.GetName("fieldExceptions");
private static readonly Name FIELD_ID = Name.GetName("fieldId");
private static readonly Name ERROR_INFO = Name.GetName("errorInfo");
private static readonly Name CATEGORY = Name.GetName("category");
private static readonly Name MESSAGE = Name.GetName("message");
private ArrayList d_securities = new ArrayList();
private ArrayList d_fields = new ArrayList();
private ArrayList d_overrides = new ArrayList();
private ArrayList d_overridevalues = new ArrayList();
static void Main()
{
BloombergFetch example = new BloombergFetch();
example.run();
System.Console.WriteLine("Press ENTER to quit");
System.Console.Read();
}
public void run()
{
string serverHost = "localhost";
int serverPort = 8194;
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.ServerHost = serverHost;
sessionOptions.ServerPort = serverPort;
System.Console.WriteLine("Connecting to " + serverHost + ":" +
serverPort);
Session session = new Session(sessionOptions);
bool sessionStarted = session.Start();
if (!sessionStarted)
{
System.Console.Error.WriteLine("Failed to start session.");
return;
}
d_securities.Add("XS0975256685 Corp");
d_securities.Add("XS1207058733 Corp");
d_fields.Add("YAS_YLD_SPREAD");
d_fields.Add("YAS_YLD_SPREAD");
d_overrides.Add("YAS_BOND_PX"); d_overridevalues.Add(116);
d_overrides.Add("YAS_BOND_PX"); d_overridevalues.Add(88);
try
{
sendRefDataRequest(session);
}
catch (InvalidRequestException e)
{
System.Console.WriteLine(e.ToString());
}
// wait for events from session.
eventLoop(session);
session.Stop();
*/
}
private void sendRefDataRequest(Session session)
{
if (!session.OpenService(APIREFDATA_SVC))
{
System.Console.Error.WriteLine("Failed to open service: " +
APIREFDATA_SVC);
return;
}
Service refDataService = session.GetService(APIREFDATA_SVC);
Request request = refDataService.CreateRequest("ReferenceDataRequest");
Element securities = request.GetElement("securities");
Element overrides = request.GetElement("overrides");
for (int i = 0; i < d_securities.Count; ++i)
{
securities.AppendValue((string)d_securities[i]);
}
Element fields = request.GetElement("fields");
for (int i = 0; i < d_fields.Count; ++i)
{
fields.AppendValue((string)d_fields[i]);
}
for (int i = 0; i < d_overrides.Count; ++i)
{
Element bboverride = overrides.AppendElement();
bboverride.SetElement("fieldId",d_overrides[i].ToString());
//bboverride.SetElement("fieldId", "YAS_BOND_PX");
bboverride.SetElement("value", Convert.ToBoolean(d_overridevalues[i]));
//bboverride.SetElement("value", 100);
}
System.Console.WriteLine("Sending Request: " + request);
session.SendRequest(request, null);
}
private void eventLoop(Session session)
{
bool done = false;
while (!done)
{
Event eventObj = session.NextEvent();
if (eventObj.Type == Event.EventType.PARTIAL_RESPONSE)
{
System.Console.WriteLine("Processing Partial Response");
processResponseEvent(eventObj);
}
else if (eventObj.Type == Event.EventType.RESPONSE)
{
System.Console.WriteLine("Processing Response");
processResponseEvent(eventObj);
done = true;
}
else
{
foreach (Message msg in eventObj.GetMessages())
{
System.Console.WriteLine(msg.AsElement);
if (eventObj.Type == Event.EventType.SESSION_STATUS)
{
if (msg.MessageType.Equals("SessionTerminated"))
{
done = true;
}
}
}
}
}
}
private void processResponseEvent(Event eventObj)
{
foreach (Message msg in eventObj.GetMessages())
{
if (msg.HasElement(RESPONSE_ERROR))
{
System.Console.WriteLine("REQUEST FAILED: " +
msg.GetElement(RESPONSE_ERROR));
continue;
}
Element securities = msg.GetElement(SECURITY_DATA);
int numSecurities = securities.NumValues;
System.Console.WriteLine("Processing " + numSecurities + " securities:");
for (int i = 0; i < numSecurities; ++i)
{
Element security = securities.GetValueAsElement(i);
string ticker = security.GetElementAsString(SECURITY);
System.Console.WriteLine("\nTicker: " + ticker);
if (security.HasElement("securityError"))
{
System.Console.WriteLine("\tSECURITY FAILED: " +
security.GetElement(SECURITY_ERROR));
continue;
}
Element fields = security.GetElement(FIELD_DATA);
if (fields.NumElements > 0)
{
System.Console.WriteLine("FIELD\t\tVALUE");
System.Console.WriteLine("-----\t\t-----");
int numElements = fields.NumElements;
for (int j = 0; j < numElements; ++j)
{
Element field = fields.GetElement(j);
System.Console.WriteLine(field.Name + "\t\t" +
field.GetValueAsString());
}
}
else System.Console.WriteLine("No fields");
}
}
}
}
}
I haven't read your code in detail but one obvious issue is that if you want to use a different overriden value for the two securities, you need to submit two separate requests.
If you submit one request for XS0975256685 only with the YAS_BOND_PX override set to 116, you should get the desired result (I got 101.8739 a minute ago which matches Excel's result at the same moment).
Also note that the returned value does change with the market so you may get different values at each run: refresh your Excel spreadsheet at the same time if you want to verify that the data match.

The best practice to debug grammar (mismatched input)

When I run Lexer+Parser (combined) using g4 grammar I get
No. of Tokens=9 line 1:1 mismatched input 'module' expecting '['
Verilog2001Visitor VisitR Visit Symbol=module Rule=74 range Line=[2]
module kuku(a,b);
The Buid is clean, no warnings/errors. What's the best practice to
find out the root cause for the mismatched input error
find out why incorrect rule range is being used
I use Antlrworks2, VS2010 Pro, Win XP SP3
here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Dfa;
using Antlr4.Runtime.Misc;
namespace Antlr4
{
public class MyVisitor : Verilog2001BaseVisitor<object>
{
public static String[] ruleNames = Verilog2001Parser.ruleNames;
public void VisitR (Verilog2001Parser.RangeContext context, CommonTokenStream CTS)
{
Console.WriteLine("Verilog2001Visitor VisitR");
context
.children
.OfType<TerminalNodeImpl>()
.ToList()
.ForEach(child => Visit(child , context, CTS));
}
private void Visit(TerminalNodeImpl node , Verilog2001Parser.RangeContext rc,
CommonTokenStream cts)
{
try
{
int NumChildrens = rc.ChildCount;
int RuleIndex = rc.GetRuleIndex();
ICharStream Line = cts.TokenSource.InputStream;
int LineNum = cts.TokenSource.Line;
int TokPos = cts.TokenSource.Column;
String RuleName = ruleNames[RuleIndex];
Console.WriteLine(" Visit Symbol={0} Rule={1} {2} Line=[{3}] {4}
Pos={5}", node.Symbol.Text, RuleIndex, RuleName, LineNum, Line.ToString(),
TokPos);
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex);
}
}
}
class Program
{
private static void Main(string[] args)
{
(new Program()).Run();
}
public void Run()
{
try
{
Console.WriteLine("START");
RunParser();
Console.Write("DONE. Hit RETURN to exit: ");
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex);
Console.Write("Hit RETURN to exit: ");
}
Console.ReadLine();
}
private void RunParser()
{
AntlrInputStream inputStream = new AntlrInputStream(" module kuku(a,b);\n");
Verilog2001Lexer Verilog2001Lexer = new Verilog2001Lexer(inputStream);
//for (int i = 1; i < Verilog2001Lexer.tokenNames.Length; i++)
//{ Console.WriteLine(Verilog2001Lexer.tokenNames[i]); }
CommonTokenStream TokenStream = new CommonTokenStream(Verilog2001Lexer);
int nTokens=TokenStream.GetNumberOfOnChannelTokens();
Console.WriteLine("No. of Tokens=" + nTokens);
//for (int i = 1; i < nTokens; i++)
//{ Console.WriteLine("Token "+i+" = "+commonTokenStream.Lt(i)); }
Verilog2001Parser Verilog2001Parser = new Verilog2001Parser(TokenStream);
MyVisitor visitor = new MyVisitor();
Verilog2001Parser.RangeContext R;
R = Verilog2001Parser.range();
visitor.VisitR(R, TokenStream);
}
}
}

Reading a file, reporting errors and inserting data into SQL Server database

The below code reads a texts file, formats it, displays any error and insert the data into SQL Server Database. I wrote the below code previously in Visual Basic, now I am trying to rewrite the code int C# but it is not working.
I cannot get the fields indicated to insert into a database: I am trying to get the records without errors to insert into the database even when their are error with other rows.
This was a project I did piece by piece as I am still learning this stuff, so please forgive my ignorance. The database portion seems fine so I did not post it but I can if requested.
Classes from file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace ConsoleApplication1
{
class ClsMethods
{
public class MemberInfo
{
public static string MemberPhone;
public static string MemberName;
public static string MemberAddr1;
public static string MemberAddr2;
public static string MemberCity;
public static string MemberState;
public static string MemberZip;
}
public class ErrLog
{
public static int RowNum;
public static List<string> Err;
public ErrLog(int row)
{
RowNum = row;
Err = new List<string>();
}
public ErrLog()
{
Err = new List<string>();
}
}
}
}
MainCode:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
public static class MainModule
{
static List<ClsMethods.ErrLog> ErrList;
public static void Main()
{
string strFilename = null;
FileInfo fiFile = default(FileInfo);
StreamReader srData = default(StreamReader);
string strRecord = "";
List<ClsMethods.MemberInfo> MbrList = default(List<ClsMethods.MemberInfo>);
ClsMethods.MemberInfo MbrInfo = default(ClsMethods.MemberInfo);
int successCount = 0;
int failedCount = 0;
int totalCount = 0;
ErrList = new List<ClsMethods.ErrLog>();
strFilename = "C:\\EMP\\Member.csv";
fiFile = new FileInfo(strFilename);
if (fiFile.Exists)
{
if (fiFile.Length > 0)
{
MbrList = new List<ClsMethods.MemberInfo>();
srData = new StreamReader(strFilename);
while (srData.Peek() > 0)
{
try
{
strRecord = srData.ReadLine().Replace("\"", "");
totalCount = totalCount + 1;
String[] rec = strRecord.Split(",".ToCharArray());
if ((ValidateRow(rec, totalCount)))
{
MbrInfo = new ClsMethods.MemberInfo();
ClsMethods.MemberInfo.MemberPhone = rec[0];
ClsMethods.MemberInfo.MemberName = rec[1];
ClsMethods.MemberInfo.MemberAddr1 = rec[2];
ClsMethods.MemberInfo.MemberAddr2 = rec[3];
ClsMethods.MemberInfo.MemberCity = rec[4];
ClsMethods.MemberInfo.MemberState = rec[5];
ClsMethods.MemberInfo.MemberZip = rec[6];
MbrList.Add(MbrInfo);
}
}
catch (Exception ex)
{
Console.WriteLine("READ: " + ex.Message);
srData.Close();
srData.Dispose();
}
Console.WriteLine(strRecord);
}
foreach (ClsMethods.MemberInfo emp in MbrList)
{
if ((ClsDatabase.InsertMemberInfo(MbrInfo)))
{
successCount = successCount + 1;
}
else
{
failedCount = failedCount + 1;
}
}
Console.WriteLine("Total rows: {0} ", totalCount);
Console.WriteLine("Records without Errors: {0} ", MbrList.Count);
Console.WriteLine("Records with errors: {0} ", ErrList.Count);
Console.WriteLine("Inserted successfully: " + successCount.ToString());
Console.WriteLine("Failed: " + failedCount.ToString());
if ((ErrList.Count > 0))
{
Console.WriteLine("If you want to display errors press D. If you want to store errors in log file press F.");
ConsoleKeyInfo cki = default(ConsoleKeyInfo);
cki = Console.ReadKey();
Console.WriteLine();
string res = "";
res = cki.Key.ToString(res.ToUpper());
if ((res == "D"))
{
DisplayErrors();
}
else if ((res == "F"))
{
WriteErrorsToFile();
}
}
}
else
{
Console.WriteLine("File " + strFilename + " is empty");
}
}
else
{
Console.WriteLine("File " + strFilename + " doesn't exists");
}
Console.WriteLine("Program End. Press any key to exit");
Console.ReadKey();
Environment.Exit(0);
}
public static void DisplayErrors()
{
foreach (ClsMethods.ErrLog err in ErrList)
{
foreach (string errDescr in ClsMethods.ErrLog.Err)
{
Console.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
}
}
}
public static void WriteErrorsToFile()
{
string path = "C:\\Log\\log.txt";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
using (StreamWriter outfile = new StreamWriter(File.Create(path)))
{
foreach (ClsMethods.ErrLog err in ErrList)
{
foreach (string errDescr in ClsMethods.ErrLog.Err)
{
outfile.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
}
}
}
}
public static bool ValidateRow(string[] rec, int rowIndex)
{
ClsMethods.ErrLog Err = new ClsMethods.ErrLog();
if ((rec.Length != 7))
{
ClsMethods.ErrLog.Err.Add("Wrong number of values in row");
}
else
{
rec[0] = rec[0].Replace("-", "");
if ((string.IsNullOrEmpty(rec[0])))
{
ClsMethods.ErrLog.Err.Add("Phone is empty");
}
if ((string.IsNullOrEmpty(rec[1])))
{
ClsMethods.ErrLog.Err.Add("Name is empty");
}
if ((string.IsNullOrEmpty(rec[2])))
{
ClsMethods.ErrLog.Err.Add("Address is empty");
}
if ((string.IsNullOrEmpty(rec[4])))
{
ClsMethods.ErrLog.Err.Add("City is empty");
}
if ((string.IsNullOrEmpty(rec[5])))
{
ClsMethods.ErrLog.Err.Add("State is empty");
}
if ((string.IsNullOrEmpty(rec[6])))
{
ClsMethods.ErrLog.Err.Add("Zip is empty");
}
}
if ((ClsMethods.ErrLog.Err.Count > 0))
{
ClsMethods.ErrLog.RowNum = rowIndex;
ErrList.Add(Err);
return false;
}
else
{
return true;
}
}
}
}
}
Database Connection and Parameters:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace ConsoleApplication1
{
class ClsDatabase
{
public static SqlConnection GetConnection()
{
SqlConnection InitCnt = null;
InitCnt = new SqlConnection();
InitCnt.ConnectionString = "Server=MyDB;database=Example;Trusted_Connection=true;";
try
{
InitCnt.Open();
}
catch (Exception ex)
{
InitCnt.Close();
InitCnt.Dispose();
}
return InitCnt;
}
public static bool InsertMemberInfo(ClsMethods.MemberInfo MbrInfo)
{
SqlConnection InitCnt = default(SqlConnection);
SqlCommand InitCmd = default(SqlCommand);
InitCnt = GetConnection();
if ((InitCnt != null))
{
InitCmd = new SqlCommand();
InitCmd.Connection = InitCnt;
InitCmd.CommandText = "uspInsertMemberInformation";
InitCmd.CommandType = CommandType.StoredProcedure;
InitCmd.Parameters.Add(new SqlParameter("#MemberPhone", SqlDbType.NVarChar, 10));
InitCmd.Parameters["#MemberPhone"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberPhone"].Value = ClsMethods.MemberInfo.MemberPhone;
InitCmd.Parameters.Add(new SqlParameter("#MemberName", SqlDbType.NVarChar, 50));
InitCmd.Parameters["#MemberName"].Value = ClsMethods.MemberInfo.MemberName;
InitCmd.Parameters["#MemberName"].Value = ClsMethods.MemberInfo.MemberName;
InitCmd.Parameters.Add(new SqlParameter("#MemberAddr1", SqlDbType.NVarChar, 30));
InitCmd.Parameters["#MemberAddr1"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberAddr1"].Value = ClsMethods.MemberInfo.MemberAddr1;
InitCmd.Parameters.Add(new SqlParameter("#MemberAddr2", SqlDbType.NVarChar, 30));
InitCmd.Parameters["#MemberAddr2"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberAddr2"].Value = ClsMethods.MemberInfo.MemberAddr2;
InitCmd.Parameters.Add(new SqlParameter("#MemberCity", SqlDbType.NVarChar, 20));
InitCmd.Parameters["#MemberCity"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberCity"].Value = ClsMethods.MemberInfo.MemberCity;
InitCmd.Parameters.Add(new SqlParameter("#MemberState", SqlDbType.NChar, 2));
InitCmd.Parameters["#MemberState"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberState"].Value = ClsMethods.MemberInfo.MemberState;
InitCmd.Parameters.Add(new SqlParameter("#MemberZip", SqlDbType.NVarChar, 9));
InitCmd.Parameters["#MemberZip"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberZip"].Value = ClsMethods.MemberInfo.MemberZip;
try
{
InitCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
return false;
}
finally
{
InitCmd.Parameters.Clear();
InitCnt.Close();
}
}
return true;
}
}
}
Some really peculiar stuff there:
ClsMethods contains only classes and is not used; remove it.
MemberInfo contains only static fields, so every instance must always contain the same data.
ErrLog contains only a static field so, again, every instance will always contain the same data.
Main pointlessly sets a bunch of variables to default, which is always null, which is redundant. Why are you doing that?
MainModule is also redundant and should be removed.
All variables are global, which is unnecessary and risky.
MbrInfo = new ClsMethods.MemberInfo(); is useless because all fields are static, you will just be overwriting what is already there.
ClsDatabase.InsertMemberInfo(MbrInfo) will always pass the last record as many times as there are records in the file. I'm guessing you want ClsDatabase.InsertMemberInfo(emp). See why globals are bad?
InsertMemberInfo ignores the parameter you pass and uses the single static value for every parameter.
The default SqlParameter.Direction is Input, you don't have to reset it.
I wouldn't add "Member" to the front to every field; it's already in the class name. I'm guessing what you want is:
public class MemberInfo
{
public string Phone;
public string Name;
public string Addr1;
public string Addr2;
public string City;
public string State;
public string Zip;
}
Then in Main you can call:
MemberInfo mi = new MemberInfo();
mi.Phone = rec[0];
mi.Name = rec[1];
mi.Addr1 = rec[2];
mi.Addr2 = rec[3];
mi.City = rec[4];
mi.State = rec[5];
mi.Zip = rec[6];
MbrList.Add(mi);
You use the word Err to refer to a class, the log, and instance variables. This is very confusing. I suggest something like:
public class ErrLog
{
public int RowNum;
public List<string> Messages;
public ErrLog(int row)
: base()
{
RowNum = row;
}
public ErrLog()
{
Messages = new List<string>();
}
}
Your InsertMemberInfo should look more like this:
var sp = new SqlParameter("#MemberPhone", SqlDbType.NVarChar, 10);
sp.Value = MbrInfo.whatever;
InitCmd.Parameters.Add(sp);
Don't do this:
try
{
InitCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
return false;
}
That will discard the reason the procedure failed. Just do this:
InitCmd.ExecuteNonQuery();
Exceptions. Use them. A few more weird things in your code; start with what I've shown.

Categories