I have about 50 users of a WPF application that need to have a search routine run when their phone rings. Part of this solution is have a WCF service that each WPF instance registers with. The WCF service gets the callback using OperationContext.Current.GetCallbackChannel. The idea is that when a call is received, the WCF service is notified; identifying the WPF instance and running a search based on the incoming phone number. This means that the representative does not have to perform a search manually.
The problem is that the service seems to stop working after an unspecified amount of time and I don't know why. It is hosted on IIS 7. Is there some setting on IIS that needs to be set?
It's a very simple setup, currently. Here is the entire code for the service:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PhoenixCommunicationService : IPhoenixCommunicationService
{
/// <summary>
/// List of registered Phoenix applications
/// </summary>
private static readonly List<PhoenixInstance> _callbackList = new List<PhoenixInstance>();
private class PhoenixInstance
{
public string UserName { get; set; }
public string Environment { get; set; }
public IPhoenixCallBack CallBack { get; set; }
}
/// <summary>
/// Returns a list of all users logged into a particular environment (DEV, QA, Live)
/// </summary>
/// <param name="enviornment">Environment to check</param>
/// <returns></returns>
public List<string> GetUserList(string enviornment)
{
List<string> retVal = new List<string>();
try
{
var userList = _callbackList.Where(l => l.Environment == enviornment).ToList();
foreach (var user in userList)
{
retVal.Add(user.UserName);
}
}
catch { }
return retVal;
}
/// <summary>
/// Register each Phoenix application
/// </summary>
public void RegisterPhoenixUser(string userName, string environment)
{
try
{
var search = _callbackList.FirstOrDefault(c => string.Equals(c.UserName, userName, StringComparison.CurrentCultureIgnoreCase) && c.Environment == environment);
if (search != null)
{
_callbackList.Remove(search);
}
IPhoenixCallBack callBack = OperationContext.Current.GetCallbackChannel<IPhoenixCallBack>();
_callbackList.Add(new PhoenixInstance
{
UserName = userName,
Environment = environment,
CallBack = callBack
});
}
catch (Exception ex)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry(String.Format("PhoenixCommunicationService failed to register user {0}. {1}", userName, ex.Message), EventLogEntryType.Information, 101, 1);
}
}
finally
{
foreach (var pu in _callbackList)
{
pu.CallBack.PhoenixUserRegistered(userName, environment);
}
}
}
/// <summary>
/// Removes the application from the Registered List
/// </summary>
public void WithdrawRegisteredPhoenixUser()
{
string userName = string.Empty;
string environment = string.Empty;
try
{
IPhoenixCallBack callBack = OperationContext.Current.GetCallbackChannel<IPhoenixCallBack>();
// Remove the application from the list of registered applications
for (int x = _callbackList.Count - 1; x >= 0; x--)
{
var pu = _callbackList[x];
if (pu.CallBack == callBack)
{
userName = pu.UserName;
environment = pu.Environment;
_callbackList.RemoveAt(x);
break;
}
}
}
catch (Exception ex)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry(String.Format("PhoenixCommunicationService failed to withdraw registered user. {0}", ex.Message), EventLogEntryType.Information, 101, 1);
}
}
finally
{
if (!String.IsNullOrEmpty(userName))
{
foreach (var pu in _callbackList)
{
pu.CallBack.PhoenixUserLoggedOff(userName, environment);
}
}
}
}
/// <summary>
/// Removes the application from the Registered List
/// </summary>
/// <param name="userName">User to remove</param>
/// <param name="environment">Environment to remove from</param>
public void WithdrawRegisteredPhoenixUserName(string userName, string environment)
{
try
{
// Remove the application from the list of registered applications
for (int x = _callbackList.Count - 1; x >= 0; x--)
{
var pu = _callbackList[x];
if (string.Equals(pu.UserName, userName, StringComparison.CurrentCultureIgnoreCase) && pu.Environment == environment)
{
userName = pu.UserName;
environment = pu.Environment;
_callbackList.RemoveAt(x);
break;
}
}
}
catch (Exception ex)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry(String.Format("PhoenixCommunicationService failed to withdraw registered user {0}. {1}", userName, ex.Message), EventLogEntryType.Information, 101, 1);
}
}
finally
{
if (!String.IsNullOrEmpty(userName))
{
foreach (var pu in _callbackList)
{
pu.CallBack.PhoenixUserLoggedOff(userName, environment);
}
}
}
}
}
It is setup as a single instance. All the methods work perfectly for a while. As a matter of fact, the GetUserList() method has never failed. But I cannot Register new users after some time.
If anyone has suggestions, I'd love to hear them.
Related
I am working in xamarin.forms. I want to create background service for Android.
My requirement is to track device location (Latitude, longitude, place name, Employee code) and inserted to the web server every after 5 min. After successful login, service has been started and for a particular employee, data is start inserting. Even if the app is closed still service should be running in background and data is keep inserting.
My code is
using Android.App;
using Android.Content;
using Android.Locations;
using Android.Net;
using Android.OS;
using HRMS;
using HRMS.Interface;
using HRMS.TableAttributes;
using Newtonsoft.Json;
using Plugin.Geolocator;
using Plugin.Geolocator.Abstractions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Xml.Linq;
using Xamarin.Forms;
using static HRMS.ServiceLayer.ServiceClasses;
using HRMS.MenuController;
using HRMS.Droid;
using Android.Provider;
namespace SilverHRMS.Droid.Service
{
[Service]
public class GPSTrackingService : Android.App.Service
{
#region Private Variables
static readonly string TAG = "X:" + typeof(GPSTrackingService).Name;
static int TimerWait = 300000; //150000;//25000 25 Sec; // 10 min 600000 and 20 Min 1200000
Timer _timer;
readonly string logTag = "GPSTrackingService";
private string deviceId = "";
private string googleAPI = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
#endregion
/// <summary>
///
/// </summary>
/// <param name="intent"></param>
/// <param name="flags"></param>
/// <param name="startId"></param>
/// <returns></returns>
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
try
{
// Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow);
//_timer = new Timer(o => { Log.Debug(TAG, "Hello from GPSTrackingService. {0}", DateTime.UtcNow); GetCurrentLocation(); }, null, 0, TimerWait);
_timer = new Timer(o => { GetCurrentLocation(); }, null, 0, TimerWait);
//_timer = new Timer(o => { GetCurrentLocation(); }, null, 0, TimerWait);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
return StartCommandResult.Sticky;
}
/// <summary>
///
/// </summary>
/// <param name="intent"></param>
/// <returns></returns>
public override IBinder OnBind(Intent intent)
{
// This example isn't of a bound service, so we just return NULL.
return null;
}
/// <summary>
/// On Destroy App
/// </summary>
public override void OnDestroy()
{
base.OnDestroy();
_timer.Dispose();
_timer = null;
//Log.Debug(logTag, "Service has been terminated");
}
/// <summary>
/// Get Current Location and Insert to DB
/// </summary>
public async void GetCurrentLocation()
{
try
{
string statusMessage = string.Empty;
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100;
//Log.Debug(TAG, " getting GPS connection...");
if (App.MyEmployeeId != null)
{
#region Check Internet Connection
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
#endregion
#region Check GPS Location Position and Emp Code
//LocationManager locationManager = (LocationManager)GetSystemService(LocationService);
bool isGPSOn = App.CheckGPSConnection();
Position position = null;
if (isGPSOn)
{
try
{
position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
}
catch (Exception)
{
position = null;
}
}
#endregion
#region Insert Location to Local DB or Server DB
//Device Has Internet Connection
if (isOnline)
{
#region Online Location Insert Direct to the Server Database
if (position != null)
{
List<GPSTrackingLocationClass> lcListOnline = new List<GPSTrackingLocationClass>();
GPSTrackingLocationClass objGPSTrack = new GPSTrackingLocationClass();
objGPSTrack.Latitude = position.Latitude;
objGPSTrack.Longitude = position.Longitude;
objGPSTrack.EmpCd = App.MyEmployeeId;
objGPSTrack.GPS_Track_DateTime = App.GetDateTime(DateTime.Now);
IDevice device = DependencyService.Get<IDevice>();
deviceId = device.GetIdentifier();
deviceId = deviceId.Replace("+", "%2B");
objGPSTrack.DeviceId = deviceId;
string url = string.Format(googleAPI, position.Latitude, position.Longitude);
try
{
XElement xml = XElement.Load(url);
if (xml.Element("status").Value == "OK")
{
objGPSTrack.PlaceName = xml.Element("result").Element("formatted_address").Value;
}
else
{
objGPSTrack.PlaceName = string.Empty;
}
}
catch (Exception ex)
{
}
lcListOnline.Add(objGPSTrack);
if (lcListOnline.Count > 0)
{
string jsonContentsOnline = JsonConvert.SerializeObject(lcListOnline);
var responseOnline = await HRMS.ServiceLayer.GetResponseFromWebService.GetResponsePostData<HRMS.ServiceLayer.ServiceClasses.RootObject>(HRMS.ServiceLayer.ServiceURL.PostGPSLocation, jsonContentsOnline);
if (responseOnline.Flag == true)
{
statusMessage = responseOnline.Message;
}
}
}
#endregion
#region Local Database Entries Insert to Server Database
List<LocationTracking> lcListOffline = SideMenu.repoLocation.GetAllLocationAsync();
if (lcListOffline != null)
{
if (lcListOffline.Count > 0)
{
ObservableCollection<LocationTracking> lvCollection = new ObservableCollection<LocationTracking>(lcListOffline);
List<GPSTrackingLocationClass> lcListGoingtoOnline = new List<GPSTrackingLocationClass>();
foreach (var item in lvCollection)
{
GPSTrackingLocationClass objGPSTrackOffline = new GPSTrackingLocationClass();
objGPSTrackOffline.Latitude = item.Latitude;
objGPSTrackOffline.Longitude = item.Longitude;
objGPSTrackOffline.EmpCd = item.EmpCd;
objGPSTrackOffline.GPS_Track_DateTime = item.GPS_Track_DateTime;
objGPSTrackOffline.DeviceId = item.DeviceID;
string urlAPI = string.Format(googleAPI, item.Latitude, item.Longitude);
try
{
XElement xmlURL = XElement.Load(urlAPI);
if (xmlURL.Element("status").Value == "OK")
{
objGPSTrackOffline.PlaceName = xmlURL.Element("result").Element("formatted_address").Value;
}
else
{
objGPSTrackOffline.PlaceName = string.Empty;
}
}
catch (Exception exe)
{
}
if (!string.IsNullOrEmpty(objGPSTrackOffline.PlaceName))
{
lcListGoingtoOnline.Add(objGPSTrackOffline);
}
}
if (lcListGoingtoOnline.Count == lvCollection.Count)
{
string jsonContentsOffline = JsonConvert.SerializeObject(lcListGoingtoOnline);
var responseOffline = await HRMS.ServiceLayer.GetResponseFromWebService.GetResponsePostData<HRMS.ServiceLayer.ServiceClasses.RootObject>(HRMS.ServiceLayer.ServiceURL.PostGPSLocation, jsonContentsOffline);
if (responseOffline.Flag == true)
{
statusMessage = responseOffline.Message;
SideMenu.repoLocation.RemoveLocationAsync();
}
}
}
}
#endregion
}
//Device Has No Internet Connection
else
{
try
{
if (position != null)
{
IDevice device = DependencyService.Get<IDevice>();
deviceId = device.GetIdentifier();
deviceId = deviceId.Replace("+", "%2B");
string newDate = App.GetDateTime(DateTime.Now);
SideMenu.repoLocation.AddNewLocationAsync(newDate, position.Latitude, position.Longitude, App.MyEmployeeId, deviceId, "--");
}
}
catch (Exception ex)
{
//Log.Debug(TAG, "Please turn on GPS in your headset");
}
}
#endregion
}
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
await fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
}
/// <summary>
/// Start Location Service
/// </summary>
public static void StartLocationService()
{
// Starting a service like this is blocking, so we want to do it on a background thread
//new Task(() =>
//{
// Start our main service
try
{
Intent intent = new Intent(Android.App.Application.Context, typeof(GPSTrackingService));
Android.App.Application.Context.StartService(intent);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
//}).Start();
}
/// <summary>
/// Start Location Service
/// </summary>
public static void StartApplication()
{
try
{
Intent start = new Intent(Android.App.Application.Context, typeof(MainActivity));
// my activity name is MainActivity replace it with yours
start.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.ApplicationContext.StartActivity(start);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
}
public static void SendEmail(string text)
{
var email = new Intent(Android.Content.Intent.ActionSend);
email.PutExtra(Android.Content.Intent.ExtraEmail, new string[] { "pankit.patel#silvertouch.com" });
email.PutExtra(Android.Content.Intent.ExtraSubject, "Send Crash Report");
email.PutExtra(Android.Content.Intent.ExtraText, "Hello, " + text);
email.AddFlags(ActivityFlags.NewTask);
email.SetType("message/rfc822");
Android.App.Application.Context.ApplicationContext.StartActivity(email);
}
/// <summary>
/// Stop Location Service
/// </summary>
public static void StopLocationService()
{
// Check for nulls in case StartLocationService task has not yet completed.
//Log.Debug("App", "StopGPSTrackingService");
try
{
Intent intent = new Intent(Android.App.Application.Context, typeof(GPSTrackingService));
Android.App.Application.Context.StopService(intent);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
}
}
}
This service is only running when app is open (even in background) but if I close the app then service is automatically stop working. How to solve this issue? I have so many xamarin blogs regarding this topic but I din't get any workaround yet.
How to make background service that should be running even after app is close?
I am using C#. I get an error:
The name 'DateAndTime','DateInterval' 'FirstDayOfWeek','FirstWeekOfYear', does not exist in the current context
which I don't understand. I tried a lot of solutions on it but it is not working.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
using Microsoft.VisualBasic;
using System.Windows.Forms;
namespace SoftwareLocker
{
// Activate Property
public class TrialMaker
{
#region -> Private Variables
private string _BaseString;
private string _Password;
private string _SoftName;
private string _RegFilePath;
private string _HideFilePath;
private int _DefDays;
private int _Runed;
private string _Text;
private string _Identifier;
#endregion
#region -> Constructor
/// <summary>
/// Make new TrialMaker class to make software trial
/// </summary>
/// <param name="SoftwareName">Name of software to make trial</param>
/// <param name="RegFilePath">File path to save password(enrypted)</param>
/// <param name="HideFilePath">file path for saving hidden information</param>
/// <param name="Text">A text for contacting to you</param>
/// <param name="TrialDays">Default period days</param>
/// <param name="TrialRunTimes">How many times user can run as trial</param>
/// <param name="Identifier">3 Digit string as your identifier to make password</param>
public TrialMaker(string SoftwareName,
string RegFilePath, string HideFilePath,
string Text, int TrialDays, int TrialRunTimes,
string Identifier)
{
_SoftName = SoftwareName;
_Identifier = Identifier;
SetDefaults();
_DefDays = TrialDays;
_Runed = TrialRunTimes;
_RegFilePath = RegFilePath;
_HideFilePath = HideFilePath;
_Text = Text;
}
private void SetDefaults()
{
SystemInfo.UseBaseBoardManufacturer = false;
SystemInfo.UseBaseBoardProduct = true;
SystemInfo.UseBiosManufacturer = false;
SystemInfo.UseBiosVersion = true;
SystemInfo.UseDiskDriveSignature = true;
SystemInfo.UsePhysicalMediaSerialNumber = false;
SystemInfo.UseProcessorID = true;
SystemInfo.UseVideoControllerCaption = false;
SystemInfo.UseWindowsSerialNumber = false;
MakeBaseString();
MakePassword();
}
#endregion
// Make base string (Computer ID)
private void MakeBaseString()
{
_BaseString = Encryption.Boring(Encryption.InverseByBase(SystemInfo.GetSystemInfo(_SoftName), 10));
}
private void MakePassword()
{
_Password = Encryption.MakePassword(_BaseString, _Identifier);
}
/// <summary>
/// Show registering dialog to user
/// </summary>
/// <returns>Type of running</returns>
public RunTypes ShowDialog()
{
// check if registered before
if (CheckRegister() == true)
return RunTypes.Full;
frmDialog PassDialog = new frmDialog(_BaseString, _Password, DaysToEnd(), _Runed, _Text);
MakeHideFile();
DialogResult DR = PassDialog.ShowDialog();
if (DR == System.Windows.Forms.DialogResult.OK)
{
MakeRegFile();
return RunTypes.Full;
}
else if (DR == DialogResult.Retry)
return RunTypes.Trial;
else
return RunTypes.Expired;
}
// save password to Registration file for next time usage
private void MakeRegFile()
{
FileReadWrite.WriteFile(_RegFilePath, _Password);
}
// Control Registeration file for password
// if password saved correctly return true else false
private bool CheckRegister()
{
string Password = FileReadWrite.ReadFile(_RegFilePath);
if (_Password == Password)
return true;
else
return false;
}
// from hidden file
// indicate how many days can user use program
// if the file does not exists, make it
private int DaysToEnd()
{
FileInfo hf = new FileInfo(_HideFilePath);
if (hf.Exists == false)
{
MakeHideFile();
return _DefDays;
}
return CheckHideFile();
}
// store hidden information to hidden file
// Date,DaysToEnd,HowManyTimesRuned,BaseString(ComputerID)
private void MakeHideFile()
{
string HideInfo;
HideInfo = DateTime.Now.Ticks + ";";
HideInfo += _DefDays + ";" + _Runed + ";" + _BaseString;
FileReadWrite.WriteFile(_HideFilePath, HideInfo);
}
// Get Data from hidden file if exists
private int CheckHideFile()
{
string[] HideInfo;
HideInfo = FileReadWrite.ReadFile(_HideFilePath).Split(';');
long DiffDays;
int DaysToEnd;
if (_BaseString == HideInfo[3])
{
DaysToEnd = Convert.ToInt32(HideInfo[1]);
if (DaysToEnd <= 0)
{
_Runed = 0;
_DefDays = 0;
return 0;
}
DateTime dt = new DateTime(Convert.ToInt64(HideInfo[0]));
DiffDays = DateAndTime.DateDiff(DateInterval.Day,
dt.Date, DateTime.Now.Date,
FirstDayOfWeek.Saturday,
FirstWeekOfYear.FirstFullWeek);
DaysToEnd = Convert.ToInt32(HideInfo[1]);
_Runed = Convert.ToInt32(HideInfo[2]);
_Runed -= 1;
DiffDays = Math.Abs(DiffDays);
_DefDays = DaysToEnd - Convert.ToInt32(DiffDays);
}
return _DefDays;
}
public enum RunTypes
{
Trial = 0,
Full,
Expired,
UnKnown
}
#region -> Properties
/// <summary>
/// Indicate File path for storing password
/// </summary>
public string RegFilePath
{
get
{
return _RegFilePath;
}
set
{
_RegFilePath = value;
}
}
/// <summary>
/// Indicate file path for storing hidden information
/// </summary>
public string HideFilePath
{
get
{
return _HideFilePath;
}
set
{
_HideFilePath = value;
}
}
/// <summary>
/// Get default number of days for trial period
/// </summary>
public int TrialPeriodDays
{
get
{
return _DefDays;
}
}
/// <summary>
/// Get or Set TripleDES key for encrypting files to save
/// </summary>
public byte[] TripleDESKey
{
get
{
return FileReadWrite.key;
}
set
{
FileReadWrite.key = value;
}
}
#endregion
#region -> Usage Properties
public bool UseProcessorID
{
get
{
return SystemInfo.UseProcessorID;
}
set
{
SystemInfo.UseProcessorID = value;
}
}
public bool UseBaseBoardProduct
{
get
{
return SystemInfo.UseBaseBoardProduct;
}
set
{
SystemInfo.UseBaseBoardProduct = value;
}
}
public bool UseBaseBoardManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseDiskDriveSignature
{
get
{
return SystemInfo.UseDiskDriveSignature;
}
set
{
SystemInfo.UseDiskDriveSignature = value;
}
}
public bool UseVideoControllerCaption
{
get
{
return SystemInfo.UseVideoControllerCaption;
}
set
{
SystemInfo.UseVideoControllerCaption = value;
}
}
public bool UsePhysicalMediaSerialNumber
{
get
{
return SystemInfo.UsePhysicalMediaSerialNumber;
}
set
{
SystemInfo.UsePhysicalMediaSerialNumber = value;
}
}
public bool UseBiosVersion
{
get
{
return SystemInfo.UseBiosVersion;
}
set
{
SystemInfo.UseBiosVersion = value;
}
}
public bool UseBiosManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseWindowsSerialNumber
{
get
{
return SystemInfo.UseWindowsSerialNumber;
}
set
{
SystemInfo.UseWindowsSerialNumber = value;
}
}
#endregion
}
}
that problem will work on Viaual basic 2005 it is not working in vb2015 if, we do so in 2015 some libraries are missing that pblm raises
So I am completely stumped on this one. I am getting an error Object reference not set to an instance of an object. and I am not sure why.
I have a class FILE
public class FILE
{
private string _fileName;
public string fileName
{
get
{
if (!Settings.Values.CaseSensitive)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (!Settings.Values.CaseSensitive)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
I am creating an instance like:
FILE test1233;
test1233 = new FILE(); // <---- Ex thrown here!? Why???
test1233.fileName = "";
folderName = "";
fileHashDigest = new byte[1];
As soon as the variable is placed on the stack, it throws an exception. BUT... if I remove all refrences to this variable on code further down (WHICH HAS NOT YET BEEN EXECUTED IN DEBUGMODE!!!) then no exception gets thrown. What on earth is going on here?
For refrence, here is the method in it's entirety:
private bool IsFolderOverride(FileCollection zipFILEList, DataTable exceptionTableFileList, DataRow currentRow, ref DataTable detectedFolderRenames)
{
bool foundInExceptionTable = false;
foreach (DataRow exRow in exceptionTableFileList.Rows)
{
if (exRow["FILE_NAME"].ToString().ToUpper() == currentRow["FILE_NAME"].ToString().ToUpper() &&
(decimal)exRow["WINDOW_GROUP_ID"] == (decimal)currentRow["WINDOW_GROUP_ID"])
{
string name = exRow["FILE_NAME"].ToString().ToUpper();
string folder = exRow["FOLDER_NAME"].ToString().ToUpper();
byte[] digest = (byte[])exRow["FILE_HASH_DIGEST"];
CopyCat exCopyCat = new CopyCat();
exCopyCat.fileName = name;
exCopyCat.folderName = folder;
exCopyCat.fileHashDigest = digest;
//HAS AN EXCEPTION!
FILE test1233 = new FILE();
test1233.fileName = "";
test1233.folderName = "";
test1233.fileHashDigest = new byte[1];
//NO EXCEPTION THROWN
FILE test = new FILE();
bool test9 = zipFileList.Contains(test1233);
test.fileName = name;
test.folderName = folder;
test.fileHashDigest = digest;
FILE test123 = new FILE();
if (zipFileList.Contains(test1233)) // Exact match found in zip in old folder from exception table.
{
FILE exists = zipFileList.Where(f => f.fileName == test1233.fileName &&
f.fileHashDigest.SequenceEqual(test1233.fileHashDigest)).First();
object[] items = exRow.ItemArray;
Array.Resize(ref items, items.Length + 4);
items[items.Length - 1] = "Y";
items[items.Length - 2] = exists.folderName;
items[items.Length - 3] = test1233.folderName;
items[items.Length - 4] = "Folder Override";
if (detectedFolderRenames.Rows.Count == 0 || !detectedFolderRenames.Rows.Contains(items[0]))
detectedFolderRenames.Rows.Add(items);
foundInExceptionTable = true;
break;
}
else if (zipFileList.ContainsPartially(test1233)) // Match in zip with Different Hash found from ex table.
{
FILE exists = zipFileList.Where(f => f.fileName == test1233.fileName).First();
object[] items = exRow.ItemArray;
Array.Resize(ref items, items.Length + 4);
items[items.Length - 1] = "N";
items[items.Length - 2] = exists.folderName;
items[items.Length - 3] = test1233.folderName;
items[items.Length - 4] = "Folder Override";
if (detectedFolderRenames.Rows.Count == 0 || !detectedFolderRenames.Rows.Contains(items[0]))
detectedFolderRenames.Rows.Add(items);
foundInExceptionTable = true;
break;
}
}
else
continue;
}
return foundInExceptionTable;
}
UPDATE: I am still working on an example for you, but in the mean time here is potentially helpful information:
test1233' threw an exception of type 'System.NullReferenceException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Object reference not set to an instance of an object."
Source: null
StackTrace: null
TargetSite: null
The Data: {System.Collections.ListDictionaryInternal} part is a little interesting to me, my class does not use any dictionary lists.
UPDATE #2: Ok, I have produced a reproducible sequence of steps for others to try. On your machines, it may be just fine, like Jon Skeet said, it might be my debug environment settings but please try and let me know. Here are the steps to reproduce.
Open console app project and copy paste code below.
Set a break point here:
First run code past break point, it works! :D
Then run code again but this time STOP at the break point and DRAG the executing statement cursor INTO the if statement from here:
to here:
There it is! So the error was caused from my method of testing, but does this make any sense or is this just me on my machine?
CODE:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
FILECollection randomCollection = new FILECollection();
// Fill with junk test data:
for(int i = 0; i<10; i++)
{
FILE junkfile = new FILE() { fileName = i.ToString(), folderName = i.ToString(), fileHashDigest = new byte[1] };
randomCollection.Add(junkfile);
}
if (true)
{
Console.WriteLine("testing this weird exception issue...");
FILE test;
test = new FILE();
test.fileName = "3";
test.folderName = "3";
test.fileHashDigest = new byte[1];
FILE exists = randomCollection.Where(f => f.fileName == test.fileName &&
f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First();
}
}
}
public class FILE
{
public FILE() { _fileName = "";}
private string _fileName;
public string fileName
{
get
{
if (false)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (false)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
public class FILECollection : IEnumerable<FILE>, ICollection<FILE>
{
private HashSet<FILE> svgHash;
private static List<FILE> PreallocationList;
public string FileName = "N/A";
/// <summary>
/// Default Constructor, will not
/// preallocate memory.
/// </summary>
/// <param name="PreallocationSize"></param>
public FILECollection()
{
this.svgHash = new HashSet<FILE>();
this.svgHash.Clear();
}
/// <summary>
/// Overload Constructor Preallocates
/// memory to be used for the new
/// FILE Collection.
/// </summary>
public FILECollection(int PreallocationSize, string fileName = "N/A", int fileHashDigestSize = 32)
{
FileName = fileName;
PreallocationList = new List<FILE>(PreallocationSize);
for (int i = 0; i <= PreallocationSize; i++)
{
byte[] buffer = new byte[fileHashDigestSize];
FILE preallocationSVG = new FILE()
{
fileName = "",
folderName = "",
fileHashDigest = buffer
};
PreallocationList.Add(preallocationSVG);
}
this.svgHash = new HashSet<FILE>(PreallocationList);
this.svgHash.Clear(); // Capacity remains unchanged until a call to TrimExcess is made.
}
/// <summary>
/// Add an FILE file to
/// the FILE Collection.
/// </summary>
/// <param name="svg"></param>
public void Add(FILE svg)
{
this.svgHash.Add(svg);
}
/// <summary>
/// Removes all elements
/// from the FILE Collection
/// </summary>
public void Clear()
{
svgHash.Clear();
}
/// <summary>
/// Determine if the FILE collection
/// contains the EXACT FILE file, folder,
/// and byte[] sequence. This guarantees
/// that the collection contains the EXACT
/// file you are looking for.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(FILE item)
{
return svgHash.Any(f => f.fileHashDigest.SequenceEqual(item.fileHashDigest) &&
f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Determine if the FILE collection
/// contains the same file and folder name,
/// byte[] sequence is not compared. The file and folder
/// name may be the same but this does not guarantee the
/// file contents are exactly the same. Use Contains() instead.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool ContainsPartially(FILE item)
{
return svgHash.Any(f => f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Returns the total number
/// of FILE files in the Collection.
/// </summary>
public int Count
{ get { return svgHash.Count(); } }
public bool IsReadOnly
{ get { return true; } }
public void CopyTo(FILE[] array, int arrayIndex)
{
svgHash.CopyTo(array, arrayIndex);
}
public bool Remove(FILE item)
{
return svgHash.Remove(item);
}
public IEnumerator<FILE> GetEnumerator()
{
return svgHash.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return svgHash.GetEnumerator();
}
}
}
I think either I am debugging in a terribly wrong way, or Microsoft should take a look at this. It's like future code is breaking current code...which is impossible!
I tried to execute the code in a console app and is working, can you give more details? Answers about the Settings initialization doesn't make sense here at this point because you should be able to create the instance of FILE. Once you try to assign(set) or request(get) then you are dealing with fileName property. I am not seeing why you get the exception when you create the instance.
static void Main(string[] args)
{
FILE test1233;
test1233 = new FILE(); // <---- Ex is not thrown here!? test1233.fileName = "";
test1233.folderName = "";
test1233.fileHashDigest = new byte[1];
}
public class FILE
{
private string _fileName;
public string fileName
{
get
{
if (YOUR SETTING CONDITION HERE)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (YOUR SETTING CONDITION HERE)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
see the cursor on the print screen
Here is my debug configuration
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "XXXXXXXXX",
ClientSecret = "XXXXXXXXXXXX"
},
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly, AnalyticsService.Scope.AnalyticsEdit },
DataStore = new FileDataStore("Analytics.Auth.Store")//new FileDataStore("Drive.Api.Auth.Store")
});
I am using above code for google console web application(Google Analytic) but it gives error System.UnauthorizedAccessException: Access to the path 'Analytics.Auth.Store' is denied.
FileDataStore stores the data in %AppData% on the pc. You need to make sure that you have access to that.
If you are planning on running this from a webserver you should not be using FileDataStore. You should create your own implementation of iDataStore, this will enable you to store the refresh tokens in the database.
Example:
///
/// Saved data store that implements .
/// This Saved data store stores a StoredResponse object.
///
class SavedDataStore : IDataStore
{
public StoredResponse _storedResponse { get; set; }
///
/// Constructs Load previously saved StoredResponse.
///
///Stored response
public SavedDataStore(StoredResponse pResponse)
{
this._storedResponse = pResponse;
}
public SavedDataStore()
{
this._storedResponse = new StoredResponse();
}
///
/// Stores the given value. into storedResponse
/// .
///
///The type to store in the data store
///The key
///The value to store in the data store
public Task StoreAsync(string key, T value)
{
var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
JObject jObject = JObject.Parse(serialized);
// storing access token
var test = jObject.SelectToken("access_token");
if (test != null)
{
this._storedResponse.access_token = (string)test;
}
// storing token type
test = jObject.SelectToken("token_type");
if (test != null)
{
this._storedResponse.token_type = (string)test;
}
test = jObject.SelectToken("expires_in");
if (test != null)
{
this._storedResponse.expires_in = (long?)test;
}
test = jObject.SelectToken("refresh_token");
if (test != null)
{
this._storedResponse.refresh_token = (string)test;
}
test = jObject.SelectToken("Issued");
if (test != null)
{
this._storedResponse.Issued = (string)test;
}
return TaskEx.Delay(0);
}
///
/// Deletes StoredResponse.
///
///The key to delete from the data store
public Task DeleteAsync(string key)
{
this._storedResponse = new StoredResponse();
return TaskEx.Delay(0);
}
///
/// Returns the stored value for_storedResponse
///The type to retrieve
///The key to retrieve from the data store
/// The stored object
public Task GetAsync(string key)
{
TaskCompletionSource tcs = new TaskCompletionSource();
try
{
string JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(this._storedResponse);
tcs.SetResult(Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize(JsonData));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
return tcs.Task;
}
///
/// Clears all values in the data store.
///
public Task ClearAsync()
{
this._storedResponse = new StoredResponse();
return TaskEx.Delay(0);
}
///// Creates a unique stored key based on the key and the class type.
/////The object key
/////The type to store or retrieve
//public static string GenerateStoredKey(string key, Type t)
//{
// return string.Format("{0}-{1}", t.FullName, key);
//}
}
Then instead of using FileDataStore you use your new SavedDataStore
//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
new[] { AnalyticsService.Scope.AnalyticsReadonly},
"user",
CancellationToken.None,
new SavedDataStore(myStoredResponse)).Result; }
This is because you dont have write access to AppData folder on a Webserver and FileDataStore uses that folder by default.
You can use a different folder by giving full path as parameter
FileDataStore(string folder, bool fullPath = false)
sample implementation
static FileDataStore GetFileDataStore()
{
var path = HttpContext.Current.Server.MapPath("~/App_Data/Drive.Api.Auth.Store");
var store = new FileDataStore(path, fullPath: true);
return store;
}
This way FileDataStore uses the App_Data folder of your application to write the TokenResponse. Dont forget to give write access to App_Data folder on the Webserver
You can read more about this at here and here
For one of my projects we utilize a Content Delivery Network (EdgeCast) and I was wondering if anyone knew of an existing (open source) library for C# that we could leverage? In a nutshell, I am investigating the ability to create directories, upload files, and allow some general maintenance (rename files, delete files) via our admin panel. Any insight would be appreciated.
NOTE: My code to do this. I don't know if they have an updated API at this point so please check. This code is circa 2009 (as-is, no warranties, use at your own risk, etc).
EdgeCast.cs
using System;
using edgeCastWS = [DOMAIN].com.edgecast.api.EdgeCastWebServices;
namespace [DOMAIN].IO.ContentDeliveryNetwork
{
/// <summary>
/// <b>Authentication</b>
/// <para>Each web service call will include a string parameter called strCredential which will ensure that customers may only access data related to their own accounts. This credential is a string made up of a few separate pieces of information.</para>
/// <para>A typical credential a customer would use may look like: “c:bas:user#email.com:password”</para>
/// <para> * The field format of this string is delimited with a colon “:” character.</para>
/// <para> * The first field is the type of client which is calling the web service. “c” represents an individual customer.</para>
/// <para> * The second field is the security type. “bas” represents Basic Authentication.</para>
/// <para> * With basic authentication the third field is the username which is usually in email address notation.</para>
/// <para> * With basic authentication the fourth field is the password associated with the user.</para>
/// <para>If the username and password are not valid, then the credential will prevent the specified function from proceeding. A SOAP exception will be generated and sent back to the client that called the function. The message contained in the exception will contain the string “Access Denied.”</para>
/// </summary>
public class EdgeCast : IDisposable
{
#region Declarations
[ThreadStatic]
private static EdgeCast _current;
private static EdgeCastCredential _credential = null;
private static string _customerID = string.Empty;
private static edgeCastWS _edgeCastWS = null;
#endregion
#region Constructor
public EdgeCast()
{
if (_current != null)
{
throw new InvalidOperationException("Only one ContentDeliveryNetwork may be created on a given thread.");
}
_current = this;
_edgeCastWS = new edgeCastWS();
ConstructCredentials();
_customerID = AppSettings.EdgeCast_CustomerID;
}
#endregion
#region API Methods
/// <summary>
/// Purges a file from all of the EdgeCast caching servers. This process may take a few minutes to fully complete.
/// </summary>
/// <param name="Path">This is path of the file or folder to purge, in URL format. To specify a folder, please put a trailing slash at the end of the URL. All files under that folder will be purged</param>
/// <param name="MediaType">HTTP Large Object = 3, HTTP Small Object = 8, Flash = 2, Windows = 1</param>
/// <returns>An integer that indicates whether or not the transaction was successful. 0 represents yes, -1 represents no</returns>
internal static short PurgeFileFromEdge(string Path, int MediaType)
{
return _edgeCastWS.PurgeFileFromEdge(_credential.Credential, _customerID, Path, MediaType);
}
/// <summary>
/// Loads a file to disk on all of the EdgeCast caching servers. This process may take a few minutes to fully complete.
/// </summary>
/// <param name="Path">This is path of the file to load, in URL format. Folders may not be loaded and will be ignored</param>
/// <param name="MediaType">HTTP Large Object = 3, HTTP Small Object = 8</param>
/// <returns>An integer that indicates whether or not the transaction was successful. 0 represents yes, -1 represents no</returns>
internal static short LoadFileToEdge(string Path, int MediaType)
{
return _edgeCastWS.LoadFileToEdge(_credential.Credential, _customerID, Path, MediaType);
}
/// <summary>
/// This method call is used to add a token authentication directory. All additions and changes should be processed every 30 minutes
/// </summary>
/// <param name="Dir">Directory Path should be starting from the root. Example: /directory1/directory2</param>
/// <param name="MediaType">Use 1 for Windows, 2 for Flash, 3 for HTTP Caching / Progressive download.</param>
/// <returns></returns>
internal static short TokenDirAdd(string Dir, int MediaType)
{
return _edgeCastWS.TokenDirAdd(_credential.Credential, _customerID, Dir, MediaType);
}
internal static string TokenEncrypt(string Key, string Args)
{
return _edgeCastWS.TokenEncrypt(_credential.Credential, Key, Args);
}
internal static short TokenKeyUpdate(string Key, int MediaType)
{
return _edgeCastWS.TokenKeyUpdate(_credential.Credential, _customerID, Key, MediaType);
}
#endregion
#region FTP Methods
/// <summary>
/// Does a FTP Upload of a file on the local system
/// </summary>
/// <param name="targetPath">The full path to save to on the FTP server (.\Campaigns\Prod\[Company GUID])</param>
/// <param name="sourceFileName">The full path and filename of the file to be uploaded (C:\[DOMAIN]\files\[filename])</param>
internal static void FTP_UploadFile(string targetPath, string sourceFileName)
{
string[] dirs = targetPath.Split(new char[] { '\\', '/' });
using (FTPFactory myFTP = new FTPFactory())
{
myFTP.login();
myFTP.setBinaryMode(true);
// Make sure the directories are there and change down to the bottom most directory...
foreach (string dirName in dirs)
{
bool dirExists = true;
try { myFTP.chdir(dirName); }
catch { dirExists = false; }
if (!dirExists)
{
myFTP.mkdir(dirName);
myFTP.chdir(dirName);
}
}
// upload the file now...
myFTP.upload(sourceFileName);
}
}
/// <summary>
/// Returns a string array of files in the target directory
/// </summary>
/// <param name="targetPath">The target directory</param>
/// <returns>string array or null if no files found</returns>
internal static string[] FTP_GetFileList(string targetPath)
{
string[] dirs = targetPath.Split(new char[] { '\\', '/' });
string[] files = null;
using (FTPFactory myFTP = new FTPFactory())
{
myFTP.login();
myFTP.setBinaryMode(true);
// Make sure the directories are there and change down to the bottom most directory...
foreach (string dirName in dirs)
{
bool dirExists = true;
try { myFTP.chdir(dirName); }
catch { dirExists = false; }
if (!dirExists)
{
myFTP.mkdir(dirName);
myFTP.chdir(dirName);
}
}
// get the list of files now...
files = myFTP.getFileList("*.*");
}
return files;
}
/// <summary>
/// Checks to see if a file exists
/// </summary>
/// <param name="targetPath">The CDN directory path to look in</param>
/// <param name="targetFile">The file to look for</param>
/// <returns>true = found, false = not found</returns>
internal static bool FTP_DoesFileExist(string targetPath, string targetFile)
{
bool retFlag = true;
string[] dirs = targetPath.Split(new char[] { '\\', '/' });
using (FTPFactory myFTP = new FTPFactory())
{
myFTP.login();
myFTP.setBinaryMode(true);
// change to the target directory - if it does not exists, neither does the file! simple...
foreach (string dirName in dirs)
{
try { myFTP.chdir(dirName); }
catch { retFlag = false; }
}
if (retFlag)
{
try { retFlag = myFTP.getFileSize(targetFile) > 0; }
catch { retFlag = false; }
}
}
return retFlag;
}
internal static bool FTP_DoesFileExist(string targetFile)
{
string targetPath = targetFile.Replace(#"http://", "");
targetPath = targetPath.Replace(#"https://", "");
targetPath = targetPath.Replace(#"cdn1.[DOMAIN].com/", "");
targetPath = targetPath.Replace(#"/", #"\");
targetPath = targetPath.Substring(0, targetPath.LastIndexOf(#"\"));
targetFile = targetFile.Substring(targetFile.LastIndexOf(#"/") + 1);
return FTP_DoesFileExist(targetPath, targetFile);
}
#endregion
#region Helper Methods
static private string ConstructCredentials()
{
_credential = new EdgeCastCredential();
return _credential.Credential;
}
static private string ConstructCredentials(string credentials)
{
_credential = new EdgeCastCredential(credentials);
return _credential.Credential;
}
static private string ConstructCredentials(string typeOfClient, string securityType, string userName, string password)
{
_credential = new EdgeCastCredential(typeOfClient, securityType, userName, password);
return _credential.Credential;
}
#endregion
#region IDisposable Members
public void Dispose()
{
_current = null;
}
#endregion
}
}
EdgeCastCredential.cs
using System;
using rivSecurity = [DOMAIN].Security.Cryptography.Internal;
namespace [DOMAIN].IO.ContentDeliveryNetwork
{
internal class EdgeCastCredential
{
#region Properties
public string TypeOfClient;
public string SecurityType;
public string UserName;
public string Password;
public string Credential { get { return String.Format("{0}:{1}:{2}:{3}", TypeOfClient, SecurityType, UserName, Password); } }
#endregion
#region Constructor
public EdgeCastCredential()
{
TypeOfClient = AppSettings.EdgeCast_TypeOfClient;
SecurityType = AppSettings.EdgeCast_SecurityType;
UserName = rivSecurity.Decrypt(AppSettings.EdgeCast_UserName);
Password = rivSecurity.Decrypt(AppSettings.EdgeCast_Password);
}
public EdgeCastCredential(string credentials)
{
string[] parts = credentials.Split(new char[] { ':' });
}
public EdgeCastCredential(string typeOfClient, string securityType, string userName, string password)
{
TypeOfClient = typeOfClient;
SecurityType = securityType;
UserName = userName;
Password = password;
}
#endregion
}
}
Never mind. I created a FTP library and used what little they had for an API. I can not now read/upload/delete files and purge the CDN.