wait() in asp.net (showing uploaded image) - asp.net

I want to force my program to wait some moments after doing something, and then do somwthing else, in asp.net and silverlight.
(In Detail, I want to upload an image by silverlight program, and then show it in my page by an Image control. But when I upload images which their size is about 6KB or upper, the image doesn't show, however it has been uplaoded successfully. I think that waiting some moments may solve the problem)
May anyone guide me?
thank you

I use the code in this page
This is the code in MyPage.Xaml:
private void UploadBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = UPLOAD_DIALOG_FILTER;
if ((bool)dlg.ShowDialog())
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 0;
_fileName = dlg.File.Name;
UploadFile(_fileName, dlg.File.OpenRead());
}
else
{
//user clicked cancel
}
}
private void UploadFile(string fileName, Stream data)
{
// Just kept here
progressBar.Maximum = data.Length;
UriBuilder ub = new UriBuilder("http://mysite.com/receiver.ashx");
ub.Query = string.Format("fileName={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
try
{
c.OpenWriteAsync(ub.Uri);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[input.Length];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, buffer.Length);
}
progressBar.Value += input.Length;
if (progressBar.Value >= progressBar.Maximum)
{
progressBar.Visibility = System.Windows.Visibility.Collapsed;
loadImage();
}
}
private void loadImage()
{
Uri ur = new Uri("http://mysite.com/upload/" + _fileName);
img1.Source = new BitmapImage(ur);
}
And this is receiver.ashx:
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString(); using (FileStream fs = File.Create(context.Server.MapPath("~/upload/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[stream.Length];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}

Related

SignalR. Timer is not stopping on the server

We are using SignalR for information exchange.
When the web browser is connected a timer starts, but it is not stopping when user close the browser.
Here is the code. starttimer function runs when browser connected.
When user disconnect the browser, timer still running on the server.
[HubName("myChatHub")]
public class InboundCallsDataShare : Hub
{
private OverrideTimer timer ;
private List<GroupNConnectionId> groupsList = new List<GroupNConnectionId>();
public void send(string message)
{
Clients.All.addMessage(message);
//Clients..addMessage(message);
}
public void starttimer(string queue)
{
//var connectionId = this.Context.ConnectionId;
//GroupNConnectionId objGroupNConnectionId=new GroupNConnectionId();
//objGroupNConnectionId.Group = queue;
//objGroupNConnectionId.ConnectionID = connectionId;
//if(groupsList.Contains(objGroupNConnectionId))return;
//////////////////////////////////////////////////////
//groupsList.Add(objGroupNConnectionId);
Groups.Add(this.Context.ConnectionId, queue);
timer = new OverrideTimer(queue);
timer.Interval = 15000;
timer.Elapsed +=new EventHandler<BtElapsedEventArgs>(timer_Elapsed);
//first time call
timer_Elapsed(timer,new BtElapsedEventArgs(){Queue = queue});
//ends
timer.Start();
Console.WriteLine("Timer for queue " +queue);
}
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected()
{
//timer.Stop();
return base.OnDisconnected();
}
public void getdatafromxml(string queue)
{
string list = (new Random()).Next(1, 10000).ToString();
Clients.All.getList(list);
//Clients..addMessage(message);
}
public ICBMObject GetInterationList(string queue)
{
//ININInterations.QueueListViewItemData _obj = new ININInterations.QueueListViewItemData();
return GetInboundCallCountFromXML(queue);
//return _obj.MainFunctionIB();
}
void timer_Elapsed(object sender, BtElapsedEventArgs e)
{
ICBMObject objICBMObject = GetInboundCallCountFromXML(e.Queue);
Clients.Group(e.Queue).getList(objICBMObject);
CreateFile(e.Queue);
//Clients.All.getList(objICBMObject);
}
private void CreateFile(string queue)
{
string path = #"D:\t.txt";
string text = File.ReadAllText(path);
text += queue+ DateTime.Now.ToString() + Environment.NewLine;
File.WriteAllText(path, text);
}
public ICBMObject GetInboundCallCountFromXML(string queue)
{
FileStream fs = null;
int totalInboundCalls = 0,
totalInboundCallsUnassigned = 0;
string longestDuration = "";
bool updateText = false;
try
{
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode;
int i = 0;
string str = null;
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "InboundXML/" + queue + ".xml",
FileMode.Open, FileAccess.Read);
if (fs.CanRead)
{
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName(queue);
for (i = 0; i <= xmlnode.Count - 1; i++)
{
totalInboundCalls = Convert.ToInt32(xmlnode[i].ChildNodes.Item(0).InnerText.Trim());
totalInboundCallsUnassigned = Convert.ToInt32(xmlnode[i].ChildNodes.Item(1).InnerText.Trim());
longestDuration = xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
}
updateText = true;
}
}
catch (Exception)
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
return new ICBMObject()
{
TotalInboundCalls = totalInboundCalls,
TotalInboundCallsUnassigned = totalInboundCallsUnassigned,
LongestDuration = longestDuration,
UpdateText = updateText
//string.Format("{0:D2}:{1:D2}:{2:D2}",
// _LongetInbound.Hours,
// _LongetInbound.Minutes,
// _LongetInbound.Seconds)
};
}
}
Besides the fact that its commented out? Did you put a break point on the timer to see if its getting hit at all? It might be that there is a delay in calling the onDisconnect, if the timeout property is set too large, it might not fire. it might be entering onReconnected if it does not know the client is closed.

How to pass image to Eval method from handler.ashx to imageurl?

I want to retrieve image from database and display in an aspx page. I use Linq to SQL. And a Generic handler.
Handler2.ashx code:
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["id"] != null)
{
int id;
string sid = context.Request.QueryString["id"];
if (int.TryParse(sid, out id))
{
Stream strm = getImage(id);
byte[] buffer = new byte[4096];
int i = strm.Read(buffer, 0, 4096);
while (i > 0)
{
context.Response.OutputStream.Write(buffer, 0, 4096);
i = strm.Read(buffer, 0, 4096);
}
}
else
{
//
}
}
}
public Stream getImage(int id)
{
using (DummyDBEntities cntx = new DummyDBEntities())
{
var db = from c in cntx.Images
where c.imageId == id
select c.imageData;
MemoryStream ms = new MemoryStream();
byte[] byteArray = new byte[db.ToArray().Length];
ms.Write(byteArray, 0, db.ToArray().Length);
return new MemoryStream(byteArray);
}
}
And a button control in Default.aspx page when I click, redirects to handler1.ashx. Gets the id of image from database and supposed to Show it in Default.aspx asp:image control
protected void btnGetID_Click(object sender, EventArgs e)
{
int id=Convert.ToInt32(txtGetID.Text);
Response.Redirect("Handler2.ashx?id="+id);
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
}
How do i supposed to write Eval method and the querystring to pass the image to imageurl?
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
Please help, thanks.
I hope I understood your problem right.
You want to display the image from your handler in the Image1. For that you can just do the following
Image1.ImageUrl = ResolveUrl("~/Handler2.ashx?id=" + id);

C# - TcpClient. Send data response after receive only works without iterate

My server receive some TCP/IP data and response to client:
private static void startClient(TcpClient clientSocket)
{
NetworkStream networkStream = null;
DateTime fecha = DateTime.Now;
try
{
clientSocket.NoDelay = true;
networkStream = clientSocket.GetStream();
string receiveData = readData(clientSocket);
string responseData = "abc"; //ProcessData(receiveData);
if (responseData != null)
writeData(networkStream, responseData);
}
catch (SocketException e)
{
throw;
}
finally
{
networkStream.Close();
}
}
private static string readData(TcpClient tcpClient)
{
try
{
var bytesFrom = new byte[tcpClient.ReceiveBufferSize];
StringBuilder dataFromClient = new StringBuilder();
int readCount;
while ((readCount = tcpClient.GetStream().Read(bytesFrom, 0, tcpClient.ReceiveBufferSize)) != 0)
{
dataFromClient.Append(Encoding.ASCII.GetString(bytesFrom, 0, readCount));
}
//int bytesRead = tcpClient.GetStream().Read(bytesFrom, 0, tcpClient.ReceiveBufferSize);
//string dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, bytesRead);
return dataFromClient.ToString();
}
catch (SocketException e)
{
throw;
}
}
private static void writeData(NetworkStream networkStream, string dataToClient)
{
Byte[] sendBytes = null;
try {
sendBytes = Encoding.ASCII.GetBytes(dataToClient);
networkStream.Write(sendBytes,0, sendBytes.Length);
networkStream.Flush();
}
catch(SocketException e)
{
throw;
}
}
With this solution the client never receives the response sent:
http://postimg.org/image/6srtslf2f/
However changing the reception to a single call to NetworkStream.Read ...
private static string readData(TcpClient tcpClient)
{
try
{
var bytesFrom = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = tcpClient.GetStream().Read(bytesFrom, 0, tcpClient.ReceiveBufferSize);
string dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, bytesRead);
return dataFromClient.ToString();
}
catch (SocketException e)
{
throw;
}
}
... the client receives the response
http://postimg.org/image/uih9hadfr/
UPDATE
I found solution here. I´ve fixed it using 2/3 ways described . First handle EOS end message. Seccond is setting receive timeout if client works bad and sends bad data without EOS:
private static string readData(TcpClient tcpClient)
{
var clientStream = tcpClient.GetStream();
var dataFromClient = string.Empty;
var buffer = new byte[RECEIVE_BUFFER_SIZE];
if (!clientStream.CanRead)
return "";
tcpClient.ReceiveTimeout = RECEIVE_TIMEOUT;
try
{
int readCount;
while ((readCount = clientStream.Read(buffer, 0, buffer.Length)) != 0)
{
dataFromClient += Encoding.ASCII.GetString(buffer, 0, readCount);
if (dataFromClient.EndsWith(EOS))
return dataFromClient;
}
return dataFromClient.ToString();
}
catch (Exception ex)
{
var socketExept = ex.InnerException as SocketException;
if (socketExept != null && socketExept.SocketErrorCode == SocketError.TimedOut)
Logger.Warn(string.Format("Se excedio el timeout de recepcion: {0} ms",RECEIVE_TIMEOUT));
else
Logger.Error(string.Format("Error leyendo el mensaje recibido"), ex);
return dataFromClient.ToString();
}
}

AESEncoder class is not supported on j2me chinese phone

I am using this encryption class in a J2ME app. My J2ME application works fine on all Nokia devices. The app doesn't work on the Chinese MIw200 phone. Perhaps this cryptography is not supported on that phone? Is there another solution or any other method to encrypt and decrypt?
Please help me. Thanks a lot in advance.
My code is below:
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class AESEncoder {
private SecretKeySpec keyspec;
private Cipher cipher;
private String secretkey;
public AESEncoder(String secretkey) {
this.secretkey = secretkey;
keyspec = new SecretKeySpec(secretkey.getBytes(), 0, 16, "AES");
// keyspec=new SecretKeySpec(key, offset, len, secretkey);
try {
cipher = Cipher.getInstance("AES/ECB/NoPadding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception {
if (text == null || text.length() == 0) {
throw new Exception("Empty string");
}
int encrypted = 0;
byte[] bytenc = null;//new byte[32];
byte[] input = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec);
// byte empty[]=padString(text).getBytes();
// encrypted = cipher.doFinal(padString(text).getBytes());
// encrypted=cipher.doFinal(padString(text).getBytes(), 0, 0, padString(text).getBytes(), 0);
input = padString(text).getBytes();
bytenc = new byte[input.length];
encrypted = cipher.doFinal(input, 0, input.length, bytenc, 0);
String str = new String(bytenc, 0, encrypted);
// encrypted=cipher.update(padString(text).getBytes(), 0, 0, 0, 0);
// System.out.println("Encrypted is:>>" + str);
// bytenc=hexToBytes(String.valueOf(encrypted));
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return bytenc;
}
public String encrypt_hsm(String text) throws Exception {
if (text == null || text.length() == 0) {
throw new Exception("Empty string");
}
String base64=null;
int encrypted = 0;
byte[] bytenc = null;//new byte[32];
byte[] input = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec);
// byte empty[]=padString(text).getBytes();
// encrypted = cipher.doFinal(padString(text).getBytes());
// encrypted=cipher.doFinal(padString(text).getBytes(), 0, 0, padString(text).getBytes(), 0);
input = padString(text).getBytes();
bytenc = new byte[input.length];
encrypted = cipher.doFinal(input, 0, input.length, bytenc, 0);
String str = new String(bytenc, 0, encrypted);
base64 = Base64.encode(bytenc);
// encrypted=cipher.update(padString(text).getBytes(), 0, 0, 0, 0);
// System.out.println("Encrypted is:>>" + str);
// bytenc=hexToBytes(String.valueOf(encrypted));
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return base64;
}
public byte[] decrypt(String code) throws Exception {
if (code == null || code.length() == 0) {
throw new Exception("Empty string");
}
int decrypted = 0;
byte[] bytedec = null;
byte[] input = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec);
// input=hexToBytes(code);
input = Base64ToBytes(code);
bytedec = new byte[input.length];
decrypted = cipher.doFinal(input, 0, input.length, bytedec, 0);
String str = new String(bytedec, 0, decrypted);
// System.out.println("Decrypted is:>>" + str);
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return bytedec;
}
public static String bytesToHex(byte[] bsData) {
int nDataLen = bsData.length;
String sHex = "";
for (int nIter = 0; nIter < nDataLen; nIter++) {
int nValue = (bsData[nIter] + 256) % 256;
int nIndex1 = nValue >> 4;
sHex += Integer.toHexString(nIndex1);
int nIndex2 = nValue & 0x0f;
sHex += Integer.toHexString(nIndex2);
}
return sHex;
}
public static byte[] hexToBytes(String str) {
if (str == null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
}
return buffer;
}
}
private static String padString(String source) {
char paddingChar = ' ';
int size = 32;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
// System.out.println("====>Pad String:" + source);
return source;
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private byte[] Base64ToBytes(String code) {
code = code.replace('-', '+');
code = code.replace('_', '/');
code = code.replace(',', '=');
System.out.println("Final Base 64:"+code);
byte[] aesString = Base64.decode(code);
// System.out.println("Base64 after decoding:"+new String(aesString));
return aesString;
}
}
Please post a stack trace. Otherwise we are all just guessing.
AES is a required cipher, sometime between v4 and v7. Spend some time and confirm that this cipher isn't available on the MIw200.
Someone getting "AES not available" on a Mac got some suggestions.
Try allowing the system to fall back to 3DES or DES, instead of forcing AES. Here's an example that tests encryption with each algorithm.
Try using the BouncyCastle API. Here is a how-to guide.

Encrypt and decrypt file in J2ME

I'm having problem decrypting an encrypted file in J2ME using bouncy castle.
What I'm trying to do is select a file to encrypt,write the encrypted file and try decrypt it back to its orginal form (write to another file for verification purpose).
I have this error when reading the encrypted file.
Stack Trace :
s: pad block corrupted
at j.a(+219)
at e.c(+38)
at e.b(+30)
at com.aaron.midlets.BluetoothServerMidlet.c(+134)
at com.aaron.midlets.BluetoothServerMidlet.b(+161)
at com.aaron.midlets.BluetoothServerMidlet.a(+67)
at com.aaron.midlets.BluetoothServerMidlet.startApp(+105)
at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
at com.sun.midp.main.Main.runLocalClass(Main.java:466)
at com.sun.midp.main.Main.main(Main.java:120)
Here are part of my code :
private void createEncryptFile() {
FileConnection fc = FileListingUtil.getFile("root1/", "test.encrypt");
try {
fc.create();
readAndEncrypt();
} catch (Exception e) {
}
}
private void readAndEncrypt() {
FileConnection fc = FileListingUtil.getFile("root1/", "test.original");
FileConnection fc2 = FileListingUtil.getFile("root1/", "test.encrypt");
try {
InputStream test = fc.openDataInputStream();
OutputStreamWriter output = new OutputStreamWriter(fc2.openOutputStream());
int fileSize = (int) fc.fileSize();
byte[] imgData = new byte[fileSize];
int bytesRead = 0;
while (bytesRead < fileSize) {
bytesRead += test.read(imgData, bytesRead, fileSize - bytesRead);
}
EncryptorUtil util = new EncryptorUtil("12345678");
try {
byte[] dataE = util.encrypt(imgData);
for (int y = 0; y < dataE.length; ++y) {
output.write((int) dataE[y]);
}
} catch (CryptoException ex) {
ex.printStackTrace();
}
test.close();
output.close();
createDecryptFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void createDecryptFile() {
FileConnection fc = FileListingUtil.getFile("root1/", "test.decrypt");
try {
fc.create();
readAndDecrypt();
} catch (Exception e) {
e.printStackTrace();
}
}
private void readAndDecrypt() {
FileConnection fc = FileListingUtil.getFile("root1/", "test.encrypt");
FileConnection fc2 = FileListingUtil.getFile("root1/", "test.decrypt");
try {
InputStream test = fc.openDataInputStream();
OutputStreamWriter output = new OutputStreamWriter(fc2.openOutputStream());
int fileSize = (int) fc.fileSize();
byte[] imgData = new byte[fileSize];
int bytesRead = 0;
while (bytesRead < fileSize) {
bytesRead += test.read(imgData, bytesRead, fileSize - bytesRead);
}
EncryptorUtil util = new EncryptorUtil("12345678");
try {
byte[] dataE = util.decrypt(imgData);
for (int y = 0; y < dataE.length; ++y) {
output.write((int) dataE[y]);
}
} catch (CryptoException ex) {
ex.printStackTrace();
}
test.close();
output.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
the last function will throw the exception.
I can see one problem. You write test.encrypt file as writer (which converts each byte into char, doubling it). You read it back as InputStream, which reads out bytes. So your encrypted data is corrupted.

Resources