|
I want to know how to define property?
|
|
|
|
|
|
|
Hi,
To add a property say Name do the following in your class.
private string _name;
public string Name
{
get{ return _name;}
set {_name = value;}
}
hope this helps.
Nitheesh George
http://www.simpletools.co.in
|
|
|
|
|
It does, but just as a note. In an instance like this it is cleaner to use the auto-property. public string name { get; set; } with no private member defined. (Your answer is still correct, of course)
I wasn't, now I am, then I won't be anymore.
|
|
|
|
|
I am writing a socket server and I have some trouble which I did expose through the program below.
If your run this program (this is a console program).
You'll find it open a web browser on a local address and shows 256 small pictures.
For the purpose of this test the pictures are actually quite large but are shown in small.
This is the complete C# 4.0 source, I encourage you to try it.
It really render really fast considering the time I have put into this.
But if you refresh your page you'll see that some of the pictures do not appear properly.
Anyone knows the reason for this.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MiniHttpServer
{
class Program
{
static void Main(string[] args)
{
HttpServer.Test();
}
class HttpServer
{
internal static Byte[] mIndex;
internal static Byte[] mPic;
Socket mMainSocket;
bool mUseHttp11;
static HttpServer()
{
mIndex = GetIndex();
mPic = GetCirclePicture();
}
public static void Test()
{
var httpServer = new HttpServer();
httpServer.StartServer(port: 3005, nbListeners: 4, useHttp11: true);
Process.Start("http://localhost:3005/");
Console.WriteLine("Press a key to exit");
Console.ReadKey(intercept: true);
httpServer.Stop();
}
private static Byte[] GetIndex()
{
StringBuilder html = new StringBuilder();
html.AppendLine("<html><body>");
html.AppendLine("<h1>Pics</h1>");
int k = 0;
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
html.AppendLine("<img width='16' height='16' src='p" + (k++) + ".png'>");
}
html.AppendLine("<br/>");
}
return Encoding.UTF8.GetBytes(html.ToString());
}
private static Byte[] GetCirclePicture()
{
var bmp = new Bitmap(256, 256);
using (var g = Graphics.FromImage(bmp))
{
for (int i = 0; i < 128; i++)
{
g.FillEllipse(new SolidBrush(Color.FromArgb(i, i, 255)), i, i, 255 - 2 * i, 255 - 2 * i);
}
}
var mem = new MemoryStream();
bmp.Save(mem, ImageFormat.Png);
return mem.ToArray();
}
public void StartServer(int port, int nbListeners, bool useHttp11)
{
mUseHttp11 = useHttp11;
var webAddress = new IPEndPoint(IPAddress.Loopback, port);
try
{
mMainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
mMainSocket.Bind(webAddress);
mMainSocket.Listen(255);
for (int i = 0; i < nbListeners; i++)
{
CreateListener(i);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void CreateListener(int l)
{
var newTask = Task.Factory.StartNew(delegate
{
var requestSocket = mMainSocket.Accept();
Console.WriteLine("L{0} is Accepted", l);
ProcessRequest(requestSocket, l);
Console.WriteLine("L{0} is dying gracefully", l);
}).ContinueWith(delegate
{
if (mMainSocket.IsBound)
{
Console.WriteLine("L{0} is really dead and is trying to resurrect", l);
CreateListener(l);
}
else
{
Console.WriteLine("L{0} is really dead and burried", l);
}
});
}
private void ProcessRequest(Socket requestSocket, int l)
{
try
{
const int BUFFER_SIZE = 4096;
var requestBuffer = new Byte[BUFFER_SIZE];
int requestPos = 0;
int requestNo = 0;
while (requestPos < BUFFER_SIZE)
{
SocketError socketError;
var read = requestSocket.Receive(requestBuffer, requestPos, requestBuffer.Length - requestPos, SocketFlags.None, out socketError);
if (socketError == SocketError.TimedOut)
{
continue;
}
if (read == 0) continue;
var requestString = Encoding.ASCII.GetString(requestBuffer, 0, read);
var sr = new StringReader(requestString);
var line = sr.ReadLine();
var request = line;
while (line != null && line.Length > 0)
{
line = sr.ReadLine();
}
if ((line = sr.ReadToEnd()) != null && line.Length > 0)
{
Console.WriteLine("Lost:" + line);
}
int len = requestPos + read;
int pos = IndexOfCrLfCrLf(requestBuffer, len);
if (pos >= 0)
{
if (pos == 0)
break;
requestNo++;
Console.WriteLine("{0} is processing request #{1}", l, requestNo);
requestPos = 0;
string response = "Hello";
string contentType = "text/plain";
Byte[] responseArray = null;
if (requestString.StartsWith("GET / "))
{
contentType = "text/html";
responseArray = mIndex;
}
else if (requestString.IndexOf(".png") >= 0)
{
contentType = "image/png";
responseArray = mPic;
}
if (responseArray == null) responseArray = Encoding.UTF8.GetBytes(response);
string header =
"HTTP/1." + (mUseHttp11 ? '1' : '0') + " 200 OK\r\n"
+ "Content-Length: " + responseArray.Length + "\r\n"
+ (mUseHttp11 ? ("Content-Type: " + contentType + "\r\n") : "")
+ "\r\n";
byte[] headerArray = Encoding.UTF8.GetBytes(header);
requestSocket.Send(headerArray, headerArray.Length, SocketFlags.None);
requestSocket.Send(responseArray, responseArray.Length, SocketFlags.None);
if (mUseHttp11 == false)
{
requestSocket.Close();
break;
}
}
else requestPos = len;
}
Console.WriteLine("Request complete");
}
catch (Exception ex)
{
Console.WriteLine("Exception " + ex.Message);
}
}
private void Nop()
{
}
public void Stop()
{
mMainSocket.Close();
}
static int IndexOfCrLfCrLf(byte[] requestBuffer, int len)
{
for (int i = 0; i <= (len - 4); i++)
{
if (requestBuffer[i] == '\r'
&& requestBuffer[i + 1] == '\n'
&& requestBuffer[i + 2] == '\r'
&& requestBuffer[i + 3] == '\n')
{
return i;
}
}
return -1;
}
}
}
}
|
|
|
|
|
The Shadow knows...
|
|
|
|
|
Considering noone will see this post in a couple of days, you'd be better off writing an article on it, how it was designed, the concepts behind it, how the code works, ...
[EDIT]
Sorry, I missed the question that was in there!
|
|
|
|
|
There was actually a question in there from the OP
"... if you refresh your page you'll see that some of the pictures do not appear properly.
Anyone knows the reason for this"
|
|
|
|
|
Crap... Missed that one.
|
|
|
|
|
The browser will reuse the connection, and you're resetting the requestPos pointer to 0 when you receive a message. What you don't do is check if there is material left at the end of the current buffer which is part of the next message (after the CRLF pair). You need to copy everything after the two CRLFs back to requestBuffer[0] and set requestPos appropriately.
This should fail the first time as well as on refresh, though.
|
|
|
|
|
I Have found what the problem was.
It was not so much as there was data in the connected socket I did not read but new connection I was not serving.
Having it in multiple threads to accept the connection didn't really help.
I was only accepting once and recreating a task was probably not fast enough.
Having it in a loop works well:
while (true)
{
var connectedSocket = mMainSocket.Accept();
Task.Factory.StartNew(delegate
{
ServeConnection(connectedSocket, l);
});
}
I copy the whole source, for all the times I found a 2 years old forum question that finishes by 'I found the solution never mind!' and I wish I could read it:
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MiniHttpServer
{
class Program
{
static void Main(string[] args)
{
HttpServer.Test();
}
class HttpServer
{
internal static Byte[] mIndex;
internal static Byte[] mPic;
Socket mMainSocket;
bool mUseHttp11;
static HttpServer()
{
mIndex = GetIndex();
mPic = GetCirclePicture();
}
public static void Test()
{
var httpServer = new HttpServer();
httpServer.StartServer(port: 3005, nbListeners: 1, useHttp11: true);
Process.Start("http://localhost:3005/");
Console.WriteLine("Press a key to exit");
Console.ReadKey(intercept: true);
httpServer.Stop();
}
private static Byte[] GetIndex()
{
StringBuilder html = new StringBuilder();
html.AppendLine("<html><body>");
html.AppendLine("<h1>Pics</h1>");
int k = 0;
for (int j = 0; j < 10; j++)
{
for (int i = 0; i < 10; i++)
{
html.AppendLine("<img width='16' height='16' src='p" + (k++) + ".png'>");
}
html.AppendLine("<br/>");
}
return Encoding.UTF8.GetBytes(html.ToString());
}
private static Byte[] GetCirclePicture()
{
var bmp = new Bitmap(256, 256);
using (var g = Graphics.FromImage(bmp))
{
for (int i = 0; i < 128; i++)
{
g.FillEllipse(new SolidBrush(Color.FromArgb(i, i, 255)), i, i, 255 - 2 * i, 255 - 2 * i);
}
}
var mem = new MemoryStream();
bmp.Save(mem, ImageFormat.Png);
return mem.ToArray();
}
public void StartServer(int port, int nbListeners, bool useHttp11)
{
mUseHttp11 = useHttp11;
var webAddress = new IPEndPoint(IPAddress.Loopback, port);
try
{
mMainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
mMainSocket.Bind(webAddress);
mMainSocket.Listen(255);
for (int i = 0; i < nbListeners; i++)
{
CreateListener(i);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void CreateListener(int l)
{
var newTask = Task.Factory.StartNew(delegate
{
while (true)
{
var connectedSocket = mMainSocket.Accept();
connectedSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
Console.WriteLine("L{0} is Accepted", l);
var task2 = Task.Factory.StartNew(delegate
{
ServeConnection(connectedSocket, l);
});
}
}).ContinueWith(delegate
{
if (mMainSocket.IsBound)
{
Console.WriteLine("L{0} is really dead and is trying to resurrect", l);
CreateListener(l);
}
else
{
Console.WriteLine("L{0} is really dead and burried", l);
}
});
}
private void ServeConnection(Socket connectedSocket, int l)
{
int requestNo = 0;
try
{
const int BUFFER_SIZE = 4096;
var requestBuffer = new Byte[BUFFER_SIZE];
int readIndex = 0;
while (true)
{
SocketError socketError;
var read = connectedSocket.Receive(requestBuffer, readIndex, requestBuffer.Length - readIndex, SocketFlags.None, out socketError);
var requestString = Encoding.ASCII.GetString(requestBuffer, 0, read);
Console.WriteLine("{0} read {1} ({2})", l, read, requestString.Substring(0, Math.Min(20, requestString.Length)));
if (read == 0) return;
int pos = IndexOfCrLfCrLf(requestBuffer, read);
readIndex += read;
if (pos < 0)
{
pos = 0;
}
else
{
while (pos >= 0)
{
if (pos == 0)
break;
requestNo++;
string response = "Hello";
string contentType = "text/plain";
Byte[] responseArray = null;
requestString = Encoding.UTF8.GetString(requestBuffer, 0, pos);
if (requestString.StartsWith("GET / "))
{
contentType = "text/html";
responseArray = mIndex;
}
else if (requestString.IndexOf(".png") >= 0)
{
contentType = "image/png";
responseArray = mPic;
}
if (responseArray == null) responseArray = Encoding.UTF8.GetBytes(response);
string header =
"HTTP/1." + (mUseHttp11 ? '1' : '0') + " 200 OK\r\n"
+ "Content-Length: " + responseArray.Length + "\r\n"
+ (mUseHttp11 ? ("Content-Type: " + contentType + "\r\n") : "")
+ "\r\n";
byte[] headerArray = Encoding.UTF8.GetBytes(header);
connectedSocket.Send(headerArray, headerArray.Length, SocketFlags.None);
connectedSocket.Send(responseArray, responseArray.Length, SocketFlags.None);
if (mUseHttp11 == false)
{
connectedSocket.Close();
return;
}
pos += 4;
readIndex -= pos;
if (readIndex > 0)
{
Array.Copy(requestBuffer, pos, requestBuffer, 0, readIndex);
pos = IndexOfCrLfCrLf(requestBuffer, readIndex);
}
else
{
readIndex = 0;
pos = -1;
}
}
}
}
Console.WriteLine("Request complete");
}
catch (Exception ex)
{
Console.WriteLine("Exception " + ex.Message);
}
finally
{
connectedSocket.Close();
}
}
private void Nop()
{
}
public void Stop()
{
mMainSocket.Close();
}
static int IndexOfCrLfCrLf(byte[] requestBuffer, int len)
{
for (int i = 0; i <= (len - 4); i++)
{
if (requestBuffer[i] == '\r'
&& requestBuffer[i + 1] == '\n'
&& requestBuffer[i + 2] == '\r'
&& requestBuffer[i + 3] == '\n')
{
return i;
}
}
return -1;
}
}
}
}
|
|
|
|
|
I had windows service and setup projects developed in VS 2008 .NET 3.5.
Setup was converted to VS 2010 and windows service project replaced with new one created in VS 2010 .NET 4.0.
There are custom actions in setup to install service in the system.
The Error 1001 System.BadImageFormatException failed to load service exe due to incorrect format appears during setup execution.
Without custom action the setup runs without problems. I can also manually install the service with installutil.exe
Are there any settings in the setup project to run correct installutil from the right .NET version?
Чесноков
|
|
|
|
|
Hi All,
I am writing text into StreamWriter by sw.Write("Text coming from Labels : so can be in english or chinese or any other languages") method.
After writing first text, I am adding tabs and then adding second text.
Now adding a new line and adding first text + tabs + second text.
It looks like this:
Model :\t \t \t \t \t XXXX
Version :\t \t \t \t YYYY
Note : I am not able to put white spaces here so just putted \t.
Assume that the first X and first Y starting position is equal.
Alignment is coming properly for English.
But if the input texts are in Chinese then it comes like this :
Model :\t \t \t \t \t XXXX
Version :\t \t \t \t YYYY
Here YYYY is not coming just below XXXX such that the start position of first X and first Y should be same,
This Tab spaces are the same for different languages.
I want atleast alignment should be proper with every languages.
Thanks in Advance..
Piyush Vaishnav
|
|
|
|
|
a text file contains text, not formatting. the only way to give it some columnar layout without using a command language, is by inserting the right number of spaces and using a non-proportional (i.e. monospaced) font, such as Courier New. I expect there isn't a non-proportional font for Chinese.
Using tabs to replace spaces could work also, there may be some issues. And it is a first step towards a command language. Real command languages would be HTML, RTF, PostScript, etc.
In summary, there is no general solution IMO.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Much as Luc said, your choices are either to use delimiters (or markup), or to go to fixed-width columns.
You can use string.PadLeft or .PadRight to achieve columns, but you'll need to know the maximum length possible in each column (or truncate longer data).
It's not good to try to store your formatting in with your data, I would recommend delimited text or finding a solution via XML and finally using something to generate your display (rather than relying intrinsically on the stored data).
Cheers.
|
|
|
|
|
Hi,
Now I used string.PadRight(40, ' ') for the first text and then after adding second text.
It's working fine for english.
But for Chinese still second text is not coming below the First Row's second text.
|
|
|
|
|
Are you adding the required line breaks? If you reveal a bit of your code it might help others solve the problem.
As previously stated, you're going to have a hard time finding a balance of content and format. Once, there was this whole thing about HTML and CSS, and then, this other time, XML and XSL/T...
|
|
|
|
|
Hi!
I started a development of a application (in Windows Mobile 6) and now i have a little problem:
My datasource have 11.000~12.000 registers and when I bind it to my ListBox, this action spend 6 seconds (I think its a lot) and now I want to reduce that time.
Anyone now a way to do this?
Some code to exemplify my situation:
SQLiteConnection cnn = openCon();
string SQL = "select cod, desc from produtcs";
SQLiteDataReader sDR;
List<MyObj> data = new List<MyObj>();
cnn.Open();
SQLiteCommand sCommand = new SQLiteCommand(SQL, cnn);
sDR = sCommand.ExecuteReader();
while (sDR.Read())
{
data.Add(new MyObj(sDR["cod"].ToString(), sDR["desc"].ToString()));
}
listBox1.DataSource = data;
I need populate MyObj after, cuz this I use the variable "data"
class MyObj
{
public MyObj(int p1, string p2){ ... }
private int cod;
private string desc;
private string ...
private int ...
}
[]'s
Eder Sá
[]'s
|
|
|
|
|
Eder Sa wrote: Anyone know a way to do this?
First place to start would be asking in the correct forum. See Mobile[^]
Reduce the amount of data you are trying to display. Users are not going to scroll through 12,000 items, particularly on a mobile device.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
My first post and my first mistake.
I need to load all the data, because when the user types some letters in a filter, the focus moves in the list, searching for the first ocorrence (I use a binary search, but modified and it works fine!)
I can move the topic to Mobile Forum?
[]'s
|
|
|
|
|
It's too late to move the post now.
Populate the list after you have filtered the data.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Eder Sa wrote: <layer>I need to load all the data, because
How many entries will the user see when typing? Fetch the top 20 and display that until the user hits enter - and page the rest. Google wouldn't be very efficient if it had to send you all it's search-results and let your browser filter it.
Imagine that, with IE4.
I are Troll
|
|
|
|
|
I implemented your suggestion and like the result.
I need to do some more tests and I back later with feedback.
Thx!
[]'s
|
|
|
|
|
Cool - you're welcome
|
|
|
|
|