The problem is in connection to MS CRM 2016 by Xrm.Tooling.Connector. There is bug. When you get object from connection method OrganizationServiceProxy is null.
We solved this problem 2 days and on the end problem was in invalid app.config in section system.serviceModel. When we repair all errors, everything was ok. I hope this solution help to other people.
I find last CRM error in connection object. You can get the message by reflection.
public void TestInit()
{
var str = "Url=https://*****; Domain=***; Username=***; Password=****; authtype=AD;";
mysvc = new CrmServiceClient(str);
var crmConSvc = GetInstanceField(mysvc.GetType(), mysvc, "CrmConnectionService");
var logEntry = GetInstanceField(crmConSvc.GetType(), crmConSvc, "logEntry");
var lastErrorMethod = GetInstanceMethod(logEntry.GetType(), logEntry, "get_LastError");
var message = lastErrorMethod.Invoke(logEntry, null);
Console.WriteLine(message);
}
internal static object GetInstanceField(Type type, object instance, string fieldName)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Static ;
FieldInfo field = type.GetField(fieldName, bindFlags);
return field?.GetValue(instance);
}
internal static MethodInfo GetInstanceMethod(Type type, object instance, string methodName)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Static;
MethodInfo met = type.GetMethod(methodName, bindFlags);
return met;
}
Related
I have a table:
Name | account info| AccountNumber
-----| ------------| ------
abc | IT | 3000
bdc | Desk | 2000
sed | Kitchen | 3000
afh | work | 4000
hsfs | home | 2000
I want to achieve something like this:
Name | account info| DisguiseInfo
-----| ------------| ------
abc | IT | Acc1
bdc | Desk | Acc2
sed | Kitchen | Acc1
afh | work | Acc3
hsfs | home | Acc2
I tried doing this:
int count = 1;
var disguise = listResults.GroupBy(x => x.ID).Select(y =>
y.First()).Distinct();
foreach (var i in disguise)
{
i.DisguiseName = "Acc " + count;
count++;
}
Which gives a results like this (very close to what I want):
Name | account info| DisguiseInfo
-----| ------------| ------
abc | IT | Acc1
bdc | Desk | Acc2
sed | Kitchen |
afh | work | Acc3
hsfs | home |
The problem with that is that, it doesn't give the ability to add the same string value 'Acc1' to the same duplicate value in the list, (the rest of the table comes blank only the fist values gets replaced), So how do I replace the entire value with matching IDs?
//EDIT
the data is being populated using sqlcommand in a class called SQLQuery, in this class there's a method called Account which execute like this:
SqlDataReader reader = command.ExecuteReader();
List<ViewModel> returnList = new List<ViewModel>();
if (reader.HasRows)
{
while (reader.Read())
{
ViewModel vm = new ViewModel();
vm.Name = reader.GetString(2);
vm.AccountInfo= reader.GetString(3);
vm.AccountNumber = reader.GetInt32(4);
returnList.Add(vm)
}
}
so this method return the first table above no issues.
In my controller action, is where I want to perhaps copy the SQLQuery return list into another list to filter so I'm doing (in the action method):
public async Task<IActionResult> DisguiseAction(string accNum)
{
List<ViewModel> executeSQL = new List<ViewModel>();
SQLQuery getQuery = new SQLQuery();
executeSQL = getQuery.Account(accNum); //at this point the sql
//gets executed with the correct value. Now I need to disguise the
//value. which I did
int count = 1;
var disguise = listResults.GroupBy(x => x.ID).Select(y =>
y.First()).Distinct();
foreach (var i in disguise)
{
i.DisguiseName = "Acc " + count;
count++;
}
}
Your problem is the .Distinct() call, that only takes the first element out of each group. Due to the fact, that you need to memoize all already seen values, it is easier to use a dictionary to hold the already mapped values. One possibility could be:
var accounts = new List<Account>
{
new Account { Name = "abc", Department = "IT", AccountInfo = 3000 },
new Account { Name = "bdc", Department = "Desk", AccountInfo = 2000 },
new Account { Name = "sed", Department = "Kitchen", AccountInfo = 3000 },
new Account { Name = "afh", Department = "work", AccountInfo = 4000 },
new Account { Name = "hsfs", Department = "home", AccountInfo = 2000 },
};
var mappings = new Dictionary<int, string>();
var summary = accounts
.Select(acc => new AccountSummary
{
Name = acc.Name,
Department = acc.Department,
DisguiseInfo = GetOrAddMapping(acc.AccountInfo, mappings)
})
.ToList();
foreach (var item in summary)
{
Console.WriteLine(JsonSerializer.Serialize(item));
}
And the helper method would in this case be:
private static string GetOrAddMapping(int accountInfo, Dictionary<int, string> mappings)
{
if (!mappings.TryGetValue(accountInfo, out var value))
{
value = $"Acc{mappings.Count + 1}";
mappings.Add(accountInfo, value);
}
return value;
}
using System;
using System.Collections.Generic;
public class Ent
{
public Ent(string a, string b, string c)
{
name = a;
location = b;
id = c;
}
public string name;
public string location;
public string id;
public override string ToString()
{
return $"{name} | {location} | {id}";
}
}
public class Program
{
public static void Main()
{
var input = new List<Ent>
{
new Ent("abc", "IT", "3000"),
new Ent("bcd", "Desk", "2000"),
new Ent("sed", "Kitchen", "3000"),
new Ent("afh", "work", "4000"),
new Ent("hsf", "home", "2000"),
};
var output = input
.GroupBy(x => x.id) // x is of type Ent
.SelectMany(y => // y is of type IGrouping<string, IEnumerable<Ent>>
y.Select(z => // z is of type Ent
new Ent(z.name, z.location, "Acc" + y.Key.Substring(0, 1))));
foreach(var line in output)
Console.WriteLine(line);
}
}
Gives an output that looks like:
abc | IT | Acc3
sed | Kitchen | Acc3
bcd | Desk | Acc2
hsf | home | Acc2
afh | work | Acc4
This code works using GroupBy on the id, then unroll the groups using SelectMany, but now we have the Key for each group. So when unrolling, re-create each line, but replace the id with a transformed value of the Key.
After grouping by AccountInfo, you could take advantage of the .SelectMany() overload that provides an indexer for the source element (i.e. an indexer for the AccountInfo values).
In the following example, I am assuming that you have two separate classes for the original (identifiable) accounts and the disguised accounts, e.g.:
public class BasicAccount
{
public string Name { get; set; }
public string AccountType { get; set; }
}
public class Account : BasicAccount
{
public int AccountInfo { get; set; }
}
public class DisguisedAccount : BasicAccount
{
public string DisguisedInfo { get; set; }
}
If your original accounts are collected in a variable List<Account> accounts as such:
List<Account> accounts = new()
{
new() { Name = "abc", AccountType = "IT", AccountInfo = 3000 },
new() { Name = "bdc", AccountType = "Desk", AccountInfo = 2000 },
new() { Name = "sed", AccountType = "Kitchen", AccountInfo = 3000 },
new() { Name = "afh", AccountType = "work", AccountInfo = 4000 },
new() { Name = "hsfs",AccountType = "home", AccountInfo = 2000 }
};
, your disguised accounts could be produced as follows:
IEnumerable<DisguisedAccount> disguisedAccounts = accounts
.GroupBy(a => a.AccountInfo)
.SelectMany(( accountsByInfo, counter ) => accountsByInfo
.Select(account => new DisguisedAccount
{
Name = account.Name,
AccountType = account.AccountType,
DisguisedInfo = $"Acc{counter}"
}));
Note: Using this approach, you lose the ordering given by the original accounts collection. The resulting collection is:
Name
AccountType
DisguisedInfo
abc
IT
Acc1
sed
Kitchen
Acc1
bdc
Desk
Acc2
hsfs
home
Acc2
afh
work
Acc3
Example fiddle here.
Im a bit confused with whats happening bellow:
Can anyone explain me why is dataType keep saying StatisticData instead of SibsMonthly??
dataType is a enum? passad as ref param to this method and its initialized as null before the method call..
Here is the code:
string errorMessage = null;
Enums.Uploads.DataType? dataType = null;
if (ValidadeFile(file, ref errorMessage, ref dataType))
{
...
}
private bool ValidadeFile(IBrowserFile file, ref string errorMessage, ref Enums.Uploads.DataType? dataType)
{
List<string> acceptedFileTypes = new List<string>
{
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};
var valid = true;
if (AcceptedFileNames != null && AcceptedFileNames.Length > 0)
{
var tmp = AcceptedFileNames.Where(x => new Regex(x.Regex).IsMatch(file.Name))
.OrderByDescending(x => x.DataType)
.Select(x => x.DataType)
.FirstOrDefault();
dataType = tmp;
if (dataType == null)
{
valid = false;
errorMessage = Constants.Uploads.Error.InvalidFileName;
}
}
...
}
The WASM debugger doesn't seem to like ref variables, it seems to look at their address, not their value:
Inspecting them at their call site or in the Debug window behaves as expected; this is a debugger isssue.
I am new in Elasticsearch.
I need to insert documents using bulk option using NEST api.
I have to index 5000 documents from a table. Below is the code that i use for bulk indexing.
public ActionResult CreateBulk()
{
var descriptor = new BulkDescriptor();
foreach (var test in db.Attendance.Take(5000).ToList())
{
descriptor.Index<Attendance>(op => op.Document(new Attendance
{
AttendanceId = test.AttendanceId,
AttendanceDate = test.AttendanceDate,
Estate = test.Estate,
Division = test.Division,
FieldNo = test.FieldNo,
Employee = test.Employee,
Activity = test.Activity,
Quantity = test.Quantity
}));
}
var bulkresult = ElasticClient.Bulk(descriptor);
return RedirectToAction("Index");
}
But when i run the code, i am getting the following error:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Nest
StackTrace:
at Nest.NestSerializer.SerializeBulkDescriptor(IBulkRequest bulkRequest) in c:\Users\gmarz\code\elasticsearch-net\src\Nest\ExposedInternals\NestSerializer.cs:line 166
at Nest.ElasticClient.<Bulk>b__1b6(ElasticsearchPathInfo`1 p, BulkDescriptor d) in c:\Users\gmarz\code\elasticsearch-net\src\Nest\ElasticClient-Bulk.cs:line 31
at Nest.ElasticClient.Dispatch[D,Q,R](D descriptor, Func`3 dispatch) in c:\Users\gmarz\code\elasticsearch-net\src\Nest\ElasticClient.cs:line 82
at Nest.ElasticClient.Dispatch[D,Q,R](Func`2 selector, Func`3 dispatch) in c:\Users\gmarz\code\elasticsearch-net\src\Nest\ElasticClient.cs:line 70
at Nest.ElasticClient.Bulk(Func`2 bulkSelector) in c:\Users\gmarz\code\elasticsearch-net\src\Nest\ElasticClient-Bulk.cs:line 27
at AttendancePOC.Controllers.AttendanceController.CreateBulk() in D:\GIT Source\ElasticSearch\AttendancePOC\AttendancePOC\Controllers\AttendanceController.cs:line 114
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:
Please help me.. Is anything wrong in my code?.
I had the same exact problem.
I forgot about setting up the index name for this query.
I had set up a configuration which was setting up a default index during creation of new ElasticClient, but the configuration changed and my index was null.
Hope that helps
Please add default index like this
connectionSettings = new ConnectionSettings(connectionPool).DefaultIndex("indexname")
I do something like this :
var node = new Uri(elasticSearchURI);
var connectionPool = new SniffingConnectionPool(new[] { node });
var config = new ConnectionSettings(connectionPool)
.SniffOnConnectionFault(false)
.SniffOnStartup(false)
.SetTimeout(600000)
.DisablePing();
var EsClient = new ElasticClient(config);
Then i create the index and after that i use something like this:
List<Categories> categList = new List<Categories>();
if (categoriesData != null)
{
Parallel.ForEach(categoriesData, element =>
{
Categories inf = new Categories();
inf.Code = element.Code;
inf.Level = element.Level;
lock(categList)
{
categList.Add(inf);
}
});
EsClient.IndexMany<Categories>(categList,"index_name","type_name")
}
I had this problem and the solution was to include the defaultIndex property in ConnectionSettings as stated here eg:
var node = new Uri("http://something:9200");
var settings = new ConnectionSettings(node, "someDefaultIndexValue");
var client = new ElasticClient(settings);
We have an application that integrates with SCCM 2012 and saves custom SCCM applications to SCCM.
The problem I am having is that attempting to save one of our custom applications when the SCCM administrator has set the application to be in the retired state causes our application to fail the saving process.
I'd like to be able to query the SCCM application state in order to determine before we attempt the save operation whether the given application is Active or Retired.
I can find no reference to "retired" status in the SMS_Application Server WMI help or any of the other pages:
http://msdn.microsoft.com/en-us/library/hh949251.aspx
I have noticed that there is a Restore() method which looks like it will change the status of a Retired package back to Active, however that's not quite what I want to do.
Can anyone help me determine how to find an applications current status?
Thanks.
There's a method in the SCCM 2012 PowerShell cmdlets that appears to be retrieving the expired status. Here's the c# code (decompiled from the dll AppUI.PS.AppMan.dll on the SCCM server)
private bool IsApplicationRetired(IResultObject applicaction)
{
IResultObject[] resultObjectArray = null;
int integerValue = applicaction["CI_ID"].IntegerValue;
object[] objArray = new object[] { integerValue };
resultObjectArray = base.ExecuteQuery(string.Format(CultureInfo.InvariantCulture, "SELECT * FROM SMS_Application WHERE CI_ID = {0}", objArray));
IResultObject[] resultObjectArray1 = resultObjectArray;
int num = 0;
if (num < (int)resultObjectArray1.Length)
{
IResultObject resultObject = resultObjectArray1[num];
this.isApplicationRetired = resultObject["IsExpired"].BooleanValue;
}
if (this.isApplicationRetired)
{
object[] objArray1 = new object[] { integerValue };
IResultObject instance = base.ConnectionManager.GetInstance(string.Format(CultureInfo.InvariantCulture, "SMS_Application.CI_ID={0}", objArray1));
if (instance != null)
{
string stringValue = instance["ModelName"].StringValue;
instance.Dispose();
object[] objArray2 = new object[] { base.ConnectionManager.EscapeQueryString(stringValue, ConnectionManagerBase.EscapeQuoteType.SingleQuote) };
resultObjectArray = base.ExecuteQuery(string.Format(CultureInfo.InvariantCulture, "SELECT CI_ID FROM SMS_Application WHERE ModelName = '{0}' AND IsLatest = 1 AND IsExpired = 0", objArray2));
IResultObject[] resultObjectArray2 = resultObjectArray;
int num1 = 0;
if (num1 < (int)resultObjectArray2.Length)
{
IResultObject resultObject1 = resultObjectArray2[num1];
if (resultObject1["CI_ID"].IntegerValue != integerValue)
{
this.isApplicationRetired = false;
}
}
}
}
return this.isApplicationRetired;
}
The code working fine when run out side the CRM2011 application. When I embedded my Code Inside the CRM it will return blank pdf file with no data.
following is my code
public static Byte[] RenderReport(string ServiceURL, string ReportName, ParameterValue[] parameters)
{
byte[] result;
string encoding;
string mimeType;
Warning[] warnings = null;
string[] streamids;
string extension;
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
binding.Security.Transport.Realm = string.Empty;
binding.MaxReceivedMessageSize = 2147483647;
string deviceInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
EndpointAddress endpoint = new EndpointAddress(ServiceURL);
ReportExecutionServiceSoapClient client = new ReportExecutionServiceSoapClient(binding, endpoint);
client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
ServerInfoHeader serverInfoHeader;
ExecutionInfo executionInfo;
ExecutionHeader executionHeader = client.LoadReport(null, ReportName, null, out serverInfoHeader, out executionInfo);
// Attach Report Parameters
//executionHeader.ExecutionID = executionInfo.ExecutionID;
if (parameters != null)
client.SetExecutionParameters(executionHeader, null, parameters, null, out executionInfo);
ServerInfoHeader Info= client.Render(executionHeader, null, "PDF", deviceInfo, out result, out extension, out mimeType, out encoding, out warnings, out streamids);
return result;
}
Thanks
I changed the Async processor to run under a user that has access to the Report Server database and it worked instantly.it was set to use network service so I changed it to Administrator in services.