C# Issues with MCP2210.dll - c#

I am currently developing a project with the USB Device MCP2210 by Microchip in c# on Visual Studio. I am using .Net v4 and the mcp2210_dll_dotnetv4_x86.dll released by Microchip. I am unfortunately stumped on why I am having issues connecting to the HID device. My issue arises from the call
D1.Handle = MCP2210.M_Mcp2210_OpenByIndex(D1.VID, D1.PID, i-1, null)<
Its on line 84. The response is error -106, The Device is already connected. Which is great and all but I need to connect it with this function call to receive the proper handle. If i change the index, currently i-1, I get a -101 error, no device at that index. Does anyone have a suggestion to diagnose or solve this problem? Ill post the project code below
using mcp2210_dll_m;
using System;
using System.Text;
namespace HID_Command_Line
{
public struct Device
{
public ushort PID { get; set; }
public ushort VID { get; set; }
public IntPtr Handle { get; set; }
public Device (ushort vid, ushort pid, IntPtr handle)
{
VID = vid;
PID = pid;
Handle = handle;
}
}
class Program
{
static void Main(string[] args)
{
byte[] Command = new byte[64];
string temp;
ConsoleKeyInfo code;
temp = ReadCommand();
do
{
Command = Converter.ToByteArray(temp);
Converter.CheckByteArray(Command);
code = Console.ReadKey();
Console.Write("\r\n");
if (code.Key == ConsoleKey.Y)
{
if (ConnectUSB() == true)
{
// SetUpDeviceSettings();
}
}
else if (code.Key == ConsoleKey.N)
{
temp = ReadCommand();
}
} while (code.Key != ConsoleKey.Escape);
Console.WriteLine("Exited Correctly");
}
public static string ReadCommand()
{
string temp;
Console.WriteLine("Please Enter the Command in Hex Format");
//Console.WriteLine(" Type Cntrl + Space for Nul ");
temp = Console.ReadLine();
int length = temp.Length / 2;
for (int i = length; i < 64; i++)
{
temp += "00";
}
return temp;
}
public static bool ConnectUSB()
{
bool confirmation = false;
Device D1 = new Device(0x04D8, 0x00DE, (IntPtr)null);
uint i = (uint) MCP2210.M_Mcp2210_GetConnectedDevCount(D1.VID, D1.PID);
if (i == 1)
{
Console.WriteLine("yeah Baby, Press any Button to Connect to Single Devices in your Area"); //assuming that the index for 1 device is always 0
Console.Read();
D1.Handle = MCP2210.M_Mcp2210_OpenByIndex(D1.VID, D1.PID, i-1, null);
Console.WriteLine("Handle is {0}", D1.Handle);
int Error = MCP2210.M_Mcp2210_GetLastError();
Console.WriteLine("Response is {0} \r\n", Error);
switch (Error)
{
case -101:
{
Console.WriteLine("Error, No Such Index Exists");
break;
}
case -103:
{
Console.WriteLine("Error, Device Not Found");
break;
}
case -104:
{
Console.WriteLine("Error, Internal Buffer too small");
break;
}
case -105:
{
Console.WriteLine("Error, Open Device Error");
break;
}
case -106:
{
Console.WriteLine("Error, Device Already Connected");
confirmation = true;
break;
}
case -20:
{
Console.WriteLine("Error, MALLOC Unsucessful");
break;
}
case -10:
{
Console.WriteLine("Error, NULL Returned");
break;
}
case -1:
{
Console.WriteLine("Error, Unknown Error");
break;
}
case 0:
{
Console.WriteLine("Success");
confirmation = true;
break;
}
}
}
else if (i > 1)
{
Console.WriteLine("To Many Devices Connected. Only one is to be run at a time \r\n");
Console.Read();
}
else
{
Console.WriteLine("System does not register the device. Please connect the device");
}
return confirmation;
}
// public static SetUpDeviceSettings()
// {
// return;
// }
}
static class Converter
{
public static void CheckByteArray(byte[] bytes)
{
var convert = new StringBuilder("Is this command correct[] { ");
foreach (var b in bytes)
{
convert.Append(b + ", ");
}
convert.Append("} \r\n [y]es, [n]o or Escape to Exit \r\n");
Console.WriteLine(convert.ToString());
}
public static byte[] ToByteArray(String HexString)
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
}
}

The third argument of the method ("M_Mcp2210_OpenByIndex") is the number MCP connected on your machine according to the dll doc (available at http://ww1.microchip.com/downloads/en/DeviceDoc/MCP2210_DLLv2.zip)
you can get this number with MCP2210.M_Mcp2210_GetConnectedDevCount(MCP2210_VID, MCP2210_PID)
try: MCP2210.M_Mcp2210_OpenByIndex(D1.VID, D1.PID, (uint) MCP2210.M_Mcp2210_GetConnectedDevCount(MCP2210_VID, MCP2210_PID), null)
OR
MCP2210.M_Mcp2210_OpenByIndex(D1.VID, D1.PID, (uint) 0, null)

Related

Linked list implementation of array using c# console

Hi i was wondering if anyone could help me. im stuck in a dead end here. I dont know how to make a peek and working pop function. i need assistance.
here is my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp13
{
class Program
{
int nextFree;
int End;
int Start;
Names[] Stack;
Names steven = new Names();
Names jacques = new Names();
Names samantha = new Names();
Names lilly = new Names();
public struct Names
{
public Int32 pointer;
public string data;
}
static void Main(string[] args)
{
Program prog = new Program();
do
{
prog.DisplayMenu();
}
while (true);
}
public void DisplayMenu()
{
Int32 userInput = 0;
Console.WriteLine("Enter number of choice:");
Console.WriteLine("=======================");
Console.WriteLine("1: Sign up for consultation");
Console.WriteLine("2: Begin consultation");
Console.WriteLine("3: Enter room");
Console.WriteLine("4: Closing time");
Console.WriteLine("5: Exit");
userInput = Int32.Parse(Console.ReadLine());
switch (userInput)
{
case 1:
this.Push();
break;
case 2:
this.Pop();
break;
case 5:
System.Environment.Exit(1);
break;
}
}
public Program()
{
Stack = new Names[20];
steven.data = "Steven";
steven.pointer = 1;
jacques.data = "Jacques";
jacques.pointer = 2;
samantha.data = "Samantha";
samantha.pointer = 3;
lilly.data = "Lilly";
lilly.pointer = -1;
Stack[0] = steven;
Stack[1] = jacques;
Stack[2] = samantha;
Stack[3] = lilly;
nextFree = 4;
End = 20;
Start = 0;
}
public string Pop()
{
string value = string.Empty;
if (nextFree == -1)
{
Console.WriteLine("Stack is empty");
Console.ReadLine();
}
else
{
Names thisNode = Stack[End];
int temp = End;
End = thisNode.pointer;
thisNode.pointer = nextFree;
nextFree = temp;
}
this.ListAllNames();
return value;
}
public void Push()
{
if (nextFree >= Stack.Length)
{
Console.WriteLine("Stackoverflow, to many elements for the stack");
Console.ReadLine();
}
else
{
Console.WriteLine("Enter a name to be added");
string input = Console.ReadLine();
Stack[nextFree].data = input;
Stack[nextFree].pointer = End;
End = nextFree;
nextFree++;
}
this.ListAllNames();
}
public void ListAllNames()
{
foreach (Names name in Stack)
{
Console.WriteLine("Name:" + name.data);
}
}
}
}
as you can see it is unfinished. im at a standstill and cannot move one.
I have trouble in using the elements here so that i could make a function such as peek and pop properly.

ZKEmkeeper: Events not triggering, DLL look like not working

I'm stucked for a while trying to use zkemkeeper sdk to use on a application that uses a InBios(Controller) for fingerprint. While i trying to trigger some event nothing happen, i just created a Console Application for test the SDK before start implementing on ASP.NET MVC here is my code, i first connect to the device and then i add the event OnAttTransactionEx someone can point me what i'm doing wrong.
Here is my code:
private static void Main(string[] args)
{
CZKEMClass zkem = new CZKEMClass();
int idwErrorCode = 0;
const string ipAddr = "10.0.1.240";
bool isConnected;
try
{
isConnected = zkem.Connect_Net(ipAddr, Convert.ToInt32(4370));
}
catch (Exception ext)
{
Console.WriteLine("Erro: " + ext);
zkem.GetLastError(ref idwErrorCode);
if (idwErrorCode != 0)
{
zkem.GetLastError(idwErrorCode);
}
else
{
Console.WriteLine("No data from terminal returns!");
}
throw new Exception();
}
if (isConnected)
{
//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
zkem.EnableDevice(1, true);
zkem.RegEvent(1, 65535);
zkem.OnAttTransactionEx += axCZKEM1_OnAttTransactionEx;
string sdwEnrollNumber = "";
int idwVerifyMode = 0;
int idwInOutMode = 0;
int idwYear = 0;
int idwMonth = 0;
int idwDay = 0;
int idwHour = 0;
int idwMinute = 0;
int idwSecond = 0;
int idwWorkcode = 0;
zkem.EnableDevice(1, false); //disable the device
if (zkem.ReadGeneralLogData(1))
{
//read all the attendance records to the memory
while (zkem.SSR_GetGeneralLogData(1, out sdwEnrollNumber, out idwVerifyMode,
out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour,
out idwMinute, out idwSecond, ref idwWorkcode))
{
//get records from the memory
DateTime datetime = new DateTime(idwYear, idwMonth, idwDay, idwHour, idwMinute, idwSecond);
int unixDate = (int) datetime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
try
{
Console.WriteLine(idwInOutMode);
Console.WriteLine(sdwEnrollNumber);
Console.WriteLine(unixDate);
}
catch (Exception ex)
{
//ignored
}
try
{
Console.WriteLine("inserted: " +
$"{idwYear}/{idwMonth}/{idwDay} {idwHour}:{idwMinute}:{idwSecond}.000");
}
catch (Exception ex)
{
}
}
}
Console.WriteLine("Fim");
}
else
{
zkem.GetLastError(ref idwErrorCode);
if (idwErrorCode != 0)
{
zkem.GetLastError(idwErrorCode);
}
else
{
Console.WriteLine("No data from terminal returns!");
}
}
zkem.EnableDevice(1, true);
Console.WriteLine("Teste");
do
{
while (!Console.KeyAvailable)
{
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
public static void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState,
int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
{
Console.WriteLine("Finger Recognized");
}
You must use STA thread .
Thread TT = new Thread(() =>
{
CZKEMClass zkem = new CZKEMClass();
Application.Run();
});
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
TT.Start();
Then create event. ZKEM events fire on STA threads.

Thread with while (true) loop exits somehow

I have a thread that is supposed to run continuously in my program and parse incoming serial data from a collection of sensors.
//initialized as a global variable
System.Threading.Thread processThread = new System.Threading.Thread(ProcessSerialData);
//this gets called when you press the start button
processThread.Start();
private void ProcessSerialData()
{
while (true)
{
//do a whole bunch of parsing stuff
}
int howDidYouGetHere = 0;
}
How is it possible that my program is reaching the "int howDidYouGetHere = 0" line??
Full code can be found here:
/// <summary>
/// ProcessSerialData thread will be used to continue testing the connection to the controller,
/// process messages in the incoming message queue (actually a linked list),
/// and sends new messages for updated data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ProcessSerialData()
{
while (true)
{
UpdateAhTextbox(test.ampHoursOut.ToString());
if (!relayBoard.OpenConn())
{
MessageBox.Show("Connection to controller has been lost.");
testInterrupted = "Lost connection. Time = " + test.duration;
UpdateStatusText(false);
ShutErDown();
}
/////////////////////////////////////////////////////
if (incomingData.Count > 0)
{
string dataLine = "";
try
{
dataLine = incomingData.First();
UpdateParsedDataTextbox(dataLine + "\r\n");
}
catch (System.InvalidOperationException emai)
{
break; //data hasn't come in yet, it will by the time this runs next.
}
incomingData.RemoveFirst();
if (dataLine.Contains("GET")) // some sensor values (analog/temp/digital) has come in
{
if (dataLine.Contains("GETANALOG")) // an analog value has come in
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]);
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 13) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(13));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
try
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
catch // can't convert to double
{
MessageBox.Show("Error occured: " + dataLine);
}
}
switch (pin)
{
case 1:
ReadVoltage(value);
break;
case 2:
ReadAmperage(value);
break;
}
}
else if (dataLine.Contains("GETTEMP")) // received reply with temperature data
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]); // using index of CH, retrieve which pin this message is coming from
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 11) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(11));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
ReadTemperature(pin, value);
}
else // must be CH3.GET
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]); // using index of CH, retrieve which pin this message is coming from
if (pin == 3) // only care if it's pin 3 (BMS), otherwise it's a mistake
{
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 7) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(7));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
ReadBMS(value);
}
}
}
else if (dataLine.Contains("REL")) // received reply about relay turning on or off.
{
if (dataLine.Contains("RELS")) // all relays turning on/off
{
if (dataLine.Contains("ON"))
{
for (int pin = 1; pin <= 4; pin++)
{
test.contactors[pin] = true;
}
}
else // "OFF"
{
for (int pin = 1; pin <= 4; pin++)
{
test.contactors[pin] = false;
}
}
}
else // single relay is turning on/off
{
int index = dataLine.IndexOf("REL");
int pin = (int)Char.GetNumericValue(dataLine[index + 3]);
if (dataLine.Contains("ON"))
{
test.contactors[pin] = true;
}
else if (dataLine.Contains("OFF"))
{
test.contactors[pin] = false;
}
else if (dataLine.Contains("GET"))
{
if (Convert.ToInt32(incomingData.First()) == 1)
test.contactors[pin] = true;
else
test.contactors[pin] = false;
incomingData.RemoveFirst();
}
}
}
}
/////////////////////////////////////////////////////
// we only want more data if we're done processing the current data, otherwise we're stuck with too much and processing is heavily delayed.
if (isTestRunning && incomingData.Count < 3)
{
//read & output v, a, bms state
sendToController("CH1.GETANALOG"); // get voltage
sendToController("CH2.GETANALOG"); // get amperage
sendToController("CH3.GET"); // get BMS state
//read & output temperature
sendToController("CH4.GETTEMP"); // get temperature
sendToController("CH5.GETTEMP");
string lines = "Ah Out: " + test.ampHoursOut + ", Voltage: " + test.voltage +
", Amperage: " + test.amperage + ", Cell Temperature: " + test.tempBattery +
", Load Temperature: " + test.tempLoad;
WriteToLog(lines);
}
}
int howDidYouGetHere = 0;
}
The break (ignoring those inside the nested switch) breaks out of the while loop.
Perhaps you have tried to update your UI using UpdateParsedDataTextbox This will cause InvalidOperationException(then breaks the while loop) because you tries to access the UI control from thread that doesn't own the control.

How to loop this?

Im having trouble learning how to loop, and Im stuck on how to do this. Basically I was asked to program that rolls a 6 sided die and it'll ask you how many times you want to roll it. Based on how many times you roll, it will out put a table of how many times it landed on each side. This is what I have so far.
using System;
namespace Dice
{
class Program
{
static void Main(string[] args)
{
bool continueRunning = true;
int sessionNumber = 1;
DisplayInstructions();
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
aDice.RollDice();
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}
}
public static bool getYorN(string question)
{
bool validInput = false;
while (!validInput)
{
Console.WriteLine("{0}", question);
Console.WriteLine("Enter 'yes' or 'no' to continue...");
string userResponse = Console.ReadLine().ToLower();
if (userResponse == "yes" || userResponse == "no")
{
validInput = true;
switch (userResponse)
{
case "yes":
return true;
case "no":
return false;
default:
return false;
}
}
else
{
Console.Clear();
Console.WriteLine("You've entered an invalid term");
}
}
return false;
}
public static void DisplayInstructions()
{
Console.WriteLine("Welcome to the Dice Game!!");
Console.WriteLine("\n\n\nThis program will simulate rolling a die and will track the frequency \neach value is rolled.");
Console.WriteLine("\n\n\nAfter rolling the die, the program will output a summary table for the session.");
Console.WriteLine("\n\n\nPlease press any key to continue.");
Console.ReadKey();
Console.Clear();
}
public static string getInfo(string what)
{
Console.WriteLine(what);
return Console.ReadLine();
}
}
}
The class I have in this is
using System;
namespace TripCalcApp
{
class Dice
{
private int side1 = 0, side2 = 0, side3 = 0, side4 = 0, side5 = 0, side6 = 0;
Random randNum = new Random();
public Dice()
{
}
public int Side1
{
get { return side1; }
set { side1 = value; }
}
public int Side2
{
get { return side2; }
set { side2 = value; }
}
public int Side3
{
get { return side3; }
set { side3 = value; }
}
public int Side4
{
get { return side4; }
set { side4 = value; }
}
public int Side5
{
get { return side5; }
set { side5 = value; }
}
public int Side6
{
get { return side6; }
set { side6 = value; }
}
public void RollDice()
//RollDice = randNum.Next(1, 7)
{
switch (randNum.Next(1, 7))
{
case 1: side1++;
break;
case 2: side2++;
break;
case 3: side3++;
break;
case 4: side4++;
break;
case 5: side5++;
break;
case 6: side6++;
break;
}
}
public override string ToString()
{
return " Freq. Rolls " +
"________________________________________" +
"\nSide 1 of Die rolled :" + side1 +
"\nSide 2 of Die rolled :" + side2 +
"\nSide 3 of Die rolled :" + side3 +
"\nSide 4 of Die rolled :" + side4 +
"\nSide 5 of Die rolled :" + side5 +
"\nSide 6 of Die rolled :" + side6 +
"\n";
}
}
}
I had an idea on how to do loop it but Im still unsure. I thought of something like this but it doesnt work and I was hoping you guys could help me!!
int howMany = int.Parse(getInfo("How many times would you like to roll the die?"));
do
{
Dice aDice = new Dice();
for (int counter = howMany; counter > 0; counter--)
{
aDice.RollDice();
}
while (howMany < 0)
{
Console.WriteLine(aDice);
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
playAgain = getYorN("Would you like to play again?");
sessionNumber++;
}
All you need to do is call aDice.RollDice method howMany times:
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
for(int i = 0; i < howMany; i++)
{
aDice.RollDice();
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}

Error 1 Cannot implicitly convert type 'int**' to 'int*'. An explicit conversion exists (are you missing a cast?)

I'm learning C and C# and this question is for C#. I looking at pointers at msdn and this code is not compiling, it gives the error:Error 1 Cannot implicitly convert type int** to int*. An explicit conversion exists (are you missing a cast?). What am I missing here?
Here is the code:
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix; **The error is on this line**
}
EDIT:
Here is the program in its entirety:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Diagnostics;
using System.Windows.Forms;
using practice;
class Program
{
public delegate bool ThisIsTheDelegate(int number);
public delegate bool ThisIsAnotherDelegate(int number);
private static string address;
public static String Address
{
get
{
return address;
}
set
{
address = value;
}
}
static void Main()
{
int[] someArray = new int[] { 1, 2, 3, 5, 6, 7, 8, 9, 0 };
foreach (int number in someArray)
{
Console.WriteLine(number);
}
int integer = 98;
string someString = "edited";
string[] someStr = { "edited" };
String[] anotherStringSomestr = new String[] { "edited" };
var readWithLinq = from far in anotherStringSomestr
select far;
foreach (var some in readWithLinq)
{
Console.WriteLine(some);
}
Program newPro = new Program();
bool isEven1 = newPro.isEven(99);
Console.WriteLine(isEven1);
ThisIsTheDelegate newDelegate = newPro.isEven;
Console.WriteLine(newDelegate(98));
int[] numbers = { 1, 2, 3, 5, 6, 7, 8, 9 };
List<int> evenNumbers = FilterArray(numbers, newDelegate);
foreach(int integer1 in evenNumbers)
{
Console.WriteLine(integer1);
}
List<int> oddNumbers = FilterArray(numbers, isOdd);
foreach (int integer1 in oddNumbers)
{
Console.WriteLine(integer1);
}
ThisIsAnotherDelegate anotherDelegate;
anotherDelegate = number => (number % 2 == 0);
Console.WriteLine("{0} is a even number", anotherDelegate(4));
for (int i = 0; i < someString.Length; i++)
{
Console.WriteLine(someString);
}
for (int i = 0; i < someStr.Length; i++)
{
Console.WriteLine(someStr[i]);
}
Console.WriteLine(integer);
SimpleStruct structss = new SimpleStruct();
structss.DisplayX();
M.x = 1;
structss.x = 98;
Console.WriteLine(M.x);
Console.WriteLine(structss.x);
M.structtaker(ref structss);
M.classtaker();
Console.WriteLine(structss.x);
Console.WriteLine(M.x);
M.x = 1;
structss.x = 98;
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
}
int selection = 98;
while (selection != 0)
{
mainMenu();
Console.Write("Enter choice: ");
selection = Convert.ToInt32(Console.ReadLine());
switch (selection)
{
case 0:
break;
case 1:
openSomething();
break;
case 2:
calculator();
break;
case 3:
coolestProgramEverALive();
break;
case 4:
make_to_do_list();
break;
case 5:
add_to_do_list();
break;
case 6:
readToDoList();
break;
case 7:
linq_and_arrays();
break;
case 8:
calendar();
break;
case 9:
linq_and_collections();
break;
default:
Console.WriteLine("Unkown selection. Try again");
break;
}
}
}
private static bool isOdd(int number)
{
return (number % 2 == 1);
}
private static List<int> FilterArray(int[] numbers, ThisIsTheDelegate newDelegate)
{
List<int> result = new List<int>();
foreach (int item in numbers)
{
if (newDelegate(item))
result.Add(item);
}
return result;
}
private static void linq_and_collections()
{
List<string> names = new List<string>();
names.Add("Billy");
names.Add("Steve");
names.Add("Casandra");
names.Insert(0, "Johanna");
names.Add("Sonny");
names.Add("Suzanne");
names.Insert(2, "Sid");
var queryLinqUpper = from name in names
where (name.StartsWith("S") || name.StartsWith("B") || name.StartsWith("J"))
let namesToUpper = name.ToUpper()
orderby namesToUpper
select namesToUpper;
foreach (var linqToUpper in queryLinqUpper)
{
Console.Write(linqToUpper + " ");
}
Console.WriteLine();
M.WriteTextToConsole("Hello, world. Programming in C# is fun");
char c = 'A';
int count = 14;
String str = new String(c, count);
str.WriteTextToConsole();
M.WriteTextToConsole(str);
}
private static void calendar()
{
Application.Run(new Form1());
}
private static void readToDoList()
{
var files = from file in Directory.GetFiles(#"C:\data", "*.txt")
select file;
int number = 1;
foreach (var file in files)
{
Console.WriteLine(number + ". " + file);
number++;
}
Console.Write("What todolist do you want to read? Give me the name:");
try
{
string name = Console.ReadLine();
Address = Path.Combine(#"C:\data", name + ".txt");
TextReader inFile = new StreamReader(Address);
while (inFile.Peek() != -1)
{
string line = inFile.ReadLine();
Console.WriteLine(line);
}
inFile.Close();
}
catch (Exception ex)
{
MessageBox.Show("Exception thrown!", "Error");
Console.WriteLine(ex.ToString());
}
}
private static void linq_and_arrays()
{
int numberOfElements;
Console.WriteLine("Start by setting the int[] array.");
Console.Write("How many elements are there in your array?");
numberOfElements = Convert.ToInt32(Console.ReadLine());
int[] array = new int[numberOfElements];
for (int i = 0, j = numberOfElements; i < numberOfElements; i++, j--)
{
Console.Write("Integers left to add {0}. Enter an integer:", j);
array[i] = Convert.ToInt32(Console.ReadLine());
}
var arrayquery = from value in array
select value;
foreach (var val in arrayquery)
{
Console.WriteLine("Value from array:{0}", val);
}
}
private static void add_to_do_list()
{
Console.WriteLine("Which todolist do you want to modify?");
listToDoLists();
Console.Write("Enter name of todolist: ");
string name = Console.ReadLine();
Address = Path.Combine(#"C:\data", name + ".txt");
String tempString;
StreamWriter stream;
stream = File.AppendText(Address);
Console.Write("Enter your new ToDo: ");
tempString = Console.ReadLine();
stream.WriteLine(tempString);
stream.Close();
TextReader inFile;
inFile = new StreamReader(Address);
while (inFile.Peek() != -1)
{
string line = inFile.ReadLine();
Console.WriteLine(line);
}
inFile.Close();
}
private static void listToDoLists()
{
int filenumber = 1;
string[] filepaths = Directory.GetFiles("C:\\data\\", "*.txt");
foreach (string file in filepaths)
{
Console.WriteLine(filenumber + ". " + file);
filenumber++;
}
}
private static void make_to_do_list()
{
string path, name;
string yesOrNo;
Console.Write("Enter name of todolist: ");
name = Console.ReadLine();
path = Path.Combine(#"C:\data", name + ".txt");
TextWriter outFile = new StreamWriter(path);
labelOne: // else clause : unknown answer
Console.WriteLine("Do you want to add something to todolist.Y/N?");
yesOrNo = Console.ReadLine();
if (yesOrNo.ToLower() == "y")
{
string line;
int lines;
Console.Write("How many lines?");
lines = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < lines; i++)
{
Console.Write("Enter a line of text: ");
line = Console.ReadLine();
outFile.WriteLine(line);
}
outFile.Close();
}
else if (yesOrNo.ToLower() == "n")
{
Console.WriteLine("You can close the application now.");
}
else
{
Console.WriteLine("Unknown answer. Try again");
goto labelOne;
}
}
private static void coolestProgramEverALive()
{
System.Diagnostics.Process.Start(#"C:\Users\KristjanBEstur\Documents\Visual Studio 2012\Projects\The_coolest_program_ever_alive\The_coolest_program_ever_alive\obj\Debug\The_coolest_program_ever_alive.exe");
}
private static void calculator()
{
System.Diagnostics.Process.Start("calc");
}
private static void openSomething()
{
System.Diagnostics.Process.Start("notepad");
}
private static void mainMenu()
{
Console.WriteLine("Main Menu");
Console.WriteLine("0. Quit");
Console.WriteLine("1. OpenSomething");
Console.WriteLine("2. Calculator");
Console.WriteLine("3. coolestProgramEverAlive");
Console.WriteLine("4. Make todolist");
Console.WriteLine("5. Add to todolist");
Console.WriteLine("6. Read to do list");
Console.WriteLine("7. Linq and arrays");
Console.WriteLine("8. Calendar");
Console.WriteLine("9. Linq and collections");
}
public bool isEven(int number)
{
return (number % 2 == 0);
}
}
static class M
{
public static int x;
public static void WriteTextToConsole(this string text)
{
Console.WriteLine(text);
}
public static void structtaker(ref SimpleStruct s)
{
s.x = 5;
}
public static void classtaker()
{
M.x = 5;
}
}
class Test
{
static int value = 20;
unsafe static void F(out int* pi1, ref int* pi2) {
int i = 10;
pi1 = &i;
fixed (int* pj = &value) {
// ...
pi2 = pj;
}
}
}
struct SimpleStruct
{
public int x;
private int xval;
public int X
{
get
{
return xval;
}
set
{
if (value < 100)
xval = value;
}
}
public void DisplayX()
{
Console.WriteLine("The stored value is: {0}", X);
}
}
I wished I could replicate this it seems like a rather interesting issue. Here is the section of the standard that I believe applies to this (sorry about the formatting):
18.3 Fixed and moveable variables The address-of operator (§18.5.4) and the fixed statement (§18.6) divide variables into two categories:
Fixed variables and moveable variables. Fixed variables reside in
storage locations that are unaffected by operation of the garbage
collector. (Examples of fixed variables include local variables, value
parameters, and variables created by dereferencing pointers.) On the
other hand, moveable variables reside in storage locations that are
subject to relocation or disposal by the garbage collector. (Examples
of moveable variables include fields in objects and elements of
arrays.) The & operator (§18.5.4) permits the address of a fixed
variable to be obtained without restrictions. However, because a
moveable variable is subject to relocation or disposal by the garbage
collector, the address of a moveable variable can only be obtained
using a fixed statement (§18.6), and that address remains valid only
for the duration of that fixed statement. In precise terms, a fixed
variable is one of the following: • A variable resulting from a
simple-name (§7.6.2) that refers to a local variable or a value
parameter, unless the variable is captured by an anonymous function.
• A variable resulting from a member-access (§7.6.4) of the form V.I,
where V is a fixed variable of a struct-type. • A variable resulting
from a pointer-indirection-expression (§18.5.1) of the form *P, a
pointer-member-access (§18.5.2) of the form P->I, or a
pointer-element-access (§18.5.3) of the form P[E]. All other variables
are classified as moveable variables. Note that a static field is
classified as a moveable variable. Also note that a ref or out
parameter is classified as a moveable variable, even if the argument
given for the parameter is a fixed variable. Finally, note that a
variable produced by dereferencing a pointer is always classified as a
fixed variable.
I spend some time trying to create a similar error but wasn't about to. The only way I was able to recreate the issue was with the following code:
void test() {
int ix = 10;
unsafe {
int* px1 = &ix;
int* px2 = &px1; // **The error is on this line**
}
}
Of course this code cannot be fixed by moving the ix declaration into the safe scope. Perhaps you could try replicating the original problem in a very small bit of code (like above) and verify that both the problem and the fix replicate. Perhaps VS became confused. I have had problems that made no sense and went away by exiting VS and restarting (not often but a few times).
I moved the i declaration down inside the unsafe block and it fixed it, I don't know why?
Here is the code:
unsafe
{
int ix = 10;
int* px1;
int* px2 = &ix;
}
I've moved the expression "int i = 10;" out of the unsafe block and now it compiles. I've also put the code in question in a new project of another instance of vs2012pro. And that also compiles. So now I'm unable to replicate the error.
Here is the code:
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
Test.F(out px1, ref px2);
Console.WriteLine("*px1 = {0}, *px2 = {1}",
*px1, *px2); // undefined behavior
}
Here is the other project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace saxerium
{
class Program
{
static void Main(string[] args)
{
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
Test.F(out px1, ref px2);
Console.WriteLine("*px1 = {0}, *px2 = {1}",
*px1, *px2); // undefined behavior
}
}
}
class Test
{
static int value = 20;
public unsafe static void F(out int* pi1, ref int* pi2)
{
int i = 10;
pi1 = &i;
fixed (int* pj = &value)
{
// ...
pi2 = pj;
}
}
}
}

Categories