Credential handles keeps going in process monitor - c#

Here I use the Microsoft Performance monitor to check the credentials handle for my c# application. I find the credentials handle keeps growing up. You can open performance monitor and add a "credentials handle" counter under "Security Per-Process Statistics". Will it cause handle leak? Will the handle be collected by GC? How can I use windbg or other tools to analyze this issue?
Here is my sample program:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DBTest
{
class DBTest2
{
class Program
{
[SuppressMessage("ReSharper", "InconsistentlySynchronizedField")]
static void Work(object data)
{
var dbConn = new SqlConnection("*********");
SqlConnection.ClearPool(dbConn);
dbConn.Open();
string sqlQuery = "SELECT DBName = name FROM master..sysdatabases WHERE name = #DBName";
using (var command = new SqlCommand(sqlQuery, dbConn) { CommandTimeout = 300 })
{
command.Parameters.Add(new SqlParameter("#DBName", SqlDbType.NVarChar) { Direction = ParameterDirection.Input, Value = "***" });
command.ExecuteScalar();
}
dbConn.Close();
}
static void Main(string[] args)
{
Timer tmr = new Timer(Work, "tick...", 1000 * 60 * 1, 30 * 1000);
Console.ReadLine();
tmr.Dispose();
return;
}
}
}
}

Put your SqlConnection in a using block as well:
using (var dbConn = new SqlConnection("*********"))
{
}

Related

C# Windows Service not connecting to Brainbox device

I am new to C# and the code below is a mashup of a Microsoft tutorial and a simple program that I created (which works on its own), so I apologize now.
The service part appears to be working. Windows is running the service and I am getting event log messages saying that the service is running.
What I am not seeing is that the server is connected to the Brainbox device (192.168.10.174) I can see this by looking at the webpage of the Brainbox device. I am guessing that I am missing something really obvious. As the Brainbox_Data program runs perfectly well on its own in a console app.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Configuration;
using Brainboxes.IO;
namespace MyNewService
{
public partial class MyNewService : ServiceBase
{
public MyNewService()
{
InitializeComponent();
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart. NEW");
BrainboxData();
Timer timer = new Timer();
timer.Interval = 60000; // 60 seconds
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}
protected override void OnStop()
{
eventLog1.WriteEntry("In OnStop.");
}
private int eventId = 1;
public void OnTimer(object sender, ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
eventLog1.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
}
static void BrainboxData()
{
string provider = ConfigurationManager.AppSettings
["provider"];
string connectionString = ConfigurationManager.AppSettings
["connectionString"];
DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
DbCommand command = factory.CreateCommand();
command.Connection = connection;
using (EDDevice ed = EDDevice.Create("192.168.10.174"))
{
ed.Label = "TrumpfE";
ed.Inputs[0].IOLineRisingEdge += (line, device, changeType) =>
{
command.CommandText = "INSERT INTO dbo.Brainbox_Data (datetimestamp, iolintimee, value, IPAddress) VALUES (GETDATE(),'" + line + "' , 1, '192.168.10.174')";
command.ExecuteNonQuery();
};
ed.Inputs[1].IOLineRisingEdge += (line, device, changeType) =>
{
command.CommandText = "INSERT INTO dbo.Brainbox_Data (datetimestamp, iolintimee, value, IPAddress) VALUES (GETDATE(),'" + line + "' , 0, '192.168.10.174')";
command.ExecuteNonQuery();
};
}
}
}
}
}
Any help would be greatly accepted.

How to execute a scheduled task with “schtasks” without opening a new command line window using C# process?

I am trying to run a scheduled task from C# without opening a new command line window, using the following code without any success (it prompts a window every time I use it)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
Process p1 = new Process();
p1.StartInfo.FileName = #"C:\Windows\System32\schtasks.exe";
p1.StartInfo.Verb = "runas";
p1.StartInfo.Arguments = "/run /tn CCleaner";
p1.StartInfo.RedirectStandardOutput = true;
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.StartInfo.CreateNoWindow = true;
p1.Start();
p1.Close();
}
catch (Exception ex)
{
}
}
}
}
How could I solve this problem ?
Thank you so much for your attention
You can use a library that provides access to Task Scheduler API.
For example using http://taskscheduler.codeplex.com/
using (var ts = new TaskService())
{
Task task = ts.GetTask("My task");
task.Run();
}

Background Agent Not Performing.: Windows Phone 8

NEED A SOLUTION
Background agent is working only once. After There is no occurrence of a background agent. It works at the first time and it works perfectly as soon as the page opens. however, after that it takes forever and ever to do that again. sometimes page close and open doesn't work. that would probably because of not removing the agenet
My background Agent Code:
#define DEBUG_AGENT
using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Xna.Framework.Media;
using System.Windows.Input;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
//private DispatcherTimer s;
Socket _socket = null;
ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
double lat = 7.16126666666667;
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
string toastTitle = "";
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
lat += 0.001;
string snmea = DD2NMEA(lat, 80.44506);
string dates = DateTime.UtcNow.ToString("ddMMyy");
string UTCTime = DateTime.UtcNow.ToString("hhmmss") + ".000";
string s1 = Checksum("$FRCMD,869444005499999,_SendMessage,,0809.67600,N,8050.70360,E,1.0,1.08,3.0,141013,055642.000,1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
string s = Send("$FRCMD,869444005499999,_SendMessage,," + snmea + ",1.0,1.08,3.0," + dates + "," + UTCTime + ",1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
startToastTask(task, toastTitle);
}
private void startToastTask(ScheduledTask task, string toastTitle)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
My Page from app which calls the agent
PeriodicTask toastPeriodicTask;
const string toastTaskName = "ToastPeriodicAgent";
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
toastPeriodicTask = ScheduledActionService.Find(toastTaskName) as PeriodicTask;
StartPeriodicAgent(toastTaskName);
}
private void StartPeriodicAgent(string taskName)
{
toastPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (toastPeriodicTask != null)
{
RemoveAgent(taskName);
}
toastPeriodicTask = new PeriodicTask(taskName);
toastPeriodicTask.Description = periodicTaskDesc;
try
{
ScheduledActionService.Add(toastPeriodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(2));
#endif
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
}
else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
{
MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
}
else
{
MessageBox.Show("An InvalidOperationException occurred.");
}
}
catch (SchedulerServiceException)
{
}
}
Ensure that your project has DEBUG_AGENT defined. This is a setting within your project properties. To set this flag, follow these steps
Right click the project within VS and select Properties
Select the Build tab
Add DEBUG_AGENT to the "Conditional compilation symbols" field.
If that is set, I've found it's best to give at least 30 seconds in the LaunchForTest. Sometimes it doesn't quite schedule it when you tell it to.

C# Program stops responding after second WebClient.DownloadString()

I am working on a program for proof of concept that does a webrequest using WebClient.DownloadString("http://website/members/login.php?user=" + textBox1.Text + "&pass=" + textBox2.Text);
to get the boolean value of wether or not the user is a valid login and then if it is it gives a success notification if it isn't ten it gives a fail notification.
The problem is when i press the button to try and login the first time it works fine but when i press it again the second tine the program freezes and gets stuck at the Webclient.download string.
If anyone can spot and tell me whats wrong that would be great. I am providing the code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public static WebClient webclient = new WebClient();
HttpWebResponse wResp;
WebRequest wReq;
bool isConnected = false;
private String Session = "";
public Form1()
{
InitializeComponent();
}
public Boolean checkUser(String username, String password)
{
String login = `webclient.DownloadString("http://connorbp.info/members/auth.php?user=" + textBox1.Text + "&pass=" + textBox2.Text);`
Boolean bLogin = Boolean.Parse(login);
if (bLogin)
{
Session = username + "-" + password;
}
return bLogin;
}
public int CanConnect(string dUrl)
{
wReq = WebRequest.Create(dUrl);
int cnt = Connect();
return cnt;
}
private int Connect()
{
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
isConnected = true;
return 1;
}
catch (Exception)
{
return 0;
}
}
private void button1_Click(object sender, EventArgs e)
{
int init = CanConnect("http://connorbp.info/members/auth.php");
if (init == 0)
{
notifyIcon1.ShowBalloonTip(200, "CBP Login", "Failed to connect to server! Try again later.", ToolTipIcon.Error);
}
else
{
if(checkUser(textBox1.Text, textBox2.Text))
{
notifyIcon1.ShowBalloonTip(20, "CBP Login", "Logged In!", ToolTipIcon.Info);
}
else
{
notifyIcon1.ShowBalloonTip(20, "CBP Login", "Invalid Username/Password!", ToolTipIcon.Error);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
notifyIcon1.ShowBalloonTip(20, "CBP Login", "for more cool things go to http://connorbp.info", ToolTipIcon.Info);
}
}
}
You are not closing the response.
The second call is trying to open something that is already open, therefore it hangs.

when i running the below code iam getting handle is invalid it takes a string and pass it to remote batch file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError

Categories