connect to Bitcoin core from c# - c#

i download bitcoin core from here https://bitcoin.org/en/download and try to connect to it from c# i use the demo code from here https://github.com/cryptean/bitcoinlib i set bitcoin.conf
like this:
rpcport=8332
rpcuser=myuser
rpcpass=mypass
txindex=1
and here is app.config:
<!-- Bitcoin settings start -->
<add key="Bitcoin_DaemonUrl" value="http://127.0.0.1:8332" />
<add key="Bitcoin_DaemonUrl_Testnet" value="http://127.0.0.1:18332" />
<add key="Bitcoin_WalletPassword" value="" />
<add key="Bitcoin_RpcUsername" value="myuser" />
<add key="Bitcoin_RpcPassword" value="mypass" />
<!-- Bitcoin settings end -->
and when i run the demo , error happened , here is the error message :
Connecting to Bitcoin MainNet via RPC at http://127.0.0.1:8332...The RPC request was either not understood by the server or there was a problem executing the request
at BitcoinLib.RPC.Connector.RpcConnector.MakeRequest[T](RpcMethods rpcMethod, Object[] parameters) in C:\Users\pc\Downloads\bitcoinlib-master\bitcoinlib-master\src\BitcoinLib\RPC\Connector\RpcConnector.cs:line 125
at BitcoinLib.Services.CoinService.GetDifficulty() in C:\Users\pc\Downloads\bitcoinlib-master\bitcoinlib-master\src\BitcoinLib\Services\RpcServices\RpcService\RpcService.cs:line 225
at ConsoleClient.Program.Main() in C:\Users\pc\Downloads\bitcoinlib-master\bitcoinlib-master\demo\Program.cs:line 104
i am not use testnet here is the code:
private static void Main()
{
try
{
var data = RequestServer("getblockcount", new List<string>() { "value" });
Console.WriteLine(data);
return;
Console.Write("\n\nConnecting to {0} {1}Net via RPC at {2}...", CoinService.Parameters.CoinLongName, (CoinService.Parameters.UseTestnet ? "Test" : "Main"), CoinService.Parameters.SelectedDaemonUrl);
// Network difficulty
var networkDifficulty = CoinService.GetDifficulty();
// networkDifficulty.ToString();
Console.WriteLine("[OK]\n\n{0} Network Difficulty: {1}", CoinService.Parameters.CoinLongName, networkDifficulty.ToString("#,###", CultureInfo.InvariantCulture));
// Mining info
var miningInfo = CoinService.GetMiningInfo();
Console.WriteLine("[OK]\n\n{0} NetworkHashPS: {1}", CoinService.Parameters.CoinLongName, miningInfo.NetworkHashPS.ToString("#,###", CultureInfo.InvariantCulture));
// My balance
var myBalance = CoinService.GetBalance();
Console.WriteLine("\nMy balance: {0} {1}", myBalance, CoinService.Parameters.CoinShortName);
// Current block
Console.WriteLine("Current block: {0}",
CoinService.GetBlockCount().ToString("#,#", CultureInfo.InvariantCulture));
// Wallet state
Console.WriteLine("Wallet state: {0}", CoinService.IsWalletEncrypted() ? "Encrypted" : "Unencrypted");
// Keys and addresses
if (myBalance > 0)
{
// My non-empty addresses
Console.WriteLine("\n\nMy non-empty addresses:");
var myNonEmptyAddresses = CoinService.ListReceivedByAddress();
foreach (var address in myNonEmptyAddresses)
{
Console.WriteLine("\n--------------------------------------------------");
Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(address.Account) ? "(no label)" : address.Account));
Console.WriteLine("Address: " + address.Address);
Console.WriteLine("Amount: " + address.Amount);
Console.WriteLine("Confirmations: " + address.Confirmations);
Console.WriteLine("--------------------------------------------------");
}
// My private keys
if (bool.Parse(ConfigurationManager.AppSettings["ExtractMyPrivateKeys"]) && myNonEmptyAddresses.Count > 0 && CoinService.IsWalletEncrypted())
{
const short secondsToUnlockTheWallet = 30;
Console.Write("\nWill now unlock the wallet for " + secondsToUnlockTheWallet + ((secondsToUnlockTheWallet > 1) ? " seconds" : " second") + "...");
CoinService.WalletPassphrase(CoinService.Parameters.WalletPassword, secondsToUnlockTheWallet);
Console.WriteLine("[OK]\n\nMy private keys for non-empty addresses:\n");
foreach (var address in myNonEmptyAddresses)
{
Console.WriteLine("Private Key for address " + address.Address + ": " + CoinService.DumpPrivKey(address.Address));
}
Console.Write("\nLocking wallet...");
CoinService.WalletLock();
Console.WriteLine("[OK]");
}
// My transactions
Console.WriteLine("\n\nMy transactions: ");
var myTransactions = CoinService.ListTransactions(null, int.MaxValue, 0);
foreach (var transaction in myTransactions)
{
Console.WriteLine("\n---------------------------------------------------------------------------");
Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(transaction.Account) ? "(no label)" : transaction.Account));
Console.WriteLine("Address: " + transaction.Address);
Console.WriteLine("Category: " + transaction.Category);
Console.WriteLine("Amount: " + transaction.Amount);
Console.WriteLine("Fee: " + transaction.Fee);
Console.WriteLine("Confirmations: " + transaction.Confirmations);
Console.WriteLine("BlockHash: " + transaction.BlockHash);
Console.WriteLine("BlockIndex: " + transaction.BlockIndex);
Console.WriteLine("BlockTime: " + transaction.BlockTime + " - " + UnixTime.UnixTimeToDateTime(transaction.BlockTime));
Console.WriteLine("TxId: " + transaction.TxId);
Console.WriteLine("Time: " + transaction.Time + " - " + UnixTime.UnixTimeToDateTime(transaction.Time));
Console.WriteLine("TimeReceived: " + transaction.TimeReceived + " - " + UnixTime.UnixTimeToDateTime(transaction.TimeReceived));
if (!string.IsNullOrWhiteSpace(transaction.Comment))
{
Console.WriteLine("Comment: " + transaction.Comment);
}
if (!string.IsNullOrWhiteSpace(transaction.OtherAccount))
{
Console.WriteLine("Other Account: " + transaction.OtherAccount);
}
if (transaction.WalletConflicts != null && transaction.WalletConflicts.Any())
{
Console.Write("Conflicted Transactions: ");
foreach (var conflictedTxId in transaction.WalletConflicts)
{
Console.Write(conflictedTxId + " ");
}
Console.WriteLine();
}
Console.WriteLine("---------------------------------------------------------------------------");
}
// Transaction Details
Console.WriteLine("\n\nMy transactions' details:");
foreach (var transaction in myTransactions)
{
// Move transactions don't have a txId, which this logic fails for
if (transaction.Category == "move")
{
continue;
}
var localWalletTransaction = CoinService.GetTransaction(transaction.TxId);
IEnumerable<PropertyInfo> localWalletTrasactionProperties = localWalletTransaction.GetType().GetProperties();
IList<GetTransactionResponseDetails> localWalletTransactionDetailsList = localWalletTransaction.Details.ToList();
Console.WriteLine("\nTransaction\n-----------");
foreach (var propertyInfo in localWalletTrasactionProperties)
{
var propertyInfoName = propertyInfo.Name;
if (propertyInfoName != "Details" && propertyInfoName != "WalletConflicts")
{
Console.WriteLine(propertyInfoName + ": " + propertyInfo.GetValue(localWalletTransaction, null));
}
}
foreach (var details in localWalletTransactionDetailsList)
{
IEnumerable<PropertyInfo> detailsProperties = details.GetType().GetProperties();
Console.WriteLine("\nTransaction details " + (localWalletTransactionDetailsList.IndexOf(details) + 1) + " of total " + localWalletTransactionDetailsList.Count + "\n--------------------------------");
foreach (var propertyInfo in detailsProperties)
{
Console.WriteLine(propertyInfo.Name + ": " + propertyInfo.GetValue(details, null));
}
}
}
// Unspent transactions
Console.WriteLine("\nMy unspent transactions:");
var unspentList = CoinService.ListUnspent();
foreach (var unspentResponse in unspentList)
{
IEnumerable<PropertyInfo> detailsProperties = unspentResponse.GetType().GetProperties();
Console.WriteLine("\nUnspent transaction " + (unspentList.IndexOf(unspentResponse) + 1) + " of " + unspentList.Count + "\n--------------------------------");
foreach (var propertyInfo in detailsProperties)
{
Console.WriteLine(propertyInfo.Name + " : " + propertyInfo.GetValue(unspentResponse, null));
}
}
}
Console.ReadLine();
}
catch (RpcInternalServerErrorException exception)
{
var errorCode = 0;
var errorMessage = string.Empty;
if (exception.RpcErrorCode.GetHashCode() != 0)
{
errorCode = exception.RpcErrorCode.GetHashCode();
errorMessage = exception.RpcErrorCode.ToString();
}
Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty);
}
catch (Exception exception)
{
//Console.WriteLine("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception);
Console.WriteLine(exception.Message+"\n"+exception.StackTrace.ToString());
}
}
also i try this code:
public static string RequestServer(string methodName, List<string> parameters)
{
string ServerIp = "http://127.0.0.1:8332";
string UserName = "myuser";
string Password = "mypass";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ServerIp);
webRequest.Credentials = new NetworkCredential(UserName, Password);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
string respVal = string.Empty;
JObject joe = new JObject();
joe.Add(new JProperty("jsonrpc", "1.0"));
joe.Add(new JProperty("id", "1"));
joe.Add(new JProperty("method", methodName));
JArray props = new JArray();
foreach (var parameter in parameters)
{
props.Add(parameter);
}
joe.Add(new JProperty("params", props));
// serialize json for the request
string s = JsonConvert.SerializeObject(joe);
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
StreamReader streamReader = null;
try
{
WebResponse webResponse = webRequest.GetResponse();
streamReader = new StreamReader(webResponse.GetResponseStream(), true);
respVal = streamReader.ReadToEnd();
var data = JsonConvert.DeserializeObject(respVal).ToString();
return data;
}
catch (Exception exp)
{
Console.WriteLine(exp.Message + "\n" + exp.StackTrace.ToString());
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
}
return string.Empty;
}
var data = RequestServer("getblockcount", new List<string>() { "value" });
Console.WriteLine(data);
but error happened:
401 unauthorized ....
i run bitcoind from command:
bitcoind.exe -server
here is the output:
C:\Program Files\Bitcoin\daemon>bitcoind.exe -server
2023-01-01T19:01:43Z Ignoring unknown configuration value rpcpass
2023-01-01T19:01:43Z Bitcoin Core version v22.0.0 (release build)
2023-01-01T19:01:43Z Assuming ancestors of block 00000000000000000008a89e854d57e5667df88f1cdef6fde2fbca1de5b639ad have valid signatures.
2023-01-01T19:01:43Z Setting nMinimumChainWork=00000000000000000000000000000000000000001fa4663bbbe19f82de910280
2023-01-01T19:01:43Z Using the 'shani(1way,2way)' SHA256 implementation
2023-01-01T19:01:43Z Using RdSeed as additional entropy source
2023-01-01T19:01:43Z Using RdRand as an additional entropy source
2023-01-01T19:01:43Z Default data directory C:\Users\pc\AppData\Roaming\Bitcoin
2023-01-01T19:01:43Z Using data directory C:\Users\pc\AppData\Roaming\Bitcoin
2023-01-01T19:01:43Z Config file: C:\Users\pc\AppData\Roaming\Bitcoin\bitcoin.conf
2023-01-01T19:01:43Z Config file arg: rpcport="8332"
2023-01-01T19:01:43Z Config file arg: rpcuser=****
2023-01-01T19:01:43Z Config file arg: server="1"
2023-01-01T19:01:43Z Config file arg: txindex="1"
2023-01-01T19:01:43Z Setting file arg: wallet = ["btc1313"]
2023-01-01T19:01:43Z Command-line arg: server=""
2023-01-01T19:01:43Z Using at most 125 automatic connections (2048 file descriptors available)
2023-01-01T19:01:43Z Using 16 MiB out of 32/2 requested for signature cache, able to store 524288 elements
2023-01-01T19:01:43Z Using 16 MiB out of 32/2 requested for script execution cache, able to store 524288 elements
2023-01-01T19:01:43Z Script verification uses 7 additional threads
2023-01-01T19:01:43Z scheduler thread start
2023-01-01T19:01:43Z HTTP: creating work queue of depth 16
2023-01-01T19:01:43Z Using random cookie authentication.
2023-01-01T19:01:43Z Generated RPC authentication cookie C:\Users\pc\AppData\Roaming\Bitcoin\.cookie
2023-01-01T19:01:43Z HTTP: starting 4 worker threads
2023-01-01T19:01:43Z Using wallet directory C:\Users\pc\AppData\Roaming\Bitcoin\wallets
2023-01-01T19:01:43Z init message: Verifying wallet(s)…
2023-01-01T19:01:43Z Using BerkeleyDB version Berkeley DB 4.8.30: (April 9, 2010)
2023-01-01T19:01:43Z Using wallet C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\wallet.dat
2023-01-01T19:01:43Z BerkeleyEnvironment::Open: LogDir=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\database ErrorFile=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\db.log
2023-01-01T19:01:43Z init message: Loading banlist…
2023-01-01T19:01:43Z SetNetworkActive: true
2023-01-01T19:01:43Z Using /16 prefix for IP bucketing
2023-01-01T19:01:43Z Cache configuration:
2023-01-01T19:01:43Z * Using 2.0 MiB for block index database
2023-01-01T19:01:43Z * Using 56.0 MiB for transaction index database
2023-01-01T19:01:43Z * Using 8.0 MiB for chain state database
2023-01-01T19:01:43Z * Using 384.0 MiB for in-memory UTXO set (plus up to 286.1 MiB of unused mempool space)
2023-01-01T19:01:43Z init message: Loading block index…
2023-01-01T19:01:43Z Switching active chainstate to Chainstate [ibd] # height -1 (null)
2023-01-01T19:01:43Z Opening LevelDB in C:\Users\pc\AppData\Roaming\Bitcoin\blocks\index
2023-01-01T19:01:43Z Opened LevelDB successfully
2023-01-01T19:01:43Z Using obfuscation key for C:\Users\pc\AppData\Roaming\Bitcoin\blocks\index: 0000000000000000
2023-01-01T19:01:48Z LoadBlockIndexDB: last block file = 3337
2023-01-01T19:01:48Z LoadBlockIndexDB: last block file info: CBlockFileInfo(blocks=82, size=82069535, heights=769632...769908, time=2022-12-31...2023-01-01)
2023-01-01T19:01:48Z Checking all blk files are present...
2023-01-01T19:01:49Z Opening LevelDB in C:\Users\pc\AppData\Roaming\Bitcoin\chainstate
2023-01-01T19:01:49Z Opened LevelDB successfully
2023-01-01T19:01:49Z Using obfuscation key for C:\Users\pc\AppData\Roaming\Bitcoin\chainstate: 6343dde5e7e6e386
2023-01-01T19:01:49Z Loaded best chain: hashBestChain=000000000000000000039b1c6364ff45a20a879f9a834fe4ed5292cf63cf942a height=769908 date=2023-01-01T18:50:35Z progress=0.999998
2023-01-01T19:01:49Z init message: Verifying blocks…
2023-01-01T19:01:49Z Verifying last 6 blocks at level 3
2023-01-01T19:01:49Z [0%]...[16%]...[33%]...[50%]...[66%]...[83%]...[99%]...[DONE].
2023-01-01T19:01:56Z No coin database inconsistencies in last 6 blocks (9918 transactions)
2023-01-01T19:01:56Z block index 12583ms
2023-01-01T19:01:56Z Opening LevelDB in C:\Users\pc\AppData\Roaming\Bitcoin\indexes\txindex
2023-01-01T19:01:56Z Opened LevelDB successfully
2023-01-01T19:01:56Z Using obfuscation key for C:\Users\pc\AppData\Roaming\Bitcoin\indexes\txindex: 0000000000000000
2023-01-01T19:01:56Z txindex thread start
2023-01-01T19:01:56Z init message: Loading wallet…
2023-01-01T19:01:56Z txindex is enabled at height 769908
2023-01-01T19:01:56Z txindex thread exit
2023-01-01T19:01:56Z BerkeleyEnvironment::Open: LogDir=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\database ErrorFile=C:\Users\pc\AppData\Roaming\Bitcoin\wallets\btc1313\db.log
2023-01-01T19:01:56Z [btc1313] Wallet File Version = 169900
2023-01-01T19:01:56Z [btc1313] Keys: 2001 plaintext, 0 encrypted, 2001 w/ metadata, 2001 total. Unknown wallet records: 0
2023-01-01T19:01:56Z [btc1313] Wallet completed loading in 53ms
2023-01-01T19:01:56Z [btc1313] setKeyPool.size() = 2000
2023-01-01T19:01:56Z [btc1313] mapWallet.size() = 0
2023-01-01T19:01:56Z [btc1313] m_address_book.size() = 0
2023-01-01T19:01:56Z block tree size = 769909
2023-01-01T19:01:56Z nBestHeight = 769908
2023-01-01T19:01:56Z loadblk thread start
2023-01-01T19:01:56Z torcontrol thread start
2023-01-01T19:01:56Z Bound to 127.0.0.1:8334
2023-01-01T19:01:56Z Bound to [::]:8333
2023-01-01T19:01:56Z Bound to 0.0.0.0:8333
2023-01-01T19:01:56Z Leaving InitialBlockDownload (latching to false)
2023-01-01T19:01:56Z init message: Loading P2P addresses…
2023-01-01T19:01:56Z Loaded 63213 addresses from peers.dat 116ms
2023-01-01T19:01:56Z Loaded 2 addresses from "anchors.dat"
2023-01-01T19:01:56Z 2 block-relay-only anchors will be tried for connections.
2023-01-01T19:01:56Z init message: Starting network threads…
2023-01-01T19:01:56Z opencon thread start
2023-01-01T19:01:56Z addcon thread start
2023-01-01T19:01:56Z dnsseed thread start
2023-01-01T19:01:56Z Waiting 300 seconds before querying DNS seeds.
2023-01-01T19:01:56Z msghand thread start
2023-01-01T19:01:56Z init message: Done loading
2023-01-01T19:01:56Z net thread start
2023-01-01T19:01:57Z Imported mempool transactions from disk: 695 succeeded, 0 failed, 0 expired, 0 already there, 0 waiting for initial broadcast
2023-01-01T19:01:57Z loadblk thread exit
2023-01-01T19:01:57Z New outbound peer connected: version: 70016, blocks=769909, peer=0 (block-relay-only)
2023-01-01T19:01:58Z New outbound peer connected: version: 70015, blocks=769909, peer=1 (block-relay-only)
2023-01-01T19:01:59Z New outbound peer connected: version: 70016, blocks=769909, peer=2 (outbound-full-relay)
2023-01-01T19:02:04Z UpdateTip: new best=00000000000000000006266ea0383ab08afa37496e4b35ae218e1b03e26b607e height=769909 version=0x32bce000 log2_work=93.924929 tx=792623260 date='2023-01-01T19:00:40Z' progress=1.000000 cache=1.3MiB(9604txo)
2023-01-01T19:02:16Z New outbound peer connected: version: 70016, blocks=769909, peer=3 (outbound-full-relay)
2023-01-01T19:02:16Z New outbound peer connected: version: 70016, blocks=769909, peer=4 (outbound-full-relay)
2023-01-01T19:02:18Z P2P peers available. Skipped DNS seeding.
2023-01-01T19:02:18Z dnsseed thread exit
2023-01-01T19:02:23Z New outbound peer connected: version: 70016, blocks=769909, peer=5 (outbound-full-relay)
2023-01-01T19:02:35Z New outbound peer connected: version: 70016, blocks=769909, peer=6 (outbound-full-relay)
2023-01-01T19:08:44Z ThreadRPCServer incorrect password attempt from 127.0.0.1:49244
2023-01-01T19:08:44Z ThreadRPCServer incorrect password attempt from 127.0.0.1:49208
2023-01-01T19:08:44Z New outbound peer connected: version: 70015, blocks=769909, peer=39 (outbound-full-relay)
2023-01-01T19:08:44Z New outbound peer connected: version: 70016, blocks=769909, peer=41 (outbound-full-relay)
2023-01-01T19:08:44Z New outbound peer connected: version: 70015, blocks=769909, peer=43 (outbound-full-relay)
also i read about this libarary NBitcoin but i cannot find simple exmple to use it,
my questions, what are the steps to connect bitcoin core from c#, what is best libarary to use it? how to fix these erros i mention above? is there a simple example of using NBitcoin? Thanks.

a little error ,the word in bitcoin.conf:
rpcpass=mypass
is wrong must be :
rpcpassword=mypass
i change it and it worked fine

Related

C# monitor SNMP timeticks from multiple IP addresses

I'm attempting to monitor multiple SNMP agents (timeticks) with SnmpSharpNet across separate networks. The code below works with a single IP address, but when I try and connect to a second IP address the code fails, I'm trying to run this asynchronously but it appears that SnmpSharpNet won't allow me to receive data from more than one agent.
Is this the right way to approach this problem? Is there a better alternative to SmnpSharpNet?
community = new OctetString("public");
// Define agent parameters class
param = new AgentParameters(community);
// Set SNMP version to 1 (or 2)
param.Version = SnmpVersion.Ver1;
for (int i = 0; i < sendsqldatalist.Count(); i++)
{
agent = new IpAddress(sendsqldatalist[i].ip);
target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
// Make SNMP request
resultlist.Add(result = (SnmpV1Packet)target.Request(pdu, param));
// If result is null then agent didn't reply or we couldn't parse the reply.r
if (resultlist[i] != null)
{
// ErrorStatus other then 0 is an error returned by
// the Agent - see SnmpConstants for error definitions
if (resultlist[i].Pdu.ErrorStatus != 0)
{
Console.WriteLine("error on - " + sendsqldatalist[i].oid + " " + sendsqldatalist[i].ip);
// agent reported an error with the request
//- Error status found here http://www.docs.snmpsharpnet.com/docs-0-9-1/
MessageBox.Show("Error in SNMP reply from " + target.Address.ToString() + Environment.NewLine + "Error status " + result.Pdu.ErrorStatus.GetType() + Environment.NewLine + "Error Index " + result.Pdu.ErrorIndex.ToString(), "WARNING!");
}
else
{
Console.WriteLine("ConnectSNMP() CONNECTED - " + sendsqldatalist[i].oid + " - " + sendsqldatalist[i].ip);
}
}
}
Thanks in advance!

How to stop a process from System.Diagnostics.Process and get the statistics in the end

I'm using this code but when i stop the process it not get the ping statistics :
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "ping";
p.StartInfo.Arguments = "-c " + count + " -i " + interval + " -s " + buffer + " -W " + timeout + " " + address;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
string readData = "";
DateTime dt = DateTime.Now.AddSeconds(5);
if (p.Start())
{
Scanner scanner = new Scanner(p.StandardOutput.BaseStream);
while (scanner.HasNextLine)
{
readData = scanner.NextLine().ToString();
Console.WriteLine(readData.ToString());
if (!string.IsNullOrEmpty(readData) && !readData.StartsWith("---"))
{
Match M = Regex.Match(readData, #"^[\d]+ bytes from ([^:]+): [^ ]+ ttl=([\d]+) time=([^ ]+) ms");
if (M != null && M.Success)
{
string IP = M.Groups[1].Value;
string TTL = M.Groups[2].Value;
string timeStr = M.Groups[3].Value;
Console.WriteLine(String.Format("Ping to {0} took {2} ms with a ttl of {1}", IP, TTL, timeStr));
// Parsing the timeStr will work the same way as above
if(dt > DateTime.Now)
{
p.StandartInput.Write("\x3");
}
}
else
{
Match M1 = Regex.Match(readData, #"^rtt [^0-9]*([\d][^\/]+)\/([^\/]+)\/([^\/]+)\/([^ ]+) ms$");
if (M1 != null && M1.Success)
{
float avgPingTime = 0;
float maxPingTime = 0;
float minPingTime = 0;
string minPingString = M1.Groups[1].Value;
string avgPingString = M1.Groups[2].Value;
string maxPingString = M1.Groups[3].Value;
// Now parse that value
float.TryParse(minPingString, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out minPingTime);
float.TryParse(avgPingString, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out avgPingTime);
float.TryParse(maxPingString, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out maxPingTime);
Console.WriteLine(String.Format("Min Time : {0} , AVG {2} ms, Max Time {1}", minPingTime, maxPingTime, avgPingTime));
}
}
}
}
}
Without using
if(dt > DateTime.Now)
{
p.StandartInput.Write("\x3");
}
the result display like this :
64 bytes from 8.8.8.8: icmp_req=1 ttl=46 time=13.9 ms
64 bytes from 8.8.8.8: icmp_req=2 ttl=46 time=13.9 ms
64 bytes from 8.8.8.8: icmp_req=3 ttl=46 time=13.9 ms
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 3016ms
rtt min/avg/max/mdev = 13.910/13.926/13.951/0.010 ms
but if I stop the ping using p.StandartInput.Write("\x3"); it never goes to the statistics part it hangs at sequence 1 : 64 bytes from 8.8.8.8: icmp_req=1 ttl=46 time=13.9 ms and dont continue reading , how to show the statistics after stoping the ping process ?
in other words my problem is when the user want to stop the ping it should display the statistics for the certain time that it was used to ping...
UPDATE
I have implemented p.StandartInput.Write("/x3"); and it interrupts the ping process but it does not display the statistics and just hangs there.
If you are actually interested in the ping values, why not just use the ping class? https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping(v=vs.110).aspx

.Net.Mail body message lose the format while is sent c# .net

I'm using a string builder to create a body message while trying to do something.
the issue es I'm getting the value from the string builder and this one is formatted.
Example from my string builder:
Following files were attached by email:
1. C:\SALASFRI2_20150824094158_ScrubLog.txt - Record Count: 8
2. C:\SALASFRI2_20150824102328_ScrubLog.txt - Record Count: 8
3. C:\SALASFRI2_20150824102516_ScrubLog.txt - Record Count: 8
4. C:\SALASFRI2_20160121125353_ScrubLog.txt - Record Count: 8
5. C:\SALASFRI2_20160121125659_ScrubLog.txt - Record Count: 8
===================================================
Total Files: 5
Please contact your system administrator for any further assitance.
That's exactly how the stringbuilder looks, but when the email arrived, it lose their format as follow:
do you know if there is a property to don't lose the format when it arrive to my email?
This is my code:
if (Notification.IncludeFileName || Notification.IncludeRecordCount)
{
BodyMessage.Append("Following files were attached by email: \n");
for (int index = 0; index < NumberOfFiles; index++)
{
if (Notification.IncludeFileName && Notification.IncludeRecordCount)
BodyMessage.Append((index + 1) + ". " + LocalFiles[index] + " - Record Count: " + File.ReadLines(LocalFiles[index]).Count() + "\n");
else
BodyMessage.Append((index + 1) + ". " + LocalFiles[index] + File.ReadLines(LocalFiles[index]).Count() + "\n");
}
}
if (Notification.IncludeNumberOfFiles)
{
BodyMessage.Append("\n===================================================\n\n");
BodyMessage.Append("Total Files: " + NumberOfFiles + "\n");
}
BodyMessage.Append("\nPlease contact your system administrator for any further assitance.");
////////////////////END OF SUBJECT AND BODY MAIL MESSAGE VALIDATION
////////............SEND THE ATTACHMENTS THROUGH EMAIL................///////////
try
{
MailMessage Email = new MailMessage();
SmtpClient smtp = new SmtpClient(AppConfiguration.SMTPServer);
Email.From = new MailAddress(AppConfiguration.EmailAddress);
Email.To.Add(protocol.SMTPEmailList);
Email.Subject = EmailSubject;
Email.Body = BodyMessage.ToString();
if (directories.Zip)
Email.Attachments.Add(new Attachment(ZipName));
else
foreach (var attachment in LocalFiles)
{
Email.Attachments.Add(new Attachment(attachment));
}
smtp.Port = AppConfiguration.SmtpPort;
smtp.UseDefaultCredentials = true;
smtp.Send(Email);
Email.Dispose();
You probably need to use "\r\n" as your newline sequence instead of just "\n".

Task.StartNew() called multiple times only returning once

I have used the following code:
var tuple = Tuple.Create("xxx.xx.xx.xxx", 6102, "109", "Metrix1", 1);
var tuple1 = Tuple.Create("xxx.xx.xx.xxx", 6102, "110", "Metrix2", 1);
var tuple2 = Tuple.Create("xxx.xx.xx.xxx", 6102, "111", "Metrix3", 1);
var tuple3 = Tuple.Create("xxx.xx.xx.xxx", 6103, "106", "Metrix4", 2);
gateways.Add(tuple);
gateways.Add(tuple1);
gateways.Add(tuple2);
gateways.Add(tuple3);
foreach (var gatewayId in gateways)
{
Task.Factory.StartNew(
() => GetJobs(
gatewayId.Item1,
gatewayId.Item2,
gatewayId.Item3,
gatewayId.Item4,
gatewayId.Item5));
}
This then calls GetJobs which calls CallGateway and if required ProcessMessageNew
private string GetJobs(string Url , int portNumber, string Engineer , string mEngineer , int GatewayId)
{
ConfigLogger.Instance.LogInfo("info", "Calling Gateway Start: " + DateTime.Now.ToString("HH:mm:ss.ffff") + " for engineer: " + Engineer);
string gatewayResult = CallGateway(Engineer, Url, portNumber);
ConfigLogger.Instance.LogInfo("info", "Calling Gateway End: " + DateTime.Now.ToString("HH:mm:ss.ffff") + " for engineer: " + Engineer);
if (gatewayResult != null)
{
ConfigLogger.Instance.LogInfo("info", "Processing Request Message: " + DateTime.Now.ToString("HH:mm:ss.ffff") + " for engineer: " + Engineer);
ProcessMessageNew(gatewayResult, Engineer, Url, portNumber , MEngineer ,PGatewayId);
}
return gatewayResult;
}
CallGateway:
public string CallGateway(string gatewayUrl, int portNumber , string engineer)
{
string result = null;
int streamBufferSize = 1000;
IPHostEntry ipHostInfo = Dns.Resolve(gatewayUrl.ToString());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, portNumber);
// Create a TCP/IP socket.
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(ipAddress, portNumber);
// Set these on app param
clientSocket.ReceiveTimeout = 300000;
clientSocket.SendTimeout = 60000;
// build message string to send to gateway
string message = BuildMessageGetJobsFromGateway(engineer, SendTypeIn);
// Create a NetworkStream that owns clientSocket and
// then create a BufferedStream on top of the NetworkStream.
// Both streams are disposed when execution exits the
// using statement.
using (var netStream = new NetworkStream(clientSocket, true),
var bufStream = new BufferedStream(netStream, streamBufferSize))
{
// Check whether the underlying stream supports seeking.
Console.WriteLine("NetworkStream {0} seeking.\n", bufStream.CanSeek ? "supports" : "does not support");
//variable used to only close once
bool doClose = true;
// Send and receive data.
if (bufStream.CanWrite)
{
try
{
SendData(netStream, bufStream, SendTypeIn, message);
}
catch (Exception exSend)
{
Console.WriteLine(exSend.Message.ToString());
}
}
if (bufStream.CanRead)
{
try
{
result = ReceiveData(netStream, bufStream, clientSocket);
}
catch (Exception exRecieve)
{
//
}
finally
{
Console.WriteLine("Closing Stream");
doClose = false;
bufStream.Close();
clientSocket.Close();
}
}
// When bufStream is closed, netStream is in turn
// closed, which in turn shuts down the connection
// and closes clientSocket.
Console.WriteLine("\nShutting down the connection.");
// only close if no exception is raised
if (doClose)
{
bufStream.Close();
clientSocket.Close();
}
}
return result;
}
}
However, I get this in the log file 4 calls to the call gateway method and only one return for engineer 106, the call to gateway creates a Socket Client which then receive data but it is only happening for one out of the 4 calls :
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:19] - Calling Gateway Start: 16:47:19.6574 for engineer: 109
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:19] - Processing Call Mobile Gateway: 16:47:19.6624
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:20] - Calling Gateway Start: 16:47:20.6685 for engineer: 110
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:20] - Processing Call Mobile Gateway: 16:47:20.6875
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:21] - Calling Gateway Start: 16:47:21.6696 for engineer: 111
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:21] - Processing Call Mobile Gateway: 16:47:21.6716
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:22] - Calling Gateway Start: 16:47:22.6686 for engineer: 106
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:22] - Processing Call Mobile Gateway: 16:47:22.6706
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:23] - Processing Call Mobile Ended: 16:47:23.0476
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:23] - Calling Gateway End: 16:47:23.0486 for engineer: 106
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:23] - Processing Request Message: 16:47:23.0486 for engineer: 106
[MobileGateway.exe] - [Info] - [25/09/2015 16:47:23] - Message Recieved From Gateway: 16:47:23.0496
The calls should be processed in Parallel or Asyncronously as there is a requirement to call this method simultaneously over 1000 times and they are long running processes so I need to process multiple at a time.
Any ideas why I am getting 1 response instead of 4 ?
Since you have xxxed the addresses in your code, I can't say assuredly but it is probably happening because you have the same port number 6102 for the previous three gateways. So you are closing and opening stream for same address three times in parallel and that is throwing exceptions only to be caught silently later.
Further, you can improve readability and maintainability of your code by passing the gateway objects in single piece like following:
foreach (var gatewayId in gateways)
{
Task.Factory.StartNew(() => GetJobs(gatewayId));
}
and modify your GetJobs method too as:
private string GetJobs(Gateway gateway)
{
ConfigLogger.Instance.LogInfo("info", "Calling Gateway Start: " + DateTime.Now.ToString("HH:mm:ss.ffff") + " for engineer: " + gateway.Engineer);
string gatewayResult = CallGateway(gateway);
ConfigLogger.Instance.LogInfo("info", "Calling Gateway End: " + DateTime.Now.ToString("HH:mm:ss.ffff") + " for engineer: " + gateway.Engineer);
if (gatewayResult != null)
{
ConfigLogger.Instance.LogInfo("info", "Processing Request Message: " + DateTime.Now.ToString("HH:mm:ss.ffff") + " for engineer: " + gateway.Engineer);
ProcessMessageNew(gatewayResult, gateway);
}
return gatewayResult;
}
Also, going down further, change your ProcessMessageNew and CallGateway too, to match with the new definition in the code above.

SEO: A whois server that work for .SE domains?

I'm developing a small domain checker and I can't get .SE to work:
public string Lookup(string domain, RecordType recordType, SeoToolsSettings.Tld tld)
{
TcpClient tcp = new TcpClient();
tcp.Connect(tld.WhoIsServer, 43);
string strDomain = recordType.ToString() + " " + domain + "\r\n";
byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
Stream s = tcp.GetStream();
s.Write(bytDomain, 0, strDomain.Length);
StreamReader sr = new StreamReader(tcp.GetStream(), Encoding.ASCII);
string strLine = "";
StringBuilder builder = new StringBuilder();
while (null != (strLine = sr.ReadLine()))
{
builder.AppendLine(strLine);
}
tcp.Close();
if (tld.WhoIsDelayMs > 0) System.Threading.Thread.Sleep(tld.WhoIsDelayMs);
return builder.ToString();
}
I've tried whois servers whois.nic-se.se and whois.iis.se put I keep getting:
# Copyright (c) 1997- .SE (The Internet Infrastructure Foundation).
# All rights reserved.
# The information obtained through searches, or otherwise, is protected
# by the Swedish Copyright Act (1960:729) and international conventions.
# It is also subject to database protection according to the Swedish
# Copyright Act.
# Any use of this material to target advertising or
# similar activities is forbidden and will be prosecuted.
# If any of the information below is transferred to a third
# party, it must be done in its entirety. This server must
# not be used as a backend for a search engine.
# Result of search for registered domain names under
# the .SE top level domain.
# The data is in the UTF-8 character set and the result is
# printed with eight bits.
"domain google.se" not found.
Edit:
I've tried changing to UTF8 with no other result.
When I try using whois from sysinternals I get the correct result, but not with my code, not even using SE.whois-servers.net.
/Niels
Hmmm, when doing a whois google.se on my Mac I get the following:
# Copyright (c) 1997- .SE (The Internet Infrastructure Foundation).
# All rights reserved.
# The information obtained through searches, or otherwise, is protected
# by the Swedish Copyright Act (1960:729) and international conventions.
# It is also subject to database protection according to the Swedish
# Copyright Act.
# Any use of this material to target advertising or
# similar activities is forbidden and will be prosecuted.
# If any of the information below is transferred to a third
# party, it must be done in its entirety. This server must
# not be used as a backend for a search engine.
# Result of search for registered domain names under
# the .SE top level domain.
# The data is in the UTF-8 character set and the result is
# printed with eight bits.
state: active
domain: google.se
holder: googoo5855-00001
admin-c: -
tech-c: -
billing-c: -
created: 2008-10-20
modified: 2010-09-18
expires: 2011-10-20
transferred: 2009-03-06
nserver: ns1.google.com
nserver: ns2.google.com
nserver: ns3.google.com
nserver: ns4.google.com
dnssec: unsigned delegation
status: ok
registrar: MarkMonitor Inc
So it's probably just your code. Maybe you have to do the request in a non-ASCII encoding, such as UTF8?
I finally solved it.
Using wireshark, I saw that the whois from sysinternals doesn't add the "DOMAIN" part:
string strDomain = recordType.ToString() + " " + domain + "\r\n";
(recordType.ToString == "DOMAIN").
So when I removed that, it worked!
without looking to your code why not:
example # http://balexandre.com/verifyDomain.aspx
this will give you, for par.se
IP Found:
- 193.13.249.142
Host name:
- parweb1.par.se
Aliases:
none
IP address list:
- 193.13.249.142
If you just want the RIPE information of an IP, you can also use my page for test
http://balexandre.com/iplookup.aspx?ip={ip to test}
Button event
protected void btnCheck_Click(object sender, EventArgs e)
{
DomainCheck domain = new DomainCheck();
string ip = domain.GetIPFromDomain(txtDomain.Text.Trim());
litResponse.Text = String.Format(
"IP{0} Found:<br/> - <strong>{1}</strong><br/>{2}",
ip.Contains(",") ? "'s" : "",
ip.Replace(",", "<br/> - "), domain.VerifyIP(ip));
}
DomainCheck code:
public class DomainCheck
{
public DomainCheck() { }
public string VerifyIP(string ipAddress)
{
if (String.IsNullOrEmpty(ipAddress))
return "IP Address is invalid!";
string r = "";
if (ipAddress.Contains(","))
{
foreach (string ip in ipAddress.Split(','))
r += String.Format("<br/><br/>#### <em>Checking {0}</em>{1}", ip, CheckIPAddress(ip));
}
else
r += CheckIPAddress(ipAddress);
return r;
}
public string GetIPFromDomain(string hostname)
{
string r = "";
IPAddress[] addresslist = Dns.GetHostAddresses(hostname);
foreach (IPAddress theaddress in addresslist)
{
r += String.Format("{0},", theaddress.ToString());
}
return String.IsNullOrEmpty(r) ? null : r.TrimEnd(',');
}
private string CheckIPAddress(string ipAddress)
{
string r = "";
try
{
IPAddress hostIPAddress = IPAddress.Parse(ipAddress);
IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
// Get the IP address list that resolves to the host names contained in
// the Alias property.
IPAddress[] address = hostInfo.AddressList;
// Get the alias names of the addresses in the IP address list.
String[] alias = hostInfo.Aliases;
r += String.Format(
"<br/>Host name: <br/>- <strong>{0}</strong><br/>Aliases: ",
hostInfo.HostName);
if (alias.Length == 0)
r += "<br/><em>none</em>";
else
for (int index = 0; index < alias.Length; index++)
r += String.Format("<br/>- <strong>{0}</strong>", alias[index]);
r += "<br/>IP address list: ";
if (address.Length == 0)
r += "<br/><em>none</em>";
else
for (int index = 0; index < address.Length; index++)
r += String.Format("<br/>- <strong>{0}</strong>", address[index]);
}
catch (SocketException e)
{
r = String.Format(
"SocketException caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
catch (FormatException e)
{
r = String.Format(
"FormatException caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
catch (ArgumentNullException e)
{
r = String.Format(
"ArgumentNullException caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
catch (Exception e)
{
r = String.Format(
"Exception caught!!!<br/>Source : {0}<br/>Message : {1}",
e.Source, e.Message);
}
return r;
}
}

Categories