How I can switch to different users desktops from windows service - c#

I am trying to record a video of a user desktop when he logged in via RDP, the monitoring is based on the windows service onSessionChange event, due the nature of it then I am facing what is so called Session 0 isolation, so what I am looking for is how to switch to the logged in user in order to be able record his session?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
namespace RdpMonitoringService
{
struct RdpSession
{
public int sessionId;
public string userName;
public string ipAddress;
public string sessionDateTime;
public string recordFileName;
public Recorder sessionRecorder;
public string generateRecordFileName()
{
string dirName = "RecordedSessions";
string path = AppDomain.CurrentDomain.BaseDirectory + "\\" + dirName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\" + dirName + "\\" + userName + " - " + sessionDateTime + ".mp4";
return filepath;
}
public override string ToString()
{
return "SessionId: " + sessionId + ", userName: " + userName;
}
}
public partial class RdpMonitoringService : ServiceBase
{
RdpSession onRdpSession;
Dictionary<int, RdpSession> rdpSessionList;
public RdpMonitoringService()
{
InitializeComponent();
this.CanPauseAndContinue = true;
this.CanHandleSessionChangeEvent = true;
rdpSessionList = new Dictionary<int, RdpSession>();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at: ============ " + DateTime.Now);
WriteToFile("this.CanHandleSessionChangeEvent: " + this.CanHandleSessionChangeEvent);
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
protected override void OnSessionChange(SessionChangeDescription sessionChangeDescription)
{
try {
var userInfo = TermServicesManager.GetSessionInfo(Dns.GetHostEntry("").HostName, sessionChangeDescription.SessionId);
IPAddress ipAddress = new IPAddress(userInfo.ClientAddress.Address.Skip(2).Take(4).ToArray());
if (!rdpSessionList.ContainsKey(sessionChangeDescription.SessionId))
{
onRdpSession.sessionId = sessionChangeDescription.SessionId;
onRdpSession.ipAddress = ipAddress.ToString();
onRdpSession.userName = userInfo.UserName;
onRdpSession.sessionDateTime = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss");
onRdpSession.recordFileName = onRdpSession.generateRecordFileName();
//onRdpSession.sessionRecorder = Recorder.CreateRecorder();
//onRdpSession.sessionRecorder.Record(onRdpSession.generateRecordFileName());
rdpSessionList.Add(sessionChangeDescription.SessionId, onRdpSession);
}
else
{
onRdpSession = rdpSessionList[sessionChangeDescription.SessionId];
}
WriteToFile("SessionChange event");
switch (sessionChangeDescription.Reason)
{
case SessionChangeReason.SessionLogon:
case SessionChangeReason.RemoteConnect:
case SessionChangeReason.SessionUnlock:
WriteToFile("SessionChange" + DateTime.Now.ToLongTimeString() + ", SessionUnlock|RemoteConnect|SessionLogon [" + sessionChangeDescription.SessionId.ToString() + "]" + ", User: " + userInfo.UserName + ", Connect state: " + userInfo.ConnectState.ToString() + ", Client address: " + ipAddress.ToString() + ", user: " + userInfo.UserName + ", WinStationName: " + userInfo.WinStationName.ToString());
// Currently the bellow line crash the service because there is no desktop
// onRdpSession.sessionRecorder = new Recorder(new RecorderParams(onRdpSession.generateRecordFileName(), 60, SharpAvi.KnownFourCCs.Codecs.MotionJpeg, 70));
// Switch to the user desktop based on his session id and start recording
break;
case SessionChangeReason.SessionLock:
case SessionChangeReason.SessionLogoff:
case SessionChangeReason.RemoteDisconnect:
WriteToFile("SessionChange: " + onRdpSession.ToString() + ", " + DateTime.Now.ToLongTimeString() + " RemoteDisconnect|SessionLogoff|SessionLock [" + sessionChangeDescription.SessionId.ToString() + "]" + ", User: " + userInfo.UserName + ", Connect state: " + userInfo.ConnectState.ToString() + ", Client address: " + ipAddress.ToString() + ", user: " + userInfo.UserName + ", WinStationName: " + userInfo.WinStationName.ToString());
onRdpSession.sessionRecorder.Dispose();
break;
default:
break;
}
}
catch(Exception ex)
{
WriteToFile("SessionChange exception: " + ex.Message + " || " + sessionChangeDescription.SessionId.ToString() + " || " + onRdpSession.sessionId.ToString());
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}

Related

Is there any way to make a global C# String?

Is there any way to share a string in C#? The string is not written in this code, but I want to share it between the public partial class MainWindow : Window and class Program. I am trying to string "{0} ({1}) {2}", course.Name, course.Id, course.CourseState into string name Courses to put into a Label. Thank you
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Threading;
namespace Azimuth_Home
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
System.Windows.Threading.DispatcherTimer Timer = new System.Windows.Threading.DispatcherTimer();
public string? MessagIn { get; set; }
public MainWindow()
{
InitializeComponent();
Timer.Tick += new EventHandler(Timer_Click);
Timer.Interval = new TimeSpan(0, 0, 1);
Timer.Start();
DataContext = this;
}
private void Timer_Click(object sender, EventArgs e)
{
DateTime d;
d = DateTime.Now;
ClockLabelHome.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelHome.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelHome.FontSize = 20;
ClockLabelNews.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelNews.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelNews.FontSize = 20;
ClockLabelWork.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelWork.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelWork.FontSize = 20;
ClockLabelChat.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelChat.FontFamily = new FontFamily("Uni Sans Regular");
ClockLabelChat.FontSize = 20;
if (d.Minute < 10)
{
ClockLabelHome.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelNews.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelWork.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelChat.Content = "Local Time: " + d.Hour + " : 0" + d.Minute + " : " + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
}
if (d.Second < 10)
{
ClockLabelHome.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelNews.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelWork.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
ClockLabelChat.Content = "Local Time: " + d.Hour + " : " + d.Minute + " : 0" + d.Second + "; " + d.Year + "/" + d.Month + "/" + d.Day;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(MessagIn);
}
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
MessageInput.Text = "You Entered: " + MessageInput.Text;
}
}
}
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/classroom.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { ClassroomService.Scope.ClassroomCoursesReadonly };
static string ApplicationName = "Classroom API .NET Quickstart";
private static void main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Classroom API service.
var service = new ClassroomService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define request parameters.
CoursesResource.ListRequest request = service.Courses.List();
request.PageSize = 10;
// List courses.
ListCoursesResponse response = request.Execute();
Console.WriteLine("Courses:");
if (response.Courses != null && response.Courses.Count > 0)
{
foreach (var course in response.Courses)
{
Console.WriteLine("{0} ({1}) {2}", course.Name, course.Id, course.CourseState);
}
}
else
{
Console.WriteLine("No courses found.");
}
Console.Read();
}
}
}
Thank you very much.
You apparently want the same combination of Name, Id and CourseState for every time you want to "print a course". The standard way to do that is to override the ToString method:
public class Course
{
//...
public override string ToString()
{
return String. Format("{0} ({1}) {2}", Name, Id, CourseState);
}
}
And if you then Console.WriteLine(course), that ToString method is called by default.

Error log inside thread not working sometime

I am calling following method inside thread. inside method i have written logs which writes some variable values in notepad file.
Problem : Sometime last log of method do not log anything. ie last line not exucuting sometime. i am not able to understand problem. please guide me if there are issue somewhere.
This is web application hosted in iis server.
Function :
public bool ResetEmployeeAssignedCoursesByRole()
{
bool bReturn = false;
DbTransactionHelper dbTransactionHelper = new DbTransactionHelper();
dbTransactionHelper.BeginTransaction();
try
{
// this line execuete fine
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Started " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
StringBuilder sbQueryEmployeeCourse = new StringBuilder();
sbQueryEmployeeCourse.Append(" set #roleID = " + roleID + "; ");
sbQueryEmployeeCourse.Append(" set #courseID = " + courseID + "; ");
sbQueryEmployeeCourse.Append(" set #inActiveReason = " + inActiveReason + "; ");
sbQueryEmployeeCourse.Append(" set #lastRecordUpdateSource = " + lastRecordUpdateSource + "; ");
sbQueryEmployeeCourse.Append(" call sp_Reset_EmpAssignedCoursesByRole (#roleID, #courseID, #inActiveReason, #lastRecordUpdateSource); ");
DataTable dtEmployeeCourse = dbTransactionHelper.GetDataTable(BusinessUtility.GetString(sbQueryEmployeeCourse), CommandType.Text, null
);
dbTransactionHelper.CommitTransaction();
bReturn = true;
// this line not execuete sometime.
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
}
catch (Exception ex)
{
ErrorLog.createRoleLog("Add Role ID " + BusinessUtility.GetString(roleID));
dbTransactionHelper.RollBackTransaction();
ErrorLog.createRoleLog("Add Course ID " + BusinessUtility.GetString(courseID));
ErrorLog.createRoleLog(ex.ToString());
}
return bReturn;
}
Calls method like below :
Thread t = new Thread(ResetEmployeeAssignedCoursesByRole);
t.Start();
FUNCTION createRoleLog :
public static void createRoleLog(string errorMessage, int empHdrID = 0)
{
try
{
//string path = BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogsDiractory")) + "Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string path = BusinessUtility.GetString(ErrorLog.ErrorLogPath) + "RoleLog" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogError")).ToString().ToUpper() == "TRUE")
{
if (!File.Exists(path))
{
StreamWriter sw = File.CreateText(path);
sw.Close();
}
//using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
//{
// sw.WriteLine("-------- " + DateTime.Now + " --------");
// sw.WriteLine(errorMessage);
// sw.WriteLine("------------------------");
// sw.Close();
//}
if (!IsFileLocked(new FileInfo(path)))
{
using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (System.IO.StreamWriter sw = new StreamWriter(stream))
{
if (empHdrID != 0)
{
sw.WriteLine("-------- [empHdrID: " + empHdrID + "] " + DateTime.Now + " --------");
}
else
{
sw.WriteLine("-------- " + DateTime.Now + " --------");
}
sw.WriteLine(errorMessage);
sw.WriteLine("------------------------");
sw.Close();
}
}
}
else
{
}
}
}
catch (Exception ex)
{
//throw ex;
}
}
Last line of function which not execution sometime is :
** this line not execuete sometime.**
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);

WCF Proxy Sending Data To Proxy

I do simple app like database management and because from server to client. Here is my method below:
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new
{
try
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
List<string> pracownicy = new List<string>();
foreach (var ps in query)
{
Console.WriteLine(ps.Title);
Console.WriteLine(ps.FirstName);
Console.WriteLine(ps.LastName);
Console.WriteLine(ps.Address);
}
}
catch (System.InvalidOperationException)
{
string blad="It's an error";
}
}
return pracownikDane;
}
And it's shows my this data in server Console like this:
And here is my code in a client:
string pdane = Console.ReadLine();
PracownikDane data = proxy.GetPracownik(pdane);
Console.WriteLine(" ");
Console.WriteLine("Zawód:" + " " + data.Tytul);
Console.WriteLine("Imie:" + " " + data.Imie);
Console.WriteLine("Nazwisko:" + " " + data.Nazwisko);
Console.WriteLine("Kraj Pochodzenia:" + " " + data.Kraj);
Console.WriteLine("Miasto:" + " " + data.Miasto);
Console.WriteLine("Adres:" + " " + data.Adres);
Console.WriteLine("Telefon:" + " " + data.Telefon);
Console.WriteLine("Strona WWW:" + " " + data.WWW);
Console.ReadLine();
I would like to know how to put this data in Client.

Log Exception Error on Network

I want to log Exception in case of error on network. I have made changes in global.asax file and generated log file in it. The code works fine on localhost but when I upload the dll of global.asax file on another server and change the web config according to network credentials similar to the localhost. In case of error the method doesnot seem to work nor the file is created to write the exception. Please help
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
try
{
DffUtility.AddCookie("verystart", "Very start of error");
Exception exc = Server.GetLastError();
Uri refurl = Request.UrlReferrer;
DffUtility.AddCookie("star655", "getting exception start");
string networkLogFolderPath = ConfigurationManager.AppSettings["Logpath"] + "\\" + DffUtility.WebSiteInfo.Folder + "\\" + DffUtility.WebSiteInfo.ThemeName + "\\";
DffUtility.AddCookie("path", networkLogFolderPath.ToString());
Network.connectToRemote(ConfigurationManager.AppSettings["Logpath"],
ConfigurationManager.AppSettings["networkusername"],
ConfigurationManager.AppSettings["pass"]);
string LogFolderPath = HttpContext.Current.Server.MapPath("~/ExceptionLogFiles/");
string filePath = networkLogFolderPath;
string stacktracemessage, stacktrace, Errormsg, extype, exurl;
stacktracemessage = (exc.InnerException).Message;
stacktrace = exc.ToString();
Errormsg = exc.GetType().Name.ToString();
extype = exc.GetType().ToString();
exurl = HttpContext.Current.Request.Url.ToString();
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filePath)))
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
if (DffUtility.Country > 0)
{
if (DffUtility.RegionArea > 0)
{
if (DffUtility.RegionCity > 0)
{
if (DffUtility.ProdID > 0)
{
filePath = (filePath + "Product_" + DffUtility.ProdID + "_" + DffUtility.RegionCity + "_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
else
{
filePath = (filePath + "City_" + DffUtility.RegionCity + "_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
}
else
{
filePath = (filePath + "Area_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
}
else
{
filePath = (filePath + "Country_" + DffUtility.Country + ".txt");
DffUtility.AddCookie("start8", "After generating product file");
}
}
System.IO.File.Create(filePath).Dispose();
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
string logFormat = Environment.NewLine + " " + Environment.NewLine;
DffUtility.AddCookie("start6", "in");
string error = "Error Message:" + " " + Errormsg + logFormat + "Exception Type:" + " " + extype + logFormat + " Error Page Url:" + " " + exurl + logFormat + " StackTraceMessage:" + " " + stacktracemessage + logFormat + " StackTrace:" + " " + stacktrace + logFormat + " " + refurl + logFormat;
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine(error);
sw.WriteLine(logFormat);
sw.Flush();
sw.Close();
DffUtility.AddCookie("start4", " after getting generated log");
}
It's because your application runs under NETWORK SERVICE account (by default) and don't have permissions to write in ExceptionLogFiles folder. Add user Everyone in folder properties and grant him that permission

Input string was not in the correct format with Entity Framework

I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.

Categories

Resources