|
Here's an example that is a little simpler and gives you what you want ("packet loss").
Note that it does not use the C# Ping class; instead it runs the Ping "command line utility" and captures and parses the output from this utility.
using System;
using System.Diagnostics;
namespace ConsoleApplication14 {
class Program {
static void Main( string[] args ) {
Process process = new Process();
process.StartInfo.FileName = @"Ping";
process.StartInfo.Arguments = @"www.msn.com";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
int start = output.IndexOf( "Lost =" );
int end = output.IndexOf( ',', start );
Console.WriteLine( output.Substring( start, end - start ) );
Console.ReadKey( true );
}
}
}
|
|
|
|
|
hello,
Please help me...
How to import excel sheet data into postgresql database table in C# windows application.
Thanks for advance..
|
|
|
|
|
|
Lots of ways. Where are you stuck?
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
Please update your question with what you have done so far and where you are stuck.
In case of complex problems, make sure to divide your problem in smaller problems.
1. Read in an excel file. This is your first. You can use the excel binaries and reference them in your C# application. From there you can use several functions to open a document and read it in. If it's a csv file you can just use a StreamReader class as csv is not an excel file, but an ASCII file (that excel just happens to understand, more or less) Google : "C# read excel file" and I'm sure you get sample code thrown at you in the results.
2. When you are able to open and read a file make sure to create objects able to hold the records. This object should also check the input for validity and quality, not allowing to add the record if wrong or at least log it somewhere/somehow
3. Now that you have a list of your objects and a database to hold the data you need to create a postgresql connection and write the data to the database (again samples can be found on google). If it is a lot of data you can generate insert queries in a loop eg. To improve performance concatenate the insert queries and only execute by the 100 eg. (make sure to finish the query with ";") Something like this:
StringBuilder builder = new StringBuilder("");
for(int i = 0; i < myrecordobject.Count; i++){
builder.append("Insert into ...");
builder.append(";");
if(i % 100 == 0){
builder = new StringBuilder("");
}
}
4. make sure when writing to the database you also log errors. It is not that data passed the quality test in the object, it also passes the quality check of the database (assuming there are quality checks)
If you do not need to use a C# application perse, maybe have a look if postgresql doesn't allow import from excel.
hope this sets you more or less on your way.
|
|
|
|
|
i want converted version of .Net scheduled Timer in vb.net i can't understand the c# one...
|
|
|
|
|
What Timer are you talking about?
|
|
|
|
|
|
C# and VB.Net are quite similar so I would suggest posting a specific line of C# code and asking about it.
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
I am developing a FTPS component in my ASP.Net application.
We configued the Personal Certificate,Intermediate Certificate and Root Certificate in Server and Client machine MMC console.
I am stuck in to implement the same as I am getting below error:
--------------------------------------------------------
.
.
.
System.Net Information: 0 : [6876] SecureChannel#65124268 - Certificate is of type X509Certificate2 and contains the private key.
System.Net Information: 0 : [6876] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent = Outbound, scc = System.Net.SecureCredential)
System.Net Error: 0 : [6876] AcquireCredentialsHandle() failed with error 0X8009030D.
System.Net Information: 0 : [6876] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent = Outbound, scc = System.Net.SecureCredential)
System.Net Error: 0 : [6876] AcquireCredentialsHandle() failed with error 0X8009030D.
System.Net.Sockets Verbose: 0 : [6876] Socket#19949373::Dispose()
System.Net Information: 0 : [6876] FtpWebRequest#64456428::(Releasing FTP connection#53218812.)
System.Net Error: 0 : [6876] Exception in FtpWebRequest#64456428::GetRequestStream - The remote server returned an error: 234 SecurFTP: SSL starting
..
at System.Net.FtpWebRequest.CheckError()
at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
at System.IO.Stream.Close()
at System.Net.ConnectionPool.Destroy(PooledStream pooledStream)
at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse)
at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetRequestStream()
System.Net Verbose: 0 : [6876] Exiting FtpWebRequest#64456428::GetRequestStream()
System.Net Information: 0 : [1320] ServicePoint#797974 - Closed as idle.
--------------------------------------------------------
Please help me to solve this issue as it is urgent.
Below is my sample code:
---------------------------------------------------------
public bool FileTransferStatus(FileInfo oFile, string localCertificateNames, bool isFileType, out string statusMessage)
{
FtpWebRequest ftpRequest;
FtpWebResponse ftpResponse;
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(FTPSite + CurrentDirectory + oFile.Name);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.Credentials = new NetworkCredential(UserName, Password);
ftpRequest.KeepAlive = KeepAlive;
ftpRequest.EnableSsl = UseSSL;
ftpRequest.UsePassive = true;
if (UseSSL)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
List<string> listLocalCertificates = localCertificateNames.Split(',').ToList<string>();
if (isFileType)
{
foreach (string localCertificate in listLocalCertificates)
{
string currentCertificate = localCertificate.Replace("\n", "").Replace("\t", "").Replace("\r", "");
X509Certificate certificate = X509Certificate.CreateFromCertFile(System.AppDomain.CurrentDomain.BaseDirectory + currentCertificate.Trim());
ftpRequest.ClientCertificates.Add(certificate);
}
}
else
{
X509Store storeRoot = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
storeRoot.Open(OpenFlags.ReadOnly);
X509Store storePersonal = new X509Store(StoreName.My, StoreLocation.LocalMachine);
storePersonal.Open(OpenFlags.ReadOnly);
List<string> listSerialNumbers = localCertificateNames.Split(',').ToList<string>();
foreach (string sn in listSerialNumbers)
{
string serialNumber = sn.Trim().ToUpper();
X509CertificateCollection certificates = storeRoot.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, false);
if (certificates.Count == 0)
{
certificates = storePersonal.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, true);
}
if (certificates.Count == 0)
{
throw new Exception(string.Format("Certificate {0} not found", serialNumber));
}
storeRoot.Close();
storePersonal.Close();
X509Certificate certificate = certificates[0];
ftpRequest.ClientCertificates.Add(certificate);
}
}
}
byte[] fileContents = new byte[oFile.Length];
using (FileStream fr = oFile.OpenRead())
{
fr.Read(fileContents, 0, Convert.ToInt32(oFile.Length));
}
using (Stream writer = ftpRequest.GetRequestStream())
{
writer.Write(fileContents, 0, fileContents.Length);
}
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
ftpRequest = null;
statusMessage = "Uploaded successfully";
return true;
}
catch (Exception webex)
{
statusMessage = webex.Message;
return false;
}
}
---------------------------------------------------------
Friendly,
Satheesh
|
|
|
|
|
|
Hello,
I am currently developing a Quiz that has to send the result of each participant to me via a TCP-connection. On the server computer (with the "master" application) the results get evaluated. It is of vital importance that the results are transmitted rapidly (that's why TCP rather than uploading result or such).
The connectin itself works, I just struggle with the StreamReader (and StreamWriter). This is my code as of now:
Client-Sending:
private void onButtonClick() {
TcpClient client;
client = new TcpClient("127.0.0.1", 25543);
StreamWriter writer = new StreamWriter(client.GetStream());
writer.Write("Test");
writer.Flush();
}
Server-Receiving (runs in Timer):
TcpClient client = new TcpClient();
TcpListener listener = new TcpListener(25543);
if (listener.Pending()) {
message = null;
client = listener.AcceptTcpClient();
StreamReader reader = new StreamReader(client.GetStream());
while (reader.Peek() != -1)
{
message += reader.Read().ToString();
}
MessageBox.Show(message);
}
Right now, when I run this, the message that gets displayed in the MessageBox is a very long number, for the message "Test" it's "84101115116". How can I convert this integer back to the original string "Test", so that the original message is displayed correctly in my server application?
I know that e.g. 84 in ASCII is the letter T, however the other numbers are different. Can some1 help?
Greetings
~Veraner
|
|
|
|
|
The Read method reads a character as an int. I believe that if you do:
message += (char)reader.Read(); (without the ToString())
it will probably work.
Yet, I believe your code has many problems...
I would recommend using WriteLine, not only Write, after all TCP/IP packets may be split in many messages. Your while() will fail if that happens.
Also, as you don't use another thread or asynchronous calls, the server is only able to deal with one client at a time.
|
|
|
|
|
Thank you - that solved my issue!
By now I made a seperate threat for this function and will have a look towards the WriteLine / while part.
|
|
|
|
|
Hi,
I have a datagridview. Under column is copy id from other tabel, i want auto change id with -1 to only number without -. Replace is dont working for datagridview. Who can help me?
This string work only for the textbox how can i change it for datagridview?
identity = identity.Replace("-", "");
modified 1-Mar-15 11:16am.
|
|
|
|
|
That should work for your DataGridView if the cell contains a string, but not if it is a numeric value.
|
|
|
|
|
Hmm that is numeric value. How connect you tabel to other tabel with relations?
|
|
|
|
|
Sorry, no idea what that means.
If it's a numeric value then you probably need to add an event handler to change it when it gets displayed.
|
|
|
|
|
sdfsdfsdfewrew3feff wrote: How connect you tabel to other tabel with relations? Usually using a number (often BIGINT) or a GUID.
If you need to remove the "-" sign from a number, consider multiplying it with -1, as opposed to converting it to a string.
Also, if it is a key-field (only there to keep relations with other records) then it should never be formatted or presented to the user at all.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
I have been writing a generic factory class; in pruned-down to walk-the-dog-bits-left-out form:
public class VTBunchOLists : List<IEnumerable<T>>
{
private bool isInt;
public VTBunchOLists()
{
isInt = typeof(T) == typeof(Int32);
}
public Int32 TToInt32(T value)
{
return (Int32)Convert.ChangeType(value, typeof(Int32));
}
public void Add(T howmanyT, bool ascending = true)
{
if (isInt)
{
var range = CreateRange(1, TToInt32(howmanyT), ascending);
this.Add(range as IEnumerable<T>);
}
}
private IEnumerable<int> CreateRange(Int32 howMany, bool ascending = true)
{
var range = Enumerable.Range(start, end);
return (ascending) ? range : range.Reverse();
}
} Here's what concerns me:
1. there's no way to constrain the Type of T to certain ValueTypes ... that I've found in my research. I guess I could look at the Type of T in the 'ctor and return null, or throw an error, if the Type didn't match what I wanted to handle, but that seems less than elegant to me.
2. obviously I'll do quite a different thing (not shown in the code) if T is a double, since you can't use Enumerable.Range for producing anything but and integer Range.
3. similarly the required casting of an integer (or double) range to IEnumerable<t> to be able to add it to the collection kind of gives me an itch I can't scratch, but what do you think ?
4. (related to concern #1) while Enumerable.Range(start#int, end#int) returns a nice IEnumerable<int> ... and so the return value of the factory is an "un-evaluated" IEnumerable, since you have to use a List<doulbe> to create the range of doubles, the return value of the factory will be an "evaluated" structure. That lack of "symmetry" bothers me, but I see no way around this ... now ... except to make the factory return a List<List<T>> ... mmmm ...
Why am I doing this: well, I've already written separate implementations for Int32 and Double, and I'm curious to see what's involved in making it generic. And, there is some very fancy stuff in the current implementations (not shown in the code here) that could be consolidated.
thanks, Bill
«I'm asked why doesn't C# implement feature X all the time. The answer's always the same: because no one ever designed, specified, implemented, tested, documented, shipped that feature. All six of those things are necessary to make a feature happen. They all cost huge amounts of time, effort and money.» Eric Lippert, Microsoft, 2009
modified 1-Mar-15 7:20am.
|
|
|
|
|
You can constrain it to a value type by making the whole class generic and adding the struct constraint:
public class VTBunchOLists<T> : List<IEnumerable<T>> where T : struct
{
private bool isInt;
public VTBunchOLists()
{
isInt = typeof(T) == typeof(Int32);
}
...
} (You have to use struct because ValueType isn't the root type for value types - it's just used for boxing)
And that might help a little - you can't use a where constraint on any sealed class (and all the primitives are sealed IIRC)
I have to say I don't like runtime type rejection in the constructor: I know what you mean, but it goes against my grain somewhat to force a run time error for something that should be a compile time problem!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Thanks, Griff !
I don't like Type rejection at run-time either, so 'struct will have to do.
If you have the bandwidth, I'd appreciate your reaction to a new "concern" I added to my original post: #4.
cheers, Bill
«I'm asked why doesn't C# implement feature X all the time. The answer's always the same: because no one ever designed, specified, implemented, tested, documented, shipped that feature. All six of those things are necessary to make a feature happen. They all cost huge amounts of time, effort and money.» Eric Lippert, Microsoft, 2009
|
|
|
|
|
Hi Bill,
as far as I know my Roslyn yet, with it you could write a source analysis that checks whether you try to use the factory class with anything other than the value types that it is intended for and include that check into your build process, so you can get an error pre runtime. Other than that, while not very beautiful, checking in the c'tor seems to be an agreed upon solution.
- Sebastian
|
|
|
|
|
Thanks, Sebastian,
It is interesting to speculate what a "range" of structs ... where the struct is a user-defined collection of whatever Types ... might be ... but I see no practical reason to go there, and so I think that if I do use the generic version, I will do run-time Type checking; I'd rather do that than engage in any reflection.
However, it's also interesting to think about if using some new feature in Roslyn (I'm using CTP 6 Visual Studio 2015 now for testing) might somehow reduce the "cost" of reflection. I'm not aware of any meta-programming features new in Roslyn ... yet.
cheers, Bill
«I'm asked why doesn't C# implement feature X all the time. The answer's always the same: because no one ever designed, specified, implemented, tested, documented, shipped that feature. All six of those things are necessary to make a feature happen. They all cost huge amounts of time, effort and money.» Eric Lippert, Microsoft, 2009
|
|
|
|
|
The core of the problem seems to be that you need to be able to add an increment to an instance of the generic type parameter T . There are various solutions for this - I tend to use some code adapted from the MiscUtil library[^]:
public static class GenericOperator<T>
{
private static readonly Func<T, T, T> _addChecked = Create<T>(Expression.AddChecked);
public static Func<T, T, T> AddChecked
{
get { return _addChecked; }
}
private static Func<T, T, TResult> Create<TResult>(Func<Expression, Expression, BinaryExpression> body)
{
try
{
Type typeT = typeof(T);
var left = Expression.Parameter(typeT, "left");
var right = Expression.Parameter(typeT, "right");
if (typeT.IsEnum)
{
Type enumType = Enum.GetUnderlyingType(typeT);
var x = Expression.Convert(left, enumType);
var y = Expression.Convert(right, enumType);
Expression op = body(x, y);
if (op.Type == enumType) op = Expression.Convert(op, typeT);
return Expression.Lambda<Func<T, T, TResult>>(op, left, right).Compile();
}
return Expression.Lambda<Func<T, T, TResult>>(body(left, right), left, right).Compile();
}
catch (InvalidOperationException ex)
{
string message = ex.Message;
return delegate { throw new InvalidOperationException(message); };
}
catch (ArgumentException ex)
{
string message = ex.Message;
return delegate { throw new InvalidOperationException(message); };
}
}
}
Since there's no way to get an instance of the generic type parameter that represents "1 ", you'll need to pass in the increment value to your Add function:
public class VTBunchOLists<T> : List<IEnumerable<T>>
{
private static readonly Func<T, T, T> AddChecked = GenericOperator<T>.AddChecked;
public VTBunchOLists()
{
}
public void Add(T startAt, T increment, int howMany, bool ascending = true)
{
IEnumerable<T> range = CreateRange(startAt, increment, howMany);
if (!ascending) range = range.Reverse();
Add(range);
}
private static IEnumerable<T> CreateRange(T startAt, T increment, int howMany)
{
T current = startAt;
for (int i = 0; i < howMany; i++)
{
yield return current;
current = AddChecked(current, increment);
}
}
}
If you want the contained ranges to be evaluated eagerly, you can do that in the Add method:
Add(range.ToList());
You can now use this class for any type which implements the addition operator:
var bunchOInt32s = new VTBunchOLists<int>();
bunchOInt32s.Add(10, 1, 15);
var bunchODoubles = new VTBunchOLists<double>();
bunchODoubles.Add(Math.PI, Math.E, 10, false);
public class Foo
{
public int Number { get; set; }
public static Foo operator+(Foo left, Foo right)
{
return new Foo { Number = left.Number + right.Number };
}
}
var bunchOFoos = new VTBunchOLists<Foo>();
bunchOFoos.Add(new Foo(), new Foo { Number = 5 }, 3);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|