Program crashes when exe is copied to different computer - deployment

I have written a program in c# on my Windows 7 computer with .NET 4.0 using Sharp Develop 4.2.
I then changed it to a release within Sharp Develop, built it, and copied the .exe in the bin\Release folder to another Windows 7 computer with .NET 4.0. It crashes immediately without loading the initial form and gives no specific error. My MainForm method is like this:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Drawing.Printing;
using System.Diagnostics;
using System.Text;
namespace BiasTracker1._
{
public partial class MainForm : Form
{
//Here are my initial variables
public static SqlConnectionStringBuilder sqlBldr = new SqlConnectionStringBuilder();
public static DataSet ds = new DataSet();
public static DataTable DisplayTable = ds.Tables.Add("DisplayTable");
SqlDataAdapter RawDataDA;
SqlCommandBuilder RawSampleSCB;
public static DataTable InstrumentDetail = ds.Tables.Add("InstrumentDetail");
public static string DatabaseOwner;
System.Windows.Forms.DataVisualization.Charting.Chart CurrentChart;
public static DataTable ImportDataTable = new DataTable();
public static string NewTransfer;
public static bool ValidatePerCell = true;
public static Image chart1Image;
public static string Title;
public static string NIRLabString;
bool ChangesNotDisplayed = false;
Point PreviousChartLocation;
List<System.Windows.Forms.DataVisualization.Charting.DataPoint> SelectedPoints = new List<System.Windows.Forms.DataVisualization.Charting.DataPoint>();
List<DataRow> SelectedRows = new List<DataRow>();
static double EPS = 2.22045e-016;
double FPMIN = 2.22507e-308 / EPS;
public static CustomPrintDoc pd = new CustomPrintDoc();
int NumOfParametersInReport = 0;
public static SqlConnectionStringBuilder SimPlusConn;
public static string SimPlusProductGUID;
public static string SimPlusSiteCode;
public double[] cof = new double[] {-1.3026537197817904,0.64196979235649026,0.019476473204185836,-0.009561514786808631,-0.000946595344482036,0.000366839497852761,0.000042523324806907,-0.000020278578112534,-0.000001624290004647,0.00000130365583558,0.000000015626441722,-0.000000085238095915,0.000000006529054439,0.000000005059343495,-0.000000000991364156,-0.000000000227365122,0.000000000096467911,0.000000000002394038,-0.000000000006886027,0.000000000000894487,0.000000000000313092,-0.000000000000112708,0.000000000000000381,0.000000000000007106,-0.000000000000001523,-0.000000000000000094,0.000000000000000121,-0.000000000000000028};
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();
public MainForm()
{
try
{
InitializeComponent();
}
catch(Exception ex)
{
MessageBox.Show("Failed in Initialization.\n" + ex.ToString());
}
//Test SQL Connection
FileStream ConnectionStream;
try
{
ConnectionStream = new FileStream(#"C:\BiasTracker\settings.ini",FileMode.OpenOrCreate);
}
catch(DirectoryNotFoundException ex)
{
MessageBox.Show("Not able to find ini... Creating one.");
Directory.CreateDirectory(#"C:\BiasTracker");
ConnectionStream = new FileStream(#"C:\BiasTracker\settings.ini",FileMode.OpenOrCreate);
}
try
{
StreamReader ConnectionRdr = new StreamReader(ConnectionStream);
string line = null;
if((line = ConnectionRdr.ReadLine()) != null)
{
sqlBldr.DataSource = line;
sqlBldr.Password = ConnectionRdr.ReadLine();
sqlBldr.UserID = ConnectionRdr.ReadLine();
sqlBldr.InitialCatalog = ConnectionRdr.ReadLine();
}
else
{
sqlBldr.DataSource = ".\\SQLEXPRESS";
sqlBldr.Password = "password";
sqlBldr.UserID = "sa";
sqlBldr.InitialCatalog = "BiasMaster";
StreamWriter ConnectionWtr = new StreamWriter(ConnectionStream);
ConnectionWtr.WriteLine(".\\SQLEXPRESS");
ConnectionWtr.WriteLine("password");
ConnectionWtr.WriteLine("sa");
ConnectionWtr.WriteLine("BiasMaster");
ConnectionWtr.WriteLine("applications\\SQLEXPRESS");
ConnectionWtr.WriteLine("password");
ConnectionWtr.WriteLine("sa");
ConnectionWtr.WriteLine("BiasMaster");
ConnectionWtr.Dispose();
}
ConnectionStream.Close();
ConnectionStream.Dispose();
ConnectionRdr.Dispose();
}
catch(Exception ex)
{
MessageBox.Show("Not Able to read connection string\n" + ex.ToString());
}
System.Data.SqlClient.SqlConnection tmpConn;
tmpConn = new SqlConnection(sqlBldr.ConnectionString);
try //Test the connection and existence of the database
{
tmpConn.Open();
tmpConn.Close();
}
catch
{
MessageBox.Show("Database Connection not Found.");
tmpConn.Close();
}
SqlDataAdapter SettingsDA = new SqlDataAdapter("SELECT * FROM Settings WHERE SettingDesc = 'Owner'",sqlBldr.ConnectionString);
DataTable SettingsTable = new DataTable();
SettingsDA.Fill(SettingsTable);
DatabaseOwner = SettingsTable.Rows[0][1].ToString();
MakeTreeView();
}
MakeTreeView is surrounded by a try catch with a messagebox.
My Form loads these controls:
privateSystem.Windows.Forms.ToolStripMenuItemsimPlusImportToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripStatusLabeltoolStripStatusLabel1;
privateSystem.Windows.Forms.ToolStripMenuItemsyncWithSharedServerToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsyncToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsetDBConnectionToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtestToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemdetectOutliersToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsaveToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemexcludeSelectedToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemgraphActionsToolStripMenuItem;
privateSystem.Windows.Forms.ComboBoxcomboBox7;
privateSystem.Windows.Forms.ToolStripMenuItemprintReportToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddToReportToolStripMenuItem;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart4;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart3;
privateSystem.Windows.Forms.Panelpanel2;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart2;
privateSystem.Windows.Forms.ComboBoxcomboBox6;
privateSystem.Windows.Forms.Labellabel7;
privateSystem.Windows.Forms.Buttonbutton3;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart1;
privateSystem.Windows.Forms.Buttonbutton2;
privateSystem.Windows.Forms.ToolStripMenuItemremoveProductFormInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcopyInstrumentProductListToAnotherInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddProductToInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddParameterToProductToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtablesToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtXTToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcSVToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItembiasDataToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemimportToolStripMenuItem;
privateSystem.Windows.Forms.Labellabel1;
privateSystem.Windows.Forms.ComboBoxcomboBox1;
privateSystem.Windows.Forms.Labellabel2;
privateSystem.Windows.Forms.ComboBoxcomboBox2;
privateSystem.Windows.Forms.Labellabel3;
privateSystem.Windows.Forms.ComboBoxcomboBox3;
privateSystem.Windows.Forms.Labellabel4;
privateSystem.Windows.Forms.ComboBoxcomboBox4;
privateSystem.Windows.Forms.Labellabel5;
privateSystem.Windows.Forms.ComboBoxcomboBox5;
privateSystem.Windows.Forms.Labellabel6;
privateSystem.Windows.Forms.DateTimePickerdateTimePicker1;
privateSystem.Windows.Forms.DateTimePickerdateTimePicker2;
privateSystem.Windows.Forms.ToolStripMenuItemparameterToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemproductToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuIteminstrumentToolStripMenuItem1;
privateSystem.Windows.Forms.ToolStripMenuItemlocationToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcompanyToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemnewToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemfileToolStripMenuItem;
privateSystem.Windows.Forms.MenuStripmenuStrip1;
privateSystem.Windows.Forms.StatusStripstatusStrip1;
privateSystem.Windows.Forms.TabPagetabPage2;
privateSystem.Windows.Forms.DataGridViewdataGridView1;
privateSystem.Windows.Forms.TreeViewtreeView1;
privateSystem.Windows.Forms.Buttonbutton1;
privateSystem.Windows.Forms.Panelpanel1;
privateSystem.Windows.Forms.TabPagetabPage1;
privateSystem.Windows.Forms.TabControltabControl1;
The only thing I can think is that I am using a reference to something that the other computer does not have access to. I thought it was the chart controls, but .NET 4.0 has those included. Any help would be immensely appreciated.

I found the culprit. It was the line:
DatabaseOwner = SettingsTable.Rows[0][1].ToString();
I found it using AppDomain.UnhandledException. It was a great tool if anyone else is running into a similar issue.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Related

Is it possible to rollback a changeset using Microsoft.TeamFoundation.SourceControl.WebApi?

Following code try to rollback a changeset using Microsoft.TeamFoundation.SourceControl.WebApi. But "The specified change type Rollback is not supported." is raised when calling CreateChangesetAsync. Is this a limitation of Microsoft.TeamFoundation.SourceControl.WebApi? Or I did something wrong?
using System;
using System.Collections.Generic;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
namespace RestRollBackInTFS
{
class Program
{
static void Main(string[] args)
{
const String collectionUri = #"https://myTfs.visualstudio.com/";
VssConnection connection = new VssConnection(new Uri(collectionUri),
new VssClientCredentials()
);
TfvcHttpClient tfsClient = connection.GetClient<TfvcHttpClient>();
int changeSetIdToRollBack = 11651;
var changeSet = tfsClient.GetChangesetAsync(changeSetIdToRollBack, maxChangeCount: 10, includeDetails: true).Result;
foreach (var c in changeSet.Changes)
{
c.ChangeType = VersionControlChangeType.Rollback;
}
TfvcChangeset newC = new TfvcChangeset();
newC.Changes = new List<TfvcChange>(changeSet.Changes);
var ret = tfsClient.CreateChangesetAsync(newC).Result;
}
}
}

Npgsql Performance

I am trying to implement Npgsql in our DAL and running into issues under heavy load. the following sample application is a decent representation of just a simple query that under heavy load, throws a 'A command is already in progress' exception. I am assuming this is due to the lack of MARS support so I also tried creating a connection each time with a using statement around each command only to have the performance become unusable. I checked that the username is indexed so that shouldn't be an issue.
Not sure what I am doing wrong here but I need some advice on how to get this performing well.
OS: Docker Container: microsoft/dotnet:2.1.301-sdk
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
namespace npgsqlTest
{
class Program
{
static async Task Main(string[] args)
{
DAL dal = new DAL();
dal.Prepare();
var tasks = dal.Users.Select(async user =>
{
Console.WriteLine(await dal.RunTest(user));
});
await Task.WhenAll(tasks);
}
}
public class DAL
{
private static string _ConnectionString;
private NpgsqlConnection _Connection;
public List<string> Users { get; set; } = new List<string>();
public DAL()
{
_ConnectionString = $"Host=192.168.1.1;Username=admin;Port=5432;Password=password;Database=BigDB;";
_Connection = new NpgsqlConnection(_ConnectionString);
_Connection.Open();
}
public void Prepare()
{
string query = "SELECT username FROM usertable;";
using (var cmd = new NpgsqlCommand(query, _Connection))
{
var reader = cmd.ExecuteReader();
using (reader)
{
while (reader.Read())
{
Users.Add(reader[0].ToString());
}
}
}
}
public async Task<string> RunTest(string user)
{
var parameters = new Dictionary<string, Object> { { "username", user } };
var query = $"SELECT name FROM usertable WHERE username = (#username);";
var reader = await QueryAsync(query, parameters);
using (reader)
{
if (reader.HasRows)
{
while (await reader.ReadAsync())
{
var name = reader["name"];
if (!(hash is DBNull))
return (string)name;
}
}
}
return String.Empty;
}
public async Task<DbDataReader> QueryAsync(string query, Dictionary<string, Object> parameters)
{
using (var cmd = new NpgsqlCommand(query, _Connection))
{
foreach (var parameter in parameters)
{
cmd.Parameters.AddWithValue(parameter.Key, parameter.Value == null ? DBNull.Value : parameter.Value);
}
cmd.Prepare();
return await cmd.ExecuteReaderAsync();
}
}
}
}

Saved Games Data Google Play Games Serivces Unity

I've successfully logged in with Google Play services in Unity, but I have a problem now that i have a class that contains some data like this:
public static class GameData
{
public static Dictionary<string, object> Name_Dic = new Dictionary<string, object>()
{
{"laura",""},
{"steph ",""},
{"Ryan",""},
};
public static Dictionary<string, string> Dialogs_Dic = new Dictionary<string, string>()
{
{"A1", "Hello"},
{"A2", "Nice"},
{"A3", "Test"},
};
public const int nbrTotal_Int = 2;
public const int TestNumber_Int = 5;
}
I have to save these data to the Google Cloud and after that load them from cloud, but i m confused i don't understand if i have to convert the dictionary in the GameManager class into String and then in to Bytes[] in order to save them in the Google Cloud or what can i do exactly. and the int variables i should convert them into string then into bytes[]. i ve searched into the internet and i can't found an explanation or tutorial for that and in the official documentation or the samples in the documentation it is not clear what can i do. Can you please help me please. Thanks a lot
Update
Hello,
Thanks for your answer, i ve written a code that let me save these variables to Google Cloud, here it is a part of the serialization the dictionary and the ints. is it correct like this. thanks for your answer.
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Connect : MonoBehaviour
{
public Dictionary Name_Dic = new Dictionary()
{
{"laura",""},
{"steph ",""},
{"Ryan",""},
};
public Dictionary Dialogs_Dic = new Dictionary()
{
{"A1", "Hello"},
{"A2", "Nice"},
{"A3", "Test"},
};
public int nbrTotal_Int = 2;
public int TestNumber_Int = 5;
public void WriteFunction() {
ISavedGameMetadata currentGame = null;
Action<SavedGameRequestStatus, ISavedGameMetadata> writeCallback =
(SavedGameRequestStatus status, ISavedGameMetadata game) => {
Debug.Log(" Saved Game Write: " + status.ToString());
};
// CALLBACK: Handle the result of a binary read
Action<SavedGameRequestStatus, byte[]> readBinaryCallback =
(SavedGameRequestStatus status, byte[] data) =>
{
Debug.Log(" Saved Game Binary Read: " + status.ToString());
if (status == SavedGameRequestStatus.Success)
{
try {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/gameInfo.dat",
FileMode.Open);
GameData data = new GameData();
// Two Dictionary
data.Name_Dic = Name_Dic;
data.Dialogs_Dic = Dialogs_Dic;
// Two Int
data.nbrTotal_Int = nbrTotal_Int;
data.TestNumber_Int = TestNumber_Int;
bf.Serialize(file, data);
file.Close();
} catch (Exception e) {
Debug.Log(" Saved Game Write: convert exception");
}
WriteSavedGame(currentGame, data, writeCallback);
}
};
}
}
[Serializable]
public class GameData
{
public Dictionary Name_Dic = new Dictionary()
{
{"laura",""},
{"steph ",""},
{"Ryan",""},
};
public Dictionary Dialogs_Dic = new Dictionary()
{
{"A1", "Hello"},
{"A2", "Nice"},
{"A3", "Test"},
};
public int nbrTotal_Int = 2;
public int TestNumber_Int = 5;
}``

List changed files in TFS but ordered by number of changes applied

Is there a way of listing all the files that have changed on a project, but ordered by the number of changes made to each file?
I want to do a code review but only from a selection of the most active files.
You may try to use Excel as a TFS reporting tool like in this blog post:
http://www.woodwardweb.com/vsts/getting_started.html
ps. I found that link in this question.
I searched different ways and finally I found that best way is using TFS API
here is the code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace VControl
{
class Program
{
class SourceElement
{
public string filename;
public int numberOfModification;
}
static void Main(string[] args)
{
TfsTeamProjectCollection projectCollection = new
TfsTeamProjectCollection(new Uri("http://server:8080/tfs/ProjectCollection/"),
new System.Net.NetworkCredential("username", "password"));
projectCollection.EnsureAuthenticated();
Workspace workspace = null;
Boolean createdWorkspace = false;
String newFolder = String.Empty;
VersionControlServer versionControl = projectCollection.GetService<VersionControlServer>();
var teamProjects = new List<TeamProject>(versionControl.GetAllTeamProjects(false));
String workspaceName = String.Format("{0}-{1}", Environment.MachineName, "TestWorkspace");
try
{
workspace = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);
}
catch (WorkspaceNotFoundException)
{
workspace = versionControl.CreateWorkspace(workspaceName, versionControl.AuthorizedUser);
createdWorkspace = true;
}
var serverFolder = String.Format("$/{0}", teamProjects[0].Name) + "/solutionFolder/";
var localFolder = Path.Combine(Path.GetTempPath(), "localFolder") + "/solutionFolder/";
var workingFolder = new WorkingFolder(serverFolder, localFolder);
// Create a workspace mapping.
workspace.CreateMapping(workingFolder);
if (!workspace.HasReadPermission)
{
throw new SecurityException(
String.Format("{0} does not have read permission for {1}",
versionControl.AuthorizedUser, serverFolder));
}
// Get the files from the repository.
workspace.Get();
string[] directories = Directory.GetDirectories(workspace.Folders[0].LocalItem);
FileStream outputFile = new FileStream("result.txt", FileMode.Create);
StreamWriter writer = new StreamWriter(outputFile);
List<SourceElement> fileLiset = new List<SourceElement>();
foreach (string dir in directories)
{
foreach (string file in Directory.GetFiles(dir))
{
string filenamae = System.IO.Path.GetFileName(file);
Item source = versionControl.GetItem(file);
System.Collections.IEnumerable history = versionControl.QueryHistory(file,
VersionSpec.Latest, 0, RecursionType.Full, null, null, null, 300, true, true, false, false);
int numberOfModification = 0;
foreach (var item in history)
numberOfModification++;
SourceElement fileElement = new SourceElement();
fileElement.filename = filenamae;
fileElement.numberOfModification = numberOfModification;
fileLiset.Add(fileElement);
}
}
var sortedList = fileLiset.OrderBy(x=> x.numberOfModification);
// Loop through keys.
foreach (var key in sortedList)
{
writer.WriteLine("{0}: {1}", key.filename, key.numberOfModification);
}
writer.Close();
}
}
}

how to execute the .cs file generated using codeDom

Here is my source code.....
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using System.IO;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
namespace CodeDOM
{
class Program
{
private string m_strFileName;
private string m_Suffix = ".cs";
public Program(string FileName)
{
m_strFileName = FileName;
}
public void CreateCodeDom()
{
Stream codeFile = File.Open("c:\\" + m_strFileName + m_Suffix, FileMode.Create);
StreamWriter sw = new StreamWriter(codeFile);
CSharpCodeProvider cscp = new CSharpCodeProvider();
ICodeGenerator codeGenerator = cscp.CreateGenerator(sw);
CodeGeneratorOptions cgo = new CodeGeneratorOptions();
CodeSnippetCompileUnit cscu = new CodeSnippetCompileUnit("imports System");
codeGenerator.GenerateCodeFromCompileUnit(cscu, sw, cgo);
CodeNamespace cnsCodeDom = new CodeNamespace("SampleNamespace");
CodeTypeDeclaration clsDecl = new CodeTypeDeclaration();
clsDecl.Name = "Sample";
clsDecl.IsClass = true;
clsDecl.TypeAttributes = TypeAttributes.Public;
cnsCodeDom.Types.Add(clsDecl);
CodeConstructor clsConstructor = new CodeConstructor();
clsConstructor.Attributes = MemberAttributes.Public;
clsDecl.Members.Add(clsConstructor);
CodeMemberField clsMember = new CodeMemberField();
clsMember.Name = "myname";
clsMember.Attributes = MemberAttributes.Private;
clsMember.Type = new CodeTypeReference("System.String");
clsDecl.Members.Add(clsMember);
CodeMemberProperty property = new CodeMemberProperty();
property.Name = "MyName";
property.Type = new CodeTypeReference("System.String");
property.Attributes = MemberAttributes.Public;
property.HasGet = true;
property.GetStatements.Add(new CodeSnippetExpression("return this.myname"));
property.HasSet = true;
property.SetStatements.Add(new CodeSnippetExpression("this.myname=value"));
//property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "this.myname")));
//property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "this.myname"), new CodePropertySetValueReferenceExpression()));
clsDecl.Members.Add(property);
CodeMemberMethod mtd = new CodeMemberMethod();
mtd.Name = "Print";
mtd.ReturnType = null;
mtd.Attributes = MemberAttributes.Public;
mtd.Statements.Add(new CodeSnippetStatement("Console.WriteLine(myname)"));
clsDecl.Members.Add(mtd);
codeGenerator.GenerateCodeFromNamespace(cnsCodeDom, sw, cgo);
sw.Close();
codeFile.Close();
}
static void Main(string[] args)
{
Program m_obj = new Program("Sample");
m_obj.CreateCodeDom();
Console.ReadLine();
}
}
}
from this i got sample.cs file.now i want to execute that sample.cs file.wil u plz suggest me how to do it?
If it is an application, in a single source file, you can simply do:
csc sample.cs && sample.exe