Exception "System.ObjectDisposedException: Safe handle has been closed" after unsuccessfully NTAccount.Translate - windows

I have this problem on a asp.net website, but it should be general for .Net Core on windows computer.
If I try to translate an nonexistent Domain, I’ll get an exception, it’s OK, but then, all next calls with correct domain name throw an exception also "System.ObjectDisposedException: Safe handle has been closed".
I'm asking about some workaround, because name translation does ‘not work until restart of application.
This behavior can be reproduced with
Microsoft.NETCore.App 2.2.0
System.Security.Principal.Windows 4.5.1
class Program
{
static string Translate(string gName)
{
try
{
var nt = new NTAccount(gName);
if (nt.IsValidTargetType(typeof(SecurityIdentifier)))
{
var si = (SecurityIdentifier)(nt).Translate(typeof(SecurityIdentifier));
return si.ToString();
}
}
catch (Exception ex)
{
Console.Write(ex.ToString()+"\n\n");
}
return "";
}
static void Main(string[] args)
{
var si= new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
var na = si.Translate(typeof(NTAccount));
var knownName = na.ToString();
foreach (var aName in new[] { knownName,
#"DOMAIN_NOT_ESISTS\Benutzer",
knownName })
{
Console.WriteLine(aName);
Console.WriteLine(Translate(aName));
}
Console.ReadKey();
}
}

Related

Can't see BlueetoothLE devices

I'm working on BluetoothLE, I want to see the devices around me in a list with their names, and I want to see the properties, services and characters of a device, but I can't see these devices even though the bluetooth of my phone and headset is turned on, the list always comes up empty.
Here is my sample code:
private GattCharacteristic gattCharacteristic;
private BluetoothLEDevice bluetoothLeDevice;
public List<DeviceInformation> bluetoothLeDevicesList = new List<DeviceInformation>();
public DeviceInformation selectedBluetoothLeDevice = null;
public bool IsScannerActiwe { get; set; }
public bool ButtonPressed { get; set; }
public bool IsConnected { get; set; }
public static string StopStatus = null;
public BluetoothLEAdvertisementWatcher watcher;
private DeviceWatcher deviceWatcher;
public void StartWatcher()
{
try
{
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.IsPresent", "System.Devices.Aep.ContainerId", "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.Manufacturer", "System.Devices.Aep.ModelId", "System.Devices.Aep.ProtocolId", "System.Devices.Aep.SignalStrength" };
deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
}
catch (Exception ex)
{
Console.WriteLine("Exception -> ", ex.Message);
}
}
public List<DeviceInformation> GetBluetoothLEDevicesList()
{
try
{
return bluetoothLeDevicesList;
}
catch (Exception ex)
{
Console.WriteLine("Exception Handled -> GetBluetoothLEDevices: " + ex);
throw ex;
}
}
public List<string> GetBluetoothLEDevices()
{
try
{
return bluetoothLeDevicesList.Select(x => x.Name).ToList();
}
catch (System.Exception ex)
{
Trace.WriteLine("Exception Handled -> GetBluetoothLEDevices: " + ex);
throw ex;
}
}
I started a few new advertisements with my iphone via the nrF Connect application and I can see it on my pc, but I want to put them all in a list and navigate through that list.
This is Test.cs:
class Test
{
static void Main(string[] args)
{
// Since the StartWatcher method is called from within the constructor method,
that method will always run whenever an instance is created.
BLEControllers bLEControllers = new BLEControllers();
var devices = bLEControllers.GetBluetoothLEDevicesList();
foreach (var device in devices)
{
if (device != null)
{
Console.WriteLine(device.Name);
}
Console.WriteLine("empty");
}
//bLEControllers.ConnectDevice(device);
//bLEControllers.ConnectDevice();
Console.Read();
}
}
Whenever I run this code, neither device names nor empty text appears on the console, only the startWatcher function works and ends. Is there any function to list all the devices? And how can I see the supported service and characteristic uuids? is there a way to do this?

Configuring Skype for Business delegates using UCMA

I have been struggling to programatically add a delegate to a user (boss/admin scenario).
After running my test code in the boss sfb client the admin appears as a delegate however, in the admin's sfb client the boss does not appear under the section "people I manage calls for". I verified in the rtc frontend database that the delegation is configured, however the admin subscription record does not list the boss. Below is the code I used to achieve this.
Any ideas why the admin sfb client is not being notified of the new delegation?
Thanks,
Simon
1) add delegate-management
public void SendAddDelegate()
{
string body = string.Format($"<setDelegates xmlns=\"http://schemas.microsoft.com/2007/09/sip/delegate-management\" version=\"1\"><delegate uri=\"sip:admin#example.com\" action=\"add\"/></setDelegates>");
byte[] encBody = Encoding.UTF8.GetBytes(body);
RealTimeAddress rta = new RealTimeAddress("sip:boss#example.com");
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType("application/msrtc-setdelegate+xml")
endpoint.InnerEndpoint.BeginSendMessage(MessageType.Service, rta, contentType, encBody, SendAddDelegateManagementMessageComplete, null);
}
private void SendAddDelegateManagementMessageComplete(IAsyncResult result)
{
try
{
SipResponseData srd = endpoint.InnerEndpoint.EndSendMessage(result);
logger.Debug($"srd.ResponseCode - {srd.ResponseCode}");
}
catch (Exception exc)
{
logger.Error("Exception SendMessageComplete with message - {0}", exc.Message);
}
}
2) Publish presence
public void PublishRoutingCategory(string delegateUri)
{
//routes not created here for sample brevity
routes.DelegateRingEnabled = true;
routes.Delegates.Add(delegateUri);
routes.SimultaneousRingEnabled = true;
routes.SimultaneousRing.Add(delegateUri);
routes.SkipPrimaryEnabled = true;
routes.ForwardAudioAppInvitesEnabled = true;
try
{
userEndpoint.LocalOwnerPresence.BeginPublishPresence(new PresenceCategory[] { routes }, PublishComplete, null);
}
catch (Exception exc)
{
logger.Error("Unknown error - {0}", exc.Message);
}
}
private void PublishComplete(IAsyncResult result)
{
try
{
endpoint.LocalOwnerPresence.EndPublishPresence(result);
}
catch (Exception exc)
{
logger.Error("Error Publish Complete- {0}", exc.Message);
}
}

Open a browser with a specific URL by Console application

I'm doing a console application in Visual Studio, but I have a little problem.
If I want to open a browser with a specified URL when any key is pressed, how can I do that?
Thanks
If you want to cover also .Net Core applications.Thanks to Brock Allen
https://brockallen.com/2016/09/24/process-start-for-urls-on-net-core/
public static void OpenBrowser(string url)
{
try
{
Process.Start(url);
}
catch
{
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
Use the ProcessStartInfo class instance to set of values that are used to start a process.
Something like this:
using System;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var psi = new ProcessStartInfo("iexplore.exe");
psi.Arguments = "http://www.google.com/";
Process.Start(psi);
}
}
}

Data serialization on WIndows Phone

I'm following this tutorial and I'm stuck at the part where the TwitterAcces class (that contains the twitter token) is serialized. This is where the serialization method is called:
void CallBackVerifiedResponse(OAuthAccessToken at, TwitterResponse response)
{
if (at != null)
{
SerializeHelper.SaveSetting<TwitterAccess>("TwitterAccess", new TwitterAccess
{
AccessToken = at.Token,
AccessTokenSecret = at.TokenSecret,
ScreenName = at.ScreenName,
UserId = at.UserId.ToString()
});
}
}
And this is my SerializeHelper.cs:
public class SerializeHelper
{
public static void SaveSetting<T>(string fileName, T dataToSave)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (var stream = store.CreateFile(fileName))
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, dataToSave);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return;
}
}
}
}
The error I'm getting is: The type or namespace name 'DataContractSerializer' could not be found (are you missing a using directive or an assembly reference?) Visual Studio can't help me resolve the problem. It suggests creating a new class. I googled around and I think the class should be inside System.Runtime.Serialization; which I am using but that doesn't solve the problem.
You got to add System.Runtime.Serialization.dll referenced in your project.

Windows Phone app throws exception (quit automatically) when running under 3G, but fine with WIFI. Very weird

I have tried hundreds of times to find errors for this piece of codes.
It only works through WIFI, but When I switch off WIFI on my phone, and run the app again, this app just shut down automatically, which means it thrown an exception.
The app is simple, I used WebClint() to download HTML source and parsed it with HTML Agility Pack, then added them to a list, foreach the list to creat each news object.
I have tried catch the exception stacktrace and bind it to a texblock, It said some of ArgumentOutOfRange exception and Genericlist(int32 index)???
I have no idea about it, It was fine in wifi, but not in 3G network. Can anyone help?
public partial class MainPage : PhoneApplicationPage
{
string srcHTML;
HtmlNode UrlNode;
ObservableCollection<News> newsList = new ObservableCollection<News>();
List<HtmlNode> headlines;
HtmlDocument hd;
News n;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClenet = new WebClient();
webClenet.Encoding = new HtmlAgilityPack.Gb2312Encoding();
webClenet.DownloadStringAsync(new Uri("http://www.6park.com/news/multi1.shtml", UriKind.RelativeOrAbsolute));
webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);
}
private void webClenet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
srcHTML = e.Result;
GetHeadlinePage(srcHTML);
}
private void GetHeadlinePage(string srcHTML)
{
hd = new HtmlDocument();
hd.LoadHtml(srcHTML);
try
{
UrlNode = hd.DocumentNode.ChildNodes[1].ChildNodes[3].ChildNodes[8].ChildNodes["tr"].ChildNodes["td"].ChildNodes["ul"];
headlines = UrlNode.Descendants("a").ToList();
foreach (var headline in headlines)
{
if (headline.Attributes["href"].Value.Contains("6park"))
{
n = new News();
n.NewsTitle = headline.InnerText;
n.NewsUrl = headline.Attributes["href"].Value;
n.NewsDetails = headline.NextSibling.InnerText.Replace("- ", "新闻来源:") + headline.NextSibling.NextSibling.InnerText + headline.NextSibling.NextSibling.NextSibling.InnerText;
newsList.Add(n);
}
}
}
catch (Exception ex)
{
//NewsSource.Text = ex.StackTrace + "\n" + ex.Message;
}
NewslistBox.ItemsSource = newsList;
//NewsHeadlineWebBrowser.NavigateToString(ConvertExtendedASCII(headNews));
}
}
I'd debug the value passed to GetHeadlinePage().
I'd suspect that the response is different based on the network or the request is timing out or you're getting some other error.
I'd assume that the call to LoadHtml() is failing as this isn't inside any exception handling/trapping and you've not validating the value passed to it.

Resources