DateTime not appearing as per system format c# windows services - c#

When we use System.DateTime.Now it displays the DateTime as per what is set in our system (if I am not wrong).
Like currently my system DateTime settings are as below :
Now I created a simple Console Application with a small snippet :
Console.WriteLine(System.DateTime.Now);
Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern+" "+System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
System.IO.File.WriteAllText("E:\\perls.txt", System.DateTime.Now.ToString() + "\r\n" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
The output both console and text is :
Now same thing I am doing via windows service and Logging some information in a Text File and even creating the same file as created in above sample:
(I have a simple Log class which logs the info i am not getting into its details)
So code is something like below:
Log.Info("System Date Time : " + System.DateTime.Now);
Log.Info("Date Time format : " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
System.IO.File.WriteAllText("E:\\perls-service.txt", System.DateTime.Now.ToString() + "\r\n" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
Now in my Log File (a text file) and the text file which I created gives following output:
Both samples are executed in the same system then why is this difference?
Where am I wrong?
Or this problem is in my system only.

You must be running into the issue described here
https://social.msdn.microsoft.com/Forums/vstudio/en-US/8fbca78b-5078-4a12-8abb-4051076febbb/c-windows-service-culture-info-problem
Your Windows Service most likely runs under one of the service accounts with the culture defined in the registry.
See if you updating the registry settings below fixes the problem.
[HKEY_USERS\.DEFAULT\Control Panel\International]
"Locale"="00000409"
"LocaleName"="en-US"

Related

userprofile path returns Default while running as a schedule task

I have created following C# console app:
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path2 = Environment.ExpandEnvironmentVariables("%userprofile%");
File.AppendAllText(#"D:\logs\info.txt", userName + " -- " + path + " -- " + path2);
When I create a scheduled task using Windows Task Scheduler and set the user account to run the task to my account (ht-laptop\huseyin), I am getting the following output in info.txt file:
ht-laptop\huseyin -- C:\Users\Default\Documents -- C:\Users\Default
This seems to be random though, I had seen cases where the printed text was as follows:
ht-laptop\huseyin -- C:\Users\huseyin\Documents -- C:\Users\huseyin
Any idea why this happens?
Are you running this on Windows 8+ (or similar)? If so, this is a known issue with user profile loading. The technote (kb2968540) has a workaround (which is kind of kludgy IMO).

Can I use .NET Remoting for the communication between a console app & a process which has created by same console app?(Both are in the same server)

I have developed some backend console apps which are supposed to run on the server.
They are called Server Process and Server Agent. The Server Process always create instances of server agents (as a process) time by time, here is the code for calling server agent
private static void CreateUpdatedBookingAgent(UpdatedBooking oUpdatedBooking)
{
try
{
//Run the Console App
string command = #"C:\ServerAgentConsole.exe";
string args = ("UpdatedBooking " + oUpdatedBooking.MeetingKey + " " + oUpdatedBooking.ServiceAccountEmail.Trim() + " " + oUpdatedBooking.ServiceAccountPassword.Trim()
+ " " + oUpdatedBooking.ServiceAccountEmail.Trim()+ " " + oUpdatedBooking.MailBoxOwnerEmail.Trim() + " " + oUpdatedBooking.Method.Trim()
+ " " + oUpdatedBooking.ExchangeURL + " " + oUpdatedBooking.ApiURL + " " + oUpdatedBooking.Subject + " " + oUpdatedBooking.Location
+ " " + oUpdatedBooking.StartTime + " " + oUpdatedBooking.EndTime).Trim();
Process process = new Process();
process.StartInfo.FileName = command;
process.StartInfo.Arguments = args;
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(processExitedUpdatedBooking);
process.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
My question is:
Can I use .NET remoting for this, I mean is it a good way of doing this?
If not, is there a better way of passing the data (arguments) to the server agent?
The server and client both must be console application. According to my knowledge, the I can not get a benefit from WCF in that case. Am I correct?
Remoting or WCF are good ways to do this. You probably should choose some of the "IPC" transports because they are restricted to local machine communication. That's a nice security guarantee.
Note, that Remoting is considered obsolete. The .NET Framework source code has the Remoting feature behind an #if FEATURE_REMOTING so they can delete that feature easily from the framework.
Make the parent pass the communication endpoint to the client. There is a security issue in the sense that anything on the local machine might connect to that endpoint. A simple strategy to deal with that is to pass a securely generated Guid on the command line to the child and make the child use that to authenticate. Or, base the endpoint URL on that Guid.
While WCF is quite rightly the best way to go, I have recently faced a similar issue to what you are facing. My scenario was the need to call a .NET 4.5 console app from a .NET 2 Winforms app.
The data being passed was trivial and I deemed it easier to simply serialise the data to disk and pass the filename of the serialised data to the .NET 4 app. The .NET 4 app retrieves the data from the filename it receives when it is called, and removes the file.
I'm not saying it's pretty, but it is effective and may be worth considering.
It seems is not trivial to do, but using a shared memory between processes should give the best performance.
How to implement shared memory in .NET?
Shared memory between 2 processes (applications)

File.AppendText attempting to write to wrong location

I have a C# console application that runs as a scheduled task within Windows Task Scheduler. This console app writes to a log file that when runs within debug mode creates and writes to the file within the application folder itself. However, when it runs in the task scheduler it throws an error saying that access is denied because it is trying to write to the same log file, but for some reason it is trying to write to it within the windows\system32 folder. Why would this be happening? And how would I correct this?
Here is the code snippet that assigns a StreamWriter to the log file:
static void Main(string[] args)
{
using (_swrtr = File.AppendText("gapi_gen_log.txt"))
{
_swrtr.Write("\r\n");
_swrtr.Write("\r\nGOOGLE CALENDAR:");
_swrtr.Write("\r\n\tDate Time - " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
start();
}
}
I also tried but this didn't work:
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
using (_swrtr = File.AppendText(dir + "gapi_gen_log.txt"))
{
_swrtr.Write("\r\n");
_swrtr.Write("\r\nGOOGLE CALENDAR:");
_swrtr.Write("\r\n\tDate Time - " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
start();
}
This is happening because you are not specifying a directory for your log file, so it's assuming the directory where the parent executable resides which, while you're debugging, is your debug output folder and when you're running it from the task scheduler, is the "c:\windows\system32" folder.
You could provide a path to the directory like this:
File.AppendText(#"c:\MyLogFiles\gapi_gen_log.txt")

How to create the special toast and swipe down on lock screen like Skype in win8.1?

In win8.1, we can swipe down on lock screen to open camera.
And also can answer a Skype call from the lock screen.
http://webwereld.nl/development/79224-skype-omzeilt-lockscreen-windows-8-1---update
http://www.stckwt.com/index.php?route=product/product&product_id=137
I want to create a windows store App like Skype.
When someone call, it will show a special toast : user can also choose how to respond – answer call or decline.
If user choose answer call in lock screen, it will auto swipe down the screen and begin answer call.
But I have no idea.
Does anyone have similar experiences?
The Alarm Toast Notification sample shows how to do this for an application that is the Alarm application for the machine:
https://code.msdn.microsoft.com/windowsapps/Alarm-toast-notifications-fe81fc74
If your application is a VOIP application then you can modify the toast XML String in that sample to be the following:
string toastXmlString =
"<toast duration=\"long\">\n" +
"<visual>\n" +
"<binding template=\"ToastText02\">\n" +
"<text id=\"1\">Alarms Notifications SDK Sample App</text>\n" +
"<text id=\"2\">" + alarmName + "</text>\n" +
"</binding>\n" +
"</visual>\n" +
"<commands scenario=\"incomingCall\">\n" +
"<command id=\"voice\"/>\n" +
"<command id=\"video\"/>\n" +
"<command id=\"decline\"/>\n" +
"</commands>\n" +
"<audio src=\"ms-winsoundevent:Notification.Looping.Alarm2\" loop=\"true\" />\n" +
"</toast>\n";
Note that this will only work if you have an application that can accept incoming calls.
Also the following blog goes over this as well:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2013/09/27/windows-8-1-preview-and-alarm-call-applications.aspx

StackTrace class methods not working in release mode

below is my piece of code which i am using to log my error details.
StackTrace sTrace = new StackTrace(true);
string functionname = Environment.NewLine + " MethodName - " + sTrace.GetFrame(1).GetMethod().Name;
string classname = Environment.NewLine + " File Path - " + sTrace.GetFrame(1).GetFileName() + Environment.NewLine + " Line No. - " + sTrace.GetFrame(1).GetFileLineNumber() + Environment.NewLine + " ClassName - " + sTrace.GetFrame(1).GetMethod().ReflectedType.Name + Environment.NewLine + " DateTime - " + DateTime.Now.ToString();
WriteLine(string.Concat("ERROR: ", errMsg, classname, functionname,
Environment.NewLine));
this works perfect in debug mode, but in relese mode, i am getting function name and class name as blank, Line Number (sTrace.GetFrame(1).GetFileLineNumber()) as 0.
is there any other best way to get function name, class name, and line number from where error originated.
thanks in advance.
StackTrace information will be most informative with Debug build configurations. By default, Debug builds include debug symbols, while Release builds do not. The debug symbols contain most of the file, method name, line number, and column information used in constructing StackFrame and StackTrace objects.
Actually, Release mode optimize code and dose not have Program DataBase file(.pdb)
In Release mode
Property -> Build -> Define Debug Constant (Check it)
Property -> Build -> Optmize Code (UnCheck it)
Here is the screenshot - http://imgur.com/Oet3SED
Properties-->Build-->Release conf-->Adv->Debug infor ( FULL).
You can get it if you are using .pdb files in your application. Please check this
You can enable it : Properties > Linker > Debugging > Generate Debug Info = "Yes"
A Note on pdb files

Categories

Resources