Check SerialPort Exist Modem? - c#-2.0

In C# 2005, I used the Nokia E63, I want to check SerialPort Exist Modem, While it run does not get run COM port, you see my code
private void btnGetPort_Click(object sender, EventArgs e)
{
cmbPort.Items.Clear();
foreach (string portName in SerialPort.GetPortNames())
{
try
{
using (SerialPort sp = new SerialPort(portName, 9600))
{
if (!(sp.IsOpen)) sp.Open();
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
sp.Write("AT\r\n");
System.Threading.Thread.Sleep(100);
string response = sp.ReadExisting();
if (response == "OK")
{
cmbPort.Items.Add(portName);
}
}
}
catch (Exception ex)
{
continue;
}
}
}

Related

Close(kill) another app in my application by package name

I would like to close(kill) another app in my application by package name. I am trying something like this, but this code don't close any app. what am i doing wrong?
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
IList<RunningAppProcessInfo> runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.SendSignal(runningProcess.Pid, Signal.Kill);
am.KillBackgroundProcesses(runningProcess.ProcessName);
}
}
}
P.S I added android.permission.KILL_BACKGROUND_PROCESSES and by this code i can close only my own app
If you want to kill a background app , check the following code
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
var runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.KillProcess(runningProcess.Uid);
}
}
}
And if you want to kill a foreground app, you could use Adb
public class SuUtil
{
private static Java.Lang.Process process;
public static void kill(string packageName)
{
initProcess();
killProcess(packageName);
close();
}
private static void initProcess()
{
if (process == null)
try
{
process = Runtime.GetRuntime().Exec("su");
}
catch (IOException e)
{
}
}
private static void killProcess(string packageName)
{
System.IO.Stream output = process.OutputStream;
Java.Lang.String cmd = new Java.Lang.String("am force-stop " + packageName + " \n");
try
{
output.Write(cmd.GetBytes());
output.Flush();
}
catch (IOException e)
{
}
}
private static void close()
{
if (process != null)
try
{
process.OutputStream.Close();
process = null;
}
catch (IOException e)
{
}
}
}

Vaadin upload with PipedInputStream & PipedOutputStream example

I just started learning Vaadin 8 and my first example is Upload button. I was stuck with an issue where I could not solve the problem for many hours and hours.
Here it is,
I am returning PipedOutputStream in the receiveUpload method,
Here is the code for receiveUpload method,
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
pipedInputStream = new PipedInputStream(pipedOutputStream);
if (filename == null || filename.trim().length() == 0) {
upload.interruptUpload();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return pipedOutputStream;
}
In the uploadSucceeded method, I need to take the pipedinputstream and send it another method to load the stream into the database
public void uploadSucceeded(SucceededEvent event) {
try {
fileUploadOperation.upload(pipedInputStream); --> I need to push all the stream data in one go into a method to generate a file at the business layer
} catch (Exception e) {
e.printStackTrace();
}
}
When I was running the application, it hangs out for a long time and I could not figure out where it is. Later I could notice that both piped input and piped output streams should be created in separate threads or at least one of them in a separate thread but don't know how to handle it.
Any help
I am pasting the complete class for more information,
public class WebCommunityView implements Receiver, FailedListener, SucceededListener, StartedListener, FinishedListener {
private PipedOutputStream pipedOutputStream = null;
private PipedInputStream pipedInputStream = null;
private Upload upload = null;
private String fileName = null, mimeType = null;
private Grid<FileListProperties> fileListGrid = null;
public final static WebCommunityView newInstance(WebContentScreen screen) {
vw.initBody();
return vw;
}
protected void initBody() {
VerticalLayout verticalLayout = new VerticalLayout();
fileListGrid = new Grid<FileListProperties>();
fileListGrid.addColumn(FileListProperties::getCreatedDate).setCaption("Date");
fileListGrid.addColumn(FileListProperties::getFileName).setCaption("File Name");
fileListGrid.addColumn(FileListProperties::getUserName).setCaption("User Name");
fileListGrid.addComponentColumn(this::buildDownloadButton).setCaption("Download");
fileListGrid.setItems(loadGridWithFileInfo());
upload = new Upload("", this);
upload.setImmediateMode(false);
upload.addFailedListener((Upload.FailedListener) this);
upload.addSucceededListener((Upload.SucceededListener) this);
upload.addStartedListener((Upload.StartedListener) this);
upload.addFinishedListener((Upload.FinishedListener) this);
Label fileUploadLabel = new Label("Label"));
verticalLayout.addComponent(currentListLabel);
verticalLayout.addComponent(fileListGrid);
verticalLayout.addComponent(fileUploadLabel);
verticalLayout.addComponent(upload);
mainbody.addComponent(verticalLayout);
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
//Model Layer
fileUploadOperation.upload(pipedInputStream);
fileUploadOperation.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null) {
Notification.show("Upload failed", Notification.Type.HUMANIZED_MESSAGE);
}
try {
//Model Layer
fileUploadOperation.abort();
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
new Thread() {
public void run() {
try {
System.out.println("pipedInputStream Thread started");
pipedInputStream = new PipedInputStream(pipedOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
if (filename == null || filename.trim().length() == 0) {
screen.displayMessage("Please select a file to upload !", WebContentScreen.MESSAGE_TYPE_WARNING);
upload.interruptUpload();
} else {
Properties properties = new Properties();
properties.setProperty("NAME", fileName);
properties.setProperty("MIME_TYPE", mimeType);
//Model Layer
fileUploadOperation.initialize(properties);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("pipedOutputStream:"+pipedOutputStream);
return pipedOutputStream;
}
private List<FileListProperties> loadGridWithFileInfo() {
List<FileListProperties> list = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
list = new ArrayList<FileListProperties>(1);
Collection<FileInfo> fileInfoList = fileCommandQuery.lstFilesForDownload();
for (Iterator iterator = fileInfoList.iterator(); iterator.hasNext();) {
FileInfo fileInfo = (FileInfo) iterator.next();
Properties properties = fileInfo.getProperties();
Collection<String> mandatoryParameters = fileInfo.getMandatoryProperties();
FileListProperties fileListProperties = new FileListProperties();
for (Iterator iterator2 = mandatoryParameters.iterator(); iterator2.hasNext();) {
String key = (String) iterator2.next();
String value = properties.getProperty(key);
if (key != null && key.equalsIgnoreCase("NAME")) {
fileListProperties.setFileName(value);
} else if (key != null && key.equalsIgnoreCase("USER_NAME")) {
fileListProperties.setUserName(value);
} else if (key != null && key.equalsIgnoreCase("CREATED_DATE")) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1550566760000L);
fileListProperties.setCreatedDate(dateFormat.format(calendar.getTime()));
}
}
if (fileListProperties != null) {
list.add(fileListProperties);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dateFormat = null;
}
return list;
}
private Button buildDownloadButton(FileListProperties fileListProperties) {
Button button = new Button("...");
button.addClickListener(e -> downloadFile(fileListProperties));
return button;
}
private void downloadFile(FileListProperties fileListProperties) {
}
}
The problem in your example is that you need to do the actual file handling in a separate thread. The Viritin add-on contains a component called UploadFileHandler that simplifies this kind of usage a lot. It will provide you InputStream to consume. The integration test for the component contains this kind of usage example.
Also, my recent blog entry about the subject might help.

how to connect TCP Socket server client with authentication in Dart

I have a java and .Net solution, but now i need to implement in Dart please help me out.
This is may java source
private Handler handler;
private int iCounter =1;
public StartQuickClient(int InstanceId)
{
try
{
handler = MarketData.GetInstance();
handler.setEventHandler(this);
handler.setAddress("122.184.137.44");
handler.setPort(9898);
handler.setUserCredentials("PREM", "xxxxx");
if (handler.connect())
{
System.out.println("Connect initiated "+ InstanceId);
}
else
{
System.out.println("Connect failed ");
}
}
catch (Exception e)
{
}
}
public static void main(String[] args) {
Random rnd = new Random();
int InstanceId = rnd.nextInt(9999);
StartQuickClient startQuickClient = new StartQuickClient(InstanceId);
}
This is the connect method:
public boolean connect()
{
try {
if (quickEvent == null) {
throw new Exception("No event handler is set, will not initiate the connection");
}
if (configuration.SERVER_ADDRESS == null) {
throw new Exception("Blank Server Address");
}
if (configuration.SERVER_PORT <= 0) {
throw new Exception("Blank Server Port");
}
tcpConnection = new TcpConnection(this, configuration);
if (isNewVersionAuthentication) {
tcpConnection.enableNewversionAuthentication();
}
tcpConnection.connect();
} catch (Exception e) {
e.printStackTrace();
mLog.error("No event handler is set and Blank Server Address,Port will not initiate the connection :" + e.getMessage());
return false;
}
return true;
}
please help me out if any one knows, i am new for dart,need any plug or how to do

xamarin.forms android service run twice after restarting it

I have this code that create an android service
[Service]
public abstract class LongRunningTaskService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Logs.Info("service started: " + this.GetType().ToString());
try
{
Tasks.RunTask(() =>
{
try
{
Task.run(() => SomeTaskFunction);
StopSelf();
Logs.Info("service ended successfully from main task");
}
catch (Android.OS.OperationCanceledException e)
{
Logs.Warning("Error in Tasks.RunTaskWithoutWaitForResult", e);
}
});
return StartCommandResult.NotSticky;
}
catch (Exception e)
{
Logs.Warning("error in OnStartCommand", e);
return StartCommandResult.NotSticky;
}
}
public override void OnDestroy()
{
try
{
Logs.Info("service destroyed: " + this.GetType().ToString());
base.OnDestroy();
}
catch (Exception e)
{
Logs.Warning("Error in service destroyed: " + this.GetType().ToString(), e);
}
}
}
when i create the service the first time it works ok, but when i destroy it from outside the service and recreate it with the same function to run there are 2 tasks running at the same time.
what am i doing wrong ?

Print in Android using a printer with IP address and Port number

My query is I have a printer connected to the Wifi and I am able to connect to that printer using the IP address of the printer but I am not able to print from that printer.
MY code:-
class MakeConnection extends AsyncTask<String, Void, String>{
String check = "NO";
#Override
protected String doInBackground(String... params) {
Socket sock = null;
PrintWriter oStream = null;
try
{
sock = new Socket(ipAddress, 9100);
oStream = new PrintWriter(sock.getOutputStream());
oStream.write("HI,test from Android Device");
check = "yes";
oStream.flush();
}
catch (IOException e)
{
e.printStackTrace();
Logger.LogError(TAG, e.toString());
AppToast.showShortToast(mContext, e.toString());
}
finally {
oStream.close();
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
Logger.LogError(TAG, check);
super.onPostExecute(s);
}
}
where I am wrong?

Resources