|
Radoslav Bielik wrote:
Also, with CryptoServiceProvider, is there a simple way of converting a byte array into a hexadecimal string represenatation
byte[] bits = ...;
string hash = System.Text.Encoding.Default.ToString(bits);
Jonathan de Halleux - My Blog
|
|
|
|
|
That would be actually very nice, but I'm not sure I get it right or if I'm doing something wrong. The ToString() method of Encoding class doesn't take any input arguments. There is the GetString(byte[] ...) method, but it will return a string representation of the bytes in the byte array, not a hexadecimal representation (like "7ba183d2") which is what I'm trying to do.
And finally, there is also the BitConverter class with its ToString(byte[] ...) method which works, but it will return a string where octets are separated by dashes.
Rado
Radoslav Bielik
http://www.neomyz.com/poll [^] - Get your own web poll
|
|
|
|
|
Sorry, ToString was GetString indeed. I though you just needed to convert a byte[] to string. Do you really need hex representation ? you can convert to Base64.
Jonathan de Halleux - My Blog
|
|
|
|
|
Jonathan de Halleux wrote:
Sorry, ToString was GetString indeed. I though you just needed to convert a byte[] to string. Do you really need hex representation ?
Yes, I should have made that more obvious Thank you for your response anyway!
Rado
Radoslav Bielik
http://www.neomyz.com/poll [^] - Get your own web poll
|
|
|
|
|
Just enumerate the byte[] array and use ToString("x2") on each byte - appending the value - to have a valid hexidecimal representation. Make sure you include the "2", though, otherwise your hex string may not be a multiple of 2 (so any value less than 128 would not have the first "0"):
byte[] buffer = Encoding.Default.GetBytes("Hello, world!");
StringBuilder sb = new StringBuilder(buffer.Length * 2);
foreach (byte b in buffer)
sb.Append(b.ToString("x2"));
return sb.ToString();
Software Design Engineer
Developer Division Sustained Engineering, Microsoft
My Articles
|
|
|
|
|
Yes, this is exactly what I'm doing but it looked too complicated to me and I thought that there surely must be a simpler way.
Originally, I was just concatenating the strings using the += operator, but using the StringBuilder's Append method is probably more efficient?
Thanks for your ideas,
Rado
Radoslav Bielik
http://www.neomyz.com/poll [^] - Get your own web poll
|
|
|
|
|
Ask yourself - do you want faster code or do you want to write less code? Using FormsAuthentication.HashPasswordForStoringInConfigFile is quicker to use (albeit a long method name!) but using the MD5 class (or MD5CryptoServiceProvider - it's really the same thing) will result in a little less code (not much, but will save a few extra IL instructions):
MD5 md5 = MD5.Create();
byte[] buffer = Encoding.UTF8.GetBytes(inputString);
byte[] hash = md5.ComputeHash(buffer);
StringBuilder sb = new StringBuilder(hash.Length * 2);
foreach (byte b in buffer)
sb.Append(b.ToString("x2");
return sb.ToString(); FormsAuthentication.HashPasswordForStoringInConfigFile adds a few steps for comparing the string you pass ("md5" or "sha1").
Software Design Engineer
Developer Division Sustained Engineering, Microsoft
My Articles
|
|
|
|
|
That's what I was basically interested in, which one is more efficient and elegant, and I thank you a lot for making it clear to me.
In this case, the performance was not really an issue because the operation doesn't occur too often, but the few more lines of code are good if it is a more elegant way to use MD5CryptoProvider.
Thanks again Heath!
Rado
Radoslav Bielik
http://www.neomyz.com/poll [^] - Get your own web poll
|
|
|
|
|
Hey all,
I have an arraylist which has InfoObjects populated in it. These infoObjects have some fields i need to implement a sort on. How is is possible to sort my arraylist having these infoobjects according to a particular field in the inofobjects?
Any comments!!
Awais Malik
|
|
|
|
|
hi,
One solution for this sort of requirement is Indexer.
Next couple of solutions will be
1. IComparable interface for single sort ( sorting based on one criteria)
2. IComparer interface for Multiple sort order ( sorting based on multiple criteria)
**************************
S r e e j i t h N a i r
**************************
|
|
|
|
|
I'm trying to accomplish a certain gradient effect using the pathGradientBrush object. I need to draw a circle having a gradient with the center color red, which flows in both directions: inwards and outwards. That is, the center of the gradient with the red color needs to be located as a middle ring of the circle, and needs to change towards white as you travel both in the direction of the center of the circle and in the opposite direction.
The code I wrote is this:
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(Location.X,Location.Y,length,width);
PathGradientBrush pBrush = new PathGradientBrush(gp);
pBrush.CenterColor =colorByValue(Color.red);
Color[] colors = {Color.White,Color.Red};
Brush.SurroundColors = colors;
e.Graphics.FillEllipse(Location.X,Location.Y,length, width);
Running this code I get a red elipse with a strange small white pie shaped strip. I tried looking for examples on how to implement a gradient that flows in more than one direction but couldn't find any. Does anyboy have any ideas ?
|
|
|
|
|
obby wrote:
Running this code
where are u using the GradientPathBrush then?
obby wrote:
I tried looking for examples on how to implement a gradient that flows in more than one direction but couldn't find any. Does anyboy have any ideas ?
I saw an article here on CP showing how it works, not sure if it will help you. From my attempts I know its tricky.
As a tip: Create an object containing all the setting you wanna apply to the drawing/path, then expose that via a propertygrid, and hence can change the settings on the fly
top secret xacc-ide 0.0.1
|
|
|
|
|
hi,
my app is constituted by a http client (ppc emulator) and a http server (desktop).
the server accepts multipart POST.
my problem is that, sometimes the server can just receive the http header sent by the client. i dunno it's the problem of my server or client.
here is my code segment:
CLIENT:
WebRequest request;
Stream requestStream;
try
{
request = HttpWebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundaryString + "\r\n";
request.ContentLength = message.Length;
request.Method = "POST";
request.Timeout = 10000;
requestStream = request.GetRequestStream();
requestStream.Write(message, 0, message.Length);
// Close the Stream object.
requestStream.Close();
// 1. Get the Web Response Object from the request
WebResponse response = request.GetResponse();
// 2. Get the Stream Object from the response
Stream responseStream = response.GetResponseStream();
// 3. Create a stream reader and associate it with the stream object
StreamReader reader = new StreamReader (responseStream);
// 4. read the entire stream
results = reader.ReadToEnd();
reader.Close();
responseStream.Close();
}
catch(WebException webEx)
{
results = "An exception occurred relating to the use of " +
"a web response or request object. The specific exception was:" +
webEx.Message;
}
//Did some type of general exception occur?
catch(Exception ex)
{
results = "A general exception occurred while attempting to " +
"retrieve the requested page." +
ex.Message;
}
SERVER:
private void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
f1.ShowSystemMessage("\r\nClient Connected!!"
+"\r\n=================="
+"\r\nCLient IP "
+ handler.RemoteEndPoint + "\r\n");
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
private void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer));
f1.ShowSystemMessage(state.sb.ToString());
ProcessRequest(state);
// Check for end-of-file tag. If it is not there, read more data.
content = state.sb.ToString();
// All the data has been read from the client. Display it on the console.
f1.ShowSystemMessage("Read " + content.Length.ToString()
+ " bytes from socket. \r\n Data : " + content );
state.ClearSB();
}//end if
}
thanks
|
|
|
|
|
You may get a faster response if you ask this on the ASP.net forum.
This group is more general C# questions rather than web-specific.
This signature left intentionally blank
|
|
|
|
|
I have a web site I want to query from my Windows Application. The web site has a search form where a variable is set in the post and submitted to the site. How can I do the same from Windows ?? example: Go to www.thetabworld.com. Whatever you can do from there in terms of searching and getting results, I want to do it from my application. IS that possible ??
I am able to request a web page, but don't know how to post values to it from C# code.
All help is highly appreciated.
Regards,
- dooL
|
|
|
|
|
From the message above:
WebRequest request;
request = HttpWebRequest.Create(url);
request.Method = "POST";
request.Timeout = 10000;
Mazy
"One who dives deep gets the pearls,the burning desire for realization brings the goal nearer." - Babuji
|
|
|
|
|
Hello,
I am developing a database application. I have one form which contains students' details. I can add, delete, and update the records in the form without any problems.
My question is, when l add a new student, should l have new add student form shows, which is the form that allows the user to enter the details. Once the user has entered the details they will confirm the details are correct than press ok. the Text boxes on the add new student form will then be copied to the main student form, and then the update code would be executed.
Is this a professional way to do this, or should l just add the new record in the main form.
I am using C#, but I don't think that matters as this is just a standard database application that could be written in any language.
A second question, should l lock the text boxes when the user is just browsing through the records, and only unlock them when the user wants to update or add new.
Thanks for your professional advice,
Steve
|
|
|
|
|
steve_rm wrote:
My question is, when l add a new student, should l have new add student form shows, which is the form that allows the user to enter the details. Once the user has entered the details they will confirm the details are correct than press ok. the Text boxes on the add new student form will then be copied to the main student form, and then the update code would be executed.
Is this a professional way to do this, or should l just add the new record in the main form.
I prefer the first one.
Mazy
"One who dives deep gets the pearls,the burning desire for realization brings the goal nearer." - Babuji
|
|
|
|
|
Thanks for your advice.
Steve
|
|
|
|
|
I have 2 sample structures in the unmanaged code(c++ dll)
typedef struct
{
char* lpszString1,
long ulField1;
}SubStruct;
typedef struct
{
int szlen;
SubStruct* arrsubstruct;
}arrstruct;
And I declare a method in the unmanaged dll
/*
*Method Structwithstructarray will print out the contents
* the members of the array sent from managed code and
* and reassign the array to point to a new set of element.
*/
void Structwithstructarray(arrstruct* mstruct)
{
cout << " Structwithstructarray "<< endl;
SubStruct* oldmanagedarray = mstruct->arrsubstruct;
for(int elem=0;elem<mstruct->szlen;elem++)
cout << oldmanagedarray[elem].lpszString1 << endl;
SubStruct* newunmanagedarray=new SubStruct[4];
newunmanagedarray[0].lpszString1="UnManaged0";
...
....
mstruct->szlen=4;
mstruct->arrsubstruct=newunmanagedarray;
}
The corresponding definitions in managed code
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
public struct submanagedStructure
{
public string sx;
public long szlen;
public submanagedStructure(string _sx,long _szlen)
{
sx=_sx;
szlen=_szlen;
}
}
structure 2:
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
public struct arrStructure
{
public int szlen;
public IntPtr mbuf;
}
[DllImport("........dll")]
public static extern int Structwithstructarray(ref arrStructure ama);
Now I invoke the function in the following sequence
//Populate structure members to send to unmanaged
submanagedStructure[] arrmanagedStructure = new submanagedStructure[3];
arrmanagedStructure[0]=new submanagedStructure("submanagedstructure1",15);
.....
....
arrStructure MyStruct = new arrStructure();
MyStruct.szlen=arrmanagedStructure.Length;
MyStruct.mbuf = Marshal.AllocCoTaskMem(
Marshal.SizeOf(arrmanagedStructure[0]) * arrmanagedStructure.Length
);
//Copy each structure into our allocated block
int iCurOffset = 0;
foreach(submanagedStructure item in arrmanagedStructure)
{
Marshal.StructureToPtr(
item,
(IntPtr)(MyStruct.mbuf.ToInt32() + iCurOffset) ,
false );
iCurOffset += Marshal.SizeOf(arrmanagedStructure[0]) ;
}
//Finally send to unmanaged module
Structwithstructarray(ref MyStruct);
//retrieve the returned structure elements
int outval = MyStruct.szlen;
IntPtr rudt=MyStruct.mbuf;
submanagedStructure[] recvmanagedarray = new submanagedStructure[outval];
for ( int i = 0 ; i < outval; i++ )
{
recvmanagedarray[i] = (submanagedStructure)Marshal.PtrToStructure (
(IntPtr )rudt, typeof ( submanagedStructure ) );
Console.WriteLine("The string element {0} of the struct {1} ",i,recvmanagedarray[i].sx );
rudt = (IntPtr)((int)rudt + Marshal.SizeOf ( typeof ( submanagedStructure ) ));
}
Now I find that just the 1 structure instance gets marshalled through the IntPtr into the unmanaged module.
So.in the unmanaged function
for(int elem=0;elem<mstruct->szlen;elem++)
cout << oldmanagedarray[elem].lpszString1 << endl;
It prints out the first structure and gives a null reference exception thereafter.(Why do the other 2 do not get marshalled?)
Similarly when the structure reference returns,the line "Console.WriteLine("The string element ....." prints out UnManaged0 and UnManaged2.
What happened to the structure elements UnManaged1 and UnManaged3?
Please advise.
|
|
|
|
|
|
How to export data from datagrid to excel?
Whats the command for that?
Anyone could help?
Thanx!
|
|
|
|
|
|
I've already read this article,but it doesn't help.
Any other suggestion?Thanx anyway!
|
|
|
|
|
This is my code:
void Button1Clicked(Object sender,System.EventArgs e)
{
Button a = (Button)FindControl("Button1");
a.Attributes.Add("OnClick","return confirm('Do you want to save?');");
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(GridView);
GridView.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
but it can't prompt out the alert page for you to save. How come?
Another problem,how to direct the page to a seperated excel page?
Can anyone pls correct it?Thanx so much!
|
|
|
|