I'm trying to create a very simple C# program for insert the data.
Here is the service file :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DataAccess;
using DataAccess.UoW;
using Model;
namespace ClassLibrary1
{
public class Service
{
private readonly Unit _uow;
public Service()
{
_uow = new Unit();
}
public bool CreateEmp(Mdl insertEntity)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Mdl, Table_1>();
});
IMapper mapper = config.CreateMapper();
var Empinsert = mapper.Map<Mdl, Table_1>(insertEntity);
_uow.Register.Insert(Empinsert);
_uow.Save(); //this line shows error
return false;
}
}
}
Unit of Work:
using DataAccess.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.UoW
{
public class Unit
{
private guruEntities _context = null;
private Repository<Table_1> _register;
public Unit()
{
_context = new guruEntities();
}
public Repository<Table_1> Register
{
get
{
if (this._register == null)
this._register = new Repository<Table_1>(_context);
return _register;
}
}
}
}
And this is the error I get :
C# 'Unit' does not contain a definition for 'Save' and no accessible extension method 'Save' accepting a first argument of type 'Unit' could be found (are you missing a using directive or an assembly reference?)
You have to add save method in your Unit Class like this
public void Save()
{
context.SaveChanges();
}
for better understand you can refer Unitofwork class from below link
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Related
I Would like to know how can i test my plugin in local?
To help me I using this link Write Unit Test for your Dataverse Plugins
In my case have some dependeces that main project plugin
The unit test:
namespace CRM.CLIENTE.Plugin.Test
{
[TestClass]
public class UnitTest1
{
[TestMethod]
[Description("Teste Template ")]
[Owner("Alexandre")]
public void TestMethod1()
{
Guid id = Guid.NewGuid();
// init
XrmFakedContext fakecontext = new XrmFakedContext();
XrmFakedPluginExecutionContext pluginContext = fakecontext.GetDefaultPluginContext();
XrmFakedTracingService iTracing = new XrmFakedTracingService();
//Prepare
Entity target = new Entity("Contact") { Id = id };
target.Attributes.Add("telephone1","90381290381 8876");
Entity postimage = new Entity("Contact") { Id = id };
postimage.Attributes.Add("telephone1", "90381290381 88763232");
ParameterCollection inputParameter = new ParameterCollection();
inputParameter.Add("Target", target);
EntityImageCollection postImages = new EntityImageCollection();
postImages.Add("PostImage", postimage);
pluginContext.InputParameters = inputParameter;
pluginContext.PostEntityImages = postImages;
fakecontext.Initialize(new List<Entity>() { postimage });
//Execute
fakecontext.ExecutePluginWith<PreOperationFormatPhoneCreateUpdate>(pluginContext);
//Assert
Entity teste = fakecontext.CreateQuery("Contact").FirstOrDefault();
Assert.Equals("903812903818876", teste["telephone1"]);
iTracing.Trace("Tested Trace in Account Create");
}
}
}
The main class of plugin
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using System.Text.RegularExpressions;
using CRM.CLIENTE.Plugin.Comum;
using CRM.CLIENTE.Plugin.Repository.Repository;
using CRM.CLIENTE.Plugin.Repository.Repository.Interface;
namespace CRM.CLIENTE.Plugin.Service
{
public class PreOperationFormatPhoneCreateUpdate : BasePlugin
{
protected override void ExecuteCrmPlugin(IPluginExecutionContext context, IOrganizationService service)
{
IContactRepository _contactRepository = new ContactRepository();
_contactRepository.formatarTelefone(context);
}
}
}
the base of plugin
namespace CRM.CLIENTE.Plugin.Comum
{
public abstract class BasePlugin : IPlugin
{
public IPluginExecutionContext localContext { get; set; }
public IOrganizationService OrganizationService { get; private set; }
public void Execute(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new InvalidPluginExecutionException("serviceProvider");
}
try
{
localContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (!localContext.InputParameters.ContainsKey("Target"))
throw new InvalidPluginExecutionException("No target found");
IOrganizationService service = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(null);
ExecuteCrmPlugin(localContext, service);
}
catch (InvalidPluginExecutionException e)
{
throw (e);
}
}
protected virtual void ExecuteCrmPlugin(IPluginExecutionContext localcontext, IOrganizationService service)
{
// Implementar o código do Plugin no proprio Plugin
}
}
}
The Repository Project
using CRM.CLIENTE.Plugin.Domain.Domain;
using CRM.CLIENTE.Plugin.Factory.Factory;
using CRM.CLIENTE.Plugin.Repository.Comum;
using CRM.CLIENTE.Plugin.Repository.Repository.Interface;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CRM.CLIENTE.Plugin.Repository.Repository
{
public class ContactRepository : IContactRepository
{
public Entity formatarTelefone(IPluginExecutionContext context)
{
Entity entity2 = context.InputParameters["Target"] as Entity;
Contact contato = new ContactFactory().d365ToObject(entity2);
contato.TelefoneComercial = Regex.Replace(contato.TelefoneComercial, #"[^\d]", "");
return new ContactFactory().objectToD365(contato);
}
}
}
The struture of my solution
Image Struture 1
Image Struture 1.1
Dependences main plugin
Image of error
Translate error
System.IO.FileLoadException: 'Could not load file or assembly 'CRM.CLIENTE.Plugin.Repository, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strong-named assembly is required. (Exception from HRESULT: 0x80131044)'
SO someone help me about this problem ?
I want use unit test to validate my plugin in local
Your plugin library is signed, because this is what is required by Dataverse.
As a consequence the projects your plugin project references must also be signed and this is also true for your test project.
Best practice is sharing one snk file and reference it from your projects. A quick fix is adding this snippet to the csproj files:
<PropertyGroup>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\CompanyKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
I have a weird error in Redis on .Net 6. When I run the test code here:
https://github.com/redis-developer/redis-graph-dotnet-basic-app/blob/main/Program.cs
It works perfectly fine. In this case the code is running in the program.cs file.
When I port that code to a class, in order to better manage encapsulation and complexity. It does not work. What it does is run the code and when it gets to the: await graph.QueryAsync part, it just stops the debugger. Very strange indeed.
Here is the code I am using. Any thoughts or suggestions:
//Program.cs (Relevant Bits)
using RedisTest //PROGRAM //WRITE TO REDIS ENTERPRISE CLOUD Process_LoadGraph process_LoadGraph = new Process_LoadGraph(); process_LoadGraph.Controller(results);
//SHARED CONNECTION CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace RedisTest
{
public class RedisSharedConnection
{
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(ConfigData.dbConnectionString);
return connectionMultiplexer;
});
}
}
//USAGE CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NRedisGraph;
namespace RedisTest
{
public class Process_LoadGraph
{
public async void Controller(List<Result> results)
{
//Setup
var redisConnection = RedisSharedConnection.Connection;
//var redisConnection = ConnectionMultiplexer.Connect(ConfigData.dbConnectionString);
var db = redisConnection.GetDatabase(ConfigData.dbId);
var graph = new RedisGraph(db);
string graphName = ConfigData.graphName;
//Test Transaction
// Create Bob
// CRASHES HERE
var createBobResult = await graph.QueryAsync("pets", "MERGE(:human{name:'Bob',age:32})");
}
}
}
Turns out the solution is to use Redis in a static class. Along the following lines:
internal static class WriteToDB
{
public static async Task WriteAsync(List<string> querieS)
{
//Load Graph
//Setup
var redisConnection = RedisSharedConnection.Connection;
//var redisConnection = ConnectionMultiplexer.Connect(ConfigData.dbConnectionString);
var db = redisConnection.GetDatabase(ConfigData.dbId);
var graph = new RedisGraph(db);
string graphName = ConfigData.graphName;
// ** DEBUG
//Test Transaction
// Create Bob
var createBobResult = await graph.QueryAsync("pets", "MERGE(:human{name:'Bob',age:32})");
{ }
//Clear Graph
await graph.QueryAsync(graphName, "MATCH(n) DETACH DELETE n");
{ }
}
}
Have spent way too much time trying to figure this out. Thanks for any help. .Net Core 3.1 trying to register a service in Startup.cs
Error CS0311: The type 'Apex.UI.MVC.ProjectService' cannot be used as type parameter 'TImplementation' in the generic type or method ServiceCollectionServiceExtensions.AddScoped<TService, TImplementation>(IServiceCollection). There is no implicit reference conversion from 'Apex.UI.MVC.ProjectService' to 'Apex.EF.Data.IProjects'. (CS0311) (Apex.UI.MVC)
services.AddScoped<IProjects, ProjectService>();
using System;
using Apex.EF.Data;
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Linq;
using Apex.UI.MVC.Models.Projects;
namespace Apex.UI.MVC.Controllers
{
public class ProjectController : Controller
{
private IProjects _projects;
public ProjectController(IProjects projects)
{
_projects = projects;
}
public IActionResult Index()
{
var projectModels = _projects.GetAll();
var listingResult = projectModels
.Select(result => new ProjectIndexListingModel
{
Id = result.Id,
ProjectName = result.ProjectName,
ProjectImage = result.ProjectImage
});
var model = new ProjectIndexModel()
{
Project = listingResult
};
return View(model);
}
}
}
using System;
using System.Collections.Generic;
using Apex.EF.Data;
using Apex.EF.Data.Models;
namespace Apex.EF.Data
{
public interface IProjects
{
IEnumerable<Project> GetAll();
Project GetById(int id);
void Add(Project newProject);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Apex.EF.Data;
using Apex.EF.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace ApexServices
{
public class ProjectService : IProjects
{
private ApexContext _context;
public ProjectService(ApexContext context)
{
_context = context;
}
public void Add(Project newProject)
{
_context.Add(newProject);
_context.SaveChanges();
}
public IEnumerable<Project> GetAll()
{
return _context.Projects
.Include(project => project.Status.IsInShop == true);
}
public Project GetById(int id)
{
return _context.Projects
.Include(project => project.Status.IsInShop==true)
.FirstOrDefault(project => project.Id == id);
}
}
}
The namespaces shown in the exception are different to the example code shown. There are probably conflicting types in the project (not shown).
If that is really the case, then include the full namespace when registering the type with the container to avoid conflicts.
Based on the shown code, that would be
services.AddScoped<IProjects, ApexServices.ProjectService>();
I am an experienced programmer but relatively new to c# mvc. I am attempting to create my first viewmodel to combine two models into one so a view can access members from both. I have followed instructions on combining distinct models into one view model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ViApplication.Models;
using System.ComponentModel.DataAnnotations;
namespace ViApplication.ViewModel
{
public class TemplateMTMQuestionViewModel
{
public TemplateVISpdat ThisTemplate { get; set; }
public MtmTemplateViSpdatQuestion ThisMTMQuestion { get; set; }
}
}
I have created a controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViApplication.ViewModel;
using ViApplication.Models;
using System.Net;
namespace ViApplication.Controllers
{
public class TemplatesMTMQuestions : Controller
{
private VulnerabilityIndexDatabaseEntities db = new VulnerabilityIndexDatabaseEntities();
public ActionResult AddQuestionToTemplate(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TemplateVISpdat templateVISpdat = GetTemplateByID(id);
if (templateVISpdat == null)
{
return HttpNotFound();
}
TemplateMTMQuestionViewModel TMTMQVM = new TemplateMTMQuestionViewModel();
TMTMQVM.ThisTemplate = GetTemplateByID(id);
TMTMQVM.ThisMTMQuestion = GetBlankMtmTemplateViSpdatQuestion();
return View(TMTMQVM);
}
public TemplateVISpdat GetTemplateByID(long? id)
{
TemplateVISpdat templateVISpdat = db.TemplateVISpdats.Find(id);
return templateVISpdat;
}
public MtmTemplateViSpdatQuestion GetBlankMtmTemplateViSpdatQuestion()
{
MtmTemplateViSpdatQuestion TMTMQVM = new MtmTemplateViSpdatQuestion();
return TMTMQVM;
}
}
}
This compiles fine. But when I try to create a view from AddQuestionToTemplate and select Empty and my ViewModel I get:
Unable to retrieve metadata for
ViApplication.ViewMdoel.TemplateMTMQuestionViewModel. One or more
validation errors were detected during model generation.
TemplateMTMQuestionViewModel::EntityType TemplateMTMQuestionViewModel
has no key defined
The only difference between this project and other projects is that I am using database first.
Any help would be greatly appreciated.
I have the following:
public class StripeController : Controller
{
private readonly UserService _userService;
public StripeController(UserService userService)
{
_userService = userService;
}
[HttpPost]
public ActionResult StripeWebook()
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
[HttpPost]
[Route("api/stripewebhook")]
public async Task<ActionResult> Index(CancellationToken ct)
{
var json = new StreamReader(Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
And requests from stripe generate an error:
The controller for path '/api/stripewebhook' was not found or does not implement IController
Any idea why this is happening when I test from the stripe portal?
Using WebApi 2 it works with no problem.
Here is the smallest WebApi controller to begin with:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
return Ok();
}
}
}
if you execute this from VS you can access it from http://localhost:(port)/api/stripewebhook
Now you only need to extend this to include the stripe code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return Ok();
}
}
}