C#: trying to set "ServerBindings" property of my website programatically, keeps crashing - c#

I am trying to Configure my IIS programmatically following the steps on this
msdn guide
the only difference i made was switching to winforms instead of console..
and variables instead of function parameters.
however the code throws an exception when i try to set the singleproperty value...
here is my code..
string metabasePath = "IIS://localhost/W3SVC/1234", propertyName = "ServerBindings";
object newValue = " :8080:";
try
{
DirectoryEntry path = new DirectoryEntry(metabasePath);
//when i try to retrieve the old value,it returns a null
PropertyValueCollection propValues = path.Properties[propertyName];
MessageBox.Show("7");
//the code throws an exception after messagebox,
//kinda old school debuging
path.Properties[propertyName][0] = newValue;
path.CommitChanges();
lblerror.Text = "Done";
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" == ex.Message)
lblerror.Text = " Property does not exist at ";
else
lblerror.Text = "Failed in SetSingleProperty "+ ex.Message.ToString();
}

The following 'helper' methods (SetServerBinding and RemoveServerBinding) should be of use:
static void Main(string[] args)
{
using(DirectoryEntry site = new DirectoryEntry("IIS://Localhost/W3SVC/1234"))
{
SetServerBinding(":8080:", site);
RemoveServerBinding(":8080:", site);
RemoveServerBinding("172.16.4.99:8087:somesite.com", site);
SetServerBinding("172.16.4.99:8087:somesite.com", site);
}
}
public static void SetServerBinding(string binding, DirectoryEntry site)
{
if(site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
return;
}
site.Properties["ServerBindings"].Add(binding);
site.CommitChanges();
}
public static void RemoveServerBinding(string binding, DirectoryEntry site)
{
if (site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
}
site.CommitChanges();
}

Related

Why can't I catch this XML exception?

Context
I've written a class to handle settings for my ASP.NET MVC app. However after testing how it handles a malformed/ missing XML file the exception it seems to throw is uncatchable and it repeats endlessly without catching or moving on with execution.
I've disabled the V.S. Debug Dialog popup in the past but again it seems repeat the same segment of code. I do not have a loop anywhere else that calls this property and there is default behavior if the property doesn't return a valid value.
Breakpoints beyond the failing function are not reached, however the breakpoint on or before the XML exception are repeatedly reached...
P.S. there is a lot of failed testing code left over to get a workaround working.
Screenshot:
Screenshot:
EDIT: I must clarify I have tried alternate XML parsing tools, any XMLException here is not caught.
Code ['Setting container' Property]:
private static Settings _singletonSettings;
public static Settings SettingsContainer
{
get
{
if (_singletonSettings == null)
{
_singletonSettings = new Settings();
_singletonSettings .LoadSettings();
}
return _singletonSettings;
}
private set
{
_singletonSettings = value;
}
}
Code ['LoadSettings function']:
public void LoadSettings()
{
string filePath = "Config/Settings.txt";
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
}
if (File.Exists(filePath))
{
try
{
SettingsContainer = LoadViaDataContractSerialization<Settings>(filePath); // Desperately trying to catch the exception.
}
catch (Exception ex)
{
Log.GlobalLog.WriteError("LoadViaDataContractSerialization() error:\n" + ex.Message + "\nStackTrace: \n" + ex.StackTrace);
}
}
else
{
File.Create(filePath);
}
if (SettingsContainer == null)
{
SettingsContainer = new Settings();
}
}
Code ['LoadViaDataContractSerialization']:
public static T LoadViaDataContractSerialization<T>(string filepath)
{
try
{
T serializableObject;
using (var fileStream = new FileStream(filepath, FileMode.Open))
{
try
{
using (var reader = XmlDictionaryReader.CreateTextReader(fileStream, new XmlDictionaryReaderQuotas())) //All execution stops here with the
{
var serializer = new DataContractSerializer(typeof(T));
serializableObject = (T)serializer.ReadObject(reader, true);
reader.Close();
}
}
catch (XmlException ex)
{
Log.GlobalLog.WriteError("LoadViaDataContractSerialization() XML Fail: Message: " + ex.Message + "\n StackTrace: " + ex.StackTrace);
return default(T);
}
fileStream.Close();
}
return serializableObject;
}
catch (Exception ex)
{
Log.GlobalLog.WriteError("LoadViaDataContractSerialization() Fail: Message: " + ex.Message + "\n StackTrace: " + ex.StackTrace);
return default(T);
}
}
Looks like the issue lay with a lack of understanding in 'return default(T)'.
I'm not sure why it was repeating but by removing the try catch blocks that returned 'default(T)' and responding to the exception 'return new settings()' it allowed the properties value to not be null and function as intended.
Code LoadViaDataContractSerialization:
public static T LoadViaDataContractSerialization<T>(string filepath)
{
T serializableObject;
using (var fileStream = new FileStream(filepath, FileMode.Open))
{
using (var reader = XmlDictionaryReader.CreateTextReader(fileStream, new XmlDictionaryReaderQuotas()))
{
var serializer = new DataContractSerializer(typeof(T));
serializableObject = (T)serializer.ReadObject(reader, true);
reader.Close();
}
fileStream.Close();
}
return serializableObject;
}
Code LoadSettings:
public void LoadSettings()
{
string filePath = "Config/Settings.txt";
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
}
if (File.Exists(filePath))
{
try
{
SettingsContainer = LoadViaDataContractSerialization<Settings>(filePath);
}
catch (Exception ex) //only exception needed
{
Log.GlobalLog.WriteError("LoadViaDataContractSerialization() error:\n" + ex.Message + "\nStackTrace: \n" + ex.StackTrace);
SettingsContainer = new Settings();//<---this was the fix
}
}
else
{
File.Create(filePath);
}
if(SettingsContainer == null)
{
SettingsContainer = new Settings();
}
}
Thank you to 'Generic Snake' for pointing me at the right place.

WFP all TextBlocks not updating

So my code was working just fine. But now, even though I can confirm the variables and strings are there through a Clipboard copy, the textblocks are not updating via TextBlock.Text. Did I turn something off? Every single one stopped doing it at the same time.
`private void actionPing_Click(object sender, RoutedEventArgs e)
{
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(HostNameIPTyped.Text.ToString(), 500);
if (reply != null)
{
string tripTime = reply.RoundtripTime.ToString();
if (tripTime == "0")
{
PingStatus1.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#660000"));
PingStatus1.Text = "Device not found"; <---NONE OF THESE ARE UPDATING ACROSS THE ENTIRE PROGRAM
}
else
{
PingStatus1.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#17b05c"));
PingStatus1.Text = "Ping Successful, " + reply.RoundtripTime.ToString() + "ms roundtrip";
//// LET'S GET THE IP AND HOSTNAME OF WHATEVER THE HELL YOU PUT IN
////IPADDRESS
try
{
System.Net.IPAddress ip = System.Net.Dns.GetHostEntry(HostNameIPTyped.Text.ToString()).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First();
ipAddress = ip.ToString();
}
catch (Exception ex)
{ }
////HOSTNAME
try
{
System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(ipAddress);
machineName = hostEntry.HostName;
string linkBuild = "http://" + machineName;
}
catch (Exception ex) { }
PingStatus1.Text += " " + machineName;
}
}
}
catch
{
{
PingStatus1.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#660000"));
PingStatus1.Text = "Device not found";
}
}
}`
It was updating the fields. I had made an adjustment to the size of the grid which flattened all of the textblock fields to the left side. Once I drug them out they were no longer auto-sized.
Thanks for the help!

C# Adding PC to AD domain group

Trying to add a hostname to a domain group, and I'm getting the exception There is a naming violation.
I've seen several accepted answers covering this exact thing and as far as I know my syntax is correct.
try
{
DirectoryEntry de = new DirectoryEntry("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Groups,OU=US,DC=aa,DC=bbbbb,DC=com");
string hostname = "CN=" + SystemInformation.ComputerName;
DirectoryEntry add = de.Children.Add(hostname, "Computer");
add.CommitChanges();
}
catch (Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
Any help would be greatly appreciated.
I figured out what the problem was - I needed to pass the Distinguished Name, rather than just the hostname... that should have been obvious, if I had actually read the MSDN doc... Also, de.Children.Add() may be a valid method to accomplish this (it was an accepted answer on SE, for .Net 3.5 IIRC), but I used de.Properties["member"].Add() to accomplish it.
Updated source code for any Googlers out there:
private void DoStuff(object sender, EventArgs e)
{
using (Process addgroup = new Process())
{
string hostname = Environment.MachineName;
AddMemberToGroup("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Group,OU=US,DC=aa,DC=bbbbb,DC=com", hostname);
}
}
private void AddMemberToGroup(string ldapString, string host)
{
try
{
DirectoryEntry de = new DirectoryEntry(ldapString);
string distHost = GetDistinguishedName(host);
if (!String.IsNullOrEmpty(distHost))
{
de.Properties["member"].Add(distHost);
de.CommitChanges();
}
else
{
MessageBox.Show("Distinguished Host Name returned NULL");
}
}
catch(Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
}
private string GetDistinguishedName(string compName)
{
try
{
PrincipalContext pContext = new PrincipalContext(ContextType.Domain);
ComputerPrincipal compPrincipal = ComputerPrincipal.FindByIdentity(pContext, compName);
return compPrincipal.DistinguishedName;
}
catch (Exception ex)
{
MessageBox.Show("Failed to get the Distinguished Hostname from Active Directory" + Environment.NewLine + Environment.NewLine + ex.ToString());
return null;
}
}

Permission screen appears every time

I want to make my WinForms-App to use the SingleSign-On (SSO) feature with Microsoft Accounts.
I created a LiveApp and I'm able to Login to my App with the LiveSDK 5.4.
But everytime I click on my Login-Button the permissions list appears and I need to accept it again.
This is my code:
private const string ClientID = "{MY_CLIENT_ID}";
private LiveAuthClient liveAuthClient;
private LiveConnectClient liveConnectClient;
string[] scopes = new string[] { "wl.offline_access", "wl.emails", "wl.signin" };
private void buttonLogin_Click(object sender, EventArgs e)
{
liveAuthClient = new LiveAuthClient(ClientID);
webBrowser1.Navigate(liveAuthClient.GetLoginUrl(scopes));
}
private async void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (this.webBrowser1.Url.AbsoluteUri.StartsWith("https://login.live.com/oauth20_desktop.srf"))
{
AuthResult authResult = new AuthResult(this.webBrowser1.Url);
if (authResult.AuthorizeCode != null)
{
try
{
LiveConnectSession session = await liveAuthClient.ExchangeAuthCodeAsync(authResult.AuthorizeCode);
this.liveConnectClient = new LiveConnectClient(session);
LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me");
dynamic meData = meRs.Result;
if(string.Equals(meData.emails.account, MyAppUser.EmailAddress))
MessageBox.Show("Successful login: " + meData.name);
}
catch (LiveAuthException aex)
{
MessageBox.Show("Failed to retrieve access token. Error: " + aex.Message);
}
catch (LiveConnectException cex)
{
MessageBox.Show("Failed to retrieve the user's data. Error: " + cex.Message);
}
}
else
{
MessageBox.Show(string.Format("Error received. Error: {0} Detail: {1}", authResult.ErrorCode, authResult.ErrorDescription));
}
}
}
What I need to change? I don't want the User to accept the permissions on each login.
You can use IRefreshTokenHandler to save token as following example:
public class RefreshTokenHandler : IRefreshTokenHandler
{
private string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\oneDrive\\RefreshTokenHandler\\RefreshTokenInfo.RefreshToken-me";
public Task<RefreshTokenInfo> RetrieveRefreshTokenAsync()
{
return Task.Factory.StartNew<RefreshTokenInfo>(() =>
{
if (File.Exists(path))
{
return new RefreshTokenInfo(File.ReadAllText(path));
}
return null;
});
}
public Task SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
{
// Note:
// 1) In order to receive refresh token, wl.offline_access scope is needed.
// 2) Alternatively, we can persist the refresh token.
return Task.Factory.StartNew(() =>
{
if (File.Exists(path)) File.Delete(path);
if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path));
File.AppendAllText(path, tokenInfo.RefreshToken);
});
}
}
after that you get session as following:
RefreshTokenHandler handler = new RefreshTokenHandler();
liveAuthClient = new LiveAuthClient(ClientID, handler);
var Session = liveAuthClient.InitializeAsync(scopes).Result.Session;
if (Session == null)
{
webBrowser1.Navigate(liveAuthClient.GetLoginUrl(scopes));
}
else
{
try
{
this.liveConnectClient = new LiveConnectClient(Session);
LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me");
dynamic meData = meRs.Result;
if (string.Equals(meData.emails.account, MyAppUser.EmailAddress))
MessageBox.Show("Successful login: " + meData.name);
}
catch (LiveAuthException aex)
{
MessageBox.Show("Failed to retrieve access token. Error: " + aex.Message);
}
catch (LiveConnectException cex)
{
MessageBox.Show("Failed to retrieve the user's data. Error: " + cex.Message);
}
}
I've only used this API in Objective C, but I had to follow two steps.
Use the wl.offline_access scope. (Which you're already doing)
You only show the login screen if the sessions object is null. If your session object is already populated, you can proceed as you would if the sign in was successful.

Output variable from void method so that a javascript function can read it

Hi I am trying to authenticate a user through this method
protected void btnLogin_Click(object sender, EventArgs e)
{
string email = txtEmail.Text;
string password = txtPassword.Text;
try
{
bool loginResult = SingletonManager.Instance.FrontendFactories.UserFrontendFactory.LoginUser(email, FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5"), chkRememberMe.Checked);
if (loginResult == true)
{
FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, true);
Context.Items.Add("email", txtEmail.Text);
}
else
{
txtEmail.CssClass += " " + "txt-error-message";
errorIconmaEmail.Visible = true;
txtPassword.CssClass += " " + "txt-error-message";
errorIconPassword.Visible = true;
}
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
}
Now i know it is a void method and void methods do not return values but is there a work around to sumhow create a bool in the else block (instead of the current code) such as bool isValidUser = false, so the javascript function will take care of the error message styling according to the value of this bool. FYI i am accessing the code behind public variables thorugh.
<%= isValidUser %>
RegisterCloentScriptBlock seems to be the function you are looking for.

Categories