Retrieve the Current App version from Package - c#

While I can get the assembly version using the following code
var assembly = typeof(App).GetTypeInfo().Assembly;
var assemblyVersion = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
I would like to retrieve the Version from Package.appxmanifest in this case 1.0.0.4
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest">
<Identity Name="zzz" Publisher="CN=zzz" Version="1.0.0.4" />
I expected to have access to Windows.ApplicationModel, but this is not available to me

Here's what you can do to retrieve the version in code:
using Windows.ApplicationModel;
public static string GetAppVersion()
{
Package package = Package.Current;
PackageId packageId = package.Id;
PackageVersion version = packageId.Version;
return string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);
}
Reference: http://www.michielpost.nl/PostDetail_67.aspx

Related

Using C# to find a single node with its path and id attribute value

Say I have the following xml, and I would like to get the value of the version attribute for the single node with id of Pkg1, which is expected to be 1.2.3.
<project>
<nugets id='test'> </nugets>
<packages>
<package id='test1' version='1'/>
<package id='Pkg1' version='1.2.3'/>
<package id='Pkg1Test' version='4.5.6'/>
</packages>
</project>
Below is my attempt, but the target node is in the field of OuterXml as a string for the target node:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStr);
string path = "project/packages/package[#id='Pkg1']"; // target node has id=Pkg1
var targetNode = xmlDoc.SelectSingleNode(path);
Console.WriteLine($"{targetNode.OuterXml}"); // prints out the target node as string.
This seems work: string version = targetN.Attributes["version"].Value, is this the right way of getting the attribute value, and why the node is in the targetNode.OuterXml?
Here is a working code to get what you need:
private const string str = #"
<project>
<nugets id='test'> </nugets>
<packages>
<package id='test1' version='1'/>
<package id='Pkg1' version='1.2.3'/>
<package id='Pkg1Test' version='4.5.6'/>
</packages>
</project>";
private static void Test()
{
var el = XElement.Parse(str);
var packages = el.Element("packages")?
.Elements("package")
.ToList();
var package = packages?
.FirstOrDefault(x => x.Attribute("id")?.Value == "Pkg1");
var id = package?.Attribute("version")?.Value;
Console.Write(id);
}

Build error while using WindowsAzure.Servicebus package version 4.1.10 on a .NET 4.5 application

I seem to be unable to use this library in project
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'WindowsAzure' could not be found (are you missing a using directive or an assembly reference?) ClassLibrary2 \Visual Studio 2017\Projects\ClassLibrary2\ClassLibrary2\EntityListener.cs 24 Active
using WindowsAzure.Servicebus;
I installed using nuget packet manager, and it is defined in my packages.config file. Why can I not use it?
Packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="WindowsAzure.ServiceBus" version="4.1.10" targetFramework="net452" />
</packages>
If your .NET project version is exactly 4.5 (not 4.5.x), you will need to fall back to WindowsAzure.ServiceBus package version 4.1.3. Moreover, this
Here is the packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="WindowsAzure.ServiceBus" version="4.1.3" targetFramework="net45" />
</packages>
In addition, the correct namespace to use is the following:
using Microsoft.ServiceBus.Messaging;
Find below a sample .NET 4.5 Console Application that sends a message to an Azure Service Bus Queue. Please note this is just a sample and it is not production ready code. I hope this helps.
using System;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
namespace ServiceBusSample
{
class Program
{
static void Main(string[] args)
{
const string ConnectionString = "your service bus connection string";
const string QueueName = "your service bus queue name";
string message = "Hello World!";
string sessionId = Guid.NewGuid().ToString();
SendMessage(ConnectionString, QueueName, sessionId, message).Wait();
Console.WriteLine("Press <ENTER> to exit...");
Console.ReadLine();
}
private static async Task SendMessage(string connectionString, string queueName, string sessionId, string message, string correlationId = null)
{
try
{
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentException("Service bus connection string cannot be null, empty or whitespace.");
}
if (string.IsNullOrWhiteSpace(queueName))
{
throw new ArgumentException("Service bus queue name cannot be null, empty or whitespace.");
}
if (string.IsNullOrWhiteSpace(sessionId))
{
throw new ArgumentException("Session id cannot be null, empty or whitespace.");
}
QueueClient queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
BrokeredMessage brokeredMessage = new BrokeredMessage(message);
brokeredMessage.SessionId = sessionId;
await queueClient.SendAsync(brokeredMessage);
}
catch
{
// TODO: Handle exception appropriately (including logging)
throw;
}
}
}
}

Azure Data Lake store create folder via C# script

I am trying to create new folder inside my datalake store, there is no error in code however nothing is being reflected in datalake store.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using Microsoft.Azure.Management.DataLake.Store;
using Microsoft.Azure.Management.DataLake.Store.Models;
using Microsoft.Rest.Azure.Authentication;
namespace test_dlstore
{
class Program
{
private static DataLakeStoreAccountManagementClient _adlsClient;
private static DataLakeStoreFileSystemManagementClient _adlsFileSystemClient;
private static string _adlsAccountName;
private static string _subId;
private static void Main(string[] args)
{
_adlsAccountName = "mycreds#mysite.com";
_subId = "2342342-97ce-a54b2-ba6e-234234234234234";
string localFolderPath = #"C:\myfolder\"; // TODO: Make sure this exists and can be overwritten.
string localFilePath = Path.Combine(localFolderPath, "try.txt");
string remoteFolderPath = "adl://mystore.azuredatalakestore.net/myfolder";
string remoteFilePath = Path.Combine(remoteFolderPath, "try.txt");
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var tenant_id = "my-tenant-id";
var nativeClientApp_clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
var activeDirectoryClientSettings = ActiveDirectoryClientSettings.UsePromptOnly(nativeClientApp_clientId, new Uri("urn:ietf:wg:oauth:2.0:oob"));
var creds = UserTokenProvider.LoginWithPromptAsync(tenant_id, activeDirectoryClientSettings).Result;
_adlsClient = new DataLakeStoreAccountManagementClient(creds) { SubscriptionId = _subId };
_adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);
Console.WriteLine(ListAdlStoreAccounts());
Console.WriteLine(AppendToFile("adl://mystore.azuredatalakestore.net/myfolder/stage/testfile.txt", "abcdefghijklmnopqrstuvwxyz"));
CreateDirectory("adl://mystore.azuredatalakestore.net/myfolder/newdir");
Console.ReadLine();
}
// Append to file
public static string AppendToFile(string path, string content)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
Console.WriteLine(_adlsAccountName, path, content);
Console.WriteLine(path);
Console.WriteLine(content);
_adlsFileSystemClient.FileSystem.AppendAsync(_adlsAccountName, path, stream);
return "Tried";
}
}
public static string CreateDirectory(string path)
{
_adlsFileSystemClient.FileSystem.MkdirsAsync(_adlsAccountName, path);
return "Tried Creating directory.";
}
}
}
After execution of above code, program exits with no error. The connection is being made.
Also it is displaying datalake stores that are present but not able to do anything at all over the data lake stores.
I am new to azure please help me out.
I do a demo test on my side,it works correctly on side. The following is my detail steps:
Preparation:
Registry an AD application and assign role to applcation, more details please
refer to Azure official tutorials. After that we can get tenantId, appId, secretKey from the Azure Portal.
Steps:
1.Create an C# console project
2.Referece the Microsoft.Azure.Management.DataLake.Store SDK, more details please refer to packages.config file section.
3.Add the follow code
var applicationId = "appid";
var secretKey = "secretkey";
var tenantId = "tenantid";
var adlsAccountName = "adlsAccount Name";
var creds = ApplicationTokenProvider.LoginSilentAsync(tenantId, applicationId, secretKey).Result;
var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds,clientTimeoutInMinutes:60);
adlsFileSystemClient.FileSystem.Mkdirs(adlsAccountName, "/tomtest/newfolder");
4.Run the test code
5.Check from the azure portal.
Packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Azure.Management.DataLake.Store" version="2.2.0" targetFramework="net452" />
<package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.13.8" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime" version="2.3.8" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime.Azure" version="3.3.7" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.0-preview" targetFramework="net452" />
<package id="Newtonsoft.Json" version="9.0.2-beta1" targetFramework="net452" />
</packages>

How to get access to nuspec file of a nuget package on official nuget server?

I have a nuget package hosted on official nuget server. I want to get access to its nuspec file.
If that's not possible, is there any way I can get access to Manifect object ?
I tried
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
var package = repo.FindPackage("trackerenableddbcontext");
string root = "c:\\";
package.ExtractContents(new PhysicalFileSystem(root), "tempfolder");
but it only extract dll files in lib folder. Not the nuspec file.
Found the solution:
public Manifest ReadServerNuspecFile(PackageRetrieveOptions options)
{
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
var package = repo.FindPackage(options.ProjectName);
using (var pkgStream = package.GetStream())
{
var pkgReader = new PackageReader(pkgStream);
var manifest = Manifest.ReadFrom(pkgReader.GetNuspec(), true);
return manifest;
}
}

Get app version from UWP (Windows 10) app [duplicate]

While I can get the assembly version using the following code
var assembly = typeof(App).GetTypeInfo().Assembly;
var assemblyVersion = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
I would like to retrieve the Version from Package.appxmanifest in this case 1.0.0.4
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest">
<Identity Name="zzz" Publisher="CN=zzz" Version="1.0.0.4" />
I expected to have access to Windows.ApplicationModel, but this is not available to me
Here's what you can do to retrieve the version in code:
using Windows.ApplicationModel;
public static string GetAppVersion()
{
Package package = Package.Current;
PackageId packageId = package.Id;
PackageVersion version = packageId.Version;
return string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);
}
Reference: http://www.michielpost.nl/PostDetail_67.aspx

Categories