Change Project Owner Using PSI 2010(Project Server Interface) - c#

I want to change ProjectOwnerUID Using PSI(Project Server Interface).I wrote that with follow similar code
var projectDataSet = this.GetProjectDataSet(projectInfo.ProjectUID);
var orginalProject = this.GetProject(projectInfo.ProjectUID, projectDataSet);
var sessionUID = this.CheckOutProject(projectInfo.ProjectUID);
if (!string.IsNullOrEmpty(projectInfo.ProjectOwnerName))
{
var resourceManager = new Resource();
var ownerResource = resourceManager.GetResource(projectInfo.ProjectOwnerName);
if (ownerResource == null)
{
throw new Exception("this is not valid");
}
orginalProject.ProjectOwnerID = ownerResource.ResourceUID;
}
this.UpdateProject(sessionUID, projectDataSet);
unfortunatly when cursor arrive to UpdateProject line it throws exception with code number
ProjectServerError(s) LastError=ProjectInvalidOwner Instructions: Pass this into PSClientError constructor to access all error information
Inner Error 1056(Invalid project owner).
I don't know what happen that Issued this exception
how can I solve this problem?

This problem occurs when you do not have permissions to edit project information using the following code snippet u can tell to project server to run this piece of code do not check permissions!!
using Microsoft.SharePoint;
public void MyVoid()
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Write ur Codes here :)
});
}
MSDN Reference

Related

Need a Way to Search through Event Logs by RecordID

I am trying to search through a folder with Event Logs in them, eventpath has the path of the specific Event Log I want to access. I want to use a specified RecordID to find it's correlated FormatDescription and display it in a MessageBox. I want to be able to use the eventpath to access each Event Log since I am using 6 separate .evtx files and need to use this method on all of them.
I found this solution, but I get an error when I'm trying to Query. I've tried to find a fix, but it seems as if it's just not going to work for what I need. I commented where exactly it is occurring in the code.
This is the exception: System.Diagnostics.Eventing.Reader.EventLogException: The specified path is invalid.
I can't find a fix for this code, but if anyone knows a fix or another way to approach searching through Event Logs by RecordID and giving the corresponding FormatDescription, it would be greatly appreciated.
I am using C# in Windows Presentation Foundation.
public void getDesc(string recordid)
{
string eventpath = getEventPath();
//takes off the .evtx of the path
string result = eventpath.Substring(0, eventpath.Length - 5);
//result1 is going to be similar to this:
//C:\Users\MyName\AppData\Local\Temp\randomTempDirectory\additional_files\DiagnosticInfo\WindowsEventLogs\Application
string sQuery = "*[System/EventRecordID=" + recordid + "]";
var elQuery = new EventLogQuery(result, PathType.LogName, sQuery);
//this is where it errors out
//error: Specified Channel Path is invalid
using (var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery))
{
List<EventRecord> eventList = new List<EventRecord>();
EventRecord eventInstance = elReader.ReadEvent();
try
{
while ((eventInstance = elReader.ReadEvent()) != null)
{
//Access event properties here:
string formatDescription = eventInstance.FormatDescription();
MessageBox.Show(formatDescription);
}
}
finally
{
if (eventInstance != null)
eventInstance.Dispose();
}
}
}

C# Google API throws exception

I am using Google API for the first time and I want to use Natural Language API.
But I don't know how.
So I search the internet and found an example code.
But when it uses APIs, the program throws an exception.
problem source code and thrown exception:
using Google.Cloud.Language.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// The text to analyze.
string text = "Hello World!";
try
{
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
Console.WriteLine($"Score: {sentiment.Score}");
Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
The console output:
The Application Default Credentials are not available.
They are available if running on Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
See https://developers.google.com/accounts/docs/application-default-credentials for more information.
What should I do?
I had used NLP a year ago for entity analysis. I had used Google.Apis.CloudNaturalLanguage.v1. I put together my code with what you have written for sentiment analysis. You will need the API key for this:
var service = new CloudNaturalLanguageService(new CloudNaturalLanguageService.Initializer { ApiKey = ApiKey });
var req = new AnalyzeSentimentRequest {
Document = new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
},
EncodingType = "UTF8"
};
var output = service.Documents.AnalyzeSentiment(req);
var exe = output.Execute();
Hope this works.

tik4net hotspot user usage report in c#

what is the best way to get daily bytes-out and byte-in report for every user in hotspot list(without the user manager).i found the tik4net but i couldn't use it and i found almost no documentation on this reference.
i have tried the mk.cs and tik4net already but no luck so far.
this was the sample on using torch tool :
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
connection.Open("IP", "USR", "PW");
var loadingContext = connection.LoadAsync<ToolTorch>(
torchItem => Console.WriteLine(torchItem.ToString()),
error => Console.WriteLine(error.ToString()),
connection.CreateParameter("interface", "DSL"),
connection.CreateParameter("port", "any"),
connection.CreateParameter("src-address", "0.0.0.0/0"),
connection.CreateParameter("dst-address", "0.0.0.0/0"));
Console.ReadLine();
loadingContext.Cancel();
{
so the question is:
what is the best reference in c# to get user reports without the user manager in c#?
can anyone please provide some sample code ?
UPDATE :
i just worked around and played with the code a little bit and got here :
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
connection.Open("IP", "USR", "PW");
var hs = connection.LoadAll<HotspotActive>();
foreach (var user in hs)
{
var ids = user.Id;
listBox1.Items.Add(ids);
connection.Delete<HotspotActive>(user);
}
}
but i get an exception error on connection.Delete<HotspotActive>(user); , i dont know if i went the correct way.

CreateOrganizationProfile error Object reference not set to an instance of an object

I'm using Microsoft code to create a new Organisation in the User Profile Server, as per http://msdn.microsoft.com/en-us/library/ms545122.aspx.
Every time I call CreateOrganizationProfile I get the following:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Office.Server.UserProfiles.OrganizationProfile.set_Parent(ProfileBase value)
The exact code I'm using is:
[WebMethod]
public void CreateOrganisation(string OrganisationName)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(_serverName))
{
// Removing this will cause the error "Operation is not valid due to the current state of the object".
HttpContext.Current = null;
SPServiceContext context = SPServiceContext.GetContext(site);
ProfileSubtypeManager psm = ProfileSubtypeManager.Get(context);
// choose default organization profile subtype as the subtype
string subtypeName = ProfileSubtypeManager.GetDefaultProfileName(ProfileType.Organization);
ProfileSubtype subType = psm.GetProfileSubtype(subtypeName);
OrganizationProfileManager opm = new OrganizationProfileManager(context);
// choose Root Organization as the parent
OrganizationProfile parentOrg = opm.RootOrganization;
// create an organization profile and set its display name
OrganizationProfile profile = opm.CreateOrganizationProfile(subType, parentOrg);
profile.DisplayName = "Test Org1";
// commit to save changes
profile.Commit();
}
});
return;
}
Curiously, somebody else ran into the exact problem here http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/7b5101fd-0ea6-4716-82b1-ac4609b9973c/, but it was never resolved.
I've confirmed the User Profile Service is running and responding. Also, parentOrg and subtypeName are not null when calling CreateOrganizationProfile.
Does anybody have anything I can try, or can anybody spot what might be the problem?
Very grateful!
I had the same problem and I fixed it by changing the line
OrganizationProfile parentOrg = opm.RootOrganization;
To
OrganizationProfile parentOrg = (OrganizationProfile)opm.GetProfile(1);
GetProfile(1) returned the RootOrganization in my case.
Hope this helps someone!
I am no sharepoint expert but this http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.organizationprofilemanager.createorganizationprofile.aspx states that you need user profile administrative permissions and this http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.organizationprofile.parent.aspx could be hint that you need user profile manager permission to do what you are trying to do.
EDIT:
since your code try to "write" something this seems relevant http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx
basically it says you are missing a call to SPUtility.ValidateFormDigest() or SPWeb.ValidateFormDigest() before calling SPSecurity.RunWithElevatedPrivileges

DynamicActivity - How to invoke a workflow that stored in Database?

This is proof of concept project - The goal is to create an application that receive some system wide events and based on some business rules invokes a specific workflow.
The workflows are created separately and the xaml source is stored in a database.
Following is the code that used to invoke the workflow:
public void RaiseEvent(IEvent e, IEventData eventData)
{
var typeName = e.GetType().FullName;
// Query Db for all workflows for the event
var repo = new WorkflowRepository();
var workflows = repo.GetActiveWorkflowsByEvent(typeName);
foreach (var wf in workflows)
{
var condition =
ConditionEvaluator.PrepareCondition(wf.Condition.Expression, eventData);
var okToStart = ConditionEvaluator.Evaluate(condition);
if (okToStart)
{
// Next line is throwing an exeption
object o = XamlServices.Parse(wf.WorkflowDefinition.Expression);
DynamicActivity da = o as DynamicActivity;
WorkflowInvoker.Invoke(da,
new Dictionary<string, object>
{{ "EventData", eventData }});
}
}
We have created very simple workflow that runs without problems on its own. But when xaml is being loaded using XamlService.Parse it throw following exception:
System.Xaml.XamlObjectWriterException was unhandled
Message='No matching constructor found on type 'System.Activities.Activity'.
You can use the Arguments or FactoryMethod directives to construct this type.'
Line number '1' and line position '30'.
Any idea what is wrong?
Thank you.
Not sure what is causing your problem, I have used XamlServices.Load() in the past without any problems, but the easiest way of loading a workflow XAML at runtime is by using the ActivityXamlServices.Load(). See here for an example.
Ok I have solved this by using ActivityXamlServices
So Instead of this line:
object o = XamlServices.Parse(wf.WorkflowDefinition.Expression);
I am using following snippet:
var mStream = new memoryStream(
ASCIIEncoding.Default.GetBytes(wf.WorkflowDefinition.Expression));
object o = ActivityXamlServices.Load(mStream);

Categories

Resources