elastic search setup in asp.net mvc - asp.net-mvc

I am working on an asp.net application where I have huge database. I want to implement elastic search. Here is what I have done in code:
var node = new Uri("http://localhost:9200/");
var setting = new ConnectionSettings(node);
setting.DefaultIndex("businessuser");
client = new ElasticClient(setting);
CanadaBusinessDBEntities db = new CanadaBusinessDBEntities();
client.DeleteIndex("businessuser", null);
var ListofBusiness = db.CanadaTables.ToList();
foreach (var Business in ListofBusiness)
{
var resutl = client.Index(Business, null);
}
This code is written in constructor which gets all records and then index them using elastic search. indexing is taking long time. I want to ask if this is correct way? I am new to elastic search. please suggest better way to do this.
Thanks.

You have to use ElasticsearchContext Class of Nest.
private readonly ElasticsearchContext _elasticsearchContext;
private const string ConnectionString = "http://localhost:9200";
private readonly IElasticsearchMappingResolver _elasticsearchMappingResolver;
_elasticsearchMappingResolver = new ElasticsearchMappingResolver();
_elasticsearchContext = new ElasticsearchContext(ConnectionString, new ElasticsearchSerializerConfiguration(_elasticsearchMappingResolver,true,true));
for Delete purpose you can use like that below
public void DeleteSkill(int Id)
{
_elasticsearchContext.DeleteDocument<Tag>(Id);
_elasticsearchContext.SaveChanges();
}

Related

How do I seed Users and Roles in MVC6

I've started in Visual Studio with a new project > ASP NET 5 > Web Application and then followed the initial tutorial here:
https://docs.asp.net/projects/mvc/en/latest/getting-started/first-mvc-app/index.html
One of the tasks I've been struggling with is seeding the database with Users, Roles, and then assigning the Roles to the Users.
This answer, or variations of it look fruitful:
https://stackoverflow.com/a/20521530/2591770
But this code:
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser {UserName = "founder"};
Results in an immediate error.
CS7036 There is no argument given that corresponds to the required formal parameter 'optionsAccessor' of 'UserManager.UserManager(IUserStore, IOptions, IPasswordHasher, IEnumerable>, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProvider, ILogger>, IHttpContextAccessor)'
Is this a change in the framework or is it likely I've omitted something elsewhere?
I can null the rest of the parameters but can't help feeling that I've missed something.
var userManager = new UserManager<ApplicationUser>(userStore,null,null,null,null,null,null,null,null,null);
This is how I did it.
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService<ApplicationDbContext>();
var userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();
and then in the Configure method of Startup.cs:
SeedData.Initialize(app.ApplicationServices);
Edit1:
var user0 = new ApplicationUser { UserName = "bob", Email = "bob#asd.com" };
var result = userManager.CreateAsync(user0, "Password1!").Result;

ASP.NET MVC + Dynamics NAV odata web services - how do I access related models?

I'm building an asp.net mvc application using Dynamics NAV Odata web services. Evertyhing is working fine and I created a controller for Service Orders using Linq queries. Then I got to the next step: accessing related models, and I'm stuck.
Lets take an example using page 5900 - Service Order and page 5903 - Service Item Lines:
Getting Service Orders or any other single model works great:
var query = from c in nav.ServiceOrder
select c;
But accessing related data fails:
var query = nav.ServiceOrder
.Expand(x => x.ServiceOrderServItemLines)
.Where(x => x.No == "SO000008");
I can access ServiceOrderServItemLines with the following url:
/DynamicsNAV71/OData/Company('the company')/ServiceOrder(Document_Type='Order',No='SO000008')/ServiceOrderServItemLines
But using expand does not seem to work.
Im not sure what the problem is. Are there no relations between the models?
If so, is there a way for me to add my own models with relations, and connect them to the odata service?
Or is it just a matter of expand not being supported in the service?
Any input would be much appreciated.
It seems that your serviceOrder has two keys. one is the Document_Type and one is the No. So please try
var query = nav.ServiceOrder
.Expand(x => x.ServiceOrderServItemLines)
.Where(x => x.Document_Type == "Order" && x.No == "SO000008");
If it doesn't solve your problem, Could you please provide the url sent by the expand query?
So after beating my head against this for some time I think I have an answer. I'll post my findings here, and hopefully it will save someone some trouble in the future.
Dynamics NAV (2013 R2) have relationships between header and list items as described here:
http://blogs.msdn.com/b/freddyk/archive/2009/05/28/handling-sales-orders-from-page-based-web-services-in-nav-2009sp1-and-rtm.aspx
In my case I want to create and access Service Item Lines for a Service Order.
Using SOAP to create Service Orders (Service Header table) and Service Item Lines can be done like this:
static void Main(string[] args)
{
ServiceOrder_Binding ctx = new ServiceOrder_Binding();
ctx.UseDefaultCredentials = true;
//Create a new Service Order
ServiceOrder so = NewSo(ctx);
//Add a couple of Service Item Lines to the Service Order
for (int i = 0; i < 5; i++)
NewSil(ctx, so.No);
}
private static ServiceOrder NewSo(ServiceOrder_Binding ctx)
{
ServiceOrder so = new ServiceOrder();
so.Customer_No = "50000";
so.Description = "New Service Order";
ctx.Create(ref so);
return so;
}
private static void NewSil(ServiceOrder_Binding ctx, string documentNo)
{
ServiceOrder so = ctx.Read(documentNo);
List<Service_Order_Line> SilList = so.ServItemLines.ToList();
Service_Order_Line Sil = new Service_Order_Line();
Sil.ServiceItemNo = "20";
Sil.Description = "New Service Item Line";
SilList.Add(Sil);
so.ServItemLines = SilList.ToArray();
ctx.Update(ref so);
}
Using Odata to read Service Orders (Service Header table) and Service Item Lines can be done like this:
static void Main(string[] args)
{
NAV ctx = new NAV(new Uri("http://localhost:7048/DynamicsNAV71/OData/Company('CRONUS Sverige AB')"));
ctx.UseDefaultCredentials = true;
//Eager loading - DOES NOT WORK!
var so = from s in ctx.ServiceOrder.Expand("ServiceOrderServItemLines")
where s.No == "SO000016"
select s;
//Lazy loading - WORKS!
var so2 = from s in ctx.ServiceOrder
where s.No == "SO000016"
select s;
ctx.LoadProperty(so2.First(), "ServiceOrderServItemLines");
}
Notice that lazy loading works, but eager loading doesn't.
For other related data, like Service Items for Service Item Lines, there doesn't seem to be any relationships. I will return with an update if I find something else, but what I ended up doing for now is passing related items in the ViewBag like this:
In the Controller Action:
var service_items = from s in ctx.ServiceItemList
where s.Customer_No.Equals(customerNo)
select s;
var serviceItemList = service_items.ToList();
ViewBag.serviceItemList = new SelectList(serviceItemList, "No", "Description");
In the View:
#Html.DropDownListFor(model => model.Service_Item_No, (IEnumerable<SelectListItem>)ViewBag.serviceItemList)
Hope this helps someone who like me is new to working with Dynamics NAV and Web Services :).

EF Code First to create multiple databases dynamically

Is it possible to generate different databases according to a specific parameter?
My final goal is john.domain.com => create john db, paul.domain.com => create paul db
How could I achieve this using EF6 code first, MVC5? Could model first do it?
Yes you can change the connection string at runtime, something like.
Need to add reference to System.Data.
public static class ConnectionStringExtension
{
public static void ChangeDatabaseTo(this DbContext db, string newDatabaseName)
{
var conStr = db.Database.Connection.ConnectionString;
var pattern = "Initial Catalog *= *([^;]*) *";
var newConStr = Regex.Replace(conStr, pattern, m =>
{
return m.Groups.Count == 2
? string.Format("Initial Catalog={0}", newDatabaseName)
: m.ToString();
});
db.Database.Connection.ConnectionString = newConStr;
}
}
Usage.
using (var db = new AppContext())
{
// Uses it just before any other execution.
db.ChangeDatabaseTo("MyNewDatabase");
}

Configure Mvc Mini Profiler with Linq DataCotext

I'm using linq-to-sql datacontext for an application.
I have the following class
UserDataContext which I instantiate the table with
var db = new UserDataContext();
How do I make Mvc Mini Profiler insert into that?
I tried to extend UserDataContext with the following partial found at another answer, but the code is never hit.
partial class UserDataContext
{
public static UserDataContext Get()
{
var sqlConnection = new HelpSaudeAPDataContext().Connection;
var profiledConnection = new MvcMiniProfiler.Data.ProfiledDbConnection(new SqlConnection("UserConnectionString"), MiniProfiler.Current);
return new HelpSaudeAPDataContext(profiledConnection);
}
}
Unfortunately there is no single point repository with the var db connection where I could simply pass the mvc mini profiler connection with.
var db = UserDataContext(profilerConnection);
but the code is never hit.
Well, hit it:
var db = UserDataContext.Get();

ASP.NET MVC Unit Testing - Sessions

Having searched StackOverflow, and Google I think what I'm doing is suppose to be right, however results don't seem to be going well
[TestMethod]
public void LoginAction_Should_Return_View_and_User_Authenticated()
{
// Arrange
var mock = new Mock<ControllerContext>();
var mockSession = new Mock<HttpSessionStateBase>();
mock.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);
var testData = FakeUserData.CreateTestUsers();
var repository = new FakeUserRepository(testData);
var controller = new AccountController(repository);
controller.ControllerContext = mock.Object;
// Act
var result = controller.Login("testuser1", "testuser1");
// Assert
Assert.AreEqual("testuser1", controller.HttpContext.Session["Username"]);
Assert.IsTrue((bool)controller.HttpContext.Session["IsAuthenticated"]);
Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
}
When I run the test the value of controller.HttpContext.Session["Username"] is null, however I set the value to the username using a Session helper. Am I doing something completely wrong, or something else? Any help would be greatly appreciated.
Use Mock.Verify to check if underlying code tried to set Session["Username"].
If your code needs to set session variable and use it - take a look here.
Quickstart is priceless too.

Resources