Rackspace Cloud Files Get Objects In Container C# - c#

I have been looking at the documentation, testing examples and getting familiar with the Rackspace Cloud Files API. I got the basic code down, got the API key, got a username, the basic stuff. Now one thing confuses me, this problem is something that appears to be not well documented.
So what I am trying to do is to get all the objects, including folders and files in a container. I have tried this example:
IEnumerable<ContainerObject> containerObjects = cloudFilesProvider.ListObjects("storage",null,null,null,null,null,false,ci);
foreach(ContainerObject containerObject in containerObjects)
{
MessageBox.Show(containerObject.ToString());
}
This doesn't return the result I am looking for, it seems to not return anything.
I am using OpenStack provided by running this in the NuGet console:
Install-Package Rackspace.
I am trying to create a file backup program for me and my family.

A common problem is not specifying the region. When your Rackspace cloud account's default region is not the same region as where your container lives, then you must specify region, otherwise you won't see any results listed. Which is quite misleading...
Here is a sample console application which prints the contents of all your containers (and their objects) in a particular region. Change "DFW" to the name of the region where your container lives. If you aren't sure which region has your container, log into the Rackspace cloud control panel and go to "Storage > Files" and note the region drop down at the top right.
using System;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
namespace ListCloudFiles
{
class Program
{
static void Main()
{
var region = "DFW";
var identity = new CloudIdentity
{
Username = "username",
APIKey = "apikey"
};
var cloudFilesProvider = new CloudFilesProvider(identity);
foreach (Container container in cloudFilesProvider.ListContainers(region: region))
{
Console.WriteLine(container.Name);
foreach (ContainerObject obj in cloudFilesProvider.ListObjects(container.Name, region: region))
{
Console.WriteLine(" * " + obj.Name);
}
}
Console.ReadLine();
}
}
}

If you are using the Openstack.NET API the reference documentation indicates that CloudFilesProvider has a method called ListObjects.
The docs say that this method:
Lists the objects in a container
The method returns IEnumerable<ContainerObject> and a quick glance at the parameter list looks to me like you can pass just a container name in the first parameter and null for the rest -- I'll leave it to you to figure out your use-case needs.
The following doc page describes the method in detail and includes a complete C# example.
http://www.openstacknetsdk.org/docs/html/M_net_openstack_Providers_Rackspace_CloudFilesProvider_ListObjects.htm

Related

Why does StoreContext.GetStoreProductsAsync(productKinds, storeIDs) get only current UWP app?

I have another UWP question.
I'm trying to get all the UWP apps that I published on the MS Store, but it seems there is something wrong: I can only get the current one beeing executed, although I insert many store IDs, the ones from my apps, as suggested by MS Docs.
Here's the code (of course, in my code I insert the real IDs):
StoreContext context = StoreContext.GetDefault();
string[] productKinds = { "Application" };
List<String> filterList = new List<string>(productKinds);
string[] storeIds = { "firstID", "secondID", "thirdID" };
StoreProductQueryResult queryResult = await context.GetStoreProductsAsync(filterList, storeIds);
if (queryResult.ExtendedError == null)
{
foreach (var product in queryResult.Products)
{
// Do something with 'product'
}
}
Well, it only returns one item, the current one.
Is there a way to obtain even other store apps?
Am I doing something wrong?
Thanks a lot.
GetStoreProductsAsync is only for the products associated with the app (i.e. add-ons):
Gets Microsoft Store listing info for the specified products that are
associated with the current app.
[docs]
To solve the problem you might want to look in the direction of Microsoft Store collection API and purchase API (requires web app setup in Azure).
Other than that StoreContext class at its current state doesn't contain API to get product information about other apps and their add-ons.

Autodesk Revit Architecture 2014 .NET API C# find host for FamilyInstance in link

The host property of a familyInstance returns a RevitLinkInstance when the host is placed within a linked document. I there a way to get the real Element (or its ID) instead of the RevitLinkInstance?
I was hoping that the stableREpresentation could give me more information, but unfortunatly, it doesn't.
Reference hostFaceReference = instance.HostFace;
string stableRepresentation = hostFaceReference.ConvertToStableRepresentation(instance.Document);
this would give "ac669fa6-4686-4f47-b1d0-5d7de6a40550-000a6a4a:0:RVTLINK:234297:0:218" where 234297 is the ID of the referenced element, in this case, still the RevitLinkInstance.
Have you tried this?
ElementId hostFaceReferenceId = instance.HostFace.LinkedElementId;
You could then try getting the Element via the linkedDocument.
Document LinkedDoc = RevitLinkInstance01.GetLinkDocument();
Element linkedEl = LinkedDoc.GetElement(hostFaceReferenceId);
Depending on the host you may have to go about it a few ways. For example, with a wall you could try the following (this is using LINQ by the way):
// filter the Host's document's items
FilteredElementCollector linkdocfec = new FilteredElementCollector(elem_inst.Host.Document);
// establish the host's type
linkdocfec.OfClass(elem_inst.Host.GetType());
// find the host in the list by comparing the UNIQUEIDS
Element hostwallinlinkedfile = (from posshost in linkdocfec
where posshost.UniqueId.ToString().Equals(elem_inst.Host.UniqueId.ToString())
select posshost).First();
// check the different faces of the host (wall in this case) and select the exterior one
Reference linkrefface = HostObjectUtils.GetSideFaces((hostwallinlinkedfile as HostObject), ShellLayerType.Exterior).First<Reference>();
// create a reference to the linked face in the the CURRENT document (not the linked document)
Reference linkref = linkrefface.CreateLinkReference(rvtlink_other);
Ultimately, according to the docs anyway, you're supposed to utilize the CreateReferenceInLink method to get your item.

How to change DCOM config identity programmatically

Is there any way to get the information about Launching identity of DCOM application programmatically. See the picture attached to understand what i mean.
I tried to use WMI
ManagementObjectSearcher s = new ManagementObjectSearcher(new ManagementScope(#"\\.\root\cimv2"), new ObjectQuery(
"select * from Win32_DCOMApplicationSetting where AppID='{048EB43E-2059-422F-95E0-557DA96038AF}'"))
ManagementObjectCollection dcomSett = s.Get();
var value = dcomSett.Cast<ManagementObject>().ToArray()
[0].Properties["RunAsUser"].Value;
but "RunAsUser" property was empty.
Also tried Interop.COMAdmin
COMAdmin.COMAdminCatalogClass catalog = (COMAdmin.COMAdminCatalogClass)new COMAdmin.COMAdminCatalog();
(COMAdmin.COMAdminCatalogCollection)catalog.GetCollection("Applications")
in this way i managed to get applications which are listed under the "COM+ Applications" node in the "Component Services" snap-in of MMC:
I'm new in COM, DCOM, COM+ stuff and sure that i missed something important.
After a while i found out why i used to get NULL in the first approach (ManagementObject).
You will receive:
NULL if identity is currently set to The launching user
"Interactive User" in case of "The interactive user"
some string with username in case of third option (see the first picture)
But still i need a way to change identity for items like Microsoft PowerPoint Slide under DCOM Config node in MMC.
In the DCOM config, if you are using a specific user for the identity and you want to update the password via code, you need to update it in the Local Security Authority (LSA). This is possible with Windows API calls. MS has some sample code for a utility called dcomperm that does it, and you can see how they implemented in C++. You could make the same calls in C#. See the SetRunAsPassword method here. They are using the method LsaOpenPolicy to get a handle to the policy and calling LsaStorePrivateData to update the password. Then they are adding "login as a batch job" access to the account (but that shouldn't be necessary if you are only changing the password).
This sample code on pinvoke.net looks like it is making the requisite calls, except for the optional part about granting the login as a batch job permission. Note the "key" in the LSA is in the format SCM:{GUID-of-DCOM-object} Example: SCM:{00000000-0000-0000-0000-000000000000}
Oh, and I should mention as an aside that if you wanted to change the RunAs user itself (i.e. the username), you'd need to also update that in the windows registry directly (AFAIK that's the only way to do it). DCOM entries are stored under HKLM\SOFTWARE\Classes\AppID. You can do that with WMI or just use the Registry classes in .NET.
This is very simple , you can get APPId from
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\{048EB43E-2059-422F-95E0-557DA96038AF}
using
(RegistryKey dcomPPTIdentity = Registry.LocalMachine.OpenSubKey("Software\\Classes\\AppID\\{048EB43E-2059-422F-95E0-557DA96038AF}"))
{
if (dcomPPTIdentity != null)
{
Registry.SetValue(dcomPPTIdentity.ToString(), "RunAs", "userName");
}
}
I am using COMAdmin DLL successfully. Try something like this:
COMAdminCatalog catalog = new COMAdminCatalog();
COMAdminCatalogCollection applications = catalog.GetCollection("Applications");
applications.Populate();
for (int i = 0; i < applications.Count; i++)
{
COMAdminCatalogObject application = COMAppCollectionInUse.Item[i];
if (application.Name == "Your COM+ application name")
{
application.Value["Identity"] = "nt authority\\localservice"; // for example
}
}
This works for me on my development server. Keep in mind, it is run against the server directly on the server
using COMAdmin;
using System;
namespace ComComponents
{
class Program
{
static void Main(string[] args)
{
COMAdminCatalog catalog = new COMAdminCatalog();
COMAdminCatalogCollection applications = catalog.GetCollection("Applications");
applications.Populate();
for (int i = 0; i < applications.Count; i++)
{
COMAdminCatalogObject application = applications.Item[i];
Console.WriteLine(application.Name);
Console.WriteLine(application.Value["Identity"]);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}

Can I run a ASPX and grep the result without making HTTP request?

How can I just make a function call, without URL, and without HTTP, to a simple ASP.NET file, and capture the byte stream it generated?
More background information,
I need a some kind of template can put a little logic inside, to render some INI like text files. I give up those libraries ported from Java and come up a solution of using ASP.NET for template engine. (I am NOT using it to build a website, not even a HTML.)
I have written a ASP.NET page (no WebForm, no MVC), which accept a XML POST, and it generate a long text file based on a set of simple but not too simple rules.
I generate the XML from DB objects, submit to the ASP page, grep the result and it works very well. However, the problem is that we want to use as a library, using by a WCF. Because of this, I failed to use a relative path and I have to store the URL of the ASP somewhere in the configuration, which I do not want to.
It will be hosted on a IIS server, but not called (at least not directly) from any frontend ASP, and will never called from end user.
PS. I was originally looking for a simple template engine for C#, but they are too old and not maintenance anymore, poor documentation, missing integrated editor/debugger, too simple, and the they might speak different languages.
PPS. I've also thought about T4, but it does not have a editor nor debugger in VS 2008.
You can run an ASPX page without IIS, without an HTTP message, if you build a host for the ASPNET runtime.
Example:
public class MyAspNetHost : System.MarshalByRefObject
{
public void ProcessRequest(string page)
{
var request = new System.Web.Hosting.SimpleWorkerRequest
(page, // the page being requested
null, // query - none in this case
System.Console.Out // output - any TextWriter will do
);
// this will emit the page output to Console.Out
System.Web.HttpRuntime.ProcessRequest(request);
}
public AppDomain GetAppDomain()
{
return System.Threading.Thread.GetDomain();
}
}
public class Example
{
public void Run(IEnumerable<String> pages)
{
// ASPNET looks for assemblies - including the assembbly
// that contains any custom ASPNET host - in the bin\
// subdirectory of the physical directory that backs the
// ASPNET Host. Because we are going to use the current
// working directory as the physical backing directory for
// the ASPNET host, we need to ensure there's a bin
// subdirectory present.
bool cleanBin = false;
if (!Directory.Exists("bin"))
{
cleanBin = true;
Directory.CreateDirectory("bin");
}
// Now, ensure that the assembly containing the custom host is
// present in that bin directory. The assembly containing the
// custom host is actually *this* assembly.
var a = System.Reflection.Assembly.GetExecutingAssembly();
string destfile= Path.Combine("bin", Path.GetFileName(a.Location));
File.Copy(a.Location, destfile, true);
host =
(MyAspNetHost) System.Web.Hosting.ApplicationHost.CreateApplicationHost
( typeof(MyAspNetHost),
"/foo", // virtual dir - can be anything
System.IO.Directory.GetCurrentDirectory() // physical dir
);
// process each page
foreach (string page in pages)
host.ProcessRequest(page);
}
}
If you want to clean up that bin directory, you have to get the AppDomain to unload first. You can do that, like this:
private ManualResetEvent aspNetHostIsUnloaded;
private void HostedDomainHasBeenUnloaded(object source, System.EventArgs e)
{
// cannot clean bin dir here. The AppDomain is not yet gone.
aspNetHostIsUnloaded.Set();
}
private Run(IEnumerable<String> pages)
{
try
{
....code from above ....
}
finally
{
if (host!= null)
{
aspNetHostIsUnloaded = new ManualResetEvent(false);
host.GetAppDomain().DomainUnload += this.HostedDomainHasBeenUnloaded;
AppDomain.Unload(host.GetAppDomain());
// wait for it to unload
aspNetHostIsUnloaded.WaitOne();
// optionally remove the bin directory
if (cleanBin)
{
Directory.Delete("bin", true);
}
aspNetHostIsUnloaded.Close();
}
}
}
This makes sense for testing ASPX pages, and that sort of thing. But I'm not so sure this is the right thing, for your scenario. There are more direct ways to generate text files. But, it may be right for you. If you really like the template engine idea, hosting ASPNET may be just the thing for you.
In your case, you would want to modify the custom Host so that the output for each page goes to a StringWriter instead of Console.Out, and then you could do Grep (or more likely a search with Regex) on that output. You might also want to modify it to accept all the input data as a querystring. You'd need to format the page request to do that.
EDIT: There's a good article on MSDN Magazine on this technique of hosting the ASPNET runtime. From December 2004.
EDIT2: There's a simpler way to manage the bin directory. Just create a symbolic link named bin, pointing to ".". Then, you can remove the symlink after the call to AppDomain.Unload(), without waiting. Looks like this:
public void Run(string[] pages)
{
bool cleanBin = false;
MyAspNetHost host = null;
try
{
// This creates a symlink.
// ASPNET always looks for a bin\ directory for the privateBinPath of the AppDomain.
// This will create the bin dir, pointing to the current dir.
if (!Directory.Exists("bin"))
{
cleanBin = true;
CreateSymbolicLink("bin", ".", 1);
}
host =
(MyAspNetHost) System.Web.Hosting.ApplicationHost.CreateApplicationHost
( typeof(MyAspNetHost),
"/foo", // virtual dir - can be anything
System.IO.Directory.GetCurrentDirectory() // physical dir
);
foreach (string page in pages)
host.ProcessRequest(page);
}
finally
{
// tell the host to unload
if (host!= null)
{
AppDomain.Unload(host.GetAppDomain());
if (cleanBin)
{
// remove symlink - can do without waiting for AppDomain unload
Directory.Delete("bin");
}
}
}
}
This eliminates the need for the ManualResetEvent, copying files, synchronization, etc. It assumes the assembly for the custom ASPNet Host as well as all the assemblies required by the ASPX pages you run are contained in the current working directory.
This sounds like a very similar issue which is generating HTML emails on a server. There are some answers here that do that (for MVC):
ASP.NET MVC: How to send an html email using a controller?
You can proceed in a similar fashion for non-MVC by loading and rendering a control (ASCX) to a file.

Location of a Windows service *not* in my project

If I right-click and choose Properties on a service (like, say, Plug and Play) in the Services dialog, I get several pieces of information, including "Path to executable". For Plug and Play (in Vista) this is:
C:\Windows\system32\svchost.exe -k DcomLaunch
Is there some way I can get this same piece of information using .NET code if I know the service name (and/or the display name)?
(I can't use GetExecutingAssembly() because I'm not running the service from my project.)
Another option, without the interop, would be a WMI lookup (or registry - bit hacky!).
Here's a quick example, based on this code:
private static string GetServiceImagePathWMI(string serviceDisplayName)
{
string query = string.Format("SELECT PathName FROM Win32_Service WHERE DisplayName = '{0}'", serviceDisplayName);
using (ManagementObjectSearcher search = new ManagementObjectSearcher(query))
{
foreach(ManagementObject service in search.Get())
{
return service["PathName"].ToString();
}
}
return string.Empty;
}
This information is in the QUERY_SERVICE_CONFIG structure. You will need to use P/Invoke to get it out.
The basic process is:
Call OpenSCManager to get a handle to the services managed.
Call OpenService to get a handle to the service.
Call QueryServiceConfig to get the QUERY_SERVICE_CONFIG structure.
There's always the WMI class Win32_Service as described here, specifically the PathName.
This works:
ManagementClass mc = new ManagementClass("Win32_Service");
foreach(ManagementObject mo in mc.GetInstances())
{
if(mo.GetPropertyValue("Name").ToString() == "<Short name of your service>")
{
return mo.GetPropertyValue("PathName").ToString().Trim('"');
}
}
If you have any issue related to Reference then add a reference of System.Management in your project.

Categories

Resources