|
I can convert image to binary string from
[HERE]
But This binary string how to convert the that image ?
|
|
|
|
|
This does not have a quick answer.
Usually an image is represented with an array of pixels where each item has a a value explaining that pixel for a 256x256 pixel image you'll have an array with size 65536 items. Assuming this is the case here, you still need to know what kind of values are accepted in that images, 8 bits, 12 bits, 24 bits (RGB) or 32 bits (ARGB) eg. Even if you know that you need to know which encoding is used to generate the string and if that string also contains any headers (like a bmp has), exif information etc...
The best thing to do is to try and figure out what encoding is used to generate the string and try to get the bytes back. From there you can work further.
It's hard to give anything more then this without more information, because of the many possibilities.
Try some stuff out and come back if you have more detailed questions.
|
|
|
|
|
Hi All
i'm working on gps tracking system
now i'm working on receiving data from gps devices throw tcp port
using tcpListner class then arrange the data then save it to sql server
i have created a console application to do so then convert it to windows service using NSSM
it is working as expected but after about 30 minutes it consumes all the server memory and CPU
it is only 4 devices connected (Test Phase)
The Code
using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Data;
using Microsoft.SqlServer.Types;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8889);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
Console.ReadLine();
}
}
public class handleClinet
{
static void WriteLog(string message, EventLogEntryType type)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry(message, type, 101, 1);
}
}
static int InsideDangerArea(double Lat, double Lng)
{
string point = "POINT(" + Lng + " " + Lat + ")";
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Select id from T_Geofncies", conn))
{
DataTable dt = new DataTable();
dt.Load(comm.ExecuteReader());
foreach (DataRow dr in dt.Rows)
{
string Query = " DECLARE @g geometry; DECLARE @h geometry; SET @g = (select(points) from T_Geofncies where id=" + dr["id"].ToString() + " );";
Query += " SET @h = geometry::STGeomFromText('" + point + "', 4326); SELECT @g.STContains(@h);";
comm.CommandText = Query;
int Val = Convert.ToInt32(comm.ExecuteScalar());
if (Val == 1)
{
conn.Close();
conn.Dispose();
return Convert.ToInt32(dr["id"]);
}
}
}
conn.Close();
conn.Dispose();
}
return 0;
}
static int OutsideSafeArea(double Lat, double Lng)
{
string point = "POINT(" + Lng + " " + Lat + ")";
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Select id from T_SafeArea", conn))
{
DataTable dt = new DataTable();
dt.Load(comm.ExecuteReader());
foreach (DataRow dr in dt.Rows)
{
string Query = " DECLARE @g geometry; DECLARE @h geometry; SET @g = (select(points) from T_SafeArea where id=" + dr["id"].ToString() + " );";
Query += " SET @h = geometry::STGeomFromText('" + point + "', 4326); SELECT @g.STContains(@h);";
comm.CommandText = Query;
int Val = Convert.ToInt32(comm.ExecuteScalar());
if (Val == 1)
{
conn.Close();
conn.Dispose();
return Convert.ToInt32(dr["id"]);
}
}
}
conn.Close();
conn.Dispose();
}
return 0;
}
static SqlGeography GetGeographyFromText(String pText)
{
SqlString ss = new SqlString(pText);
SqlChars sc = new SqlChars(ss);
try
{
return SqlGeography.STPointFromText(sc, 4326);
}
catch (Exception ex)
{
throw ex;
}
}
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
int requestCount = 0;
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
int i;
int size = (int)clientSocket.ReceiveBufferSize;
Byte[] bytes = new Byte[size];
string data = "";
string IMEI;
while ((i = networkStream.Read(bytes, 0, bytes.Length)) != 0)
{
try
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
string[] tokens = data.Split(new[] { "GPRMC" }, StringSplitOptions.None);
var longest = Regex.Matches(data, @"\d+").Cast().OrderByDescending(m => m.Length).First();
IMEI = longest.ToString();
if (IMEI.Length > 15)
IMEI = IMEI.Substring(1);
foreach (string item in tokens)
{
try
{
string[] Values = item.Split(',');
string time = Values[1];
string lat;
string lng;
string speed;
string date;
lat = Values[3];
lng = Values[5];
speed = Values[7];
date = Values[9];
string NewDString = date.Substring(2, 2) + date.Substring(0, 2) + date.Substring(4, 2);
string myDate = (NewDString + time).Insert(2, "-").Insert(5, "-").Insert(8, " ").Insert(11, ":").Insert(14, ":");
double latDeg = Convert.ToDouble(Convert.ToDouble(lat).ToString().Substring(0, 2));
double latMin = Convert.ToDouble(Convert.ToDouble(lat).ToString().Substring(2));
double lngDeg = Convert.ToDouble(Convert.ToDouble(lng).ToString().Substring(0, 2));
double lngmin = Convert.ToDouble(Convert.ToDouble(lng).ToString().Substring(2));
double latmap = latDeg + (latMin / 60);
double lngmap = lngDeg + (lngmin / 60);
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"INSERT INTO T_Tracking " +
"([IMEI], [TrackTime], [Longitude], [Lattitude], [speed],[MapPoint],[SafeAreaID],[GeoFenceID]) " +
"VALUES(@IMEI, @TrackTime, @Longitude, @Lattitude, @speed,@MapPoint,@SafeAreaID,@GeoFenceID)";
SqlParameter p_IMEI = new SqlParameter("@IMEI", IMEI);
cmd.Parameters.Add(p_IMEI);
SqlParameter p_TrackTime = new SqlParameter("@TrackTime", myDate);
cmd.Parameters.Add(p_TrackTime);
SqlParameter p_Longitude = new SqlParameter("@Longitude", lngmap);
cmd.Parameters.Add(p_Longitude);
SqlParameter p_Lattitude = new SqlParameter("@Lattitude", latmap);
cmd.Parameters.Add(p_Lattitude);
SqlParameter p_Speed = new SqlParameter("@speed", speed);
cmd.Parameters.Add(p_Speed);
SqlParameter p_Points = new SqlParameter("@MapPoint", System.Data.SqlDbType.Udt);
p_Points.UdtTypeName = "geometry";
p_Points.Value = GetGeographyFromText("Point(" + lngmap + " " + latmap + ") ");
cmd.Parameters.Add(p_Points);
SqlParameter P_Safe = new SqlParameter("@SafeAreaID", OutsideSafeArea(latmap, lngmap));
cmd.Parameters.Add(P_Safe);
SqlParameter P_GeoFence = new SqlParameter("@GeoFenceID", InsideDangerArea(latmap, lngmap));
cmd.Parameters.Add(P_GeoFence);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception exp) { WriteLog(exp.ToString(), EventLogEntryType.Error); }
}
}
catch { }
}
}
catch (Exception ex)
{
}
}
}
}
}
what optimization can be done ?
Imagine on live version it will be about 1000 device
Thank you for the help
|
|
|
|
|
There's a bit much here to look at so I haven't completely gone through the logic, but it seems that you're making clients on new threads and those clients never kill themselves so they're basically leaked.
|
|
|
|
|
i guess you are right
please check that code part
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
it will never go to the close part
|
|
|
|
|
I don't see you close the connection or the NetworkStream. So, it may be one of the issues.
|
|
|
|
|
i'm using
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Select id from T_SafeArea", conn))
{
}
conn.Close();
conn.Dispose();
}
|
|
|
|
|
you are right about closing the network stream and the clients
could you point out where in the code to do so
|
|
|
|
|
When you call GetStream, do it with a using clause. Put an {
And at the end of the method, the closing }
This would solve the issue.
|
|
|
|
|
i tried that it got worse it hang after starting by 2 minutes
|
|
|
|
|
Yeah... I didn't notice the GetStream was inside a while(true)... so you shouldn't dispose the stream at that moment.
Yet, I think I found your issue. You put the try / catch inside the while (true). That means that as soon as there is the first exception, your code will be actively rerunning and rethrowing exceptions forever.
So, the right thing would be to put the while(true) inside the try... actually, inside the using clause for the network stream. But if you want to test it without too many changes, simply put returns in your catch clauses and it should solve the eternal loop issue.
|
|
|
|
|
sorry for late replay
it didn't work
still 92% CPU after 20 min
with only 4 devices
i put stream.close inside the catch
i put clientsocket.close inside the catch the error was
cannot access a disposed object system.net.sockets.socket
should i use Async
Asynchronous Server Socket
|
|
|
|
|
It is not a matter of calling Dispose or Close in the catch. The problem is that you have an eternal loop and, inside the loop, you have a try/catch accessing an object that may be disposed.
That means:
You start running it OK. As soon as the client disconnects, you receive an exception, you catch it, maybe you close/dispose objects, it doesn't matter, the loop runs again, you try to access a disposed object, you get a new exception, you catch it, you dispose again (nothing changes) and you run again... infinitely.
So, with a while(true) and a try/catch inside the while, you will always make the application consume 100% CPU when you have as many disconnected clients as you have CPUs (that is, on a 4-cpu machine, the CPU will go up to a total near of 100% as soon as 4 clients disconnect, as you simply don't allow the code to exit the eternal loop).
|
|
|
|
|
Hi, Avoid creating too many instances using new keyword. If you still need then dispose them once used immediately.
ravindrapc
|
|
|
|
|
hi all I developing a program in c#, I have two form. in the form1 I have a texbox, label and combobox, and in the second form I have a button the name cleaning and the class clean.I need is calling me class clean with me button clean and cleaning the form 1
|
|
|
|
|
Sorry?
That doesn't make a whole lot of sense - what does your Clean class have to do with Form1?
If you mean "I want to press a button on Form2, and it empties the data on Form1" then it depends who opened what.
IF Form1 opened Form2, then you need an event in Form2, which is handled in Form1: Transferring information between two forms, Part 2: Child to Parent[^] - Form1 then clears out it's own fields.
If Form2 opened Form1, then use a method in Form1 which is called from Form2, and which clear out teh info: Transferring information between two forms, Part 1: Parent to Child[^] - the example uses a property, but a method is more appropriate.
If neither of them knows about the existence of the other (i.e. both were opened from Form3) then combine the two methods: Transferring information between two forms, Part 3: Child to Child[^]
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
in my form1 I have a texbox and I want to clean from my button clean in my form 2 whit my class clean
I think is the is the second opcion
|
|
|
|
|
Assume you create a Windows Class Library, 'MyLibrary'; you create a Windows Form project 'MyProject;' you add a reference to MyLibrary's .dll to MyProject.
If MyLibrary has a static variable, 'MyVar,' every instance of MyLibrary in MyProject will, of course, access the one-and-only MyVar.
However, what if you want each instance of MyLibrary to store a reference to itself that can be accessed from outside the scope of the instance ... as if each instance of MyLibrary had a unique static value ?
Perhaps there is a way using separate Application Contexts ?
Will add code samples, shortly (hardware problems, here).
thanks, Bill
«There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008
|
|
|
|
|
I'm not sure I get how that would work. If you are accessing an instance from outside that instance, how could you tell which instance you were actually accessing?
The only thing I can come up with that comes close, that I actually have used in the past, is a static Dictionary, where the keys are some sort of instance identifier, and the value is the instance itself. The constructor adds itself to that dictionary, and Dispose or some sort of release method removes it again.
Cheers,
Mick
------------------------------------------------
It doesn't matter how often or hard you fall on your arse, eventually you'll roll over and land on your feet.
|
|
|
|
|
Maybe I don't get it but there is only one instance of a DLL in a process.
However, a DLL might use Thread Local Storage (Windows)[^] so that each thread of a process has access to it's own data.
|
|
|
|
|
You're over thinking it. A static variable has nothing to do with any instance of a class, the point of static means it's tied to the Class and not the Instance.
For example
class ClassName {
static string VariableName;
}
it wouldn't matter if you said..
ClassName newInstance = new ClassName();
newInstance.VariableName = "test";
or if you said
ClassName.VariableName = "test";
In both instances, you're dealing with the same thing.
If you want to have a variable tied to an instance, you shouldn't mark it as static. In that way, each instance of ClassName would have it's own instance of VariableName
Hope that helps!
|
|
|
|
|
DataSet ds = new DataSet();
conn_DB();
OracleCommand Cmd = null;
Cmd = new OracleCommand();
Cmd.Connection = mConn;
try
{
string sql = "SELECT * FROM USER_INFO WHERE USE_UID='" + userid + "'" + " AND PWD='" + userpw + "'";
Cmd.CommandText = sql;
OracleDataAdapter adapter = new OracleDataAdapter(Cmd);
adapter.Fill(ds);
}
catch (OracleException e)
{
return null;
}
How to fix "
System.InvalidOperation.Exception"
or Exception "
modified 7-Nov-16 2:36am.
|
|
|
|
|
You set Cmd to Null, create a new command called navicallCmd, set it up then pass Cmd as the argument to the adapter...try passing navicallCmd.
|
|
|
|
|
Just to add to what Micheal says, don't do it like that either: Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
|