Roslyn Rename variable const in Majusucle - c#

Trying to convert that:
const string maj = "variable";
in
const string MAJ = "variable";
I'm using a Diagnostic with CodeFix.
I've already done the Diagnostic:
var localDeclarationConst = node as LocalDeclarationStatementSyntax;
if (localDeclarationConst != null &&
localDeclarationConst.Modifiers.Any(SyntaxKind.ConstKeyword)
)
{
foreach (VariableDeclaratorSyntax variable in localDeclarationConst.Declaration.Variables)
{
var symbol = model.GetDeclaredSymbol(variable);
if (symbol != null)
{
string varName = symbol.Name;
if (!varName.Equals(varName.ToUpper()))
{
addDiagnostic(Diagnostic.Create(Rule, localDeclarationConst.GetLocation(), "Les constantes doivent être en majusucle"));
}
}
}
}
But I cannot find a way for the CodeFix. Here is what I already wrote:
if (token.IsKind(SyntaxKind.ConstKeyword))
{
var ConstClause = (LocalDeclarationStatementSyntax)token.Parent;
var test = ConstClause.GetText();
var newConstClause = ConstClause.With //What with this With ??
var newRoot = root.ReplaceNode(ConstClause, newConstClause);
return new[] { CodeAction.Create("Mettre en maj", document.WithSyntaxRoot(newRoot)) };
}
As you can see, I'm looking for something that I can use with the .With
Edit:
So, I begin to understand how it works. But there is a point that I cannot know how it works. Let me explain:
if (token.IsKind(SyntaxKind.ConstKeyword))
{
var ConstClause = (VariableDeclaratorSyntax)token.Parent;
var test = ConstClause.Identifier.Text;
var newConstClause = ConstClause.ReplaceToken(SyntaxFactory.Identifier(test), SyntaxFactory.Identifier(test.ToUpperInvariant()));
var newRoot = root.ReplaceNode(ConstClause, newConstClause);
return new[] { CodeAction.Create("Make upper", document.WithSyntaxRoot(newRoot)) };
}
Here it's what I've done. To acces to the name of the variable (ConstClause.Identifier.Text) I use a VariableDeclaratorSyntax instead of the LocalDeclarationStatementSyntax.
But it doesn't work. What does I have to use??
It will be very helpful, because I will know how to change the name of my variables. And I need that.

Try ReplaceToken() instead of a With method.
Also, in your diagnostic, you could just use VariableDeclarator.Identifier instead of forcing the symbol to be created with GetDeclaredSymbol.

Okey, I'll find a way a now it works!
Here is the Diagnostic:
var localDeclarationConst = node as LocalDeclarationStatementSyntax;
if (localDeclarationConst != null &&
localDeclarationConst.Modifiers.Any(SyntaxKind.ConstKeyword)
)
{
foreach (VariableDeclaratorSyntax variable in localDeclarationConst.Declaration.Variables)
{
string varName = variable.Identifier.Text;
if (!varName.Equals(varName.ToUpper()))
{
addDiagnostic(Diagnostic.Create(Rule, variable.GetLocation(), "Les constantes doivent être en majusucle"));
}
}
And here is the CodeFix:
var root = await document.GetSyntaxRootAsync(cancellationToken); (root)
var token = root.FindToken(span.Start);
var node = root.FindNode(span);
if (node.IsKind(SyntaxKind.VariableDeclarator))
{
if (token.IsKind(SyntaxKind.IdentifierToken))
{
var variable = (VariableDeclaratorSyntax)node;
string newName = variable.Identifier.ValueText;
string NameDone = String.Empty;
for (int i = 0; i < newName.Length; i++)
{
NameDone = NameDone.ToString() + char.ToUpper(newName[i]);
}
var leading = variable.Identifier.LeadingTrivia;
var trailing = variable.Identifier.TrailingTrivia;
VariableDeclaratorSyntax newVariable = variable.WithIdentifier(SyntaxFactory.Identifier(leading, NameDone, trailing));
var newRoot = root.ReplaceNode(variable, newVariable);
return new[] { CodeAction.Create("Make upper", document.WithSyntaxRoot(newRoot)) };
}
}
If something looks wrong tell me, but I tried it and it works!

Related

MOQ Exception Was unhandled by user

I am pretty new to MOQ and I am in learning right now. I got task that I need to write unit test But I am getting the below error which I couldn't able to find. Please anyone help me with this. Also please review the code and give me some advises if my testcase needs changes.
Expection: IAcronisService.GetActivitiesFromDate("mygroup", 5/24/2016
8:33:34 PM) invocation failed with mock behavior Strict.....
for Save method(I have commented at save method where the exception has been thrown)
Process method calls save method
public int Process()
{
AcronisService = AcronisSvcManager.Get(ClientFactory, DataProviderFactory, LogAdapter);
DataObject backupGroupsDO = GetListOfAllCurrentGroups();
int activitiesSavedCount = Save(backupGroupsDO);
return activitiesSavedCount;
}
When I debug I also have seen the below line when I mouse over at first line on above process method. I thought service object is not calling/mocking. Is this anything to do with above exception? Please suggest some changes.
(IAcronisServiceProxy)AcronisService).AcronisURL threw a exception of type MOQ.MockException.
Save Method
private int Save(DataObject backupGroupsDO)
{
int count = 0;
foreach (DataRecord dr in backupGroupsDO.DataRecord)
{
BackupGroup backupGroup = new BackupGroup(dr);
// Get all activities for each group
AcronisClient.DataModel.Activity.ActivitiesResponse acronisActivities;
if (backupGroup.LastActivityDate == null)
{
// Get all activities for each group
***//Got Exception at this line***
acronisActivities = AcronisService.GetActivitiesFromDate(backupGroup.GroupName, DateTime.Now.AddDays(-90));
}
else
{
acronisActivities = AcronisService.GetActivitiesFromDate(backupGroup.GroupName, backupGroup.LastActivityDate);
}
if (acronisActivities == null || acronisActivities.Activities == null)
{
// Stop processing b/c might be an issue with the connection to Acronis
LogAdapter.LogError(KCBLog.Main, "Stopped processing activities, possible Acronis connection issue with getting Activities");
return -1;
}
var lastBackUpActivity = acronisActivities.Activities.OrderByDescending(z => z.StartTime).FirstOrDefault();
List<string> lastSuccessfulActivities = new List<string>();
List<string> lastActivities = new List<string>();
foreach (var acronisActivity in acronisActivities.Activities)
{
Kaseya.KCB.Common.DataModels.AcronisActivity activity = new AcronisActivity();
activity.BackupPlanId = acronisActivity.BackupPlanId;
activity.BytesProcessed = acronisActivity.BytesProcessed;
activity.BytesSaved = acronisActivity.BytesSaved;
activity.Cause = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Cause;
activity.Reason = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Reason;
activity.Effect = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Effect;
activity.DateCreated = DateTime.Now;
activity.FinishTime = acronisActivity.FinishTime;
activity.GroupId = backupGroup.Id;
activity.Id = acronisActivity.Id;
activity.InitiatedBy = acronisActivity.InitiatedBy;
activity.InstanceId = acronisActivity.InstanceId;
activity.IsRootActivity = (bool)acronisActivity.IsRootActivity;
activity.ParentActivityId = acronisActivity.ParentActivityId;
activity.PartitionId = PartitionId;
activity.StartTime = acronisActivity.StartTime;
activity.State = acronisActivity.State;
activity.Status = acronisActivity.Status;
activity.Title = acronisActivity.Title;
activity.UpdateTime = acronisActivity.UpdateTime;
AcronisActivityDataProvider.AddUpdateAcronisActivity(activity);
AcronisClient.DataModel.Activity.Activity lastSuccessfulActivity = acronisActivities.Activities.Where(z => z.Status == "ok" && z.Title.Contains("Running backup plan") && z.InstanceId==acronisActivity.InstanceId).OrderByDescending(z => z.FinishTime).FirstOrDefault();
var lastActivity = acronisActivities.Activities.Where(z => z.Title.Contains("Running backup plan") && z.InstanceId == acronisActivity.InstanceId).OrderByDescending(z => z.FinishTime).FirstOrDefault();
if (!string.IsNullOrEmpty(acronisActivity.InstanceId))
{
DataRecord assetDR = AssetDataProvider.GetByInstanceId(acronisActivity.InstanceId, PartitionId);
if (assetDR != null)
{
var assetId = assetDR.FindValue<string>("id", "");
if (lastSuccessfulActivity != null && !lastSuccessfulActivities.Contains(acronisActivity.InstanceId))
{
AssetDataProvider.UpdateLastSuccessfulActivityId(assetId, lastSuccessfulActivity.ParentActivityId);
lastSuccessfulActivities.Add(acronisActivity.InstanceId);
}
if (lastActivity != null && !lastActivities.Contains(acronisActivity.InstanceId))
{
AssetDataProvider.UpdateLastActivityId(assetId, lastActivity.ParentActivityId);
lastActivities.Add(acronisActivity.InstanceId);
}
}
}
count++;
}
if (acronisActivities.Activities != null && acronisActivities.Activities.Count>0)
{
//backupGroup.LastActivityDate = lastBackUpActivity.StartTime;
BackupGroupDataProvider.UpdateLastBackupGroupActivityDate(backupGroup.Id, lastBackUpActivity.StartTime);
}
}
return count;
}
Test Method I have writtern,
public void Test()
{
string groupName = "mygroup";
string mybackupAccountName = "mybackupaccount";
decimal PartitionId = 9m;
DateTime lastActivityDate = DateTime.Parse("2016-08-14T20:47:05");
string instanceId = "utinstanceId";
string assetId = "123";
DataRecord asset = new DataRecord();
asset.AddField("id", 123);
DataObject backupGroupsDO = new DataObject();
DataRecord groupDataRecord = new DataRecord();
groupDataRecord.AddField("id", 123);
groupDataRecord.AddField("partitionId", PartitionId);
groupDataRecord.AddField("groupName", groupName);
//groupDataRecord.AddField("lastActivityDate", lastActivityDate);
groupDataRecord.AddField("backupAccountName", mybackupAccountName);
backupGroupsDO.DataRecord.Add(groupDataRecord);
AcronisActivity acronisActivity = new AcronisActivity();
acronisActivity.BackupPlanId = "utBackupPlanId";
ActivitiesResponse activitiesResponse = new ActivitiesResponse();
AcronisClient.DataModel.Activity.Activity activity = new AcronisClient.DataModel.Activity.Activity();
activity.BackupPlanId = "utackupPlanId";
activity.BytesProcessed = 124674;
activity.BytesSaved = 06446;
activity.CompletionResult = new CompletionResult()
{
Cause = "utCause",
Reason = "utReason",
Effect = "utEffect"
};
activity.FinishTime = DateTime.Parse("2016-08-14T20:47:04");
activity.Id = "utId";
activity.InitiatedBy = "utInitiatedBy";
activity.InstanceId = "utInstanceId";
activity.IsRootActivity = true;
activity.ParentActivityId = "utParentActivityId";
activity.StartTime = DateTime.Parse("2016-08-14T20:47:02");
activity.State = "utState";
activity.Status = "utStatus";
activity.Title = "utTitle";
activity.UpdateTime = DateTime.Parse("2016-08-14T20:47:03");
activitiesResponse.Activities = new List<AcronisClient.DataModel.Activity.Activity>();
activitiesResponse.Activities.Add(activity);
var moqFactory = new MockRepository(MockBehavior.Strict);
var moqDataProviderFactory = moqFactory.Create<IDataProviderFactory>();
var moqDataProvider = moqFactory.Create<IDataProvider>();
var moqLogAdapter = moqFactory.Create<ILogAdapter>();
var moqAcronisServiceManager = moqFactory.Create<IAcronisServiceManager>();
var moqAcronisService = moqFactory.Create<IAcronisService>();
var moqAssetDataProvider = moqFactory.Create<IAssetDataProvider>();
var moqAcronisActivityDataProvider = moqFactory.Create<IAcronisActivityDataProvider>();
var moqBackupGroupDataProvider = moqFactory.Create<IBackupGroupDataProvider>();
Credential MSPCredential = new Credential();
moqDataProviderFactory.Setup(m => m.BackupGroupDataProvider.GetBackupGroups()).Returns(backupGroupsDO);
moqAcronisServiceManager.Setup(m => m.Get(It.IsAny<IRestClientFactory>(), It.IsAny<IDataProviderFactory>(), It.IsAny<ILogAdapter>(), "")).Returns(moqAcronisService.Object);
moqDataProvider.Setup(m => m.VerifyPartitionId(ref PartitionId));
moqDataProvider.Setup(m => m.ExecuteNonQuery(It.IsAny<AddUpdateAcronisActivity>())).Returns(1);
moqAcronisService.Setup(m => m.GetActivitiesFromDate(groupName, lastActivityDate)).Returns(activitiesResponse);
moqAcronisActivityDataProvider.Setup(m => m.AddUpdateAcronisActivity(acronisActivity));
moqAssetDataProvider.Setup(m => m.GetByInstanceId(instanceId, PartitionId,1)).Returns(asset);
moqAssetDataProvider.Setup(m => m.UpdateLastActivityId(assetId, activity.ParentActivityId));
moqAssetDataProvider.Setup(m => m.UpdateLastSuccessfulActivityId(assetId, activity.ParentActivityId));
moqBackupGroupDataProvider.Setup(m => m.UpdateLastBackupGroupActivityDate("1234", lastActivityDate));
// moqAcronisService.Setup(m => m.GetActivitiesFromDate(groupName, Convert.ToDateTime("2016-08-18T13:18:40.000Z"))).Returns(activitiesResponse);
ActivityHarvester activityHarvester = new ActivityHarvester();
activityHarvester.PartitionId = PartitionId;
activityHarvester.DataProvider = moqDataProvider.Object;
activityHarvester.LogAdapter = moqLogAdapter.Object;
activityHarvester.AcronisSvcManager = moqAcronisServiceManager.Object;
activityHarvester.DataProviderFactory = moqDataProviderFactory.Object;
activityHarvester.AcronisService = moqAcronisService.Object;
activityHarvester.AssetDataProvider = moqAssetDataProvider.Object;
activityHarvester.BackupGroupDataProvider = moqBackupGroupDataProvider.Object;
activityHarvester.AcronisActivityDataProvider = moqAcronisActivityDataProvider.Object;
activityHarvester.process();//*process method calls above save method method*
moqFactory.VerifyAll();
}
From your example, your setup for IAcronisService.GetActivitiesFromDate shows that it is expecting lastActivityDate of 2016-08-14T20:47:05 based on the code but the error shows that you used a different date 5/24/2016 8:33:34 PM than expected. As the moq behavior is Strict, this
Causes the mock to always throw an exception for invocations that don't have a corresponding setup.
You can make the setup a little more flexible by using It.IsAny<DateTime>()
moqAcronisService
.Setup(m => m.GetActivitiesFromDate(groupName, It.IsAny<DateTime>()))
.Returns(activitiesResponse);
or changing the behavior in your moq factory to use Default or Loose MockBehavior.

foreach loop is not working in mvc

foreach (int workFlowServiceDetail in workFlowServiceDetails)
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
/*****************************************Problem in this loop**********/
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Aspir.Pan.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;
Inside this loop a condition is checked to find a particular user form alist of user.Once the condition is true it jump out of the loop without checking the next one.
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Asire.Pan.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
this is mainly because of the " return userList". so how can i make the loop run again. or please suggest some way to make it work.Is it possible to copy that returning userList to some List and return it after the loop.If so how can i write i list there. Please help me..?
Remove return in Foreach loop
var userListsTemp=null;
foreach (int workFlowServiceDetail in workFlowServiceDetails)
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
/*****************************************Problem in this loop**********/
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Aspir.Pan.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
//return userLists;
if(userListsTemp==null)
{
userListsTemp=userLists;
}
else
{
userListsTemp.Concat(userLists).ToList();
}
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;

How i can add Couchbase Documents in a list?

I'm experimenting with Couchbase + Xamarin.Forms trying to do a simple search, showing the results in a ListView but I've stuck. :(
Someone know how to add the rows/documents of a query in a list?
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView ("ByName");
viewByName.SetMap((doc, emit) => {
emit (new object[] {doc["first_name"], doc["last_name"]}, doc);
}, "2");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = new List<object> {word};
// visitorQuery.EndKey = new List<object> {word, new Dictionary<string, object>()};
visitorQuery.Limit = 100;
var visitors = visitorQuery.Run();
var visitorList = new List<Visitor> ();
foreach (var visitor in visitors) {
// visitorList.Add(visitor.Document); <-- Error.
System.Console.WriteLine(visitor.Key);
}
return visitorList;
}
I get the error messages:
Error CS1501: No overload for method Add' takes2' arguments
(CS1501) (Demo_Couchbase.Droid) Error CS1502: The best overloaded
method match for
System.Collections.Generic.List<Demo_Couchbase.Visitor>.Add(Demo_Couchbase.Visitor)'
has some invalid arguments (CS1502) (RegistroAgil_Couchbase.Droid)
Error CS1503: Argument#1' cannot convert Couchbase.Lite.Document'
expression to typeDemo_Couchbase.Visitor' (CS1503)
(Demo_Couchbase.Droid)
Thank you in advance for any help you can provide.
There is problem in your mapping part. You can directly cast documents on GetView.
You can try bellow code.
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView<Visitor>("ByName","ByName");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = new List<object> {word};
visitorQuery.Limit = 100;
var visitors = visitorQuery.Run();
var visitorList = new List<Visitor> ();
foreach (var visitor in visitors) {
visitorList.Add(visitor.Document);
System.Console.WriteLine(visitor.Key);
}
return visitorList;
}
I don't know if this is the most elegant solution though but my code works fine now.
Visitor ToRecord(Document d) {
var props = d.Properties;
return new Visitor {
Id = props["_id"].ToString(),
FirstName = (string)props["first_name"],
LastName = (string)props["last_name"],
Occupation = (string)props["occupation"],
Company = (string)props["company"],
Email = (string)props["email"],
Phone = (string)props["phone"],
Birthday = (string)props["birthday"],
LastVisit = (string)props["last_visit"],
LocalImagePath = (string)props["local_image_path"],
Type = (string)props["type"],
CreatedAt = (string)props["created_at"],
UpdatedAt = (string)props["updated_at"],
DeletedAt = (string)props["deleted_at"]
};
}
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView ("ByName");
viewByName.SetMap((doc, emit) => {
if ((doc.ContainsKey("type") && doc["type"].ToString() == "visitor") && (doc.ContainsKey("deleted_at") && doc["deleted_at"] == null))
emit (new [] {doc["first_name"], doc["last_name"]}, doc);
}, "2");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = word;
visitorQuery.Limit = 50;
var rows = visitorQuery.Run();
var visitorList = new List<Visitor> ();
for (int i = 0; i < rows.Count (); i++) {
var row = rows.GetRow (i);
var name = row.Document.GetProperty ("first_name").ToString ().ToLower () + " " + row.Document.GetProperty ("last_name").ToString ().ToLower ();
if (name.Contains (word))
visitorList.Add(ToRecord(row.Document));
}
return visitorList;
}

How to judge the node of json exists

I am using Newtonsoft.Json to Deserialize json string to Object, but I can't judge if the node is null or not. eg. jo["data"]["prevtime"], sometimes json has the node of ["prevtime"], sometimes doesn't have ["prevtime"]. If ["prevtime"] is null, it will report an error.
var jo = JObject.Parse(content);
if (jo["data"].ToString() == "")
return new StatusCollection();
var jInfo = jo["data"]["info"];
StatusCollection list = new StatusCollection();
Status status = null;
if (jInfo != null)
{
foreach (var j in jInfo.Children())
{
if (jo["data"]["prevtime"] != null)
{
status.Nexttime = jo["data"]["nexttime"].ToString();
status.Prevtime = jo["data"]["prevtime"].ToString();
}
status = j.ToObject<Status>();
if (!string.IsNullOrEmpty(status.Head))
{
status.Head += "/50";
}
if (!string.IsNullOrEmpty(status.From))
{
status.From = "来自" + status.From;
}
list.Add(status);
}
}
In the current version, it would be like :
if (jo["data"].Select***Token***("prevtime") != null)
{
status.Prevtime = jo["data"].Value<string>("prevtime");
status.Nexttime = jo["data"].Value<string>("nexttime");
}
Try to select the token you want, and there is a property to get the token value
if (jo["data"].Select("prevtime") != null)
{
status.Prevtime = jo["data"].Value<string>("prevtime");
status.Nexttime = jo["data"].Value<string>("nexttime");
}
JSON.NET Documentation:
Link 1
Link 2

Error when returning value in C# 2.0

I downloaded an example application for using some web services with an online system.
I am not sure if all code below is needed but it is what I got and what I am trying to do is to use the search function.
I start by calling searchCustomer with an ID I have:
partnerRef.internalId = searchCustomer(customerID);
And the code for searchCustomer:
private string searchCustomer(string CustomerID)
{
string InternalID = "";
CustomerSearch custSearch = new CustomerSearch();
CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();
String nameValue = CustomerID;
SearchStringField entityId = null;
entityId = new SearchStringField();
entityId.#operator = SearchStringFieldOperator.contains;
entityId.operatorSpecified = true;
entityId.searchValue = nameValue;
custSearchBasic.entityId = entityId;
String statusKeysValue = "";
SearchMultiSelectField status = null;
if (statusKeysValue != null && !statusKeysValue.Trim().Equals(""))
{
status = new SearchMultiSelectField();
status.#operator = SearchMultiSelectFieldOperator.anyOf;
status.operatorSpecified = true;
string[] nskeys = statusKeysValue.Split(new Char[] { ',' });
RecordRef[] recordRefs = new RecordRef[statusKeysValue.Length];
for (int i = 0; i < nskeys.Length; i++)
{
RecordRef recordRef = new RecordRef();
recordRef.internalId = nskeys[i];
recordRefs[i] = recordRef;
}
status.searchValue = recordRefs;
custSearchBasic.entityStatus = status;
}
custSearch.basic = custSearchBasic;
SearchResult response = _service.search(custSearch);
if (response.status.isSuccess)
{
processCustomerSearchResponse(response);
if (seachMoreResult.status.isSuccess)
{
processCustomerSearchResponse(seachMoreResult);
return InternalID;
}
else
{
_out.error(getStatusDetails(seachMoreResult.status));
}
}
else
{
_out.error(getStatusDetails(response.status));
}
return InternalID;
}
In the code above processCustomerSearchResponse gets called
processCustomerSearchResponse(response);
The code for this function is:
public string processCustomerSearchResponse(SearchResult response)
{
string InternalID = "";
Customer customer;
customer = (Customer)records[0];
InternalID = customer.internalId;
return InternalID;
}
What the original code did was to write some output in the console but I want to return the InternalID instead. When I debug the application InternalID in processCustomerSearchResponse contains the ID I want but I don't know how to pass it to searchCustomer so that function also returns the ID. When I debug searchCustomer InternalID is always null. I am not sure on how to edit the code under response.status.isSuccess
to return the InternalID, any ideas?
Thanks in advance.
When you call processCustomerSearchResponse(response);, you need to store the return value in memory.
Try modifying your code like this:
InternalID = processCustomerSearchResponse(response);

Categories