redirecting output to the text file c# - c#

This is my code:
Process pr2 = new Process();
pr2.StartInfo.FileName = "show-snps";
pr2.StartInfo.Arguments = #"-Clr -x 2 out.delta > out.snps";
pr2.Start();
pr2.WaitForExit();
show-snps writes an error. when I delete the part "> out.snps" everything is ok and it writes the result into the terminal, but I need to redirect it to the text file.
How can I do this?

You can't redirect like that when you are starting the program like that. It requires a shell such as CMD.EXE to do that.
Instead, you need to set ProcessStartInfo.RedirectStandardOutput to a stream that you manage yourself.
There's an example here.
That example shows how to get the data that the console process creates via a StreamReader. For your requirement, you would read from that StreamReader and write to a FileStream output.
In case it's any help, here's a utility class I wrote years ago (for .Net 2) which might be instructive:
using System;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
namespace ProcessUtilities
{
/// <summary>
/// Encapsulates an executable program.
/// This class makes it easy to run a console app and have that app's output appear
/// in the parent console's window, and to redirect input and output from/to files.
/// </summary>
/// <remarks>
/// To use this class:
/// (1) Create an instance.
/// (2) Set the ProgramFileName property if a filename wasn't specified in the constructor.
/// (3) Set other properties if required.
/// (4) Call Run().
/// </remarks>
public class Executable
{
#region Constructor
/// <summary>Runs the specified program file name.</summary>
/// <param name="programFileName">Name of the program file to run.</param>
public Executable(string programFileName)
{
ProgramFileName = programFileName;
_processStartInfo.ErrorDialog = false;
_processStartInfo.CreateNoWindow = false;
_processStartInfo.UseShellExecute = false;
_processStartInfo.RedirectStandardOutput = false;
_processStartInfo.RedirectStandardError = false;
_processStartInfo.RedirectStandardInput = false;
_processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_processStartInfo.Arguments = "";
}
/// <summary>Constructor.</summary>
public Executable(): this(string.Empty)
{
}
#endregion // Constructor
#region Public Properties
/// <summary>The filename (full pathname) of the executable.</summary>
public string ProgramFileName
{
get
{
return _processStartInfo.FileName;
}
set
{
_processStartInfo.FileName = value;
}
}
/// <summary>The command-line arguments passed to the executable when run. </summary>
public string Arguments
{
get
{
return _processStartInfo.Arguments;
}
set
{
_processStartInfo.Arguments = value;
}
}
/// <summary>The working directory set for the executable when run.</summary>
public string WorkingDirectory
{
get
{
return _processStartInfo.WorkingDirectory;
}
set
{
_processStartInfo.WorkingDirectory = value;
}
}
/// <summary>
/// The file to be used if standard input is redirected,
/// or null or string.Empty to not redirect standard input.
/// </summary>
public string StandardInputFileName
{
set
{
_standardInputFileName = value;
_processStartInfo.RedirectStandardInput = !string.IsNullOrEmpty(value);
}
get
{
return _standardInputFileName;
}
}
/// <summary>
/// The file to be used if standard output is redirected,
/// or null or string.Empty to not redirect standard output.
/// </summary>
public string StandardOutputFileName
{
set
{
_standardOutputFileName = value;
_processStartInfo.RedirectStandardOutput = !string.IsNullOrEmpty(value);
}
get
{
return _standardOutputFileName;
}
}
/// <summary>
/// The file to be used if standard error is redirected,
/// or null or string.Empty to not redirect standard error.
/// </summary>
public string StandardErrorFileName
{
set
{
_standardErrorFileName = value;
_processStartInfo.RedirectStandardError = !string.IsNullOrEmpty(value);
}
get
{
return _standardErrorFileName;
}
}
#endregion // Public Properties
#region Public Methods
/// <summary>Add a set of name-value pairs into the set of environment variables available to the executable.</summary>
/// <param name="variables">The name-value pairs to add.</param>
public void AddEnvironmentVariables(StringDictionary variables)
{
if (variables == null)
throw new ArgumentNullException("variables");
StringDictionary environmentVariables = _processStartInfo.EnvironmentVariables;
foreach (DictionaryEntry e in variables)
environmentVariables[(string)e.Key] = (string)e.Value;
}
/// <summary>Run the executable and wait until the it has terminated.</summary>
/// <returns>The exit code returned from the executable.</returns>
public int Run()
{
Thread standardInputThread = null;
Thread standardOutputThread = null;
Thread standardErrorThread = null;
_standardInput = null;
_standardError = null;
_standardOutput = null;
int exitCode = -1;
try
{
using (Process process = new Process())
{
process.StartInfo = _processStartInfo;
process.Start();
if (process.StartInfo.RedirectStandardInput)
{
_standardInput = process.StandardInput;
standardInputThread = startThread(new ThreadStart(supplyStandardInput), "StandardInput");
}
if (process.StartInfo.RedirectStandardError)
{
_standardError = process.StandardError;
standardErrorThread = startThread(new ThreadStart(writeStandardError), "StandardError");
}
if (process.StartInfo.RedirectStandardOutput)
{
_standardOutput = process.StandardOutput;
standardOutputThread = startThread(new ThreadStart(writeStandardOutput), "StandardOutput");
}
process.WaitForExit();
exitCode = process.ExitCode;
}
}
finally // Ensure that the threads do not persist beyond the process being run
{
if (standardInputThread != null)
standardInputThread.Join();
if (standardOutputThread != null)
standardOutputThread.Join();
if (standardErrorThread != null)
standardErrorThread.Join();
}
return exitCode;
}
#endregion // Public Methods
#region Private Methods
/// <summary>Start a thread.</summary>
/// <param name="startInfo">start information for this thread</param>
/// <param name="name">name of the thread</param>
/// <returns>thread object</returns>
private static Thread startThread(ThreadStart startInfo, string name)
{
Thread t = new Thread(startInfo);
t.IsBackground = true ;
t.Name = name;
t.Start();
return t;
}
/// <summary>Thread which supplies standard input from the appropriate file to the running executable.</summary>
private void supplyStandardInput()
{
// feed text from the file a line at a time into the standard input stream
using (StreamReader reader = File.OpenText(_standardInputFileName))
using (StreamWriter writer = _standardInput)
{
writer.AutoFlush = true;
for (;;)
{
string textLine = reader.ReadLine();
if (textLine == null)
break;
writer.WriteLine(textLine);
}
}
}
/// <summary>Thread which outputs standard output from the running executable to the appropriate file.</summary>
private void writeStandardOutput()
{
using (StreamWriter writer = File.CreateText(_standardOutputFileName))
using (StreamReader reader = _standardOutput)
{
writer.AutoFlush = true;
for (;;)
{
string textLine = reader.ReadLine();
if (textLine == null)
break;
writer.WriteLine(textLine);
}
}
if (File.Exists(_standardOutputFileName))
{
FileInfo info = new FileInfo(_standardOutputFileName);
// if the error info is empty or just contains eof etc.
if (info.Length < 4)
info.Delete();
}
}
/// <summary>Thread which outputs standard error output from the running executable to the appropriate file.</summary>
private void writeStandardError()
{
using (StreamWriter writer = File.CreateText(_standardErrorFileName))
using (StreamReader reader = _standardError)
{
writer.AutoFlush = true;
for (;;)
{
string textLine = reader.ReadLine();
if (textLine == null)
break;
writer.WriteLine(textLine);
}
}
if (File.Exists(_standardErrorFileName))
{
FileInfo info = new FileInfo(_standardErrorFileName);
// if the error info is empty or just contains eof etc.
if (info.Length < 4)
info.Delete();
}
}
#endregion // Private Methods
#region Private Fields
private StreamReader _standardError ;
private StreamReader _standardOutput ;
private StreamWriter _standardInput ;
private string _standardInputFileName;
private string _standardOutputFileName;
private string _standardErrorFileName;
ProcessStartInfo _processStartInfo = new ProcessStartInfo();
#endregion // Private Fields
}
}

This is an old question, but it came up on the first google link for searching for how to redirect the standard output of a launched Process to a file.
The answer I think works well is to add a OutputDataReceived event and write to the file there.
Here is a complete working example.
using System;
using System.IO;
using System.Diagnostics;
using System.Text;
class StandardAsyncOutputExample
{
public static void Main()
{
var outputStream = new StreamWriter("output.txt");
Process process = new Process();
process.StartInfo.FileName = "ipconfig.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
outputStream.WriteLine(e.Data);
}
});
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.Close();
outputStream.Close();
Console.WriteLine("\n\nPress any key to exit.");
Console.ReadLine();
}
}

It didn't work because > redirect was supported by cmd.exe shell. Try the following code instead.
Process pr2 = new Process();
pr2.StartInfo.FileName = #"c:\windows\system32\cmd.exe";
pr2.StartInfo.Arguments = #"/k \"show-snps -Clr -x 2 out.delta > out.snps\"";
pr2.Start();
pr2.WaitForExit();

Related

Understanding the error "the name does not exists in the current context"

I am using C#. I get an error:
The name 'DateAndTime','DateInterval' 'FirstDayOfWeek','FirstWeekOfYear', does not exist in the current context
which I don't understand. I tried a lot of solutions on it but it is not working.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
using Microsoft.VisualBasic;
using System.Windows.Forms;
namespace SoftwareLocker
{
// Activate Property
public class TrialMaker
{
#region -> Private Variables
private string _BaseString;
private string _Password;
private string _SoftName;
private string _RegFilePath;
private string _HideFilePath;
private int _DefDays;
private int _Runed;
private string _Text;
private string _Identifier;
#endregion
#region -> Constructor
/// <summary>
/// Make new TrialMaker class to make software trial
/// </summary>
/// <param name="SoftwareName">Name of software to make trial</param>
/// <param name="RegFilePath">File path to save password(enrypted)</param>
/// <param name="HideFilePath">file path for saving hidden information</param>
/// <param name="Text">A text for contacting to you</param>
/// <param name="TrialDays">Default period days</param>
/// <param name="TrialRunTimes">How many times user can run as trial</param>
/// <param name="Identifier">3 Digit string as your identifier to make password</param>
public TrialMaker(string SoftwareName,
string RegFilePath, string HideFilePath,
string Text, int TrialDays, int TrialRunTimes,
string Identifier)
{
_SoftName = SoftwareName;
_Identifier = Identifier;
SetDefaults();
_DefDays = TrialDays;
_Runed = TrialRunTimes;
_RegFilePath = RegFilePath;
_HideFilePath = HideFilePath;
_Text = Text;
}
private void SetDefaults()
{
SystemInfo.UseBaseBoardManufacturer = false;
SystemInfo.UseBaseBoardProduct = true;
SystemInfo.UseBiosManufacturer = false;
SystemInfo.UseBiosVersion = true;
SystemInfo.UseDiskDriveSignature = true;
SystemInfo.UsePhysicalMediaSerialNumber = false;
SystemInfo.UseProcessorID = true;
SystemInfo.UseVideoControllerCaption = false;
SystemInfo.UseWindowsSerialNumber = false;
MakeBaseString();
MakePassword();
}
#endregion
// Make base string (Computer ID)
private void MakeBaseString()
{
_BaseString = Encryption.Boring(Encryption.InverseByBase(SystemInfo.GetSystemInfo(_SoftName), 10));
}
private void MakePassword()
{
_Password = Encryption.MakePassword(_BaseString, _Identifier);
}
/// <summary>
/// Show registering dialog to user
/// </summary>
/// <returns>Type of running</returns>
public RunTypes ShowDialog()
{
// check if registered before
if (CheckRegister() == true)
return RunTypes.Full;
frmDialog PassDialog = new frmDialog(_BaseString, _Password, DaysToEnd(), _Runed, _Text);
MakeHideFile();
DialogResult DR = PassDialog.ShowDialog();
if (DR == System.Windows.Forms.DialogResult.OK)
{
MakeRegFile();
return RunTypes.Full;
}
else if (DR == DialogResult.Retry)
return RunTypes.Trial;
else
return RunTypes.Expired;
}
// save password to Registration file for next time usage
private void MakeRegFile()
{
FileReadWrite.WriteFile(_RegFilePath, _Password);
}
// Control Registeration file for password
// if password saved correctly return true else false
private bool CheckRegister()
{
string Password = FileReadWrite.ReadFile(_RegFilePath);
if (_Password == Password)
return true;
else
return false;
}
// from hidden file
// indicate how many days can user use program
// if the file does not exists, make it
private int DaysToEnd()
{
FileInfo hf = new FileInfo(_HideFilePath);
if (hf.Exists == false)
{
MakeHideFile();
return _DefDays;
}
return CheckHideFile();
}
// store hidden information to hidden file
// Date,DaysToEnd,HowManyTimesRuned,BaseString(ComputerID)
private void MakeHideFile()
{
string HideInfo;
HideInfo = DateTime.Now.Ticks + ";";
HideInfo += _DefDays + ";" + _Runed + ";" + _BaseString;
FileReadWrite.WriteFile(_HideFilePath, HideInfo);
}
// Get Data from hidden file if exists
private int CheckHideFile()
{
string[] HideInfo;
HideInfo = FileReadWrite.ReadFile(_HideFilePath).Split(';');
long DiffDays;
int DaysToEnd;
if (_BaseString == HideInfo[3])
{
DaysToEnd = Convert.ToInt32(HideInfo[1]);
if (DaysToEnd <= 0)
{
_Runed = 0;
_DefDays = 0;
return 0;
}
DateTime dt = new DateTime(Convert.ToInt64(HideInfo[0]));
DiffDays = DateAndTime.DateDiff(DateInterval.Day,
dt.Date, DateTime.Now.Date,
FirstDayOfWeek.Saturday,
FirstWeekOfYear.FirstFullWeek);
DaysToEnd = Convert.ToInt32(HideInfo[1]);
_Runed = Convert.ToInt32(HideInfo[2]);
_Runed -= 1;
DiffDays = Math.Abs(DiffDays);
_DefDays = DaysToEnd - Convert.ToInt32(DiffDays);
}
return _DefDays;
}
public enum RunTypes
{
Trial = 0,
Full,
Expired,
UnKnown
}
#region -> Properties
/// <summary>
/// Indicate File path for storing password
/// </summary>
public string RegFilePath
{
get
{
return _RegFilePath;
}
set
{
_RegFilePath = value;
}
}
/// <summary>
/// Indicate file path for storing hidden information
/// </summary>
public string HideFilePath
{
get
{
return _HideFilePath;
}
set
{
_HideFilePath = value;
}
}
/// <summary>
/// Get default number of days for trial period
/// </summary>
public int TrialPeriodDays
{
get
{
return _DefDays;
}
}
/// <summary>
/// Get or Set TripleDES key for encrypting files to save
/// </summary>
public byte[] TripleDESKey
{
get
{
return FileReadWrite.key;
}
set
{
FileReadWrite.key = value;
}
}
#endregion
#region -> Usage Properties
public bool UseProcessorID
{
get
{
return SystemInfo.UseProcessorID;
}
set
{
SystemInfo.UseProcessorID = value;
}
}
public bool UseBaseBoardProduct
{
get
{
return SystemInfo.UseBaseBoardProduct;
}
set
{
SystemInfo.UseBaseBoardProduct = value;
}
}
public bool UseBaseBoardManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseDiskDriveSignature
{
get
{
return SystemInfo.UseDiskDriveSignature;
}
set
{
SystemInfo.UseDiskDriveSignature = value;
}
}
public bool UseVideoControllerCaption
{
get
{
return SystemInfo.UseVideoControllerCaption;
}
set
{
SystemInfo.UseVideoControllerCaption = value;
}
}
public bool UsePhysicalMediaSerialNumber
{
get
{
return SystemInfo.UsePhysicalMediaSerialNumber;
}
set
{
SystemInfo.UsePhysicalMediaSerialNumber = value;
}
}
public bool UseBiosVersion
{
get
{
return SystemInfo.UseBiosVersion;
}
set
{
SystemInfo.UseBiosVersion = value;
}
}
public bool UseBiosManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseWindowsSerialNumber
{
get
{
return SystemInfo.UseWindowsSerialNumber;
}
set
{
SystemInfo.UseWindowsSerialNumber = value;
}
}
#endregion
}
}
that problem will work on Viaual basic 2005 it is not working in vb2015 if, we do so in 2015 some libraries are missing that pblm raises

C# - Odd Null Reference Exception during testing, why does this happen?

This references my last question which appears to have been abandoned. I am experiencing an odd "bug" if you will with C# and MS VS 2015. To reproduce the error, follow the steps:
Open console app project and copy paste code below.
Set a break point here:
First run code past break point, it works! :D
Then run code again but this time STOP at the break point and DRAG the executing statement cursor INTO the if statement from here:
to here:
Hit Continue and an NRE exception is thrown. Why does this happen? Is it just me? What is the technical explination for this?
CODE:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
FILECollection randomCollection = new FILECollection();
// Fill with junk test data:
for(int i = 0; i<10; i++)
{
FILE junkfile = new FILE() { fileName = i.ToString(), folderName = i.ToString(), fileHashDigest = new byte[1] };
randomCollection.Add(junkfile);
}
if (true)
{
Console.WriteLine("testing this weird exception issue...");
FILE test;
test = new FILE();
test.fileName = "3";
test.folderName = "3";
test.fileHashDigest = new byte[1];
FILE exists = randomCollection.Where(f => f.fileName == test.fileName &&
f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First();
}
}
}
public class FILE
{
public FILE() { _fileName = "";}
private string _fileName;
public string fileName
{
get
{
if (false)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (false)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
public class FILECollection : IEnumerable<FILE>, ICollection<FILE>
{
private HashSet<FILE> svgHash;
private static List<FILE> PreallocationList;
public string FileName = "N/A";
/// <summary>
/// Default Constructor, will not
/// preallocate memory.
/// </summary>
/// <param name="PreallocationSize"></param>
public FILECollection()
{
this.svgHash = new HashSet<FILE>();
this.svgHash.Clear();
}
/// <summary>
/// Overload Constructor Preallocates
/// memory to be used for the new
/// FILE Collection.
/// </summary>
public FILECollection(int PreallocationSize, string fileName = "N/A", int fileHashDigestSize = 32)
{
FileName = fileName;
PreallocationList = new List<FILE>(PreallocationSize);
for (int i = 0; i <= PreallocationSize; i++)
{
byte[] buffer = new byte[fileHashDigestSize];
FILE preallocationSVG = new FILE()
{
fileName = "",
folderName = "",
fileHashDigest = buffer
};
PreallocationList.Add(preallocationSVG);
}
this.svgHash = new HashSet<FILE>(PreallocationList);
this.svgHash.Clear(); // Capacity remains unchanged until a call to TrimExcess is made.
}
/// <summary>
/// Add an FILE file to
/// the FILE Collection.
/// </summary>
/// <param name="svg"></param>
public void Add(FILE svg)
{
this.svgHash.Add(svg);
}
/// <summary>
/// Removes all elements
/// from the FILE Collection
/// </summary>
public void Clear()
{
svgHash.Clear();
}
/// <summary>
/// Determine if the FILE collection
/// contains the EXACT FILE file, folder,
/// and byte[] sequence. This guarantees
/// that the collection contains the EXACT
/// file you are looking for.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(FILE item)
{
return svgHash.Any(f => f.fileHashDigest.SequenceEqual(item.fileHashDigest) &&
f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Determine if the FILE collection
/// contains the same file and folder name,
/// byte[] sequence is not compared. The file and folder
/// name may be the same but this does not guarantee the
/// file contents are exactly the same. Use Contains() instead.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool ContainsPartially(FILE item)
{
return svgHash.Any(f => f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Returns the total number
/// of FILE files in the Collection.
/// </summary>
public int Count
{ get { return svgHash.Count(); } }
public bool IsReadOnly
{ get { return true; } }
public void CopyTo(FILE[] array, int arrayIndex)
{
svgHash.CopyTo(array, arrayIndex);
}
public bool Remove(FILE item)
{
return svgHash.Remove(item);
}
public IEnumerator<FILE> GetEnumerator()
{
return svgHash.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return svgHash.GetEnumerator();
}
}
}
I think either I am debugging in a terribly wrong way, or Microsoft should take a look at this. It's like future code is breaking current code...which is impossible!
OK here's my best guess..
First, as I mentioned in the comments, the exception doesn't occur if you comment out the line FILE exists = randomCollection.Where(f => f.fileName == test.fileName && f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First()‌​;
Second, I noticed the same behavior can be reproduced with the following code:
if (true)
{
object o;
o = new object();
Func<bool> m = () => o == null;
}
i.e. the cause seems to be related to the variable being used in a lambda expression. So, looking at the same code snippet above in ILSpy I get the following:
Program.<>c__DisplayClass0_0 <>c__DisplayClass0_ = new Program.<>c__DisplayClass0_0();
<>c__DisplayClass0_.o = new object();
Func<bool> func = new Func<bool>(<>c__DisplayClass0_.<Main>b__0);
so my best guess is that the NullReferenceException refers to <>c__DisplayClass0_ intance being null - and I'm therefore inclined to believe that the stepping through the if(true) actually skipped the first line where <>c__DisplayClass0_ is instantiated

c# - Code that HAS NOT RUN YET is causing an exception? How is this even possible?

So I am completely stumped on this one. I am getting an error Object reference not set to an instance of an object. and I am not sure why.
I have a class FILE
public class FILE
{
private string _fileName;
public string fileName
{
get
{
if (!Settings.Values.CaseSensitive)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (!Settings.Values.CaseSensitive)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
I am creating an instance like:
FILE test1233;
test1233 = new FILE(); // <---- Ex thrown here!? Why???
test1233.fileName = "";
folderName = "";
fileHashDigest = new byte[1];
As soon as the variable is placed on the stack, it throws an exception. BUT... if I remove all refrences to this variable on code further down (WHICH HAS NOT YET BEEN EXECUTED IN DEBUGMODE!!!) then no exception gets thrown. What on earth is going on here?
For refrence, here is the method in it's entirety:
private bool IsFolderOverride(FileCollection zipFILEList, DataTable exceptionTableFileList, DataRow currentRow, ref DataTable detectedFolderRenames)
{
bool foundInExceptionTable = false;
foreach (DataRow exRow in exceptionTableFileList.Rows)
{
if (exRow["FILE_NAME"].ToString().ToUpper() == currentRow["FILE_NAME"].ToString().ToUpper() &&
(decimal)exRow["WINDOW_GROUP_ID"] == (decimal)currentRow["WINDOW_GROUP_ID"])
{
string name = exRow["FILE_NAME"].ToString().ToUpper();
string folder = exRow["FOLDER_NAME"].ToString().ToUpper();
byte[] digest = (byte[])exRow["FILE_HASH_DIGEST"];
CopyCat exCopyCat = new CopyCat();
exCopyCat.fileName = name;
exCopyCat.folderName = folder;
exCopyCat.fileHashDigest = digest;
//HAS AN EXCEPTION!
FILE test1233 = new FILE();
test1233.fileName = "";
test1233.folderName = "";
test1233.fileHashDigest = new byte[1];
//NO EXCEPTION THROWN
FILE test = new FILE();
bool test9 = zipFileList.Contains(test1233);
test.fileName = name;
test.folderName = folder;
test.fileHashDigest = digest;
FILE test123 = new FILE();
if (zipFileList.Contains(test1233)) // Exact match found in zip in old folder from exception table.
{
FILE exists = zipFileList.Where(f => f.fileName == test1233.fileName &&
f.fileHashDigest.SequenceEqual(test1233.fileHashDigest)).First();
object[] items = exRow.ItemArray;
Array.Resize(ref items, items.Length + 4);
items[items.Length - 1] = "Y";
items[items.Length - 2] = exists.folderName;
items[items.Length - 3] = test1233.folderName;
items[items.Length - 4] = "Folder Override";
if (detectedFolderRenames.Rows.Count == 0 || !detectedFolderRenames.Rows.Contains(items[0]))
detectedFolderRenames.Rows.Add(items);
foundInExceptionTable = true;
break;
}
else if (zipFileList.ContainsPartially(test1233)) // Match in zip with Different Hash found from ex table.
{
FILE exists = zipFileList.Where(f => f.fileName == test1233.fileName).First();
object[] items = exRow.ItemArray;
Array.Resize(ref items, items.Length + 4);
items[items.Length - 1] = "N";
items[items.Length - 2] = exists.folderName;
items[items.Length - 3] = test1233.folderName;
items[items.Length - 4] = "Folder Override";
if (detectedFolderRenames.Rows.Count == 0 || !detectedFolderRenames.Rows.Contains(items[0]))
detectedFolderRenames.Rows.Add(items);
foundInExceptionTable = true;
break;
}
}
else
continue;
}
return foundInExceptionTable;
}
UPDATE: I am still working on an example for you, but in the mean time here is potentially helpful information:
test1233' threw an exception of type 'System.NullReferenceException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Object reference not set to an instance of an object."
Source: null
StackTrace: null
TargetSite: null
The Data: {System.Collections.ListDictionaryInternal} part is a little interesting to me, my class does not use any dictionary lists.
UPDATE #2: Ok, I have produced a reproducible sequence of steps for others to try. On your machines, it may be just fine, like Jon Skeet said, it might be my debug environment settings but please try and let me know. Here are the steps to reproduce.
Open console app project and copy paste code below.
Set a break point here:
First run code past break point, it works! :D
Then run code again but this time STOP at the break point and DRAG the executing statement cursor INTO the if statement from here:
to here:
There it is! So the error was caused from my method of testing, but does this make any sense or is this just me on my machine?
CODE:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
FILECollection randomCollection = new FILECollection();
// Fill with junk test data:
for(int i = 0; i<10; i++)
{
FILE junkfile = new FILE() { fileName = i.ToString(), folderName = i.ToString(), fileHashDigest = new byte[1] };
randomCollection.Add(junkfile);
}
if (true)
{
Console.WriteLine("testing this weird exception issue...");
FILE test;
test = new FILE();
test.fileName = "3";
test.folderName = "3";
test.fileHashDigest = new byte[1];
FILE exists = randomCollection.Where(f => f.fileName == test.fileName &&
f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First();
}
}
}
public class FILE
{
public FILE() { _fileName = "";}
private string _fileName;
public string fileName
{
get
{
if (false)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (false)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
public class FILECollection : IEnumerable<FILE>, ICollection<FILE>
{
private HashSet<FILE> svgHash;
private static List<FILE> PreallocationList;
public string FileName = "N/A";
/// <summary>
/// Default Constructor, will not
/// preallocate memory.
/// </summary>
/// <param name="PreallocationSize"></param>
public FILECollection()
{
this.svgHash = new HashSet<FILE>();
this.svgHash.Clear();
}
/// <summary>
/// Overload Constructor Preallocates
/// memory to be used for the new
/// FILE Collection.
/// </summary>
public FILECollection(int PreallocationSize, string fileName = "N/A", int fileHashDigestSize = 32)
{
FileName = fileName;
PreallocationList = new List<FILE>(PreallocationSize);
for (int i = 0; i <= PreallocationSize; i++)
{
byte[] buffer = new byte[fileHashDigestSize];
FILE preallocationSVG = new FILE()
{
fileName = "",
folderName = "",
fileHashDigest = buffer
};
PreallocationList.Add(preallocationSVG);
}
this.svgHash = new HashSet<FILE>(PreallocationList);
this.svgHash.Clear(); // Capacity remains unchanged until a call to TrimExcess is made.
}
/// <summary>
/// Add an FILE file to
/// the FILE Collection.
/// </summary>
/// <param name="svg"></param>
public void Add(FILE svg)
{
this.svgHash.Add(svg);
}
/// <summary>
/// Removes all elements
/// from the FILE Collection
/// </summary>
public void Clear()
{
svgHash.Clear();
}
/// <summary>
/// Determine if the FILE collection
/// contains the EXACT FILE file, folder,
/// and byte[] sequence. This guarantees
/// that the collection contains the EXACT
/// file you are looking for.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(FILE item)
{
return svgHash.Any(f => f.fileHashDigest.SequenceEqual(item.fileHashDigest) &&
f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Determine if the FILE collection
/// contains the same file and folder name,
/// byte[] sequence is not compared. The file and folder
/// name may be the same but this does not guarantee the
/// file contents are exactly the same. Use Contains() instead.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool ContainsPartially(FILE item)
{
return svgHash.Any(f => f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Returns the total number
/// of FILE files in the Collection.
/// </summary>
public int Count
{ get { return svgHash.Count(); } }
public bool IsReadOnly
{ get { return true; } }
public void CopyTo(FILE[] array, int arrayIndex)
{
svgHash.CopyTo(array, arrayIndex);
}
public bool Remove(FILE item)
{
return svgHash.Remove(item);
}
public IEnumerator<FILE> GetEnumerator()
{
return svgHash.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return svgHash.GetEnumerator();
}
}
}
I think either I am debugging in a terribly wrong way, or Microsoft should take a look at this. It's like future code is breaking current code...which is impossible!
I tried to execute the code in a console app and is working, can you give more details? Answers about the Settings initialization doesn't make sense here at this point because you should be able to create the instance of FILE. Once you try to assign(set) or request(get) then you are dealing with fileName property. I am not seeing why you get the exception when you create the instance.
static void Main(string[] args)
{
FILE test1233;
test1233 = new FILE(); // <---- Ex is not thrown here!? test1233.fileName = "";
test1233.folderName = "";
test1233.fileHashDigest = new byte[1];
}
public class FILE
{
private string _fileName;
public string fileName
{
get
{
if (YOUR SETTING CONDITION HERE)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (YOUR SETTING CONDITION HERE)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
see the cursor on the print screen
Here is my debug configuration

InvalidCastException was unhandled for C# to use in VB6

What I'm trying to achieve is slowly modularizing old VB6 code to C#.
I am creating a test in VB6 to press a button and execute my c# form and pass back a string value.
I had it working yesterday and something somehow changed and it no longer works. Below is my C# code that I'm having the issue.
#define USE_COM
using System;
using System.Linq;
using System.Windows.Forms;
namespace CMS_DB_Operator_Input
{
static class Program
{
/// <summary>
/// Open the OperatorInput Form
///
/// Note: Will output the result to console out on success
/// </summary>
/// <param name="args">0: The Default Filter to Use</param>
/// <returns>
/// 0: Failure to Select
/// 1: Successfully Selected an Item
/// </returns>
[STAThread]
static int Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string displayName = (args.Length > 1) ? args[1] : null;
string result = "";
displayName = "CBU35PN42";
//displayName = "";
#if USE_COM
CMS_DB_GateKeeper.IGateKeeperUI api = new MS_DB_GateKeeper.GateKeeperUI();
result = api.AskOperatorInput(displayName); // <- INVALID CAST EXCEPTION was unhandled
#else
CMS_DB_GateKeeper.CMS_DB_GateKeeper_OperatorInput op = new CMS_DB_GateKeeper.CMS_DB_GateKeeper_OperatorInput(displayName);
if (displayName == null)
{
Application.Run(op);
if (op.SelectedDisplayName != null)
{
result = op.GetXmlResult(op.SelectedDisplayName); // Success
}
}
else
{
result = op.GetXmlResult(displayName);
}
#endif
Console.WriteLine(result);
return 0;
}
}
}

Calling a method in C#

I have problem to call a method in a WCFService. I downladed the file below for a project and I want to call a method in SampleHttpResquestAndResponse class in my WCFService (Also, I tried to do it in a main method and i couldn't succeed it either). However I can't do it, i can't find the method when I type it. How to call those methods in SampleHttpResquestAndResponse class?
using System;
using System.IO;
using System.Net;
using System.Text;
using System.IO.Compression;
using System.Xml.Serialization;
namespace Sample
{
public class SampleHttpResquestAndResponse
{
/// <summary>
/// Adonis servisi ile iletişim kurmayı sağlar.
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="prm_ServiceName">string</param> SearchHotels // BasketHotels // ConfirmHotels
/// <param name="prm_Criteria">object</param>
/// <param name="prm_Url">string</param> "http://xmltest.adonis.com/AdonisServices"
/// <returns>T</returns>
public static T AdonisRequestResponseMethod<T>(string prm_ServiceName, object prm_Criteria, string prm_Url)
{
#region Variables
HttpWebRequest HttpWebRequest;
T ReturnValue;
#endregion
try
{
#region Xml Serializer
var XmlString = SampleHttpResquestAndResponse.ConvertTypeToXml<object>(prm_Criteria).ToString();
#endregion
#region Http Web Request
HttpWebRequest = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}?prm_CurrentData={2}", prm_Url, prm_ServiceName, XmlString));
HttpWebRequest.ContentType = "text/xml;charset=\"utf-8\"";
HttpWebRequest.Method = "POST";
HttpWebRequest.Timeout = 80000000;
#endregion
#region Http Web Response
StreamWriter StreamWriterPost = new StreamWriter(HttpWebRequest.GetRequestStream());
StreamWriterPost.Write(XmlString);
StreamWriterPost.Close();
HttpWebResponse HttpWebResponse = (HttpWebResponse)HttpWebRequest.GetResponse();
StreamReader StreamReaderResponse = new StreamReader(HttpWebResponse.GetResponseStream(), Encoding.UTF8);
string StringResponse = string.Empty;
if (HttpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream decompress = new GZipStream(HttpWebResponse.GetResponseStream(), CompressionMode.Decompress))
{
StreamReader reader = new StreamReader(decompress);
StringResponse = reader.ReadToEnd();
}
}
else
{
StreamReader reader = new StreamReader(HttpWebResponse.GetResponseStream(), Encoding.UTF8);
StringResponse = reader.ReadToEnd();
}
#endregion
#region Return Value Type Process (DESERIALIZE)
ReturnValue = SampleHttpResquestAndResponse.ConvertXmlToType<T>(StringResponse.ToString()).Data;
#endregion
#region Return Value
return ReturnValue;
#endregion
}
catch (Exception ex)
{
#region Return Value
return ReturnValue = SampleHttpResquestAndResponse.ConvertXmlToType<T>(ex.Message).Data;
#endregion
}
}
public static ResultDTO<T> ConvertXmlToType<T>(string prm_Xml)
{
#region Variables
T ReturnValue;
#endregion
try
{
#region Replace String Value
prm_Xml = prm_Xml.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
, "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
prm_Xml = prm_Xml.Replace("<", "<").Replace(">", ">").Replace(""", "\"");
#endregion
#region Deserialize
using (MemoryStream MemoryStream = new MemoryStream())
{
using (StreamWriter StreamWriter = new StreamWriter(MemoryStream))
{
StreamWriter.Write(prm_Xml);
StreamWriter.Flush();
MemoryStream.Position = 0;
XmlSerializer XmlSerializer = new XmlSerializer(typeof(T));
using (StreamReader StreamReader = new StreamReader(MemoryStream))
{
StreamReader.ReadLine();
#region Result Value (SET)
ReturnValue = (T)XmlSerializer.Deserialize(StreamReader);
#endregion
}
}
}
#endregion
#region Return Value
return new ResultDTO<T>
{
Data = ReturnValue,
Success = true
};
#endregion
}
catch (Exception ex)
{
#region Return Value
return new ResultDTO<T>
{
Success = false,
Message = string.Format("Error Type : {0} Code : {1} Method Name : {2} Error Mesage : {3}", "Undetermined", "1000", "ConvertXmlToType", ex.Message),
};
#endregion
}
}
public static string ConvertTypeToXml<T>(T prm_Criteria)
{
#region Variables
XmlSerializer XmlSerializer;
StringWriter StringWriter = new StringWriter();
#endregion
try
{
#region Xml Serializer
XmlSerializer = new XmlSerializer(prm_Criteria.GetType());
XmlSerializer.Serialize(StringWriter, prm_Criteria);
var XmlString = StringWriter.ToString();
#endregion
#region Request Replace
return XmlString = XmlString.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "");
#endregion
}
catch (Exception ex)
{
throw ex;
}
finally
{
GC.SuppressFinalize(StringWriter);
}
}
}
public class ResultDTO
{
#region Properties
/// <summary>
/// İslem durumu.
/// </summary>
public bool Success { get; set; }
/// <summary>
/// İşlem mesajı.
/// </summary>
public string Message { get; set; }
#endregion
}
public class ResultDTO<T> : ResultDTO
{
#region Fields
/// <summary>
/// Generic data tipi.
/// </summary>
private T data = Activator.CreateInstance<T>();
#endregion
#region Properties
/// <summary>
/// Generic data tipi
/// </summary>
public T Data
{
get
{
if (data == null)
return data = default(T);
return data;
}
set { data = value; }
}
#endregion
}
}
PS: I know it is a little bit silly question, but i couldn't figure it. If it is needed, the below is how i try to call any method in this class in a simple way
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.Net;
using System.Text;
using System.IO.Compression;
using System.Xml.Serialization;
using Sample;
namespace Adonis
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AdonisService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select AdonisService.svc or AdonisService.svc.cs at the Solution Explorer and start debugging.
public class AdonisService : IAdonisService
{
ResultDTO res = new ResultDTO();
SampleHttpResquestAndResponse samp = new SampleHttpResquestAndResponse();
public string results()
{
string a1 = "";
object c = new object();
c = 434;
string b = "";
string a = "";
a= samp.AdonisRequestResponseMethod(a, c, b);
}
}
}
AdonisRequestResponseMethod is static, and as such would be called like this:
SampleHttpResquestAndResponse.AdonisRequestResponseMethod(a, b, c);
However, it is also a generic method, so you will have to supply the type you require:
SampleHttpResquestAndResponse.AdonisRequestResponseMethod<string>(a, b, c);
I see 2 things wrong here:
The method is both a generic method.
Since it's a generic method, you must provide a type for it:
SampleHttpResquestAndResponse samp = new SampleHttpResquestAndResponse ();
samp.AdonisRequestResponseMethod<SomeType>(a, b, c);
However, that's not the complete answer,
It's a static method, which means that you can't reference the method from an instance of the class, rather you must reference it from the class type
SampleHttpResquestAndResponse.AdonisRequestResponseMethod<SomeType>(a, b, c);
Oh, and one more thing... SampleHttpResquestAndResponse has an extra 's' in the 'Request' portion of the name. That might give you headaches later. Hope this helps!

Categories