C# code running locally but not in web hosting - c#

in my asp.net web application i have this entity framework code snippet that work perfectly in local
CONNECTIONS_STATS cs = new CONNECTIONS_STATS();
cs.CS_ID_USER = 5211;
cs.CS_DATE = DateTime.Now;
using (var dbCtx = new ModelEntities())
{
dbCtx.CONNECTIONS_STATS.Add(cs);
dbCtx.SaveChanges();
}
but when i deploy it to my web host, i have this error at line
dbCtx.CONNECTIONS_STATS.Add(cs);
CS1502: The best overloaded method match for 'System.Data.Entity.DbSet.Add(MyAPP.CONNECTIONS_STATS)' has some invalid arguments
in the detailed compiler output
error CS1503: Argument 1: cannot convert from 'CONNECTIONS_STATS' to 'MyApp.CONNECTIONS_STATS'
i have checked that all the classes are in the same namespace , and like i said this code Work perfectly in local
any idea on this please ?

Related

How do you run a federated query in Google BigQuery using the Google.Apis.Bigquery.v2 and C#?

I have a working .netcore console app written in C# that can run pretty much every example shown here: Google .Net client library
For example, this code runs perfectly fine:
BigQueryClient client = BigQueryClient.Create(projectId);
string sql = "SELECT * FROM projectid.datasetname.tablename";
BigQueryParameter[] parameters = null;
BigQueryResults results = client.ExecuteQuery(sql, parameters);
foreach (BigQueryRow row in results)
{
Console.WriteLine($"{row["colname1"]}: {row["colname2"]}");
}
However, if I try to run a federated query as shown below, the API complains about the single quote right after "EXTERNAL_QUERY(". This code does not work:
BigQueryClient client = BigQueryClient.Create(projectId);
string sql = "SELECT * FROM EXTERNAL_QUERY('connection-id', 'SELECT * FROM schema.tablename;');";
BigQueryParameter[] parameters = null;
BigQueryResults results = client.ExecuteQuery(sql, parameters);
foreach (BigQueryRow row in results)
{
Console.WriteLine($"{row["colname1"]}: {row["colname2"]}");
}
I've tried using escaped double quotes as well.
Does anyone know how to send this type of request?
Google's documentation includes examples which you can view here: Google API .Net Client Library
However, the documentation does not cover how to run federated queries, so I'm stumped.
A few clarification points for anyone else who needs them:
I am using a real connection id; I've replaced the real information with placeholders in the example code I provided.
I have no trouble running the federated query exactly as I've shown it here (with triplets, or double quotes) inside BigQuery. That tells me there's nothing wrong with the query syntax itself
The problem only occurs when I try running the exact same federated query inside my c# app. The specific exception I get is: Google.GoogleApiException (The service bigquery has thrown an exception. HttpStatusCode is BadRequest. Encountered "" at line 1, column 30.) --- You can see it's basically complaining about the single, double, or tipple quotation mark right before the connection-id.

Excute powershell SCVMM cmdlets from Asp.Net Web API

I'm developing a Web Api in Asp.Net. I need that the web API comunicates with SCVMM, using .Net Framework.
We all know that SCVMM does not provide an API o interface similar to execute functions from c# code, but we have the option to run commands from PowerShell.
The situation is as follows:
From PowrShell prompt I can comunicate without any problem with SCVMM
From c# code using Cake.Pworsehl Nuget Package I can execute cmdlets with SCVMM commands
and comunicate with SCVNMM without problems.
Using the functions that I've wrote before, I've created a Dll with all the
functionality that I need, I have also added a TestProject for that dll and all works
fine.
The problem is that when I call the same functions from the WebApi project using
debugmode in VS 2022 I have the following error:
System.Management.Automation.CmdletInvocationException: 'You do not have access to the management server VMM NO_PARAM. (Error Id: 1604)
The weird thing is that, as I said before, I can run all funcitons from PowerShell prompt, and execute all the code from TestProjects and even a console application, but if I call the same functions form web api, I get that error.
I'm thinking that the problemas has to be realted with de Identity or something similar, but I can not found any way to specify credentials for run powershell cmdlets form c# code.
This is the function that gives me the error:
public List<Vm> GetVMsBase()
{
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;
initialSessionState.ImportPSModule(new string[] { "virtualmachinemanager" });
using (var myRunSpace = RunspaceFactory.CreateRunspace(initialSessionState))
{
myRunSpace.Open();
using (var pipeLine = myRunSpace.CreatePipeline())
{
Command cmd = new Command("Get-SCVirtualMachine");
cmd.Parameters.Add("VMMServer", "vmmserver.domain.com");
pipeLine.Commands.Add(cmd);
return pipeLine.Invoke().Select(vm =>
new Vm
{
Name = vm.Properties["name"].Value.ToString(),
Owner = ((string[])vm.Properties["CustomProperties"].Value)[1],
ExpirationDate = DateTime.TryParse(
((string[])vm.Properties["CustomProperties"].Value)[0], new CultureInfo("es-ES"), DateTimeStyles.None, out DateTime dt) ?
dt : new DateTime(1800, 1, 1),
CreationDate = DateTime.TryParse(
vm.Properties["CreationTime"].Value.ToString(), new CultureInfo("es-ES"), DateTimeStyles.None, out DateTime dt2) ?
dt2 : new DateTime(1800, 1, 1),
Hlnumber = ((string[])vm.Properties["CustomProperties"].Value)[2],
State = Enum.TryParse(vm.Properties["VirtualMachineState"].Value.ToString(), out VirtualMachineState vmState) ? vmState : VirtualMachineState.Unknow
}).ToList();
if (pipeLine.Error != null && pipeLine.Error.Count > 0)
{
//check error
}
}
}
Is there any way to call or run this code from web api?
thanks for your attention.
finaly I'v solved this problem, there was nothing wrong with the code to run powershell cmdlets, the problem was with the configuration of IIS expres (in visual studio) and when deploy the api in IIS 10.
In both cases I have to setup de configuration in a way that Anonymous logon was disabled and the only Authettication method used was "Windows", and that's it.
In IIS express you have to edit the .config file located in the .vs directory of the solution, and in IIS 10 you have to edit your site setting in the Authetication Options.

Linq expression fails in query parser under bizarre conditions

I've been unable to figure this error out for some time now and am hoping that someone can provide some insight. First, I'll explain the conditions and next I'll describe the conditions under which the error does/doesn't occur.
I have a web api, it has two endpoints /api/getData1 and /api/getData2
I have a web client that makes requests to /api/getData1
I have another application that makes requests to api/getData2
The web api controllers for getData1 and getData2 both end up making a service call to dataService.getData(DateTime date)
dataService.getData(DateTime date) calls StaticFilterClass.buildFilter(DateTime date)
StaticFilterClass.buildFilter(DateTime date)
AlarmFilter filter = null;
var paramExpr = Expression.Parameter(typeof(Alarm), "a");
var fieldRef = Expression.Property(paramExpr, "UtcEnd");
var binaryExpression = Expression.And(
Expression.GreaterThanOrEqual(fieldRef, Expression.Constant(earliestEnd.Date.Add(new TimeSpan(0, 0, 0)).ToUniversalTime(), typeof(DateTime))),
Expression.LessThanOrEqual(fieldRef, Expression.Constant(latestEnd.Date.Add(new TimeSpan(23, 59, 59)).ToUniversalTime(), typeof(DateTime))));
filter = (AlarmFilter)Expression.Lambda(binaryExpression, paramExpr);
dataService.getData(DateTime date), after getting the filter
dbAlarms = tenantDb.Alarms.Where(completeFilter)?.ToList() ?? dbAlarms;
The line above conditionally throws
"The query view generated for the EntitySet 'Alarms' is not valid. The query parser threw the following error : The argument type 'Edm.String' is not compatible with the property 'UtcEnd' of formal type 'Edm.DateTime'. Near member access expression, line 3, column 77.."}
Now, the conditions under which this line throws an error is what has me puzzled.
When the web api is started, if my web client goes to /api/getData1, there is no error. Subsequent calls from the web client to /api/getData1 succeed and subsequent calls from the other application to /api/getData2 succeed.
When the web api is started, if my other application goes to /api/getData2 first, the error above is generated. Subsequent calls from the application to /api/getData2 and subsequent calls from the web client to /api/getData1 throw the error above.
Can anyone help to point me in the right direction?
Edit:
It seemed to have something to do with the load order of the database project .dll (referenced by the client app and the api). I moved a couple of db transactions from the client application (where it accessed the db directly) into the web api so that the api would be the first thing to hit the database, and because it made more sense anyway. Still not sure of the root cause, but this resolves the issue.
I can think only 2 think:
1) You need to specify a where return object like below:
bAlarms = tenantDb.Alarms.Where<MyReturnObject>(completeFilter)?.ToList<MyReturnObject>() ?? dbAlarms;
2) Inside "alarms" there is a static class/function that will be accessed at the same time by getData1 and Getdata2.

C# create site in IIS programatically in asp.net project

I am trying to create a site in IIS using Microsoft.Web.Administration dll in C#. I am using following code
using (var serverManager = new ServerManager())
{
ApplicationPool pool = serverManager.ApplicationPools.Add(ClientDomain);
pool.ManagedRuntimeVersion = "v4.0";
Site site = serverManager.Sites.Add(SiteName, httpProtocol, httpBindingInformation, physicalPath);
site.Bindings.Add(httpsBindingInformation, httpsProtocol);
serverManager.CommitChanges();
}
I am getting following exception "The method or operation is not implemented" when I run the code from asp.net project but if same code is run from console project, it works fine. Here is the details of the exception
at Microsoft.Web.Administration.Interop.IAppHostProperty.get_Value()
at Microsoft.Web.Administration.ConfigurationElement.GetPropertyValue(IAppHostProperty property)
at Microsoft.Web.Administration.ConfigurationElement.GetAttributeValue(String attributeName)
at Microsoft.Web.Administration.Binding.get_CertificateHash()
at Microsoft.Web.Administration.BindingCollection.Add(Binding binding)
at Microsoft.Web.Administration.BindingCollection.Add(String bindingInformation, String bindingProtocol)
at TestProject.BLL.CRMSiteManagement.CRMSiteIISSetup.Process() in e:\CRMSiteManagement\CRMSiteIISSetup.cs:line 35
at TestProject.BLL.CRMSiteManagement.CRMSiteService.CreateNewCRMSite(CRMSite newSite) in e:CRMSiteManagement\CRMSiteService.cs:line
Seems like an issue with rights but I have not idea how to fix it.
Update 1:
Error is coming on following line of code on localhost
site.Bindings.Add(httpsBindingInformation, httpsProtocol);
I think you're trying to set the same bindings twice :
Once by calling the Add method
Site site = serverManager.Sites.Add(SiteName, httpProtocol, httpBindingInformation, physicalPath);
Then you add again the same binding:
site.Bindings.Add(httpsBindingInformation, httpsProtocol);

Error saving Entity dynamics crm 2011

I have an error that I can not repair.
Im developing an application that takes a guid as a parameter and "clone" that entity in another. (I know I can do this through javascript, the problem is the CRM server don't have the required rollup and I can't update it).
The projects works fine when I'm debugging in my computer, but when I deploy it to production server it just crash. My first guess was that it was an authentication problem, but I modified the authentication rules in IIS and impersonate any windows user that use the app with mine but didn't worked anyway.
The error it throws is: -2146233088 System.Collections.ListDictionaryInternal An error occured while processing this request. at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options) at Ambiente.DataAccess.Entities.CRMOrdenDeCompra.CreateOrdenDeCompra(Guid guidSolicitudDeCompra) in c:\Wip\Projects\Dev\CRMINTEGRATION\CRMINTEGRATION.DataAccess\Entities\CRMOrdenDeCompra.cs:line 42 at CRMINTEGRATION.WebApp.Controllers.RequestController.CreateOrdenDeCompra(String guid) in c:\Wip\Projects\Dev\CRMINTEGRATION\CRMINTEGRATION.WebApp\Controllers\RequestController.cs:line 22
The code that insert the entity:
var solicituddecompraContext = new CRMSolicitudDeCompra();
var solicituddecompra = new new_solicituddecompra();
solicituddecompra = context.new_solicituddecompraSet.FirstOrDefault(q => q.new_solicituddecompraId == parameterGuid);
new_ordendecompra ordendecompra = new new_ordendecompra();
ordendecompra.new_ordendecompraId = Guid.NewGuid();
ordendecompra.new_name = string.Format(solicituddecompra.new_name + " ({0})", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
ordendecompra.new_FechaRequirida = solicituddecompra.new_Fecharequerida;
ordendecompra.new_Tipodesolicitud = solicituddecompra.new_Tipodesolicitud;
ordendecompra.new_Observaciones = solicituddecompra.new_observaciones;
ordendecompra.new_Numerodesolicitud = solicituddecompra.new_SolicitudNo;
var detallerequisicion = CRMDetalleRequisicion.getDetalleRequisicion(context, guidSolicitudDeCompra);
context.AddObject(ordendecompra);
context.SaveChanges();
I generated the XRM class of CRM with the crmsvcutil.exe. So the name of the classes you see in the code are actually the name of the entities in CRM. All of the above works fine until it reaches the method entidad.SaveChanges().
Ps. As you can see in the code, english is not my native language. Feel free to correct me if I make any mistake. I will apreciate that :).

Categories