How to get the selected build configuration (on a property page) programmatically in Eclipse CDT? - eclipse

The task is to get the selected build configuration on the project's property page.
I have tried to achieve this by writing the following code:
private static IConfiguration getSelectedBuildConf(IProject proj) {
IManagedBuildInfo info = ManagedBuildManager.getBuildInfo(proj);
if (info == null) {
return null;
} else {
IConfiguration cfg = info.getSelectedConfiguration();
return cfg;
}
}
The problem here is that getSelectedConfiguration() always returns null.
getSelectedConfiguration() returns always Debug configuration.

I think you want to use getDefaultConfiguration() instead of getSelectedConfiguration()...
As explained on cdt-dev list here.

Related

Detecting installed plugin in Eclipse

I'd like to detect the presence of a plugin from within the Eclipse plugin I'm maintaining. From a few other questions asked on this subject it looks like this is difficult.
The plugin I'm looking to detect provides a view. As such the following works, but I'm hoping that a prettier option exists:
public static boolean internalPluginInstalled() {
IExtensionRegistry reg = Platform.getExtensionRegistry();
IExtensionPoint point = reg.getExtensionPoint("org.eclipse.ui.views");
IExtension[] extensions = point.getExtensions();
for(IExtension extension : extensions) {
IConfigurationElement[] configs = extension.getConfigurationElements();
for (IConfigurationElement config : configs) {
if (config.getName().equals("view") && config.getAttribute("id").equals("view.id.goes.here")) {
return true;
}
}
}
return false;
}
Use Platform.getBundle (org.eclipse.core.runtime.Platform):
Bundle bundle = Platform.getBundle("plugin id");
bundle will be non-null if the plug-in is installed.
bundle.getState() returns you the exact state of the plug-in - Bundle.ACTIVE if the plug-in has been started.

Load SAML2 configuration on the runtime instead of loading it on the Startup

All of the ITfoxtec.Identity.Saml2 example projects on Github load the SAML configuration in the ConfigureServices method of the Startup class. I have stored all the configurations in the database. Is there a way to load the SAML configuration from within the code at the runtime (after my .Net Core project is started)?
public void ConfigureServices(IServiceCollection services)
{
services.Configure<Saml2Configuration>(Configuration.GetSection("Saml2"));
services.Configure<Saml2Configuration>(saml2Configuration =>
{
//saml2Configuration.SignAuthnRequest = true;
saml2Configuration.SigningCertificate = CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SigningCertificateFile"]), Configuration["Saml2:SigningCertificatePassword"]);
//saml2Configuration.SignatureValidationCertificates.Add(CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SignatureValidationCertificateFile"])));
saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);
var entityDescriptor = new EntityDescriptor();
entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(Configuration["Saml2:IdPMetadata"]));
if (entityDescriptor.IdPSsoDescriptor != null)
{
saml2Configuration.AllowedIssuer = entityDescriptor.EntityId;
saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
saml2Configuration.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
if (entityDescriptor.IdPSsoDescriptor.WantAuthnRequestsSigned.HasValue)
{
saml2Configuration.SignAuthnRequest = entityDescriptor.IdPSsoDescriptor.WantAuthnRequestsSigned.Value;
}
}
else
{
throw new Exception("IdPSsoDescriptor not loaded from metadata.");
}
});
services.AddSaml2(slidingExpiration: true);
services.AddControllersWithViews();
}
Yes, it is possible to move the configuration load from startup to later. You can load the content of the Saml2Configuration config object just before it is used by calling a method. In the sample e.g., before the Saml2Configuration is used in the Login method.

Plug-In that Converted Note entity pre-existing attachment XML file into new .MMP file

strong text [Plugin error at Note entity][1]
[1]: http://i.stack.imgur.com/hRIi9.png
Hi,Anyone resolved my issue i got a Plug-in error which i worked at Update of "Note" entity.Basically i want a Plugin which converted pre-exiting Note attachment XML file into new .MMP extension file with the same name.
I have done following procedure firstly i created a "Converter_Code.cs" dll which contains Convert() method that converted XML file to .MMP file here is the constructor of the class.
public Converter(string xml, string defaultMapFileName, bool isForWeb)
{
Xml = xml;
DefaultMapFileName = defaultMapFileName;
Result = Environment.NewLine;
IsForWeb = isForWeb;
IsMapConverted = false;
ResultFolder = CreateResultFolder(MmcGlobal.ResultFolder);
}
In ConvertPlugin.cs Plug-in class firstly i retrieved Note entity attachment XML file in a string using following method in
IPluginExecutionContext context =(IPluginExecutionContext)serviceProvider.
GetService (typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory= (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService
(context.UserId);
if (context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
var annotationid = entity.GetAttributeValue<Guid>("annotationid");
if (entity.LogicalName != "annotation")
{
return;
}
else
{
try
{
//retrieve annotation file
QueryExpression Notes = new QueryExpression { EntityName ="annotation"
,ColumnSet = new ColumnSet("filename", "subject", "annotationid",
"documentbody") };
Notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal,
annotationid);
EntityCollection NotesRetrieve = service.RetrieveMultiple(Notes);
if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
{
{
//converting document body content to bytes
byte[] fill = Convert.FromBase64String(NotesRetrieve.Entities[0]
.Attributes["documentbody"].ToString());
//Converting to String
string content = System.Text.Encoding.UTF8.GetString(fill);
Converter objConverter = new Converter(content, "TestMap", true);
objConverter.Convert();
}
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("something is going wrong");
}
}
}
}
and than A string is passed to "Converter" constructor as a parameter.
finally i merged all dll using ILMerge following method:
ilmerge /out:NewConvertPlugin.dll ConvertPlugin.dll Converter_Code.dll
and NewConvertPlugin is registered successfully but while its working its generate following error:
Unexpected exception from plug-in (Execute): ConverterPlugin.Class1: System.Security.SecurityException: That assembly does not allow partially trusted callers.
i also debug the plugin using Error-log but its not worked so i could not get a reason whats going wrong.
The error is caused by the library you merged inside your plugin.
First of all you are using CRM Online (from your screenshot) and with CRM Online you can use only register plugins inside sandbox.
Sandbox means that your plugins are limited and they run in a partial-trust environment.
You merged an external library that requires full-trust permissions, so your plugin can't work and this is the reason of your error.
Because you are in CRM Online, or you find another library (the Converter) that requires only partial-trust, hoping that the merge process will work, or you include (if you have it) the source code of the converter library directly inside your plugin.

The given key was not present in the dictionary

I am developing a plugin in crm 5.0 to retrieve date "ct_valuedate" from an entity called "ct_marketvalue" and formatting and saving in a field called "ct_dateserial"
I get an error while I debug "The given key was not present in the dictionary"
public class MarketValueDateFormatting : PluginBase
{
protected override void ExecutePlugin()
{
try
{
switch (_crmMessage)
{
case CrmPluginMessageEnum.Create:
if (_context.InputParameters.Contains("ct_marketvalue"))
{
//Obtain the logical name of the entity
string moniker1 = ((EntityReference)_context.InputParameters["EntityMoniker"]).LogicalName;
//Verify that the target entity represents an Account.
//If not, this plug-in was not registered correctly.
if (moniker1.Equals("ct_marketvalue"))
{
Entity marketvalueimage = (Entity)_context.PostEntityImages["ct_marketvalue"];
Guid marketvalueid = marketvalueimage.Id;
if (marketvalueimage.Contains("ct_valuedate"))
{
DateTime dateserial = (DateTime)marketvalueimage.Attributes["ct_valuedate"];
String dateserialstring = dateserial.ToString("YYYYMMdd");
Ct_marketvalue marketvalue = new Ct_marketvalue();
marketvalue.Ct_dateserial = dateserialstring;
marketvalue.Id = marketvalueid;
_serviceContext.UpdateObject(marketvalue);
}
}
}
break;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Few notes about your code.
You should check in your code that _context.PostEntityImages contains "ct_marketvalue". It's possible either to forgot register or to do a mistake in image name.
Might be better use .ToEntity rather than access attributes using .Attributes["ct_valuedate"].
I'm not sure what is purpose of the plugin you wrote, but it looks it is post stage plugin and it updates the same entity instance, that was in InputParameters. Might be better to make this plugin pre stage and update value directly in InputParameters. Because, if not "The given key was not present in the dictionary" exception, it will cause infinite loop. You will need check context.Depth.

Reading from an assembly with embedded resources

I built an assembly containing one js file.
I marked the file as Embedded Resource and added it into AssemblyInfo file.
I can't refernce the Assembly from a web site. It is in the bin folder but I don't see the reference to it.
It seems like not having at least a class inside the assembly I can't reference it.
I would include the js file into my pages from the assembly.
How should I do this?
Thanks
I do exactly the same thing in one of my projects. I have a central ScriptManager class that actually caches the scripts as it pulls them, but the core of extracting the script file from the embedded resource looks like this:
internal static class ScriptManager
{
private static Dictionary<string, string> m_scriptCache =
new Dictionary<string, string>();
public static string GetScript(string scriptName)
{
return GetScript(scriptName, true);
}
public static string GetScript(string scriptName, bool encloseInCdata)
{
StringBuilder script = new StringBuilder("\r\n");
if (encloseInCdata)
{
script.Append("//<![CDATA[\r\n");
}
if (!m_scriptCache.ContainsKey(scriptName))
{
var asm = Assembly.GetExecutingAssembly();
var stream = asm.GetManifestResourceStream(scriptName);
if (stream == null)
{
var names = asm.GetManifestResourceNames();
// NOTE: you passed in an invalid name.
// Use the above line to determine what tyhe name should be
// most common is not setting the script file to be an embedded resource
if (Debugger.IsAttached) Debugger.Break();
return string.Empty;
}
using (var reader = new StreamReader(stream))
{
var text = reader.ReadToEnd();
m_scriptCache.Add(scriptName, text);
}
}
script.Append(m_scriptCache[scriptName]);
if (encloseInCdata)
{
script.Append("//]]>\r\n");
}
return script.ToString();
}
}
EDIT
To provide more clarity, I've posted my ScriptManager class. To extract a script file, I simply call it like this:
var script = ScriptManager.GetScript("Fully.Qualified.Script.js");
The name you pass in it the full, case-sensitive resource name (the exception handler gets a list of them by calling GetManifestResourceNames()).
This gives you the script as a string - you can then put it out into a file, inject it into the page (which is what I'm doing) or whatever you like.
Assembly myAssembly = // Get your assembly somehow (see below)...
IList<string> resourceNames = myAssembly.GetManifestResourceNames();
This will return a list of all resource names that have been set as 'Embedded Resource'. The name is usually the fully qualified namespace of wherever you put that JS file. So if your project is called My.Project and you store your MyScript.js file inside a folder in your project called Resources, the full name would be My.Project.Resources.MyScript.js
If you then want to use that JS file:
Stream stream = myAssembly.GetManifestResourceStream(myResourceName);
Where myResourceName argument might be "My.Project.Resources.MyScript.js". To get that JS file in that Stream object, you'll need to write it as a file to the hard drive, and serve it from your website as a static file, something like this:
Stream stream = executingAssembly.GetManifestResourceStream(imageResourcePath);
if (stream != null)
{
string directory = Path.GetDirectoryName("C:/WebApps/MyApp/Scripts/");
using (Stream file = File.OpenWrite(directory + "MyScript.js"))
{
CopyStream(stream, file);
}
stream.Dispose();
}
And the code for CopyStream method:
private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
You might want to stick all this code in an Application_Start event in your Global.asax. You don't want it to run for each request
Now getting a reference to your Assembly is a different matter, there are many ways. One way is to include all the above code in your Assembly in question, then make sure you reference that Assembly from your main WebApp project in Visual Studio, then get a reference to the currently executing Assembly like so.
namespace My.Project
{
public class ResourceLoader
{
public static void LoadResources()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
// rest of code from above (snip)
}
}
}
Then call ResourceLoader.LoadResources() from your Application_Start event in your Global.asax.
Hope this helps
Fully working example (I hope):
namespace TestResources.Assembly
{
public class ResourceLoader
{
public static void LoadResources()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream stream = myAssembly
.GetManifestResourceStream("TestResources.Assembly.CheckAnswer.js");
if (stream != null)
{
string directory = Path.GetDirectoryName("C:/WebApps/MyApp/Scripts/");
using (Stream file = File.OpenWrite(directory + "MyScript.js"))
{
CopyStream(stream, file);
}
stream.Dispose();
}
}
private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
}
}
Some caveats:
Change "C:/WebApps/MyApp/" to wherever your web app is located, maybe write some code to work this out dynamically
Make sure the /Scripts folder exists in your webapp root
I think it will overwrite the 'MyScript.js' file if it already exists, but just in case you might want to add some code to check for that file and delete it
Then stick a call to this code in your Global.asax file:
protected void Application_Start()
{
ResourceLoader.LoadResources();
}
Then the path for your web site will be /Scripts/MyScript.js eg:
<head>
<!-- Rest of head (snip) -->
<script type="text/javascript" src="/Scripts/MyScript.js"></script>
</head>