Can't convert a variable to Guid - c#-4.0

I know my question is really easy but i can't get its solution since last three hours.
I have created a gridview which has three columns PeriodID,PeriodName and Checkbox.
now when i go through for each loop for this grid,i want to get periodid value of each row in this gridview..
for this i have writen code like this.
foreach (GridViewRow row in gvdchk.Rows)
{
int i = row.RowIndex;
var cb = (HtmlInputCheckBox)row.FindControl("chkPaid");
var Periodid = gvdchk.Rows[i].FindControl("PeriodID");
//string su = Periodid.ToString();
// Guid PeriodID = Guid.Parse(su);
// Guid guid = new Guid(Periodid);
//var PeriodID = row.FindControl("PeriodID");
//Guid PeriodId = (Guid) PeriodID;
//Guid PeriodId = (Guid)(gvdchk.Rows[row.RowIndex].FindControl("datemonth2"));
// int order = m.bussinesCollection.BussinesPeriod.GetOrder(PeriodID);
if (cb != null && cb.Checked)
{
}
}
When I debug my code,I found that var Periodid gets the correct value of the period id but I want it as Guid.
Can anyone help in this..?

The following code that you have in your post
Guid guid = new Guid(Periodid);
will work fine to convert the string to GUID.
You can also check what is the datatype for the Periodid that you get in the line no. 5 of your code.

Related

ServiceStack Bug serializing GUIDs, numbers, etc. when value is default and SerializeFn is specified

When you try and serialize a Guid that is empty (not null, but empty) the result will be omitted if you set ExcludeDefaultValues = true.
But, if you then set ExcludeDefaultValues = false it will generate the string ""
JsConfig.IncludeNullValues = false;
JsConfig.ExcludeDefaultValues = false;
var tt = new { Name="Fred", Value=Guid.Empty, Value2=Guid.NewGuid() };
var test = JSON.stringify(tt);
Console.WriteLine(test);
Gives
{"Name":"Fred","Value":"00000000000000000000000000000000","Value2":"598a6e08af224db9a08c2d0e2f6cff11"}
But we want the Guid's formatted as a Microsoft format Guid at the client end, so we add a serializer:
JsConfig.IncludeNullValues = false;
JsConfig.ExcludeDefaultValues = false;
JsConfig<Guid>.SerializeFn = guid => guid.ToString();
var tt = new { Name="Fred", Value=Guid.Empty, Value2=Guid.NewGuid() };
var test = JSON.stringify(tt);
Console.WriteLine(test);
Gives
{"Name":"Fred","Value2":"07a2d8c0-48ad-4e72-b6f3-4fec81c36a1d"}
So the presence of a SerializeFn seems to make it ignore the config settings so it's impossible to generate the empty Guid.
The same bug applies to numbers, so if (like us) you reformat all Double to three decimal places they are omitted if zero, which is wrong.
Has anyone found a workaround for this?
Stepping through the source, it appears you need to explicitly call out what Types you want to include the default value for if there is a SerializeFn for that Type. Source reference. Note the JsConfig<Guid>.IncludeDefaultValue = true; line below.
Example Source
JsConfig.Reset();
JsConfig.IncludeNullValues = false;
JsConfig.ExcludeDefaultValues = false;
JsConfig<Guid>.SerializeFn = guid => guid.ToString();
JsConfig<Guid>.IncludeDefaultValue = true;
var tt = new { Name = "Fred", Value = Guid.Empty, Value2 = Guid.NewGuid() };
var test = tt.ToJson();
Console.WriteLine(test);
Output
{"Name":"Fred","Value":"00000000-0000-0000-0000-000000000000","Value2":"b86c4a18-db07-42f8-b618-6263148219ad"}
Your problem statement: Gistlyn: Note how it does not return the default GUID in the console.
The answer proposed above: Gistlyn: Notice how it does return the default GUID in the console.

How to create purchase order via code?

I had wrote some code for creating po via code, but it faild with error message: "CS Error: Cannot generate the next number for the sequence."
How can I fix this? Anything I missed? Thx for helping!
protected void createPO() {
POOrder order = new POOrder();
POOrderEntry graph = PXGraph.CreateInstance < POOrderEntry > ();
order.OrderType = "Normal";
order.OrderDesc = "some text";
order.EmployeeID = 215;
order.Hold = false;
var branch = (Branch)PXSelect<Branch, Where<Branch.branchCD, Equal<Required<Branch.branchCD>>>>.Select(Base, "WEST");
graph.FieldDefaulting.AddHandler<POOrder.branchID>((s, e) =>
{
e.NewValue = branch.BranchID;
e.Cancel = true;
});
order.VendorID = 79;
order = graph.CurrentDocument.Insert(order);
graph.CurrentDocument.Update(order);
graph.Actions.PressSave();
throw new PXRedirectRequiredException(graph, null);
}
Try to simply it first to see if something like this works...
protected void createPO()
{
var graph = PXGraph.CreateInstance<POOrderEntry>();
var order = graph.Document.Insert(new POOrder());
order.OrderType = POOrderType.RegularOrder; // This is the default so not necessary
order.OrderDesc = "some text";
order.EmployeeID = 215;
order.Hold = false;
order.VendorID = 79;
graph.Document.Update(order);
graph.Actions.PressSave();
throw new PXRedirectRequiredException(graph, null);
}
Using the Document view in place of the CurrentDocument view which is based on the current record of Document. Document is the primary view and the primary view should be used.
Also for the purchase order type the attribute related to the list values should be used for the stored value of the database (vs what you had was the displayed list value). For example order.OrderType = POOrderType.RegularOrder. Also this is the default value for a PO so it is not necessary to set this value unless you want a different constant found in the POOrderType class.

Dynamics CRM - Accessing Custom Product Option Value

Is there a way to programmatically access the Label & Value fields that has been created as a custom Field in MS CRM Dynamics please?
I have added a custom field called "new_producttypesubcode" which, for example, has 2 options, Trophy = 1000000 and Kit = 10000001.
I am writing an import utility that mirrors products between the customers website and their CRM and I want to get a list of all possible product options in the CRM to see if they are matched in the website.
So, in essence I want to...
get the list of possible new_producttypesubcodes and their corresponding values.
Iterate through the product variants in the website.
if the product variant name matches any name in the list of new_producttypecodes then add the value 1000000
So, if I find a product added to the website and its marked as a "Trophy" and "Trophy" exists in the CRM then new OptionSetValue(100000001)
I hope that makes sense...
Thanks
This function retrieves a dictionary of possible values localised to the current user. Taken from: CRM 2011 Programatically Finding the Values of Picklists, Optionsets, Statecode, Statuscode and Boolean (Two Options).
static Dictionary<String, int> GetNumericValues(IOrganizationService service, String entity, String attribute)
{
RetrieveAttributeRequest request = new RetrieveAttributeRequest
{
EntityLogicalName = entity,
LogicalName = attribute,
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse response = (RetrieveAttributeResponse)service.Execute(request);
switch (response.AttributeMetadata.AttributeType)
{
case AttributeTypeCode.Picklist:
case AttributeTypeCode.State:
case AttributeTypeCode.Status:
return ((EnumAttributeMetadata)response.AttributeMetadata).OptionSet.Options
.ToDictionary(key => key.Label.UserLocalizedLabel.Label, option => option.Value.Value);
case AttributeTypeCode.Boolean:
Dictionary<String, int> values = new Dictionary<String, int>();
BooleanOptionSetMetadata metaData = ((BooleanAttributeMetadata)response.AttributeMetadata).OptionSet;
values[metaData.TrueOption.Label.UserLocalizedLabel.Label] = metaData.TrueOption.Value.Value;
values[metaData.FalseOption.Label.UserLocalizedLabel.Label] = metaData.FalseOption.Value.Value;
return values;
default:
throw new ArgumentOutOfRangeException();
}
}
So you would then need to do something like:
Dictionary<String, int> values = GetNumericValues(proxy, "your_entity", "new_producttypesubcode");
if(values.ContainsKey("Trophy"))
{
//Do something with the value
OptionSetValue optionSetValue = values["Trophy"];
int value = optionSetValue.Value;
}
Yes, that data is all stored in the metadata for an attribute (SDK article). You have to retrieve the entity metadata for the entity and then find the attribute in the list. Then cast that attribute to a PicklistAttributeMetadata object and it will contain a list of options. I would mention that typically retrieving Metadata from CRM is an expensive operation, so think about caching.
private static OptionSetMetadata RetrieveOptionSet(IOrganizationService orgService,
string entityName, string attributeName)
{
var entityResponse = (RetrieveEntityResponse)orgService.Execute(
new RetrieveEntityRequest
{ LogicalName = entityName, EntityFilters = EntityFilters.Attributes });
var entityMetadata = entityResponse.EntityMetadata;
for (int i = 0; i < entityMetadata.Attributes.Length; i++)
{
if (attributeName.Equals(entityMetadata.Attributes[i].LogicalName))
{
if (entityMetadata.Attributes[i].AttributeType.Value ==
AttributeTypeCode.Picklist)
{
var attributeMD = (PicklistAttributeMetadata)
entityMetadata.Attributes[i];
return attributeMD.OptionSet;
}
}
}
return null;
}
Here is how to write the options to the console using the above call.
var optionSetMD = RetrieveOptionSet(orgService, "account", "accountcategorycode");
var options = optionSetMD.Options;
for (int i = 0; i < options.Count; i++)
{
Console.WriteLine("Local Label: {0}. Value: {1}",
options[i].Label.UserLocalizedLabel.Label,
options[i].Value.HasValue ? options[i].Value.Value.ToString() : "null");
}
I believe this works for global option set attributes as well, but if you know it is a global option set there is a different message for it that would probably a bit more efficient (SDK article).

Azure Table QuerySegmented no return

I am trying to pull a group of entities from an AzureTable and am using the following code to query it.
string partitionKey = string.Format(CultureInfo.InvariantCulture, "{0:d20}", accountId);
string rowKeyStart = string.Format(CultureInfo.InvariantCulture, "{0}:g", work.lead.id);
string rowKeyEnd = string.Format(CultureInfo.InvariantCulture, "{0}:h", work.lead.id);
var context = table.ServiceClient.GetTableServiceContext();
var query = context.CreateQuery<LinkedInPostEntity>(table.Name)
.Where(w => w.PartitionKey == partitionKey && w.RowKey.CompareTo(rowKeyStart) > 0 && w.RowKey.CompareTo(rowKeyEnd) <= 0)
.AsTableServiceQuery(context);
List<PostEntity> postsForLead = new List<PostEntity>();
TableContinuationToken continuation = null;
do
{
TableQuerySegment<PostEntity> segment = await AzureHelper.QuerySegmented(query, continuation);
postsForLead.AddRange(segment.Results);
continuation = segment.ContinuationToken;
} while (continuation != null);
table is an instance of CloudTable, accountId is an int, and work.lead.id is a string. I want to pull all entities which have a RowKey prefixed by that work.lead.id:g and followed by a string id. I feel like this code should work but it hangs on the await never finishing the Task given by QuerySegmented.
My thought might be that the Query is incorrectly formatted but I'm not sure how or why.
BTW I am new to posting so please let me know if I have forgotten any important information or can help clarify in anyway.
EDIT: here is very similar code that does work, its being called on a similar (though different) table which has a different id scheme. I need to use the id scheme given to me by the api I am using so I don't think reformatting it prior to entry is an option. The only difference between the two is the query so I have the feeling my query is to blame. Any ideas?
string partitionKey = string.Format(CultureInfo.InvariantCulture, "{0:d20}", accountId);
string rowKeyStart = string.Format(CultureInfo.InvariantCulture, "{0}:{1:d20}", work.ScreenName, (long)0);
string rowKeyEnd = string.Format(CultureInfo.InvariantCulture, "{0}:{1:d20}", work.ScreenName, long.MaxValue);
var context = table.ServiceClient.GetTableServiceContext();
var query = context.CreateQuery<TweetEntity>(table.Name)
.Where(w => w.PartitionKey == partitionKey && w.RowKey.CompareTo(rowKeyStart) >= 0 && w.RowKey.CompareTo(rowKeyEnd) <= 0)
.AsTableServiceQuery(context);
List<TweetEntity> tweetsForLead = new List<TweetEntity>();
TableContinuationToken continuation = null;
do
{
TableQuerySegment<TweetEntity> segment = await AzureHelper.QuerySegmented(query, continuation);
tweetsForLead.AddRange(segment.Results);
continuation = segment.ContinuationToken;
} while (continuation != null);
My spidey-sense tells me that you're calling this method and then calling Wait or Result on the returned task, from an ASP.NET or UI context. If you do this, you'll deadlock, as I explain on my blog.

Programmatically set a TaxonomyField on a list item

The situation:
I have a bunch of Terms in the Term Store and a list that uses them.
A lot of the terms have not been used yet, and are not available yet in the TaxonomyHiddenList.
If they are not there yet they don't have an ID, and I can not add them to a list item.
There is a method GetWSSIdOfTerm on Microsoft.SharePoint.Taxonomy.TaxonomyField that's supposed to return the ID of a term for a specific site.
This gives back IDs if the term has already been used and is present in the TaxonomyHiddenList, but if it's not then 0 is returned.
Is there any way to programmatically add terms to the TaxonomyHiddenList or force it happening?
Don't use
TaxonomyFieldValue tagValue = new TaxonomyFieldValue(termString);
myItem[tagsFieldName] = tagValue;"
because you will have errors when you want to crawl this item.
For setting value in a taxonomy field, you have just to use :
tagsField.SetFieldValue(myItem , myTerm);
myItem.Update();"
Regards
In case of usage
string termString = String.Concat(myTerm.GetDefaultLabel(1033),
TaxonomyField.TaxonomyGuidLabelDelimiter, myTerm.Id);
then during instantiation TaxonomyFieldValue
TaxonomyFieldValue tagValue = new TaxonomyFieldValue(termString);
exception will be thrown with message
Value does not fall within the expected range
You have additionally provide WssId to construct term string like shown below
// We don't know the WssId so default to -1
string termString = String.Concat("-1;#",myTerm.GetDefaultLabel(1033),
TaxonomyField.TaxonomyGuidLabelDelimiter, myTerm.Id);
On MSDN you can find how to create a Term and add it to TermSet. Sample is provided from TermSetItem class description. TermSet should have a method CreateTerm(name, lcid) inherited from TermSetItem. Therefore you can use it in the sample below int catch statement ie:
catch(...)
{
myTerm = termSet.CreateTerm(myTerm, 1030);
termStore.CommitAll();
}
As for assigning term to list, this code should work (i'm not sure about the name of the field "Tags", however it's easy to find out the proper internal name of the taxonomy field):
using (SPSite site = new SPSite("http://myUrl"))
{
using (SPWeb web = site.OpenWeb())
{
string tagsFieldName = "Tags";
string myListName = "MyList";
string myTermName = "myTerm";
SPListItem myItem = web.Lists[myListName].GetItemById(1);
TaxonomyField tagsField = (TaxonomyField) myList.Fields[tagsFieldName];
TaxonomySession session = new TaxonomySession(site);
TermStore termStore = session.TermStores[tagsField.SspId];
TermSet termSet = termStore.GetTermSet(tagsField.TermSetId);
Term myTerm = null;
try
{
myTerm = termSet.Terms[myTermName];
}
catch (ArgumentOutOfRangeException)
{
// ?
}
string termString = String.Concat(myTerm.GetDefaultLabel(1033),
TaxonomyField.TaxonomyGuidLabelDelimiter, myTerm.Id);
if (tagsField.AllowMultipleValues)
{
TaxonomyFieldValueCollection tagsValues = new TaxonomyFieldValueCollection(tagsField);
tagsValues.PopulateFromLabelGuidPairs(
String.Join(TaxonomyField.TaxonomyMultipleTermDelimiter.ToString(),
new[] { termString }));
myItem[tagsFieldName] = tagsValues;
}
else
{
TaxonomyFieldValue tagValue = new TaxonomyFieldValue(termString);
myItem[tagsFieldName] = tagValue;
}
myItem.Update();
}
}

Resources