TCP communication has a random delay - tcp

I made a very simple client->server program and it works as it should but sometimes it connects to server immideatly but in other cases it takes more than 20 seconds or it wont connect at all. It happens even if i start the client and server on SAME PC.
Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace TCPListener
{
class Program
{
static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect("95.102.185.157", 8001);
Console.WriteLine("Connected");
string message = Console.ReadLine();
NetworkStream stream = client.GetStream();
ASCIIEncoding ncoder = new ASCIIEncoding();
Byte[] transfer = ncoder.GetBytes(message);
stream.Write(transfer, 0, transfer.Length);
client.Close();
Console.ReadKey();
}
}
}
server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("192.168.1.12");
TcpListener listener = new TcpListener(ip, 8001);
listener.Start();
Console.WriteLine("Listening on " + ip.ToString());
Socket s = listener.AcceptSocket();
Console.WriteLine("Recieved socket" + s.RemoteEndPoint);
Byte[] b = new Byte[100];
s.Receive(b);
foreach (Byte byt in b)
{
Console.Write(Convert.ToChar(byt));
}
ASCIIEncoding ncoder = new ASCIIEncoding();
Byte[] message = ncoder.GetBytes("cud");
s.Send(message);
s.Close();
listener.Stop();
Console.ReadKey();
}
}
}

Related

.NET MAUI - SELECT UUID FROM Win32_ComputerSystemProduct

Is posible using this code in .NET Maui ?
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
string ComputerName = "localhost";
ManagementScope Scope;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName),
null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT UUID FROM Win32_ComputerSystemProduct");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}", "UUID", WmiObject["UUID"]);// String
}
Console.Read();
}
}
}
Thank you.

Retrieve name and image from database where image is stored as upload folder and reference is stored in database?

Trying the following code but could't get the desired result.
I have stored the image in the upload folder and its reference is saved in database while storing the data in the database from the admin side.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Admin
{
public partial class fetch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs =
ConfigurationManager.ConnectionStrings["DBSC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUploadImage", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter ParamId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(ParamId);
con.Open();
byte[] Bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
FileUpload1.ImageUrl = "data:image/png;base64, +strBase64";
}
}
}
}

Unable to access a file to be deleted in a qr code programme

I have a qr code asp.net web form and I am getting an error
System.IO.IOException: 'The process cannot access the file 'C:\Users\Asus.DESKTOP-BTB81TA\Desktop\bikestop\bikestop\images\qr code stuff\fileName.png' because it is being used by another process.'
in one of my lines :
File.Delete(filePath2);
Here is the full code :
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.IO; //For MemoryStream
using System.Web.Services; //For WebMethod attribute
using Bytescout.BarCode;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Text;
using System.IO;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using ZXing;
using ZXing.Aztec;
namespace bikestop
{
public partial class bookRide : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
// int i = 0;
protected void Scan_Click(object sender, EventArgs e)
{
Rectangle rect = new Rectangle(0, 0, 2000, 1000);
string filePath = AppDomain.CurrentDomain.BaseDirectory;
string filePath2;
filePath2 = #"" + filePath + "\\images\\qr code stuff\\fileName.png";
//do stuff
using (Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
}
if (System.IO.Directory.Exists(filePath2) == true)
{
bmp.Save(filePath2, ImageFormat.Png);
bmp.Dispose();
}
else
{
File.Delete(filePath2);
bmp.Save(filePath2, ImageFormat.Png);
bmp.Dispose();
}
try
{
IBarcodeReader barcodeReader = new BarcodeReader();
var barcodeBitmap = (Bitmap)Bitmap.FromFile(filePath2);
var barcodeResult = barcodeReader.Decode(barcodeBitmap);
Output.Text = barcodeResult.Text;
Output.NavigateUrl = barcodeResult.Text;
}
catch
{
Output.Text = "No barcode found";
}
}
}
}
}

How to get data from API on POST method

I have to accesss an get some data from one of API.This API has only mentoned this method.No documentation showing how to acess and all.Data will be returned as Json.
This is the product API
1. GetAllProducts
POST
http://api.domain.com/api/Products/All
Content-Type: application/json; charset=utf-8
{"Token":"EncryptedToken"}
I have generated the Token and I tried to access it like this.But nothing is recieving.I found an example and tried to do like this.May be this is wrong.Can any one show me how to access and get the data.Please see my code below and thanks in advanced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Web.Script;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Text;
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All?Token=U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_");
request.Method = "POST";
string postData = "Data to post here";
byte[] post = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
}
}
I think you should change these things:
content type
request.ContentType = "application/json";
the post data
string postData = "{\"Token\":\"U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_\"}";
the URI
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All");

Error CS1729: 'Attachment' does not contain a constructor that takes 2 arguments

I am trying to send mail with attachment through smtp protocol, so I found this tutorial in http://csharpdotnetfreak.blogspot.com/2009/10/send-email-with-attachment-in-aspnet.html. And tried the following simple coding, the object got created correctly for attachment but it tell me the error that does not take 2 arguments.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
public partial class composemail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendMail()
{
MailMessage mail = new MailMessage();
mail.To.Add(YourEmail.Text);
mail.From = new MailAddress(YourName.Text);
mail.Subject = YourSubject.Text;
mail.Body = Comments.Text;
mail.IsBodyHtml = true;
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SendMail();
}
}
As M4N mentioned you cannot have code directly in the class. You need to encapsulate it in a method:
using System.IO;
using System.Net.Mail;
namespace AttachmentTest
{
class Program
{
static void Main(string[] args)
{
var mail = new MailMessage();
var fs = new FileStream("somepath", FileMode.Open);
var att = new Attachment(fs, "");
mail.Attachments.Add(att);
}
}
}

Resources