Can't retrieve application rules with HNetCfg.FwMgr + AuthorizedApplications - c#

I'm trying to retrieve all authorized applications with C#:
ArrayList result = new ArrayList();
INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
foreach (INetFwAuthorizedApplication app in firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
{
Console.WriteLine(app.Name);
}
The AuthorizedApplications is empty, but in Control Panel I can see many rules, enabled or not:
What was wrong? I tried other profiles, e.g DOMAIN/STANDARD, same result.

console.write(result); check if forEach method brings you all aplications authorized with C# should be a loop instead
foreach (INetFwAuthorizedApplication app in
firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
{
Console.WriteLine(app.Name);
}e.g for(INetFwAuthorizedApplication app in
firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications){console.log(app.Name);} Are you sure Name is the correct value?, shouldn't be app.name?
It seems you can iterate the app list, but you are not finding the correct name for app. Use name instead Name. Try console.WriteLine(app.name) or console.WriteLine(app.GetName)
Maybe try this:
public List<Object>(String name){
ArrayList result = new ArrayList();
INetFwMgr firewallManager =
(INetFwMgr)Activator.CreateInstance
(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
foreach (INetFwAuthorizedApplication app in
firewallManager.LocalPolicy
.CurrentProfile.AuthorizedApplications)
{
if(app.Name == _name){
app.Name = name;
Console.WriteLine(app.Name);
}
}
return result;
}

Related

How to prevent fill in values when saving over CSOM to a choice field

I am writing some ETL code to move data between an external system and SharePoint Online.
I am using the nuget package Microsoft.SharePointOnline.CSOM to communicate with SP in C#.
I am using the following code to update my field values.
spListItem[fieldName] = "Test Value";
spListItem.Update();
spClientContext.ExecuteQuery();
I noticed with Choice fields, if I save a non existing value SharePoint does not complain and just adds the value even if Allow 'Fill-in' choices is set to NO.
Is there a validate function anywhere in SharePoint? I saw some methods like ValidateUpdateListItem, but they didn't seem to do what I needed.
You could consider to validate choice field value before saving its value as demonstrated below:
static class ListItemExtensions
{
public static bool TryValidateAndUpdateChoiceFieldValue(this ListItem item, string fieldName, string fieldValue)
{
var ctx = item.Context;
var field = item.ParentList.Fields.GetByInternalNameOrTitle(fieldName);
ctx.Load(field);
ctx.ExecuteQuery();
var choiceField = ctx.CastTo<FieldChoice>(field);
if (!choiceField.FillInChoice)
{
var allowedValues = choiceField.Choices;
if (!allowedValues.Contains(fieldValue))
{
return false;
}
}
item.Update();
return true;
}
}
In that case the ListItem will be updated once the validation is
succeeded.
Usage
using (var ctx = new ClientContext(webUri))
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(itemId);
if(listItem.TryValidateAndUpdateChoiceFieldValue(fieldName,fieldValue))
ctx.ExecuteQuery();
}

How to retrieve list item attachments with SharePoint 2013 Event Receiver in correct order

I've created a Standard SharePoint 2013 Event Receiver on a custom list.
Watched Event = "ItemAdded".
Later in my code I need to retrieve the attachments of the list item in the same order as the user inserted them. But unfortunately it seems that SharePoint does not do this by Default.
Example:
The User creates a list item and attach the following files
Picture_front.jpg
Picture_back.png
Picture_231.jpg
Now in my Event Receiver it is possible that I first get 'Picture_back' then 'Picture_front'... or in any other order.
How can I retrieve the attachments in the same order as they have been attached to the list item?
I tried to use the SPFile Property 'TimeCreated' but this is also not working... They got the same timestamp :( (also if I am using 'Ticks')
Any ideas or I am doing something wrong?
Here is my Code:
public override void ItemAdded(SPItemEventProperties properties)
{
SPAttachmentCollection attachments = properties.ListItem.Attachments;
if (attachments.Count > 0)
{
int p = 1;
Dictionary<string, string> attachementDict = new Dictionary<string, string>();
try
{
foreach (string attachement in attachments)
{
SPFile attachementFile = properties.ListItem.ParentList.ParentWeb.GetFile(properties.ListItem.Attachments.UrlPrefix + attachement);
string imageUrlPath = properties.WebUrl + attachementFile.ServerRelativeUrl;
string imageTimestamp = attachementFile.TimeCreated.Ticks.ToString();
// This Dict is used lator for sorting
// but at the Moment I get here the error that the same key already exists because of the same timestamp of the files :(
attachementDict.Add(imageTimestamp, imageUrlPath);
}
}
catch (Exception ex)
{
// SPLog
}
}
here my code ..i hope it help you!
try
{
string strUrl = SPContext.Current.Site.Url + "/" + subSite;
using (SPSite Site = new SPSite(strUrl))
{
using (SPWeb Web = Site.OpenWeb())
{
SPList List = Web.Lists[listName];
SPListItem item = List.GetItemById(ID);
foreach (String attachmentname in item.Attachments)
{
AnnouncementsCommon objAnnouncementsCommon = new AnnouncementsCommon();
String attachmentAbsoluteURL = item.Attachments.UrlPrefix + attachmentname;
objAnnouncementsCommon.AttachmentName = attachmentname;
objAnnouncementsCommon.AttachmentURL = attachmentAbsoluteURL;
lstAnnouncementsCommon.Add(objAnnouncementsCommon);
}
}
}
}
catch (Exception Exc)
{
Microsoft.Office.Server.Diagnostics.PortalLog.LogString("SSC DAL Exception Occurred: {0} || {1}", Exc.Message, Exc.StackTrace);
}
return lstAnnouncementsCommon;
}
As an alternative approach you could use your receiver to store the attachments in a picture library and add two fields to this library: a lookup column to your original custom list item and an option column with "default", "front view", "back view" (or similar).
One advantage is that you can easily update your images in the future and another is that SharePoint automatically creates two preview miniatures in convenient sizes for your images which allows you to reduce bandwidth.

The current user has insufficient permissions to perform this operation. Add Termset in sharepoint

I am trying to bind a field to a termset, and if the termset does not exist I want to create it by code. However, even when the code is running with elevated privileges I get the following exception.
The current user has insufficient permissions to perform this operation.
public static void BindTaxonomyField(string taxonomyFieldId, string taxonomyNoteFieldId, string termSetName, string termGroup, SPWeb web)
{
try
{
if (web != null)
{
// get the taxonomyfield from the sitecollection
var field = web.Fields[new Guid(taxonomyFieldId)] as TaxonomyField;
if (field != null)
{
// attach the note field
field.TextField = new Guid(taxonomyNoteFieldId);
// set up the field for my termstore
var session = new TaxonomySession(web.Site);
if (session.TermStores.Count > 0)
{
// get termstore values
TermStore ts = session.TermStores[0];
Group group = GetGroup(termGroup, ts);
if (group == null)
{
ts.CreateGroup(termGroup);
//throw new Exception("Group was not found in the termstore");
}
// ReSharper disable PossibleNullReferenceException
TermSet termSet = group.TermSets.Any(s => s.Name == termSetName) ? group.TermSets[termSetName] : group.CreateTermSet(termSetName);
// ReSharper restore PossibleNullReferenceException
//TermSet termSet = group.TermSets[termSetName];
// actually setup the field for using the TermStore
field.SspId = ts.Id;
field.TermSetId = termSet.Id;
}
field.Update();
}
}
}
catch (Exception ex)
{
}
}
private void BindColumnsToTermStore(string url)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
if (!web.AllowUnsafeUpdates)
web.AllowUnsafeUpdates = true;
BindTaxonomyField("EF810CD2-F2D2-4BD2-9ABF-C19815F13568",
"67E6E777-0D1E-4840-B858-17400CFABD14",
"Business Audience", "IctDocumentation",
web);
web.AllowUnsafeUpdates = false;
}
}
});
}
If you go in to central administration and navigate to your term store(this is in the left hand nav) in the main container of the page there is a box with a few usernames. Is the account you are running the code in listed? If not stick them in there.
i think the path is something like Central admin -> Manage service application -> Managed meta data service - and the are on the page is call Term store Administrators
There is also one more place you must check but check this first and them run again.
The next place to check is to highlight your Manage metadata service which is located
Central admin -> Manage service application
and click on permissions on the ribbon and make sure the users your running the code with has the correct access.
I always start by making sure i know who i am running the code as first of all then do the checks

Display sharepoint people/group field list's value in people editor

i want to display value of sharepoint people/group value in people editor(web part) when the page is loaded. This is the code that i use to get the value displayed in web part
if(SPContext .Current .ListItem .ID >= 1)
using (SPSite site = new SPSite("sitename"))
{
using (SPWeb web = site.OpenWeb())
{
var id = SPContext.Current.ListItem.ID;
SPList lists = web.Lists["DDClist"];
SPListItem item = lists.GetItemById(id);
{
string test = Convert.ToString(item["Project No"]);
tb_pno.Text = test;
string test2 = Convert.ToString(item["Project Title"]);
tb_pname.Text = test2;
string test3 = Convert.ToString(item["DDC No"]);
tb_idcno.Text = test3;
string test4 = Convert.ToString(item["Date In"]);
TextBox3.Text = test4;
}
}
}
is there a way to do the same thing with people editor?
This is all a little tricky; when I've had to do it before, I use the following to get SPUser object out of a field:
SPUser singleUser = new SPFieldUserValue(
item.Web, item["Single User"] as string).User;
SPUser[] multipleUsers = ((SPFieldUserValueCollection)item["MultipleUsers"])
.Cast<SPFieldUserValue>().Select(f => f.User);
I'm not sure why one user is stored as a string, but multiple users are stored as a specific object; it may also not be consistent in this so you might have to debug a bit and see what the type in your field is.
Once you have these SPUsers, you can populate your PeopleEditor control
using the account names as follows (quite long-winded):
ArrayList entityArrayList = new ArrayList();
foreach(SPUser user in multipleUsers) // or just once for a single user
{
PickerEntity entity = new PickerEntity;
entity.Key = user.LoginName;
entity = peMyPeople.ValidateEntity(entity);
entityArrayList.Add(entity);
}
peMyPeople.UpdateEntities(entityArrayList);
This also performs validation of the users of some kind.
If the page this control appears on may be posted-back, you need the following to be done during the postback in order for the values to be correctly roundtripped; I put it in PreRender but it could happen elsewhere in the lifecycle:
protected override void OnPreRender(EventArgs e)
{
if (IsPostBack)
{
var csa = peMyPeople.CommaSeparatedAccounts;
csa = peMyPeople.CommaSeparatedAccounts;
}
}
If you want to check any error messages that the control generates for you (if the user input is incorrect), you need to have done this switchout already:
var csa = usrBankSponsor.CommaSeparatedAccounts;
csa = usrOtherBankParties.CommaSeparatedAccounts;
//ErrorMessage is incorrect if you haven't done the above
if (!String.IsNullOrEmpty(usrBankSponsor.ErrorMessage))
{
...
}
It's really not very nice and there may be a much better way of handling it, but this is the result of my experience so far so hopefully it will save you some time.

Getting all startup items?

Ok, I guess I'm having a brain fart here and cant find my way out of it. What I'm trying to accomplish is to list all startup items (applications, processes, etc) and display them on a form (like what you get with msconfig.exe). I thought this code would do it:
private List<StartupItems> getStartupItems()
{
try
{
ManagementClass cls = new ManagementClass("Win32_StartupCommand");
ManagementObjectCollection coll = cls.GetInstances();
List<StartupItems> items = new List<StartupItems>();
foreach (ManagementObject obj in coll)
{
items.Add(
new StartupItems
{
Command = obj["Command"].ToString(),
Description = obj["Description"].ToString(),
Name = obj["Name"].ToString(),
Location = obj["Location"].ToString(),
User = obj["User"].ToString()
});
}
return items;
}
catch (Exception ex)
{
_message = ex.ToString();
_status = false;
return null;
}
But all that gets are the enabled ones with my username. What I'm trying to get is all items, either my username or system, all the enabled ones and all the disabled ones as well (just like msconfig). I've done tons of searching and cannot find anything really any different than what I'm using.
Have you considered reading directly from the registry?
One alternative would be to run autorunssc (it's the command-line version of autoruns) in the background and read its response.

Categories