listing virtual directories in IIS 6.0 - C# - c#

I have written a Windows Application.My question is:I have been listing virtual directories in IIS 6.0 with through code as below.I have to find pyhsical path of the virtual directory that are selected.
Also,DirectoryEntry class has a property called properties. But,I can't use it. Lastly,I getting the following the error.
The directory cannot report the number of properties
Code:
try
{
string serverName = "localhost";
string VirDirSchemaName = "IIsWebVirtualDir";
iisServer = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1");
DirectoryEntry folderRoot = iisServer.Children.Find("Root",VirDirSchemaName);
return folderRoot.Children;
}
catch (Exception e)
{
throw new Exception("Error while retrieving virtual directories.",e);
}

why don't you use WMI
using System.DirectoryServices;
private DirectoryEntry _iisServer = null;
private DirectoryEntry iisServer
{
get
{
if (_iisServer == null)
{
string path = string.Format("IIS://{0}/W3SVC/1", serverName);
_iisServer = new DirectoryEntry(path);
}
return _iisServer;
}
}
private IDictionary<string, DirectoryEntry> _virtualDirectories = null;
private IDictionary<string, DirectoryEntry> virtualDirectories
{
get
{
if (_virtualDirectories == null)
{
_virtualDirectories = new Dictionary<string, DirectoryEntry>();
DirectoryEntry folderRoot = iisServer.Children.Find("Root", VirDirSchemaName);
foreach (DirectoryEntry virtualDirectory in folderRoot.Children)
{
_virtualDirectories.Add(virtualDirectory.Name, virtualDirectory);
}
}
return _virtualDirectories;
}
}
List all virtual directories in IIS 5,6 and 7

Related

Type variable always returns null when running the GetTypes() method

I have been running into a rather frustrating issue. I am attempting to authenticate a user against an Active Directory, and in order to do so I pass my users variables into the following class.
public static ILdapAuthentication CreateInstance(string domainAndUser, string password, string ldapPath)
{
string[] dllPaths = Directory.GetFiles(ExecutingAssemblyDirectory, "*.dll");
List<Assembly> listOfAssemblies = new List<Assembly>();
foreach (var dllPath in dllPaths.Where(x => x.Contains("ActiveDirectoryAuthentication")))
{
Assembly assembly = Assembly.LoadFrom(dllPath);
listOfAssemblies.Add(assembly);
}
Type type = null;
int foundTypes = 0;
foreach (var assembly in listOfAssemblies)
{
type =
assembly.GetTypes()
.FirstOrDefault(x => x.GetInterfaces().Any(i => i == typeof(ILdapAuthentication)));
if (type == null)
continue;
foundTypes++;
}
if (foundTypes == 0)
throw new Exception("ActiveDirectoryAuthentication DLL not found.");
if (foundTypes > 1)
throw new Exception("Only one ActiveDirectoryAuthentication DLL must be used.");
return Activator.CreateInstance(type, domainAndUser, password, ldapPath) as ILdapAuthentication;
}
The issue occurs in the foreach loop, as I attempt to get my Types, it always returns null, and doesn't even hit the Interface (ILDPAuthentication) code below.
public interface ILdapAuthentication
{
bool IsActiveDirectoryUserValid();
}
which invokes the following code:
public class LdapAuthentication : ILdapAuthentication
{
private string DomainAndUser { get; set; }
private string Password { get; set; }
private string LdapPath { get; set; }
public LdapAuthentication(string domainAndUser, string password, string ldapPath)
{
this.DomainAndUser = domainAndUser;
this.Password = password;
this.LdapPath = ldapPath;
}
public bool IsActiveDirectoryUserValid()
{
try
{
if (!this.DomainAndUser.Contains('\\'))
throw new Exception("Domain User is invalid.");
string[] userLogin = this.DomainAndUser.Split('\\');
string domain = userLogin[0];
string userName = userLogin[1];
DirectoryEntry entry = new DirectoryEntry(this.LdapPath, this.DomainAndUser, this.Password);
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + userName + ")";
search.PropertiesToLoad.Add("CN");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
}
The initial class looks for the DLLs in my application folder called ActiveDirectoryAuthentication which I have copied in.
I have seen this before - types in a explicitly loaded assembly do not match types in a referenced project. Because you are using:
i == typeof(ILdapAuthentication)
you are reliant on the equality comparison for the Type class, which may not return equality when you are expecting it to. I suggest instead you do:
i.FullName == typeof(ILdapAuthentication).FullName
which will use a simple string comparison.

ldap principalsearcher very slow

I want to get information from only 1 user out of 20,000 users. The response time of the method I used below is 40 seconds. What is the solution to this problem?
public AuthenticatedUserProperties Info(string Username)
{
try
{
var context = new PrincipalContext(ContextType.Domain, Settings.LDAPDomain, Settings.LDAPContainer, Settings.LDAPUsername, Settings.LDAPPassword);
UserPrincipal user = new UserPrincipal(context);
user.SamAccountName = Username;
var searcher = new PrincipalSearcher(user);
var searchResults = searcher.FindOne();
DirectoryEntry de = searchResults.GetUnderlyingObject() as DirectoryEntry;
ActiveDirectoryUserProperties prop = ConvertLdapUserPropertyToArray(de);
return new AuthenticatedUserProperties
{
Status = true,
Properties = prop
};
}
catch (Exception e)
{
return new AuthenticatedUserProperties
{
Status = false,
Properties = null
};
}
}
I use the System.DirectoryServices.Protocols library instead. It is always blazing fast. I can never get System.DirectoryServices.AccountManagement to have reliable performance and it is often agonizingly slow (10+ seconds) to get just one user. TBH - I think our Network setup is likely to blame causing the bind to be dysfunctional - but the Protocols library yields good results without much effort regardless of our network dysfunction.
You have to do slightly more work - but nothing particularly difficult. I'm not an expert with this library - but this sample code works reliably for me.
using System.DirectoryServices.Protocols;
public class UserInfo
{
public string SAMAccountName;
public string DomainHostName;
public string ADSDirectory;
public Dictionary<string, string> UserAttributes;
// Some attributes not really strings and require extra handling - but simplied for example
// This is really just for illustrative purposes
public UserInfo(string a_SAMAccountName, string a_DomainHostName = "ldap.mydomain:3268", string a_ADSDirectory = "ours.net")
{
UserAttributes = new Dictionary<string, string>();
SAMAccountName = a_SAMAccountName;
DomainHostName = a_DomainHostName;
ADSDirectory = a_ADSDirectory;
}
}
public static class GetUserAttributes
{
public static List<string> WantedAttributes;
static GetUserAttributes()
{
WantedAttributes = new List<string>();
WantedAttributes.Add("mail");
//... Add Properties Wanted
}
public static void GetUserAttributes(UserInfo a_user)
{
using (HostingEnvironment.Impersonate())
{
LdapDirectoryIdentifier z_entry = new LdapDirectoryIdentifier(a_user.DomainHostName, true, false);
using (LdapConnection z_remote = new LdapConnection(z_entry))
{
z_remote.SessionOptions.VerifyServerCertificate = delegate (LdapConnection l, X509Certificate c) { return true; };
z_remote.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
z_remote.SessionOptions.ProtocolVersion = 3;
z_remote.Bind();
SearchRequest z_search = new SearchRequest();
z_search.Scope = System.DirectoryServices.Protocols.SearchScope.Subtree;
z_search.Filter = "(SAMAccountName=" + a_user.SAMAccountName + ")";
z_search.DistinguishedName = a_user.ADSdirectory;
foreach (List<string> z_item in WantedAttributes)
{
z_search.Attributes.Add(z_item);
}
SearchResponse z_response = (SearchResponse)z_remote.SendRequest(z_search);
if (z_response != null)
{
foreach (SearchResultEntry z_result in z_response.Entries)
{
foreach (string z_property in z_result.Attributes.AttributeNames)
{
if (WantedAttributes.ContainsKey(z_property))
{
DirectoryAttribute z_details = a_result.Attributes[z_property];
if (z_details.Count == 1)
{
// Special handling required for Attributes that aren't strings objectSid, objectGUID, etc
string z_value = z_details[0].ToString().Trim();
if (!string.IsNullOrWhiteSpace(z_value))
{
a_user.UserAttributes.Add(z_property, z_value);
}
}
}
}
}
}
}
}
}
}

How to set proxy for Android in a Xamarin C# application using WebView?

I have an Android application created in C# using Xamarin.
This is essentially a web browser with some additional functionalities and now I would like add the option to set up a proxy to use. In the application I use WebView for connection to websites.
I tried to implement solution from this topic (How can I set ProxySettings and ProxyProperties on Android Wi-Fi connection using Java?), but there is no linkProperties in WifiConfiguration. This is how it looks like:
private static Java.Lang.Object getField(Java.Lang.Object obj, String name)
{
Field f = obj.Class.GetField(name);
Java.Lang.Object o = f.Get(obj);
return o;
}
public void SetHttpProxy(string proxyServerAddress, int proxyServerInt)
{
try
{
var wifiManager = context.GetSystemService(Context.WifiService) as WifiManager;
if (!wifiManager.IsWifiEnabled)
return;
var configurationList = wifiManager.ConfiguredNetworks;
var cur = wifiManager.ConnectionInfo.NetworkId;
var configuration = configurationList.FirstOrDefault(conf => conf.NetworkId == cur);
getField(configuration, "linkProperties");
}
catch (Exception e)
{
throw;
}
}
Here is solution that works for 4., 5., 6.* and 7.* Android OS versions for sure:
public static void SetProxy(WebView webView, string host, int port, bool bypass)
{
Context appContext = webView.Context.ApplicationContext;
JavaSystem.SetProperty("http.proxyHost", host);
JavaSystem.SetProperty("http.proxyPort", port + "");
JavaSystem.SetProperty("https.proxyHost", host);
JavaSystem.SetProperty("https.proxyPort", port + "");
if (bypass)
JavaSystem.SetProperty("http.nonProxyHosts", BYPASS_PATTERN);
try
{
Class applictionCls = Class.ForName(APPLICATION_CLASS_NAME);
Field loadedApkField = applictionCls.GetField("mLoadedApk");
loadedApkField.Accessible = true;
Object loadedApk = loadedApkField.Get(appContext);
Class loadedApkCls = Class.ForName("android.app.LoadedApk");
Field receiversField = loadedApkCls.GetDeclaredField("mReceivers");
receiversField.Accessible = true;
ArrayMap receivers = (ArrayMap) receiversField.Get(loadedApk);
foreach (Object receiverMap in receivers.Values())
{
foreach (Object rec in Extensions.JavaCast<ArrayMap>(receiverMap).KeySet())
{
Class clazz = rec.Class;
if (clazz.Name.Contains("ProxyChangeListener"))
{
Method onReceiveMethod = clazz.GetDeclaredMethod("onReceive", Class.FromType(typeof(Context)), Class.FromType(typeof(Intent)));
Intent intent = new Intent(Android.Net.Proxy.ProxyChangeAction);
onReceiveMethod.Invoke(rec, appContext, intent);
}
}
}
}
catch (Exception)
{
}
}

Memory Issue event receiver

I have an event receiver when i upload documents to share point list.
The event calls a functions that copies the item to two different places.
The problem is that the performance is very bad and the application is taking +/- 10 GB of memory when i upload 5 documents each is +/- 400 KB.
Without the upload the application is working fine.
private static void AttachRoutingEventListener(SPWeb web)
{
web.AllowUnsafeUpdates = true;
try
{
var uploadList = web.Lists[SPUtility.GetLocalizedString("$Resources:MailRoom_List_UploadList_Title", "Matri", web.Language)];
uploadList.EventReceivers.Add(SPEventReceiverType.ItemAdded, "Com.Gimi.Matri.Artifacts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=dad1f8c1ceb5d9440", "Com.Gimi.Matri.Artifacts.RouteScannedDocuments");
uploadList.Update();
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
public override void ItemAdded(SPItemEventProperties properties)
{
using (SPWeb web = properties.Web)
{
base.ItemAdded(properties);
ListItemRouting.RouteItem(properties.ListItem);
}
properties.Dispose();
}
public static void RouteItem(SPListItem item)
{
SPWeb web = item.Web;
SPList documents = web.Lists[SPUtility.GetLocalizedString("$Resources:Matri,MailRoom_List_MailDocuments_Title", "Matri", web.Language)];
SPList metadata = web.Lists[SPUtility.GetLocalizedString("$Resources:MailRoom_List_LetterData_Title", "Matri", web.Language)];
DateTime scanDate = GetScanDate();
Regex mailExtension = new Regex(#"^.+\.(eml)$", RegexOptions.IgnoreCase);
string fileDestinationUrl = CreateFullRelativePath(documents, scanDate) + "/" + item.File.Name;
if (!mailExtension.IsMatch(item.File.Name))
{
try
{
lock (lockObjects)
{
try
{
CopyFile(item, documents, fileDestinationUrl);
}
catch (DirectoryNotFoundException ex)
{
//In case the folder not created
EnsureFolders(documents, scanDate);
CopyFile(item, documents, fileDestinationUrl);
}
try
{
// copy to letterData
CopyMetadata(metadata, item, fileDestinationUrl, scanDate);
}
catch (DirectoryNotFoundException dnEx)
{
//In case the folder not created
EnsureListItemFolders(metadata, scanDate);
CopyMetadata(metadata, item, fileDestinationUrl, scanDate);
}
}
}
catch (Exception genEx)
{
Log.Warn("ZZ ERROR error in eventhandler of upload lis ==> " + genEx.Message);
Log.Error("error in eventhandler of upload list", genEx);
}
}
}
private static DateTime GetScanDate()
{
return DateTime.Now;
}
private static void EnsureListItemFolders(SPList list, DateTime scanDate)
{
SPFolder dayFolder = list.ParentWeb.GetFolder(CreateFullRelativePath(list, scanDate));
SPListItem folder = null;
if (!dayFolder.Exists)
{
folder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, GetFolderName(scanDate));
folder.Update();
}
}
private static void EnsureFolders(SPList list,DateTime scanDate)
{
SPFolder dayFolder = list.ParentWeb.GetFolder(CreateFullRelativePath(list, scanDate));
if (!dayFolder.Exists)
list.RootFolder.SubFolders.Add(CreateFullRelativePath(list, scanDate));
}
private static void CopyMetadata(SPList metadata, SPListItem item, string fileDestinationUrl, DateTime scanDate)
{
SPListItemCollection metadataItems = metadata.Items;
SPListItem destination = metadataItems.Add(CreateFullRelativePath(metadata, scanDate), SPFileSystemObjectType.File, null);
destination["Title"] = item["Title"];
destination["DateOfLetter"] = item["DateOfLetter"];
destination["SenderName"] = item["SenderName"];
destination["CompanyAddressee"] = item["CompanyAddressee"];
destination["AddresseeName"] = item["AddresseeName"];
destination["Recipient"] = item["Recipient"];
destination["DateOfScan"] = DateTime.Now;
destination["MailType"] = item["MailType"];
destination["Priority"] = item["Priority"];
destination["ScanLocation"] = item["ScanLocation"];
destination["LetterURL"] = new Uri(new Uri(item.Web.Url), new Uri(fileDestinationUrl, UriKind.Relative)).AbsoluteUri;
destination.Update();
}
private static void CopyFile(SPListItem item, SPList documents, string fileDestinationUrl)
{
using (Stream docStream = item.File.OpenBinaryStream())
{
documents.RootFolder.Files.Add(fileDestinationUrl, docStream, true);
docStream.Flush();
docStream.Close();
}
}
private static string CreateFullRelativePath(SPList destination, DateTime scanDate)
{
return destination.RootFolder.ServerRelativeUrl + "/" + GetFolderName(scanDate);
}
private static string GetFolderName(DateTime date)
{
return date.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
}
Thank you in advance!
It seems that SpWeb.Lists["list name"] was the issue
I replaced it by
SpWeb.GetList("Url");
Reference url Best Practices: SharePoint Object Model for Performance Tuning

How to resolve the Error " Unable to locate local.config.user file. Make sure you have run 'build.cmd local' '

i am trying to run this test on local host, but it keeps throwing the error " Unable to locate local.config.user file. Make sure you have run 'build.cmd local'"
So how do I locate local.config.user file? Or how to run build.cmd local ? Please try see Code below
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Configurations
{
public class ConfigurationProvider : IConfigurationProvider, IDisposable
{
readonly Dictionary<string, string> configuration = new Dictionary<string, string>();
EnvironmentDescription environment = null;
const string ConfigToken = "config:";
bool _disposed = false;
public string GetConfigurationSettingValue(string configurationSettingName)
{
return this.GetConfigurationSettingValueOrDefault(configurationSettingName, string.Empty);
}
public string GetConfigurationSettingValueOrDefault(string configurationSettingName, string defaultValue)
{
try
{
if (!this.configuration.ContainsKey(configurationSettingName))
{
string configValue = string.Empty;
bool isEmulated = true;
bool isAvailable = false;
try
{
isAvailable = RoleEnvironment.IsAvailable;
}
catch (TypeInitializationException) { }
if (isAvailable)
{
configValue = RoleEnvironment.GetConfigurationSettingValue(configurationSettingName);
isEmulated = RoleEnvironment.IsEmulated;
}
else
{
configValue = ConfigurationManager.AppSettings[configurationSettingName];
isEmulated = Environment.CommandLine.Contains("iisexpress.exe") ||
Environment.CommandLine.Contains("WebJob.vshost.exe");
}
if (isEmulated && (configValue != null && configValue.StartsWith(ConfigToken, StringComparison.OrdinalIgnoreCase)))
{
if (environment == null)
{
LoadEnvironmentConfig();
}
configValue =
environment.GetSetting(configValue.Substring(configValue.IndexOf(ConfigToken, StringComparison.Ordinal) + ConfigToken.Length));
}
try
{
this.configuration.Add(configurationSettingName, configValue);
}
catch (ArgumentException)
{
// at this point, this key has already been added on a different
// thread, so we're fine to continue
}
}
}
catch (RoleEnvironmentException)
{
if (string.IsNullOrEmpty(defaultValue))
throw;
this.configuration.Add(configurationSettingName, defaultValue);
}
return this.configuration[configurationSettingName];
}
void LoadEnvironmentConfig()
{
var executingPath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
// Check for build_output
int buildLocation = executingPath.IndexOf("Build_Output", StringComparison.OrdinalIgnoreCase);
if (buildLocation >= 0)
{
string fileName = executingPath.Substring(0, buildLocation) + "local.config.user";
if (File.Exists(fileName))
{
this.environment = new EnvironmentDescription(fileName);
return;
}
}
// Web roles run in there app dir so look relative
int location = executingPath.IndexOf("Web\\bin", StringComparison.OrdinalIgnoreCase);
if (location == -1)
{
location = executingPath.IndexOf("WebJob\\bin", StringComparison.OrdinalIgnoreCase);
}
if (location >=0)
{
string fileName = executingPath.Substring(0, location) + "..\\local.config.user";
if (File.Exists(fileName))
{
this.environment = new EnvironmentDescription(fileName);
return;
}
}
throw new ArgumentException("Unable to locate local.config.user file. Make sure you have run 'build.cmd local'.");
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
if (environment != null)
{
environment.Dispose();
}
}
_disposed = true;
}
~ConfigurationProvider()
{
Dispose(false);
}
}
}
Hi sir, thank you for your help. I have tried "Build.cmd build" and "Build.cmd local" it gave me this error.
Normally in the root folder of your Visual Studio solution you should have a build.cmd file.
You need to run Developer Command Prompt for VS2015 (or with an another version of installed Visual Studio, use Windows Search in the Start menu) as an Administrator and change directory (cd [directory with solution]) to the root folder of mentioned solution and then type and run build.cmd local by clicking Enter.

Categories