foreach loop is not working in mvc - c#

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;

Related

How to append the values to the json filter format using c#

I have a C# method which takes the filter from URI based on the user input search in the format {"serialNumber":null,"deviceType":"Com'X 510"}.
My method also gets the serialNumber from other endpoints.
siteSNresult and partnerSNresult will fetch the external serial numbers from other endpoints.
I want the serialNumber to be appended to the filter which is fetched from the user input. Please find my code below.
public IEnumerable<EtpDevice> GetUpdatableDevices(int tenantId, [FromUri] string filter, string siteId, string partnerId)
{
var result = new List<EtpDevice>();
StringBuilder str = new StringBuilder();
var siteSNresult = "";
StringBuilder partnerSNresult = new StringBuilder();
var connectedUser = this.permissionService.GetConnectedUser();
if (siteId != "null")
{
var siteList = this.feeDataAccess.GetSitesListById(connectedUser.CurrentEnvironment, siteId);
siteSNresult = siteList.Gateways[0].SerialNumber;
}
if (partnerId != "null")
{
var partnerList = this.feeDataAccess.GetPartnerListbyId(connectedUser.CurrentEnvironment, partnerId);
foreach (var item in partnerList)
{
var partnerSN = item.Gateways[0].SerialNumber;
partnerSNresult = str.Append(partnerSN).AppendLine(";");
}
}
var finalFilter = $"{filter}" + ";" + $"{siteSNresult}" + ";" + $"{partnerSNresult}";
for (int offset = 0; result.Count() == 0 || result.Count() == _defaultLimit; offset += result.Count())
{
result = GetDevices(tenantId, offset, _defaultLimit, finalFilter).ToList();
}
return result;
}
Appended values must be in the var finalFilter. finalFilter must look something like this:
{"serialNumber":"RN-DN18184SE000078-046;AB-TEST51000000136-123","deviceType":"Com'X 510"}
How can I do this? Please help me. Thanks in advance.

Instagram API: How to insert all user media in c# asp.net mvc?

I am trying the get all user media from the instagram api and store into database but how can do that i don't know. i am write the code but using this code just add one media in the database. any one have the idea then please let me know how can do that. here below list the my code.
This is my C# method :
public string makePostFromInstagram()
{
var serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
var nodes1 = serializer1.Deserialize<dynamic>(GetData(strInstagramUserId));
foreach (var date in nodes1)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
int userCount = 0;
foreach (var post in thisNode)
{
if (thisNode[userCount]["username"] == strInstagramUserId)
{
id = thisNode[userCount]["id"].ToString();
}
userCount++;
}
}
}
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> csObj = serializer.Deserialize<Dictionary<string, object>>(GetRecentPost(id, accessToken));
int length = ((ArrayList)csObj["data"]).Count;
var nodes = serializer.Deserialize<dynamic>(GetRecentPost(id, accessToken));
foreach (var date in nodes)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
foreach (var post in thisNode)
{
UsersOnInstagram objUserInsta = new UsersOnInstagram();
string result = null;
//here i am add just one image so i want to here add multiple image insert
if (post["type"] == "image")
result = UsersOnInstagram.addInstagramPost(strPtId, HttpUtility.UrlEncode(post["caption"]["text"]), post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), null, post["type"]);
else if (post["type"] == "video")
result = objUserInsta.addInstagramPost(HttpUtility.UrlEncode(post["caption"]["text"]), strPtId, post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), post["videos"]["standard_resolution"]["url"], post["type"]);
}
}
}
Response.End();
}
this is my api method :
public static string GetRecentPost(string instagramaccessid, string instagramaccesstoken)
{
Double MAX_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-1));
Double MIN_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-2));
string url = "https://api.instagram.com/v1/users/" + instagramaccessid + "/media/recent?access_token=" + instagramaccesstoken + "&min_timestamp=" + MIN_TIMESTAMP + "&maz_timestamp=" + MAX_TIMESTAMP;
var webClient = new System.Net.WebClient();
string d = webClient.DownloadString(url);
return d;
}
any one know how can do that please let me know.

Get list of users from trusted domain

How do I get users list from trusted domain?
I have tried to run a LDAP query but I am not able to get users from trusted domain. This is my code:
public virtual List<UserModel> SearchUsers(string textValue)
{
var users = new List<UserModel>();
string context;
const string nameProperty = "name";
const string samAccountNameProperty = "samaccountname";
const string distinguishedNameProperty = "distinguishedname";
if (textValue.Contains("(").Equals(true) || textValue.Contains(")").Equals(true) || textValue.Contains("*").Equals(true))
{
textValue = EscapeInvalidCharacters(textValue);
}
var filterForDomainUser ="(&(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(|(samaccountname=" + textValue + "*)(name=" + textValue + "*)))";
using (HostingEnvironment.Impersonate())
{
using (var root = new DirectoryEntry("LDAP://RootDSE"))
{
context = root.Properties["defaultNamingContext"].Value.ToString();
}
using (var entry = new DirectoryEntry("GC://" + context))
{
using (
var search = new DirectorySearcher(entry,filterForDomainUser,
new[]
{
samAccountNameProperty, nameProperty,
distinguishedNameProperty
}, SearchScope.Subtree))
{
search.ReferralChasing = ReferralChasingOption.All;
search.PageSize = 10;
var resultCol = search.FindAll();
for (var counter = 0; counter < resultCol.Count; counter++)
{
var result = resultCol[counter];
var distinguishedName = (String)result.Properties[distinguishedNameProperty][0];
var domainName =
distinguishedName.Substring(distinguishedName.IndexOf("DC=",
StringComparison
.InvariantCultureIgnoreCase))
.Split(',')[0].Replace("DC=", "");
var name = (String)result.Properties[nameProperty][0];
var samAccountName = string.Format("{0}{1}{2}", domainName, #"\",
result.Properties[samAccountNameProperty][0]);
var userModel = new UserModel
{
DisplayName = name,
UserName = samAccountName
};
users.Add(userModel);
}
}
}
}
//SearchLocalUser(textValue, users);
return users;
}

Roslyn Rename variable const in Majusucle

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!

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