Implementing Overrides in Bloomberg C# API - c#

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.

Related

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.

C# - connecting to SQL Server

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'.

Unity C# GraphQL Post Request Body Authentication

I am working on trying to connect to my GraphQL server my developers have setup from within Unity. I have found some scripts to help with this process, however, I am still not able to connect because i need to be logged into the system hosting graphql to be able to query externally, I cannot just use the endpoint url.
My developer has told me to do a POST request to mysystem/login and in the request body add {email: string, password: string}. I have tried a few different things and nothing is working. I have to log into the mysystem/login with email and password, then i will be able to connect to mygraphql endpoint from the code below.--i was assuming this portion would go where I have the //smt authentication notes. Any help on how to setup the post request and where it should be or how it should work would be much appreciated.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using SimpleJSON;
using UnityEngine;
using UnityEngine.Networking;
namespace graphQLClient
{
public class GraphQuery : MonoBehaviour
{
public static GraphQuery instance = null;
[Tooltip("The url of the node endpoint of the graphQL server being queried")]
public static string url;
public delegate void QueryComplete();
public static event QueryComplete onQueryComplete;
public enum Status { Neutral, Loading, Complete, Error };
public static Status queryStatus;
public static string queryReturn;
string authURL;
public static string LoginToken;
public class Query
{
public string query;
}
public void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
StartCoroutine("PostLogin");
}
private void Start()
{
LoginToken = "";
}
public static Dictionary<string, string> variable = new Dictionary<string, string>();
public static Dictionary<string, string[]> array = new Dictionary<string, string[]>();
// Use this for initialization
// SMT Authentication to ELP
// SMT Needed for Authentication--- if (token != null) request.SetRequestHeader("Authorization", "Bearer " + token);
//In the request body: {email: string, password: string}
//You’ll either get a 401 with an empty response or 201 with {token: string, user: object}
IEnumerator PostLogin()
{
Debug.Log("Logging in...");
string authURL = "https://myapp.com/login";
string loginBody = "{\"email\":\"myemail.com\",\"password\":\"mypassowrd\"}";
var request = new UnityWebRequest(authURL, "POST");
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(loginBody);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log("Login error!");
foreach (KeyValuePair<string, string> entry in request.GetResponseHeaders())
{
Debug.Log(entry.Value + "=" + entry.Key);
}
Debug.Log(request.error);
}
else
{
Debug.Log("Login complete!");
//Debug.Log(request.downloadHandler.text);
LoginToken = request.downloadHandler.text;
Debug.Log(LoginToken);
}
}
public static WWW POST(string details)
{
//var request = new UnityWebRequest(url, "POST");
details = QuerySorter(details);
Query query = new Query();
string jsonData = "";
WWWForm form = new WWWForm();
query = new Query { query = details };
jsonData = JsonUtility.ToJson(query);
byte[] postData = Encoding.ASCII.GetBytes(jsonData);
Dictionary<string, string> postHeader = form.headers;
//postHeader["Authorization"] = "Bearer " + downloadHandler.Token;
if (postHeader.ContainsKey("Content-Type"))
//postHeader["Content-Type"] = "application/json";
postHeader.Add("Authorization", "Bearer " + LoginToken);
else
//postHeader.Add("Content-Type", "application/json");
postHeader.Add("Authorization", "Bearer " + LoginToken);
WWW www = new WWW(url, postData, postHeader);
instance.StartCoroutine(WaitForRequest(www));
queryStatus = Status.Loading;
return www;
}
static IEnumerator WaitForRequest(WWW data)
{
yield return data; // Wait until the download is done
if (data.error != null)
{
Debug.Log("There was an error sending request: " + data.error);
queryStatus = Status.Error;
}
else
{
queryReturn = data.text;
queryStatus = Status.Complete;
}
onQueryComplete();
}
public static string QuerySorter(string query)
{
string finalString;
string[] splitString;
string[] separators = { "$", "^" };
splitString = query.Split(separators, StringSplitOptions.RemoveEmptyEntries);
finalString = splitString[0];
for (int i = 1; i < splitString.Length; i++)
{
if (i % 2 == 0)
{
finalString += splitString[i];
}
else
{
if (!splitString[i].Contains("[]"))
{
finalString += variable[splitString[i]];
}
else
{
finalString += ArraySorter(splitString[i]);
}
}
}
return finalString;
}
public static string ArraySorter(string theArray)
{
string[] anArray;
string solution;
anArray = array[theArray];
solution = "[";
foreach (string a in anArray)
{
}
for (int i = 0; i < anArray.Length; i++)
{
solution += anArray[i].Trim(new Char[] { '"' });
if (i < anArray.Length - 1)
solution += ",";
}
solution += "]";
Debug.Log("This is solution " + solution);
return solution;
}
}
}

ProcessEvent not called in TFS plugin

Recently i have decided to create a plugin for the TFS for tracking work item changes based on ISubscriber interface.
So the workflow would be the following:
1) Work item state changes
2) Plugin catches the WorkItemChangedEvent
3) Send an email to the person specified in the Requester
As the base for my project, i used the following project from CodePlex - The Mail Alert
After i adopted it to my needs and saved compiled binaries in %TFS-DIR%\Microsoft Team Foundation Server 14.0\Application Tier\Web Services\bin\Plugins the TFS restarted the tier and... that's it. On work item change the ProcessEvent method is not called, but it should be.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
using System.Diagnostics;
using System.Xml.Linq;
using System.Xml;
using System.DirectoryServices;
using System.Net.Mail;
using System.Xml.Xsl;
using System.Configuration;
using System.Reflection;
namespace MailAlert
{
public class WorkItemChangedEventHandler : ISubscriber
{
static string serverPath = "";
static string ExternalURL = "";
static string MailAddressFrom = "";
static string SMTPHost = "";
static string Password = "";
static int Port = 25;
static int index = 0;
static string projectCollectionFolder;
static Uri projectCollectionUri;
static WorkItemStore wiStore;
static WorkItem wItem;
static WorkItemChangedEvent workItemChangedEvent;
static string teamProjectPath = "";
static VersionControlServer versionControlServer;
static TfsTeamProjectCollection projectCollection;
static Dictionary<IdentityDescriptor, TeamFoundationIdentity> m_identities = new Dictionary<IdentityDescriptor, TeamFoundationIdentity>(IdentityDescriptorComparer.Instance);
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(WorkItemChangedEvent) };
}
public WorkItemChangedEventHandler()
{
TeamFoundationApplicationCore.Log("WorkItemChangedEvent Started", index++, EventLogEntryType.Information);
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType,
object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: ProcessEvent entered", index++, EventLogEntryType.Information);
statusCode = 0;
properties = null;
statusMessage = String.Empty;
GetTfsServerName();
projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(serverPath));
try
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
workItemChangedEvent = notificationEventArgs as WorkItemChangedEvent;
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: WorkItem " + workItemChangedEvent.WorkItemTitle + " was modified", index++, EventLogEntryType.Information);
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: serverPath - " + serverPath, index++, EventLogEntryType.Information);
projectCollectionFolder = requestContext.ServiceHost.VirtualDirectory.ToString();
projectCollectionUri = new Uri(serverPath + projectCollectionFolder);
projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(projectCollectionUri);
wiStore = projectCollection.GetService<WorkItemStore>();
versionControlServer = projectCollection.GetService<VersionControlServer>();
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: Before process workitem", index++, EventLogEntryType.Information);
ProcessWorkItem();
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: After process workitem", index++, EventLogEntryType.Information);
}
}
catch (Exception ex)
{
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: FUCKING EXCEPTION! =>\n" + ex.Message, index++, EventLogEntryType.Error);
}
return EventNotificationStatus.ActionPermitted;
}
private static void GetTfsServerName()
{
try
{
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(assemblyFolder + #"\Settings.xml");
// Declare the xpath for finding objects inside the XML file
XmlNodeList XmlDocNodes = XmlDoc.SelectNodes("/configuration/tfssettings");
XmlNodeList XmlDocExt = XmlDoc.SelectNodes("/configuration/Externaltfssettings");
// Define a new List, to store the objects we pull out of the XML
serverPath = XmlDocNodes[0].InnerText;
ExternalURL = XmlDocExt[0].InnerText;
XmlNodeList XmlDocNodes2 = XmlDoc.SelectNodes("/configuration/appSettings");
foreach (XmlNode mailNode in XmlDocNodes2)
{
foreach (XmlNode varElement in mailNode.ChildNodes)
{
switch (varElement.Attributes["key"].Value)
{
case "MailAddressFrom":
MailAddressFrom = varElement.Attributes["value"].Value;
break;
case "SMTPHost":
SMTPHost = varElement.Attributes["value"].Value;
break;
case "Password":
Password = varElement.Attributes["value"].Value;
break;
case "Port":
Port = Convert.ToInt32(varElement.Attributes["value"].Value);
break;
}
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry("WorkItemChangedEventHandler", ex.Message);
}
}
public string Name
{
get { return "WorkItemChangedEventHandler"; }
}
public SubscriberPriority Priority
{
get { return SubscriberPriority.High; }
}
private static void ProcessWorkItem()
{
var teamProjects = versionControlServer.GetAllTeamProjects(false);
for (int i = 0; i < teamProjects.Length; i++)
{
string teamProjectName = teamProjects[i].Name;
var teamProject = teamProjects[i];
Project teamProjectWI = wiStore.Projects[i];
teamProjectPath = projectCollectionUri + teamProject.Name;
if (workItemChangedEvent.PortfolioProject == teamProjectName)
{
//get the workitem by ID ( CoreFields.IntegerFields[0] == ID ?!)
//check if any of String changed fields
foreach(StringField sf in workItemChangedEvent.ChangedFields.StringFields)
{
//is the State field
if (sf.Name.Equals("State"))
{
//then notify Reuqester
wItem = wiStore.GetWorkItem(workItemChangedEvent.CoreFields.IntegerFields[0].NewValue);
string CollGuid = projectCollection.InstanceId.ToString();
string Requester = wItem.Fields["Requester"].Value.ToString();
string WorkItemId = wItem.Id.ToString();
string mail = GetEmailAddress(Requester);
SendMail(CollGuid, WorkItemId, mail);
}
}
}
}
}
private static string GetEmailAddress(string userDisplayName)
{
DirectorySearcher ds = new DirectorySearcher();
ds.PropertiesToLoad.Add("mail");
ds.Filter = String.Format("(&(displayName={0})(objectCategory=person)((objectClass=user)))", userDisplayName);
SearchResultCollection results = ds.FindAll();
if (results.Count == 0)
{
return string.Empty;
}
ResultPropertyValueCollection values = results[0].Properties["mail"];
if (values.Count == 0)
{
return string.Empty;
}
return values[0].ToString();
}
private static void SendMail(string collID,string workItemId,string tomailAddrees)
{
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = Port;
client.Host = SMTPHost;
client.Timeout = 200000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(MailAddressFrom, Password);
objeto_mail.From = new MailAddress(MailAddressFrom);
objeto_mail.To.Add(new MailAddress(tomailAddrees));
//objeto_mail.CC.Add(new MailAddress("nagarajb#hotmail.com"));
objeto_mail.Subject = "Work Item Changed:"+workItemId;
string mailbody = serverPath+"/tfs/web/wi.aspx?pcguid=" + collID + "&id=" + workItemId;
string mailbody2 = "";
if (ExternalURL.Length > 0)
{
mailbody2 = ExternalURL + "/tfs/web/wi.aspx?pcguid=" + collID + "&id=" + workItemId;
}
string tables = "<table border=1><tr><td>Work Item ID</td><td>" + wItem.Id.ToString() + "</td></tr><tr><td>Title</td><td>" + wItem.Title + "</td></tr><tr><td>State</td><td>" + wItem.State + "</td></tr><tr><td>Assigned To</td><td>" + wItem.Fields["Assigned to"].Value.ToString() + "</td></tr><tr><td>Internal URL</td><td>" + mailbody + "</td></tr><tr><td>External URL</td><td>" + mailbody2 + "</td></tr></table>";
objeto_mail.IsBodyHtml = true;
objeto_mail.Body = "<i>Hi " + wItem.Fields["Requester"].Value.ToString() + ","+"</i></br></br></br>" + tables + " </br></br> Best regards; </br></br>Configuration Management Team</br></br></br>";
client.Send(objeto_mail);
EventLog.WriteEntry("WorkItemChangedEventHandler", "Email Sent");
}
}
}
No errors or exceptions are thrown in the Event Log either. Tracing TFS (trace=true property in web.config) also was of no help.
Maybe someone could help or shed light on this mysterious case?
UPDATE:
Thanks for a reply Giulio Vian!
Here how it goes:
1) I haven't seen the dependencies broken, plus the constructor WorkItemChangedEventHandler is successfully called. That is seen in the Windows Event Log - WorkItemChangedEvent Started message is written.
2) I am not sure how to register the event handler.... i'll look that up
3) I am not sure how this works. I thought just copy-pasting dlls in the appropriate folder will do the trick, and there is no need for an account for the plugin. Mind giving a bit more info on this?
4) yes. Web.config in the main Web config in Application Tier\Web Services
5) Yes. Using an account with Administer rights. if i set a break point in the constructor, it is reached. Any other place in the code is not reached.
Many things can be wrong.
If any dependency is broken, you should see an error in the Event log
If you do not register the "WorkItemChangedEventHandler" event source, no message is written
Can the user account running the plugin access TFS?
How did you enabled the tracing (you pasted a bunch of code, but no configuration)?
Have you attached the debugger to the TFS process and set a breakpoint (do not this on a production TFS)?
We have collected similar suggestions in the documentation for our plugin at
https://github.com/tfsaggregator/tfsaggregator/wiki.

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