Pulling the Display name of an attribute from entity Metadata - c#

I am fairly new at trying to get data from CRM using C#, I am trying to get the display names of all of my attribute on CRM, When I try, I am getting a result of Microsoft.Xrm.Sdk.Label and it doesn't seem to straight forward to get the value of that label, could someone point me in the right direction?
using System;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace CRM_MetaData_Download
{
class Program
{
static void Main(string[] args)
{
try {
var connectionString = #"AuthType = Office365; Url = https://CRMINFORMATION";
CrmServiceClient conn = new CrmServiceClient(connectionString);
IOrganizationService service;
service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.All,
LogicalName = "account"
};
RetrieveEntityResponse retrieveAccountEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
EntityMetadata AccountEntity = retrieveAccountEntityResponse.EntityMetadata;
Console.WriteLine("Account entity attributes:");
foreach (object attribute in AccountEntity.Attributes)
{
AttributeMetadata a = (AttributeMetadata)attribute;
Console.WriteLine(a.LogicalName + " " +
a.Description + " " +
a.DisplayName + " " +
a.EntityLogicalName + " " +
a.SchemaName + " " +
a.AttributeType + " "
);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

Since Dynamics CRM supports multi-lingual capabilities, the display name label will be stored for each language. You can get it like below:
a.DisplayName.UserLocalizedLabel.Label

Related

I use ManagementClass to run a Process, but I want that process to run in Background instead of UI console

I'm using Mangement class to create a process, but That starts a UI console - I want to console to run in background.
public uint LaunchProcess(string sIPAddress, string sPort)
{
uint iPid = 0;
try
{
logger.AddLog("LaunchProcess : " + sIPAddress + " " + sPort);
object[] PlugInRunnerInfo = { StaticUtils.GetLocation(AgilentPluginCommonConstants.PlugInRunnerPath) + "\\" + "PlugInRunner.exe" + " " + sIPAddress + " " + sPort, null, null, 0 };
//ManagementClass is a part of Windows Management Intrumentation,namespaces. One of its use is to provides access to manage applications.
//Here this class is used to launch PlugInRunner as detached process.By setting the ManagementClass object's property 'CreateFlags' to value 0x00000008
//we can start the PlugInRunner as detached one.
using (var mgmtObject = new ManagementClass("Win32_Process"))
{
var processStartupInfo = new ManagementClass("Win32_ProcessStartup",null);
processStartupInfo.Properties["CreateFlags"].Value = 0x00000008;//DETACHED_PROCESS.
var result = mgmtObject.InvokeMethod("Create", PlugInRunnerInfo);
if (result != null)
{
logger.AddLog("Process id " + Convert.ToUInt32(PlugInRunnerInfo[3]));
iPid = Convert.ToUInt32(PlugInRunnerInfo[3]);
}
}
}
catch (Exception ex)
{
logger.AddLog("Exception " + ex.Message);
}
return iPid;
}
The above code what I have got. Please help me.

Accessing and displaying certain xml elements from a Service Reference

I'm writing a Stock Quote app in Silverlight and I can't figure out how to display only the information that I want from the xml, such as the price of the stock. It will display the tags and everything.
Here is my code:
private void getQuote_Click(object sender, RoutedEventArgs e)
{
bool check = NetworkInterface.GetIsNetworkAvailable();
if (check)
{
//available
GetQuote.StockQuoteSoapClient client = new StockQuoteSoapClient();
//call that method
client.GetQuoteAsync(symbolBox.Text);
//event handler response
client.GetQuoteCompleted +=client_GetQuoteCompleted;
}
else
{
return;
}
}
public void client_GetQuoteCompleted(object sender, GetQuoteCompletedEventArgs e)
{
result.Text = e.Result;
}
And here is the xml being returned by http://www.webservicex.net/stockquote.asmx?op=GetQuote
<string><StockQuotes><Stock><Symbol>msft</Symbol><Last>46.62</Last><Date>7/17/2015</Date><Time>4:00pm</Time><Change>-0.04</Change><Open>46.59</Open><High>46.78</High><Low>46.26</Low><Volume>29467107</Volume><MktCap>377.14B</MktCap><PreviousClose>46.66</PreviousClose><PercentageChange>-0.09%</PercentageChange><AnnRange>40.12 - 50.05</AnnRange><Earns>2.41</Earns><P-E>19.35</P-E><Name>Microsoft Corporation</Name></Stock></StockQuotes></string>
This is for a mobile app; it has to provide new, up-to-date information from the web service every time it is used, and I only need a few different pieces of the information. Also, the information shouldn't be specifically Microsoft, but any real company whose stock symbol is entered by the user.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<string>" +
"<StockQuotes>" +
"<Stock>" +
"<Symbol>msft</Symbol>" +
"<Last>46.62</Last>" +
"<Date>7/17/2015</Date>" +
"<Time>4:00pm</Time>" +
"<Change>-0.04</Change>" +
"<Open>46.59</Open>" +
"<High>46.78</High>" +
"<Low>46.26</Low>" +
"<Volume>29467107</Volume>" +
"<MktCap>377.14B</MktCap>" +
"<PreviousClose>46.66</PreviousClose>" +
"<PercentageChange>-0.09%</PercentageChange>" +
"<AnnRange>40.12 - 50.05</AnnRange>" +
"<Earns>2.41</Earns>" +
"<P-E>19.35</P-E>" +
"<Name>Microsoft Corporation</Name>" +
"</Stock>" +
"</StockQuotes>" +
"</string>";
XDocument doc = XDocument.Parse(input);
var stocks = doc.Descendants("Stock").Select(x => new {
symbol = x.Element("Symbol").Value,
last = double.Parse(x.Element("Last").Value),
date = DateTime.Parse(x.Element("Date").Value),
time = DateTime.Parse(x.Element("Time").Value),
change = double.Parse(x.Element("Change").Value),
open = double.Parse(x.Element("Open").Value),
high = double.Parse(x.Element("High").Value),
low = double.Parse(x.Element("Low").Value),
volume = long.Parse(x.Element("Volume").Value),
mktcap = double.Parse(x.Element("MktCap").Value.Replace("B", "")),
previousClose = double.Parse(x.Element("PreviousClose").Value),
percentChange = double.Parse(x.Element("PercentageChange").Value.Replace("%", "")),
annRange = x.Element("AnnRange").Value,
earns = double.Parse(x.Element("Earns").Value),
p_e = double.Parse(x.Element("P-E").Value),
name = x.Element("Name").Value,
}).ToList();
}
}
}
​

SQLite doesn't create database tables, crashes irc bot

So, when I connected, or attempt, it runs this code in Database.cs.
Also, I'm using SmartIRC4Net for IRC handling
Now I know this is the error because Init() in Database.cs doesn't even run! If it is, it doesn't create the "trubot.sqlite" file with the tables.
I have no idea why it's doing it, but it is.
Here's the Database.cs code:
public void Init(){
try {
if (File.Exists("trubot.sqlite")) {
dbf = new SQLiteConnection("Data Source=trubot.sqlite;Version=3");
dbf.Open();
String db;
db = "CREATE TABLE IF NOT EXISTS '"+chan+"' (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, battletag TEXT DEFAULT null, uLevel INTEGER DEFAULT 0, mod INTEGER DEFAULT 0, rlvl INTEGER DEFAULT 0);";
using (query = new SQLiteCommand(db, dbf)){
query.ExecuteNonQuery();
}
} else {
SQLiteConnection.CreateFile("trubot.sqlite");
dbf = new SQLiteConnection("Data Source=trubot.sqlite;Version=3");
dbf.Open();
String db;
db = "CREATE TABLE IF NOT EXISTS '"+chan+"' (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, battletag TEXT DEFAULT null, uLevel INTEGER DEFAULT 0, mod INTEGER DEFAULT 0, rlvl INTEGER DEFAULT 0);";
using (query = new SQLiteCommand(db, dbf)){
query.ExecuteNonQuery();
}
}
} catch (Exception s) {
Console.WriteLine("[ERROR] Error in code. " + s.Message);
}
}
public void addUser(String user) {
// add new user
try {
if (!usrExist(user)) {
String db = "INSERT INTO '"+chan+"' (user) VALUES ('"+user+"');";
using (query = new SQLiteCommand(db,dbf)) {
query.ExecuteNonQuery();
}
}
} catch (Exception err) {
Console.WriteLine("addUser is causing an error: " + err.Message);
}
}
and here's the other reason it crashes (which is in Program.cs)
public static void OnJoined(object sender, JoinEventArgs e) {
try {
var conf = new Config();
var db = new Database();
Console.WriteLine("[SELF] ["+conf.Channel+"] > *** "+e.Data.Nick+" has joined the channel!");
if (!db.usrExist(e.Data.Nick)) {
try {
db.addUser(e.Data.Nick);
} catch (Exception er1) {
string lnNum = er1.StackTrace.Substring(er1.StackTrace.Length - 7, 7);
Console.WriteLine("Error: -- Trubot Error "+ er1.Message + " " + er1.Data.ToString()
+ " " + er1.InnerException.Message.ToString()
+ " " + er1.TargetSite.ToString() + " Ln: " + lnNum);
Console.ReadKey();
}
}
} catch (Exception er1) {
string lnNum = er1.StackTrace.Substring(er1.StackTrace.Length - 7, 7);
Console.WriteLine("Error: -- Trubot Error "+ er1.Message + " " + er1.Data.ToString()
+ " " + er1.InnerException.Message.ToString()
+ " " + er1.TargetSite.ToString() + " Ln: " + lnNum);
Console.ReadKey();
}
}
Side note: I'd use MySQL but I need this application to be as portable as possible and run on as many operating systems as possible. I'd rather use SQLite than MSSQL or MySQL.
I fixed it. The problem was when I assigned the channel to the SQL as a Table Name, I needed to remove the "#" from it. So here's the resulting code:
public Database() {
var conf = new Config();
chan = conf.Channel.Replace("#","");
Init();
}

How do I access a tasks collection on user stories using Rally .NET toolkit?

I get:
Unhandled Exception: System.Collections.Generic.KeyNotFoundException: The given
key was not present in the dictionary.
when iterating over user story query results and try to access story["Tasks"]
foreach (var story in queryStoryResults.Results)
{
Console.WriteLine("FormattedID: " + story["FormattedID"]);
Console.WriteLine("Name: " + story["Name"]);
Console.Write("Tasks: " + story["Tasks"]);
}
First, make sure that Tasks are being fetched, along with task specific fields that you want to extract, e.g. State.
Next, a nested loop is needed inside the loop that iterates over user story results.
Here is the code example. It queries on user stories from the current iteration and prints out FormattedID and State of tasks associated with the query results:
namespace RESTexample_storiesFromIteration
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#domain.com", "1984", "https://rally1.rallydev.com", "1.43");
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/1111";
String projectRef = "/project/2222";
bool projectScopingUp = false;
bool projectScopingDown = true;
DateTime now = DateTime.Today;
String nowString = now.ToString("yyyy-MM-dd");
Request iterationRequest = new Request("Iteration");
iterationRequest.Workspace = workspaceRef;
iterationRequest.Project = projectRef;
iterationRequest.Fetch = new List<string>()
{
"Name",
"StartDate",
"EndDate",
"Project",
"State"
};
String iterationQueryString = "((StartDate <= \"" + nowString + "\") AND (EndDate >= \"" + nowString + "\"))";
iterationRequest.Query = new Query(iterationQueryString);
QueryResult queryIterationResults = restApi.Query(iterationRequest);
var myIteration = queryIterationResults.Results.First();
var myIterationName = myIteration["Name"];
var myIterationProject = myIteration["Project"];
var myIterationProjectName = myIterationProject["Name"];
Console.WriteLine("Name: " + myIterationName);
Console.WriteLine("Project Ref: " + myIterationProjectName);
Console.WriteLine("State: " + myIteration["State"]);
// Query for Stories
Request storyRequest = new Request("hierarchicalrequirement");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"ObjectID",
"ScheduleState",
"State",
"FormattedID",
"PlanEstimate",
"Iteration",
"Tasks"
};
storyRequest.Query = new Query("Iteration.Name", Query.Operator.Equals, myIterationName);
QueryResult queryStoryResults = restApi.Query(storyRequest);
foreach (var s in queryStoryResults.Results)
{
Console.WriteLine("----------");
Console.WriteLine("FormattedID: " + s["FormattedID"]);
Console.WriteLine("Name: " + s["Name"]);
Console.WriteLine("PlanEstimate: " + s["PlanEstimate"]);
var tasks = s["Tasks"];
foreach (var t in tasks)
{
Console.WriteLine("Task: " + t["FormattedID"] + " " + t["State"]);
}
}
}
}
}

client.get("me/statuses") returns empty "data" array using C# Facebook SDK 5.0.3

Using the C# Facebook SDK 5.0.3 everything works fine whit the client.Get("/me").
But when retrieving the status, I should get aan arraylist "data" with all the status messages according to the facebook Graph API, but instead my data array is empty and I get a 'Index out of bounds' exception.
Does anyone have an idea what my problem could be?
if (Request.Params["code"] != null)
{
var client = new FacebookClient(GetAccessToken());
dynamic me = client.Get("/me");
imgUser.ImageUrl = "https://graph.facebook.com/" + me.id + "/picture";
lblUsername.Text = me.name;
lblHometown.Text = me.hometown.name;
lblBirthday.Text = me.birthday;
lblCurrenttown.Text = me.location.name;
lblEmail.Text = me.email;
lblOpleidingen.Text = "";
lblOpleidingen.Text += me.education[1].type + ": " + me.education[1].school.name + ", " + me.education[1].year.name + "<br />"
+ me.education[0].type + ": " + me.education[0].school.name + ", " + me.education[0].year.name;
lblSex.Text = me.gender;
dynamic status = client.get("/me/statuses");
txtStatus.Text = status.data[0].message;
}
It requires the read_stream permission. Ensure you have it.
Your permission array should look like follows:
string[] extendedPermissions = new[] { "user_about_me", "read_stream" };
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
furthermore your second get() should be capitalized: Get()
dynamic status = client.get("/me/statuses");
dynamic status = client.Get("/me/statuses");

Categories