How can I use start script change IIS Application pool pipeline mode - iis

I used a web role.
I just wonder if I can use Start script for my project to change the pipeline mode to classic.
I can use C# code achieve that, but I prefer to use cmd, The problem I meet here is how can I get the applicationPool name by cmd?
Here is my C# code:
{
using (ServerManager serverManager = new ServerManager())
{
Site site = serverManager.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_Web"];
Configuration config = serverManager.GetApplicationHostConfiguration();
string AppPoolName = site.Applications[0].ApplicationPoolName;
ConfigurationSection applicationPoolsSection = config.GetSection("system.applicationHost/applicationPools");
ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection();
ConfigurationElement addElement = FindElement(applicationPoolsCollection, "add", "name", AppPoolName);
if (addElement == null) throw new InvalidOperationException("Element not found!");
addElement["managedPipelineMode"] = #"Classic";
serverManager.CommitChanges();
return base.OnStart();
}
}
private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues)
{
foreach (ConfigurationElement element in collection)
{
if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
{
bool matches = true;
for (int i = 0; i < keyValues.Length; i += 2)
{
object o = element.GetAttributeValue(keyValues[i]);
string value = null;
if (o != null)
{
value = o.ToString();
}
if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
{
matches = false;
break;
}
}
if (matches)
{
return element;
}
}
}
return null;
}
}
So How can I do that ?

If the pool name is the only problem you are facing, try using appcmd for listing all available pools:
appcmd.exe list apppool /text:*
This should give you all apppools available on IIS with the app names (provided you have enough rights).

Related

Windows Form in a Revit Addin

I have written quite a few different add-ins now but I keep struggling to get a windows form working on Revit. The program builds fine and I have the dll set up for Revit to access.
Here are the different sections of my code. The program is more extensive than what is seen but I believe that the problem is a reference issue or a problem with my ADDIN file. Maybe there is a different way I need to set up my ADDIN file since I have a windows form in it?? Let me know.
Here is a Dropbox folder with the screenshots in it.
Let me know if there is anything else you need to see. The error in Revit says it has to do with the FullName but I believe I put it in the ADDIN file correctly, and I did it the same as I had for other ADDINs.
Thank you for your help!
[TransactionAttribute(TransactionMode.Manual)]
[RegenerationAttribute(RegenerationOption.Manual)]
public class CicuitChecker : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
//set document variable
Document document = commandData.Application.ActiveUIDocument.Document;
using (Transaction trans = new Transaction(document))
{
trans.Start("Circuit Checker");
UIApplication uiApp = commandData.Application;
Document doc = uiApp.ActiveUIDocument.Document;
//run through looped form in case of user not selecting needed fields, and store what family the user wants the program to check
Boolean messedUp = false;
Boolean All = false, lightF = false, recep = false, elecEquip = false, equipCon = false, junc = false, panels = false;
FilteredElementCollector collector = new FilteredElementCollector(doc), collector2 = new FilteredElementCollector(doc);
while (messedUp)
{
CircuitChecker.CircuitCheckerForm form = new CircuitChecker.CircuitCheckerForm();
form.ShowDialog();
//Get application and document objects
foreach (String item in form.getSelectionElementsLB())
{
if (item.Equals("All"))
{
All = true;
break;
}
else if (item.Equals("Lighting Fixtures"))
{
lightF = true;
}
else if (item.Equals("Recepticales"))
{
recep = true;
}
else if (item.Equals("Electrical Equipment (including Panels)"))
{
elecEquip = true;
}
else if (item.Equals("Junctions"))
{
junc = true;
}
else
{
messedUp = true;
TaskDialog.Show("Error", "At least one element must be selected.");
}
}
if (form.getSelectionPlaceLB().Equals("Entire Project"))
{
collector
= new FilteredElementCollector(doc)
.WhereElementIsNotElementType();
collector2
= new FilteredElementCollector(doc)
.WhereElementIsNotElementType();
}
else if (form.getSelectionPlaceLB().Equals("Elements in Current View"))
{
collector
= new FilteredElementCollector(doc, document.ActiveView.Id)
.WhereElementIsNotElementType();
collector2
= new FilteredElementCollector(doc, document.ActiveView.Id)
.WhereElementIsNotElementType();
}
else
{
messedUp = true;
TaskDialog.Show("Error", "A place must be selected.");
}
}
Color color = new Color(138, 43, 226); // RGB
OverrideGraphicSettings ogs = new OverrideGraphicSettings();
OverrideGraphicSettings ogsOriginal = new OverrideGraphicSettings();
ogs.SetProjectionLineColor(color);
int notCircuited = 0;
//ElementId symbolId = family
ElementCategoryFilter lightFilter = new ElementCategoryFilter(BuiltInCategory.OST_LightingFixtures);
ElementCategoryFilter recepFilter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalFixtures);
ElementCategoryFilter elecEquipFilter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalEquipment);
//ElementClassFilter filter = new ElementClassFilter(typeof("Junction Boxes - Load"));
//FamilyInstanceFilter juncFilter1 = new FamilyInstanceFilter(doc, );
LogicalOrFilter first = new LogicalOrFilter(lightFilter, recepFilter);
if (All)
{
collector.WherePasses(first);
IList<Element> allArr = collector.ToElements();
foreach (Element e in allArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
collector2.WherePasses(elecEquipFilter);
IList<Element> elecEquipArr = collector.ToElements();
foreach (Element e in elecEquipArr)
{
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_PANEL_SUPPLY_FROM_PARAM).AsString();
if ((panel.Equals("")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
TaskDialog.Show("Circuit Checker", notCircuited + " lighting fixtures are not circuited in this view.");
trans.Commit();
}
if (!trans.HasEnded())
{
if (lightF)
{
collector.WherePasses(lightFilter);
IList<Element> lightArr = collector.ToElements();
foreach (Element e in lightArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
if (recep)
{
collector.WherePasses(recepFilter);
IList<Element> recepArr = collector.ToElements();
foreach (Element e in recepArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
if (elecEquip)
{
collector.WherePasses(elecEquipFilter);
IList<Element> elecEquipArr = collector.ToElements();
foreach (Element e in elecEquipArr)
{
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_PANEL_SUPPLY_FROM_PARAM).AsString();
if ((panel.Equals("")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
if (junc)
{
collector.WherePasses(recepFilter);
IList<Element> juncArr = collector.ToElements();
foreach (Element e in juncArr)
{
int cirNum = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER).AsInteger();
String panel = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM).AsString();
if (!(IsNumeric(cirNum)) || (panel.Equals("")) || (panel.Equals("<unnamed>")))
{
doc.ActiveView.SetElementOverrides(e.Id, ogs);
notCircuited++;
}
else
{
doc.ActiveView.SetElementOverrides(e.Id, ogsOriginal);
}
}
}
TaskDialog.Show("Circuit Checker", notCircuited + " lighting fixtures are not circuited in this view.");
trans.Commit();
}
}
return Result.Succeeded;
}
public static Boolean IsNumeric(Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if (Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
}
catch { } // just dismiss errors but return false
return false;
}
}
This code is having the functionality in the 'main class.' I have since moved the functionality to the form class as konrad suggested but am still receiving the FullClassName error in Revit. Please Help!
The schedule data add-in provides a full Visual Studio solution demonstrating how to display a Windows form in a Revit add-in, including the generation of the Windows form on the fly:
http://thebuildingcoder.typepad.com/blog/2012/05/the-schedule-api-and-access-to-schedule-data.html
Here's how I usually set up my Windows Forms based External Commands. Remember that you have to create an External Command, and your addin manifest must point at this class. Then from this class you can launch the Form like so:
[Transaction(TransactionMode.Manual)]
public class SomeCommand : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
// Get application and document objects
UIApplication uiApp = commandData.Application;
Document doc = uiApp.ActiveUIDocument.Document;
UIDocument uidoc = uiApp.ActiveUIDocument;
try
{
SomeNamespace.SomeForm form = new SomeNamespace.SomeForm(doc);
form.ShowDialog();
return Result.Succeeded;
}
// Catch any exceptions and display them
catch (Autodesk.Revit.Exceptions.OperationCanceledException)
{
return Result.Cancelled;
}
catch (Exception ex)
{
message = ex.Message;
return Result.Failed;
}
}
}
So I have a Form class that I instantiate from my ExternalCommand and pass Document to its constructor. That way I have access to document when I am interacting with the form later. I wire up all functionality in code behind of the Form.
Agree, the OP's question is why doesn't the addin work...
From looking at the images, it seems like the issue is that Revit is not properly finding the full class name of the command.
It's a little unusual that you don't have your command class wrapped in a namespace (your form class is, for example).
I would recommend wrapping it in a namespace like "circuitchecker" - like your form class.
Then the "full name" in the addin file would become "circuitchecker.circuitchecker"
(the namespace.classname) - this helps Revit distinguish different classes that might have the same name.
side note: I don't believe that putting a URL into the Image/LargeImage fields in the addin will work - but not positive.

Azure Web App staging monitoring

everyone.
Right now I'm using nice nuGet package to monitor my azure web app. The code could look something like this
var certificate = BuildCertificate(StoreName.My, StoreLocation.LocalMachine, " certificate thumbprint");
string subscriptionId = "subscriptionId";
string webspace = "westuswebspace";
string website = "websitename";
using (var client = new MetricsClient(new CertificateCloudCredentials(subscriptionId, certificate)))
{
var metricDefs = client.MetricDefinitions.List(ResourceIdBuilder.BuildWebSiteResourceId(webspace, website), null, null);
var end = DateTime.UtcNow;
var start = end.AddHours(-12);
var timeGrain = TimeSpan.FromHours(1);
var metricVals = client.MetricValues.List(ResourceIdBuilder.BuildWebSiteResourceId(webspace, website),
metricDefs.MetricDefinitionCollection.Value.Select(md => md.DisplayName).ToList(), "",
timeGrain, start, end);
foreach (var metric in metricVals.MetricValueSetCollection.Value)
{
Console.WriteLine("Metric Name: {0}", metric.DisplayName);
Console.WriteLine("Metric Namespace: {0}", metric.Namespace);
foreach (var val in metric.MetricValues)
{
Console.WriteLine("Value: {0}", val.Average.HasValue ? val.Average.Value : 0);
}
Console.WriteLine("//////////////////////");
}
}
certificate retrieval logic
private static X509Certificate2 BuildCertificate(StoreName storeName, StoreLocation storeLocation, string thumbprint)
{
var store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
try
{
var builder = new StringBuilder(thumbprint.Length);
foreach (char c in thumbprint.Where(char.IsLetterOrDigit))
{
builder.Append(c);
}
string cleanThumbprint = builder.ToString();
X509Certificate2Collection list = store.Certificates.Find(X509FindType.FindByThumbprint, cleanThumbprint, false);
X509Certificate2 cert;
if (list == null || list.Count != 1)
{
cert = null;
}
else
{
cert = list[0];
}
return cert;
}
finally
{
store.Close();
}
}
so, everything works perfectly fine, when I'm working with prod, but I can't figure out, how I can monitor my staging environment.
Please, help me with that. I would highly appreciate any help.

Creating loggers for a windows service and a wcf service hosted by that windows service

I create a logger in my windows service and it works fine until that service creates/hosts a wcf service. When I create the logger in the wcf service, logging destined for the windows service log is actually logged to the wcf service log. Here's some code excerpts:
Windows Service:
enum LoggingListeningPorts
{
MCMessageService = 8182,
MCService = 8183,
MCWCFService = 8184,
MyCourtsAdmin = 8185,
MyCourtsWeb = 8186,
MCManager = 8187,
MCSupport = 8188,
MyCourts = 8189
}
First I start logging in the Windows Service to the file directly as the TCP Listeners haven't been initialized:
private void startFileLogging()
{
string location = "target";
try
{
LoggingConfiguration config = new LoggingConfiguration();
FileTarget target = new FileTarget();
target.Layout = "${longdate} ${machineName} ${callsite} ${message} ${exception:format=tostring}";
target.FileName = Path.Combine(dataDirectory, "MCService.log");
target.KeepFileOpen = false;
eventLog1.WriteEntry(string.Format("target.FileName [{0}]", target.FileName), EventLogEntryType.Information);
LoggingRule normalRule = new LoggingRule("*", LogLevel.Trace, target);
config.LoggingRules.Add(normalRule);
LogManager.Configuration = config;
location = "Config";
LogFactory fac = logger.Factory as LogFactory;
fac.GlobalThreshold = loglevel;
location = "Logging";
//logger.Debug(string.Format("### NRMAP{0}_{1}", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version));
//logger.Debug(string.Format("### MCCommon_{0}", mccommonVersionNumber));
logger.Debug("##########################################");
logger.Debug(string.Format("######## MyCourts Service {0} ", Assembly.GetExecutingAssembly().GetName().Version).PadRight(42, '#'));
logger.Debug("##########################################");
//logger.Debug(string.Format("#### MyCourts Service {0} StartUp ", Assembly.GetExecutingAssembly().GetName().Version));
logger.Debug(string.Format("Database directory [{0}]", dataDirectory));
logger.Log(LogLevel.Trace, "Trace level is [{0}]", logger.IsTraceEnabled);
}
catch (Exception ex)
{
eventLog1.WriteEntry(string.Format("MCService Service logging failed at location [{0}]: {1}", location, ex.Message), EventLogEntryType.Warning);
}
}
Then I start the wcf service:
mcwcfServiceHost.Open();
logger.Trace("MCWCFService opened.");
At this stage the logging for the Windows Service is working perfectly. I then execute the following method in my Windows Service which includes starting logging on the wcf service:
private void initializeMCWCFService()
{
logger.Debug("Set DB Path in MCWCFService");
int pauseTime = 2000;
System.Threading.Thread.Sleep(pauseTime);
EndpointAddress basicHTTPendpoint = null;
EndpointAddress serverTCPEndpoint = null;
var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
var findCriteria = FindCriteria.CreateMetadataExchangeEndpointCriteria(typeof(MCWCFService.MCManagementService));
findCriteria.MaxResults = 1;
var findResults = discoveryClient.Find(findCriteria);
if (findResults.Endpoints.Count > 0)
{
var endpoints = MetadataResolver.Resolve(typeof(MCWCFService.MCManagementService), findResults.Endpoints[0].Address);
if (endpoints.Count > 0)
{
foreach (var item in endpoints)
{
if (item.Address.Uri.Scheme == "net.tcp")
{
logger.Debug("Discovered NetTcpAddress [{0}]", item.Address);
//serverTCPEndpoint = item.Address;
IPAddress[] serverIPAddresses = Dns.GetHostAddresses(item.Address.Uri.Host);
foreach (var address in serverIPAddresses)
{
if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
serverTCPEndpoint = item.Address;
break;
}
}
}
if (item.Address.Uri.Scheme == "http")
{
logger.Debug("Discovered basicHTTPAddress [{0}]", item.Address);
basicHTTPendpoint = item.Address;
}
}
}
}
else
logger.Debug("Discovery failed for MCWCFService");
logger.Debug("MCWCFService TCPEndpoint = [{0}]", serverTCPEndpoint);
mcWCFEndpointAddress = serverTCPEndpoint;
string hostName = Dns.GetHostName();
IPAddress hostIPAddress = null;
IPHostEntry host;
host = Dns.GetHostEntry(hostName);
//logger.Debug("Host = [{0}]", host);
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
hostIPAddress = ip;
logger.Debug("MCService Host [{0}] IP address = [{1}]", hostName, ip);
}
}
ChannelFactory<MCWCFService.IMCManagementService> scf = null;
string location = "";
try
{
location = "create scf";
scf = new ChannelFactory<MCWCFService.IMCManagementService>(
new NetTcpBinding(SecurityMode.None),
serverTCPEndpoint);
location = "create channel";
MCWCFService.IMCManagementService channel = scf.CreateChannel();
location = "set db path";
channel.SetMyCourtsDataDirectory(dataDirectory);
location = "set hostIPaddress";
channel.SetMCServiceIPAddress(hostIPAddress);
location = "start logging";
channel.StartLogging();
}
catch (Exception ex)
{
logger.Fatal("Unable to complete setdb path in MCWCFService # [{0}]: {1}", location, ex);
}
finally
{
if (scf != null && scf.State != CommunicationState.Faulted)
{
if (scf.State == CommunicationState.Opened)
scf.Close();
}
}
}
Here's the method to start the logging on the WCF Service:
public void StartLogging()
{
try
{
LoggingConfiguration cfg = new LoggingConfiguration();
NetworkTarget networkTarget = new NetworkTarget();
networkTarget.Layout = "${longdate} ${machineName} ${callsite} ${message} ${exception:format=tostring}";
networkTarget.Address = string.Format("tcp://{0}:{1}", mcServiceIPAddress, (int)LoggingListeningPorts.MCWCFService);
networkTarget.NewLine = false;
networkTarget.KeepConnection = false;
networkTarget.Name = "network1";
LoggingRule networkRule = new LoggingRule("*", LogLevel.Trace, networkTarget);
cfg.LoggingRules.Add(networkRule);
LogManager.Configuration = cfg;
mcmLogger = LogManager.GetLogger("MCManagementService");
mcmLogger.Fatal("##########################################");
mcmLogger.Trace(string.Format("######## MCWCFService {0} ",
Assembly.GetExecutingAssembly().GetName().Version).PadRight(42, '#'));
mcmLogger.Fatal("##########################################");
}
catch (Exception ex)
{
eventlog.WriteEntry(string.Format("MCManagemntService error {0}", ex), EventLogEntryType.Error);
//errorLogger.FatalException("Unable to start logging: ", ex);
}
At this point, the loging from the Windows Service now gets logged to the WCF Service log.
The obvious solution is that I have mixed up the TCP Listening ports but I've checked that so many times I've got a headache.
I have also tried executing the following method on the Windows Service immediately after starting the logging on the WCF Service but it doesn't do anything...
private void startTCPLogging()
{
logger.Debug("Starting TCP Logger");
try
{
if (logger != null)
logger = null;
LoggingConfiguration cfg = new LoggingConfiguration();
NetworkTarget networkTarget = new NetworkTarget();
networkTarget.Layout = "${longdate} ${machineName} ${callsite} ${message} ${exception:format=tostring}";
networkTarget.Address = string.Format("tcp://{0}:{1}", mcWCFEndpointAddress, (int)LoggingListeningPorts.MCService);
networkTarget.NewLine = false;
networkTarget.KeepConnection = false;
networkTarget.Name = "network1";
LoggingRule networkRule = new LoggingRule("*", LogLevel.Trace, networkTarget);
cfg.LoggingRules.Add(networkRule);
LogManager.Configuration = cfg;
logger = LogManager.GetCurrentClassLogger();
logger.Fatal("Logger switched to TCP Listener");
}
catch (Exception ex)
{
//eventlog1.WriteEntry(string.Format("MCManagemntService error {0}", ex), EventLogEntryType.Error);
//errorLogger.FatalException("Unable to start logging: ", ex);
}
I need two separate logs and I can't see why they are combined into the WCF Service log?
If you are running the Windows Service and the WCF Service in the same process, then it could be due to the fact that you are resetting the LogManager.Configuration .
The instance of LogManager is available within your whole process. So, every time you set the configuration with a new LoggingConfiguration(), you loose the previous set configuration.
Try to set the LogManager.Configuration once, and from there just add or remove targets with methods like :
LogManager.Configuration.FindTargetByName(..)
LogManager.Configuration.RemoveTarget(..)
LogManager.Configuration.AddTarget(...)
or with the help of the property :
LogManager.Configuration.AllTargets

Sharepoint list does not exist on the site efter but it exists in my code when debugging

I shall eventually create a sharepoint calendar. I want to create a eventslist here but I'll get this strange error here.
I create a a eventslist and then check [to see] if its already created. If it is, not I want to create it but then my testLabel says that its already exists.
When I try to delete the list, on the myButton_Click, it gives me this error:
Microsoft.SharePoint.Client.ServerException: List 'CompanyCalendar'
does not exist at site with URL 'http://server1'.
Code
using Microsoft.SharePoint.Client;
namespace CalendarWeb.Pages
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
Web web = clientContext.Web;
ListCreationInformation listCreator = new ListCreationInformation();
listCreator.Title = "CompanyCalendar";
listCreator.Description = "Workcalendar";
listCreator.TemplateType = (int)ListTemplateType.Events;
var ifListExcists = web.Lists.GetByTitle(listCreator.Title);
if (ifListExcists == null)
{
web.Lists.Add(listCreator);
clientContext.ExecuteQuery();
testLabel.Text = "The " + listCreator.Title + " list was created";
}
else
{
testLabel.Text = "List already excist";
}
}
}
protected void myButton_Click(object sender, EventArgs e)
{
Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
Web web = clientContext.Web;
var deleteList = web.Lists.GetByTitle("CompanyCalendar");
deleteList.DeleteObject();
clientContext.ExecuteQuery();
testLabel.Text = "list deleted";
}
}
}
}
When I look at my server1 site the list is not there but in the code it seems like its there since my variable "ifListExcists" is never null.
Your ifListExists variable would never be null because its not executed on server.
Use following method to check if list exists or not:
private bool ValdiateList(ClientContext clientContext, string listName, out List existingList)
{
Web web = clientContext.Web;
existingList =null;
ListCollection lists = web.Lists;
var existingLists
= clientContext.LoadQuery(lists.Where(list => list.Title == listName));
clientContext.ExecuteQuery();
existingList = existingLists.FirstOrDefault();
return (existingList != null);
}

RequestToJoinLeaveEmailSetting is not being set properly in sharepoint 2010

Using object model I am updating group. The value I am setting in 'RequestToJoinLeaveEmailSetting' field is not showing when using PowerShell command. However, when I am fetching it by the object model, it is showing the new value set to 'RequestToJoinLeaveEmailSetting' field.
Using the PowerShell commands I am able to update this field. However, from the object model I am getting the value set from itself, not that is set by PowerShell.
How, can it be in sync? Any help/idea?
Thanks in advanced.
Mohak
Here is my Code:
SPSite Site = new SPSite(siteUrl);
SPWeb spWeb = Site.OpenWeb();
SPGroup spGroup = spWeb.SiteGroups[oldname];
SPRoleCollection roles = spGroup.Roles;
if (roles != null)
{
oldRoles = new ArrayList();
foreach (SPRole role in roles)
{
oldRoles.Add(role.Name);
}
}
// here we are comparing the old and new roles to be updated and separating out
// which roles to be deleted and which is to be updated.
foreach (string role in oldRoles)
{
if (newRoles.Contains(role))
{
updatedRoles.Add(role);
}
else
{
removeRoles.Add(role);
}
}
foreach (string rolenames in newRoles)
{
if (!oldRoles.Contains(rolenames))
{
updatedRoles.Add(rolenames);
}
}
if (removeRoles != null && removeRoles.Count > 0)
{
SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup);
foreach (string str in removeRoles)
{
SPRoleDefinition role = spWeb.RoleDefinitions[str];
//SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup);
roleAssignment.RoleDefinitionBindings.Remove(role);
spWeb.RoleAssignments.Remove(roleAssignment.Member);
spWeb.Update();
}
spWeb.Update();
}
if (spGroup != null)
{
spGroup.Description = description;
spGroup.Name = name;
spGroup.OnlyAllowMembersViewMembership = viewprmsn;
spGroup.AllowMembersEditMembership = edprmsn;
spGroup.AllowRequestToJoinLeave = mbrrqst;
spGroup.AutoAcceptRequestToJoinLeave = acptrqst;
spGroup.RequestToJoinLeaveEmailSetting = emailid;
if (updatedRoles != null && updatedRoles.Count > 0)
SPRoleAssignment roleAssignment = new SPRoleAssignment(spGroup);
// SPRoleDefinition roleDefinition = spWeb.RoleDefinitions["Contribute"];
foreach (string str in updatedRoles)
{
SPRoleDefinition roleDefinition = spWeb.RoleDefinitions[str];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
}
spWeb.RoleAssignments.Add(roleAssignment);
}
//spGroup.RequestToJoinLeaveEmailSetting = emailid;
spGroup.Update();
}
spWeb.Update();
}
catch (Exception ex)
{
SPTlogger.Error("-------------------------ERROR-------------------------");
SPTlogger.Error("Error in UpdateGroup():" + ex.Message);
throw new Exception(ex.Message);
}
finally
{
SPTlogger.Debug("<-- : UpdateGroup()");
}
}
It seems you forgot to apply changes using SPGroup.Update method when the group properties have been updated
PS example:
$web = Get-SPWeb $webUrl
$membersGroup = $web.AssociatedMemberGroup
$membersGroup.RequestToJoinLeaveEmailSetting = "admin#intranet.contoso.com"
$membersGroup.Update() #save group changes

Resources