|
Here[^] is a link on how to do binary math, have a look at the Decimal Conversion section and see if you can use this to figure out what you need to do.
Here, now try to do the reverse yourself;
string originalNumberString = "3454587632090873454498766009893432389887";
char[] numberValues = originalNumberString.ToCharArray();
int numberLength = numberValues.Length;
int originalLength = numberValues.Length;
string binaryNumber = string.Empty;
do
{
char[] newNumberString = new char[numberLength];
double remainderValue = 0.00;
foreach (char numberValue in numberValues)
{
double valueNumber = (double.Parse(numberValue.ToString()) / 2) + remainderValue;
remainderValue = (valueNumber % 1) * 10;
newNumberString[originalLength - numberLength] = (valueNumber - (valueNumber % 1)).ToString().ToCharArray()[0];
--numberLength;
}
binaryNumber += (remainderValue > 0 ? 1 : 0);
int offSetValue = (newNumberString[0] == '0' ? 1 : 0);
numberValues = new char[numberValues.Length - offSetValue];
Array.Copy(newNumberString, offSetValue, numberValues, 0, numberValues.Length);
numberLength = numberValues.Length;
originalLength = numberValues.Length;
} while (originalLength > 0);
while (((binaryNumber.Length / 8.0) % 1) > 0)
{
binaryNumber += "0";
}
char[] charArray = binaryNumber.ToCharArray();
Array.Reverse(charArray);
binaryNumber = new string(charArray);
byte[] numberArray = new byte[binaryNumber.Length / 8];
System.Collections.BitArray bitArray = new System.Collections.BitArray(binaryNumber.Length);
for (int bitIndex = 0; bitIndex < binaryNumber.Length; ++bitIndex)
{
bitArray[bitIndex] = (binaryNumber[bitIndex] == '1' ? true : false);
}
bitArray.CopyTo(numberArray, 0);
This will give you a 17 byte array or a 136 bit BitArray for a 41 digit number.modified on Friday, March 12, 2010 2:15 AM
|
|
|
|
|
There's a BigInteger class here on CP:
C# BigInteger Class[^].45 ACP - because shooting twice is just silly ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997 ----- "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001
modified on Friday, March 12, 2010 8:18 AM
|
|
|
|
|
This is his 5th time asking this question, though it is just from a spec on windows WPA Activation, he has been pointed to a big int class before so I thought I would give him some code that would do exactly what he wanted.
|
|
|
|
|
my main form is form1.
<br />
<br />
private void newToolStripMenuItem_Click(object sender, EventArgs e)<br />
{<br />
newToolStripMenuItem.Enabled = false;<br />
<br />
Form2 frm2 = new Form2();<br />
frm2.Owner = this;<br />
frm2.Show();<br />
<br />
<br />
how can i enable back newToolStripMenuItem to true if the form2 to is closed i tried to create if form2 close event but
i can't get the intelisense of newToolStripMenuItem
|
|
|
|
|
Subscribe to the FormClosed event of frm2 and enable the menu item.
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
newToolStripMenuItem.Enabled = false;
Form2 frm2 = new Form2();
frm2.Owner = this;
frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
frm2.Show();
}
private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
newToolStripMenuItem.Enabled = true;
} Dave
Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) Why are you using VB6? Do you hate yourself? (Christian Graus)
|
|
|
|
|
i cant get the intelisense of newToolStripMenuItem.Enabled = true;
in the event private void frm2_FormClosed(object sender, FormClosedEventArgs e)
my newToolStripMenuItem is in my form1 and i want to show the form2 but disable the newToolStripMenuItem if form2 is loade already. and if form2 is close then the newToolStripMenuItem is enabled
|
|
|
|
|
error does not exist in the current context
|
|
|
|
|
because all the code I posted goes in form1.
Form2 doesn't know about form1, and shouldn't, and doesn't ever need to know! Therefore you can't access it's instance properties, methods, controls etc...
Form1 knows about form2 however, so it can listen for it's FormClosed event (and any others too) and react accordingly.Dave
Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) Why are you using VB6? Do you hate yourself? (Christian Graus)
|
|
|
|
|
My program has a main message loop as follows:
ContextMenu trayMenu = new ContextMenu();
trayIcon = new NotifyIcon();
trayIcon.Visible = true;
trayIcon.MouseDoubleClick += new MouseEventHandler(trayIcon_MouseDoubleClick);
while (true)
{
try
{
MainForm = new Form();
MainForm.WindowState = FormWindowState.Minimized;
MainForm.ShowInTaskbar = false;
Application.Run(MainForm);
}
catch (Exception)
{
continue;
}
break;
}
When my forms (made on main thread via trayIcon_MouseDoubleClick) throw an exception (on the main thread) they are caught with the above method and the program keeps on running just fine and I can lauch another form via the trayIcon;
My issue is that my forms that are being made call other functions asyncronously, and if those functions throw exceptions they are not caught and my program crashes.
I’m starting the asyncronous functions via System.Threading.ThreadPool.QueueUserWorkItem() incase it makes a difference.
My question is, how can I catch these exceptions?
Thank you all for your knowldege and advice!
|
|
|
|
|
One of these events may be what you are looking for: AppDomain.UnhandledException, Application.ThreadException. Read about them on MSDN (Google will bring you there).
If you want a more customized approach, you can have the thread wrap all the logic in a try/catch and then in the catch have it call some static method that handles exceptions.
Or you could pass a delegate to the code that runs in the thread. Using the same try/catch wrapper, you can have the code in the catch block call the delegate, passing in the exception. The code that you pass in the delegate can be whatever you want (can call back to the form and display a MessageBox or whatever you want).
Instead of a delegate, you could pass in an instance of an object that implements an interface that contains a method that accepts a parameter of type Exception. This acts like the delegate, except you call a method on an object instance instead of calling the delegate.
If you really want, you can create your own class that executes delegates in thread. It could contain logic that catches any exceptions in those delegates and then handles them in a standard way (e.g., any of the ways I described above). The advantage to doing this is that you only have to write the try/catch block and exception handling logic once, rather than for each thread you create.
|
|
|
|
|
Hi,
simply restarting your main form whenever a problem occurs, I don't like it a bit. You are not in control, old threads may still be running, files may still be open, memory leaks and deadlocks are possible.
What you should do is solve any potential problem as near as possible to the location where it occurs. And then you could/should add an extra safety net to catch whatever exception that slips through; those should be logged in full detail, and result in a "fatal error" message to the user (assuming an interactive program); or a real shutdown-and-restart of your app (when an embedded application, e.g. a server). For the safety net, you would need the things aspdotnetdev mentioned.
|
|
|
|
|
Thank you both, your comments are very insightful.
I will implement the additional Exception catching that aspdotnetdev mentioned and after catching the exceptions I will report them, then restart my application as Luc recommended.
Thanks Luc and aspdotnetdev, I appreciate both of your input.
|
|
|
|
|
you're welcome.
|
|
|
|
|
Hi,
I have been struggling with receiving events from a server to a client (using .NET remoting) for quite a long time now but I keep receiving the following message on client side (“Exception has been thrown by the target of an invocation.”). This message is received as the server is trying to call the event handler while the event handler exists in the client and since the client assembly is not available on the side of the server, this message comes.
Any idea?
Server Class library
-----------------------------
public delegate void MyDel();
public class ServerClass : MarshalByRefObject
{
public event MyDel myEvent;
public void StartServer (bool shouldFireEvent)
{
TcpServerChannel tsc;
BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary di = new Hashtable();
di["port"] = 8085;
di["bindTo"] = "172.19.35.191";
tsc = new TcpServerChannel(di, provider);
ChannelServices.RegisterChannel(tsc, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServerClass), "myURI", WellKnownObjectMode.Singleton);
if (shouldFireEvent)
{
while (true)
{
myEvent();
Thread.Sleep(1000);
}
}
}
}
Server GUI
-----------------------------
class ServerGui
{
static void Main(string[] args)
{
ServerClass server = new ServerClass();
server.myEvent += new MyDel(ReceivedEventFromServerHandler);
server.StartServer(true);
Console.WriteLine("server is running. press enter to quit");
Console.ReadKey();
}
static void ReceivedEventFromServerHandler()
{
Console.WriteLine("I am the server GUI. Got a message from the server");
}
}
Client
--------------
class ClientClass
{
static void Main(string[] args)
{
ServerClass server = (ServerClass)Activator.GetObject(typeof(ServerClass), "tcp://172.19.35.191:8085/myURI");
server.myEvent += new MyDel(server_myEvent);
while (true)
{
Thread.Sleep(1000);
}
}
static void server_myEvent()
{
Console.WriteLine("I am the client. Got a message from the server over the network");
}
}
|
|
|
|
|
Guys, anyone? please please please, it's becoming urgent for me. I don't have a solution even after looking in the web for a week now...
|
|
|
|
|
Hi,
This is my second post, I hope to do better that the first one..
I wrote a small addin in C# to Outlook 2007.
It connects to a local DB and should remove mail addresses which are either "Bounced" (not vaild) or asked to un-subscribe from the mailing list.
The addin was written using Visual Studio 2008 VSTO tools.
It does what it should, when I debug, yet when I step out of my managed code, the Outlook hangs, CPU is 100% and the message I see at the system tray is "Outlook is synchronizing folders".
When I remove my logic and use a "hard coded" address - it works.
I would also like to attach my code, since it's very long, I will only put some part of it here,
I can send the complete file (300 lines totally) by mail.
I will appreciate if someone is familiar with this
TIA,
Amit.
<code>
void App_ItemSend(object Item, ref bool Cancel)
{
Outlook.MailItem Mail = (Outlook.MailItem)Item;
//Get the addresses from the "To" field
string[] toArray =
Mail.To == null ? new string[] { } : Mail.To.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
//Internal Data Structures to hold the "To"recipients
Dictionary<string, Recipient> toDic = new Dictionary<string, Recipient>();
List<string> emailToCheck = new List<string>();
List<string> invalidEmails = null;
//Remove spaces from the "To" list (originally recieved as "tuktuk@blabla.com; oved@sabih.com")
for (int i = 0; i < toArray.Length; i++)
{
toArray[i] = toArray[i].Replace(" ", "");
}
try
{
while (Mail.Recipients.Count > 0)
{
//Get the first recipient object in the recipient list
Recipient rec = Mail.Recipients[1];
//Remove the first object from the recipient list
Mail.Recipients.Remove(1);
List<Recipient> recList = new List<Recipient>();
ICollection<string> emailList = GetEmailsList(rec.AddressEntry);
foreach (string email in emailList)
{
//Create a new recipient
Recipient newRec = Mail.Session.CreateRecipient(email);
if (!newRec.Resolve())
{
//if eMail address can't be verified against the Outlook address book - skip it
continue;
}
//if eMail address is valid against the address book, add it to the current recipient list
recList.Add(newRec);
//Add the new recipient to the list of emails to check "Bounced"/"Un-Subscribed"
if (!emailToCheck.Contains(newRec.Address))
{
emailToCheck.Add(newRec.Address);
}
}
//If the current recipient is contained in the original "To" list, then go over the recipient list
//For each such recipient under that recipient name, add it the the "To" group
if (Array.IndexOf(toArray, rec.Name) >= 0)
{
foreach (Recipient r in recList)
{
toDic[r.Address.ToLower()] = r;
}
}
}
// Get the list of invalid email lists
invalidEmails = GetInvalidEmails(emailToCheck);
}
catch (System.Exception e)
{
Cancel = true;
MessageBox.Show(e.Message + "\nMailing Canceled", "Error Validating Emails");
return;
}
//Create the final data structure for the email lists
StringBuilder toList = new StringBuilder();
//Go over each entry in the "To" dictionary. In case the current entry is valid, add it to the "To" final list
foreach (KeyValuePair<string, Recipient> kvp in toDic)
{
if (invalidEmails == null || !invalidEmails.Contains(kvp.Key.Replace("'", "")))
{
toList.AppendFormat("{0};", kvp.Key);
}
}
if (toList.Length == 0 && ccList.Length == 0 && bccList.Length == 0)
{
MessageBox.Show("All recipients addresses are invalid or unsubscribed.\nSend operation aborted.");
Cancel = true;
return;
}
Mail.To = null;
//Add the address lists back to the original "To" list of the Outlook 2007 object
if (toList.Length > 0)
{
Mail.To = toList.ToString().Substring(0, toList.Length - 1);
}
}
</code>
|
|
|
|
|
Perhaps it's been mentioned before, but I'm looking at a switch (with sixteen cases, a little bit large) and it has occurred to me that because it's controlled by an enumerated value (zero to fifteen) that I might get better performance (or maybe worse), and perhaps better readability from an array of delegates (perhaps anonymous methods).
The value has already been validated so I know that it won't be out of range. I would also know that none of the values is null.
Maintainability might be hindered somewhat, depending on how I implement it.
Any experiences? Discuss...
|
|
|
|
|
I do not know the answer, but I would put it to the test. And forcing it to run through the loop many times. Lets say 1000 times. and add a measuring system. And see what results you get
|
|
|
|
|
If possible, a better object model.
Enums are often the sign of a missing inheritance hierarchy, I many times before using them. The other thing they lead to is switces, which are almost the work of the devil. This follows Martin Fowler's work on re-factoring:
http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html[^]Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
|
|
|
|
|
|
An array of delegates is approximately 4 times as slow, if the switch is non-sparse and compiled down to a switch instruction in MSIL
|
|
|
|
|
And a V-table for a class hierarchy might be as well?
|
|
|
|
|
So, I benchmarked it.
Switch: 150
Array of delegates: 676
Abstract methods, sealed: 2868
Abstract methods, not sealed: 2866
(the number is the tick count / 10 million, for a loop of 500 million iterations)
I'm surprised to see that sealed vs unsealed made absolutely no difference..
All tests were done in 64bit mode, on release, with no debugger attached, using the Stopwatch class. The methods did nothing, the switch had some integer additions in it to keep it from being optimized away (not sure whether it would even do that, but an addition is nearly free anyway and it's safer that way)
|
|
|
|
|
Yowch! I had a feeling that calling methods would outweigh the switch, but that's surprising. Thanks.
Article?
|
|
|
|
|
You're welcome
But a whole article about this? I'd have to dig up the "real disassembly" (without debugger attached) to make it article-worthy..
|
|
|
|
|