'newwcf.Client' does not contain a definition for 'Where' - asp.net

hi i have the following code:
but i m getting an error
'newwcf.Client' does not contain a definition for 'Where'
please help..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
namespace newwcf
{
public class myservice : Imyservice
{
public List<ClientDetails> getClient()
{
List<ClientDetails> client = new List<ClientDetails>();
var sql = Client.Where(cn => cn.ClientName).ToList(); //getting the error here
return sql;
}
}
}

c# is case sensitive...should you try
var sql = client.Where(cn => cn.ClientName).ToList();

Related

Dotnet core integration test fixture causing a json parsing error

So I am building a template API project and am currently working on adding in some integration tests.
At the moment, when I run my test, for some reason it returns a JSON parsing error:
Newtonsoft.Json.JsonReaderException : Unexpected character encountered
while parsing value: A. Path '', line 0, position 0.
This looks like it's an issue with my endpoint, but it works fine when just running localhost with a normal startup routine, so I think it's because I can't get my fixture just right. especilaly because, when i try another fixture (listed below) it doesn't give me an error anymore and just hangs.
The test itself can be found here.
namespace Foundation.Api.Tests.IntegrationTests
{
using FluentAssertions;
using Foundation.Api.Data;
using Foundation.Api.Models;
using Foundation.Api.Tests.Fakes;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
public class GetValueToReplaceIntegrationTests : IClassFixture<CustomWebApplicationFactory<Startup>>
{
public GetValueToReplaceIntegrationTests(CustomWebApplicationFactory<Startup> factory)
{
_factory = factory;
}
private readonly CustomWebApplicationFactory<Startup> _factory;
[Fact]
public async Task GetValueToReplaces_ReturnsSuccessCodeAndResourceWithAccurateFields()
{
var fakeValueToReplaceOne = new FakeValueToReplace { }.Generate();
var fakeValueToReplaceTwo = new FakeValueToReplace { }.Generate();
var appFactory = _factory;
using (var scope = appFactory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ValueToReplaceDbContext>();
context.Database.EnsureCreated();
context.ValueToReplaces.RemoveRange(context.ValueToReplaces);
context.ValueToReplaces.AddRange(fakeValueToReplaceOne, fakeValueToReplaceTwo);
context.SaveChanges();
}
var client = appFactory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var result = await client.GetAsync($"api/v1/ValueToReplaceLowers")
.ConfigureAwait(false);
var responseContent = await result.Content.ReadAsStringAsync()
.ConfigureAwait(false);
var response = JsonConvert.DeserializeObject<IEnumerable<ValueToReplaceDto>>(responseContent);
// Assert
result.StatusCode.Should().Be(200);
response.Should().ContainEquivalentOf(fakeValueToReplaceOne);
response.Should().ContainEquivalentOf(fakeValueToReplaceTwo);
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
The fixture can be found here.
namespace Foundation.Api.Tests
{
using Foundation.Api.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.ConfigureServices(services =>
{
// Remove the app's ValueToReplaceDbContext registration.
var descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<ValueToReplaceDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// Add ValueToReplaceDbContext using an in-memory database for testing.
services.AddDbContext<ValueToReplaceDbContext>(options =>
{
options.UseInMemoryDatabase("TestingDb");
});
// Build the service provider.
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
// context (ValueToReplaceDbContext).
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<ValueToReplaceDbContext>();
// Ensure the database is created.
db.Database.EnsureCreated();
try
{
db.RemoveRange(db.ValueToReplaces);
// Seed the database with test data.
//Utilities.InitializeDbForTests(db);
}
catch (Exception ex)
{
}
}
});
}
}
}
I've also tried a fixture like so inspired by this one which just times out.
namespace Foundation.Api.Tests
{
using Foundation.Api.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.ConfigureServices(services =>
{
// Create a new service provider.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
// Add a database context using an in-memory
// database for testing.
services.AddDbContext<ValueToReplaceDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
options.UseInternalServiceProvider(serviceProvider);
});
services.AddScoped(provider => provider.GetService<ValueToReplaceDbContext>());
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
using var scope = sp.CreateScope();
var scopedServices = scope.ServiceProvider;
var context = scopedServices.GetRequiredService<ValueToReplaceDbContext>();
// Ensure the database is created.
context.Database.EnsureCreated();
try
{
// Seed the database with test data.
//Utilities.InitializeDbForTests(context);
}
catch (Exception ex)
{
//logger.LogError(ex, "An error occurred seeding the " +
// $"database with test messages. Error: {ex.Message}");
}
})
.UseEnvironment("Test");
}
}
}
The repo can be found here.

The type or namespace name 'Func<,>' could not be found (are you missing a using directive or an assembly reference?

Below is the sample I found from online Tutorial to host the website suing OWIN, however when I try to run on my machine, I got this error
CS0246 The type or namespace name 'Func<,>' could not be found (are you missing a using directive or an assembly reference?)
I think for using 'Func<,>' I have using System, and for IDictionary, I have using System.Collections.Generic; so I don't understand why it still can't work.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using AppFunc = Func<IDictionary<string, object>, Task>;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var middleware = new Func<AppFunc, AppFunc>(MyMiddleWare);
app.Use(middleware);
app.Use<OtherMiddleware>();
}
public AppFunc MyMiddleWare(AppFunc next)
{
AppFunc appFunc = async (IDictionary<string, object> environment) =>
{
var response = environment["owin.ResponseBody"] as Stream;
byte[] str = Encoding.UTF8.GetBytes("My First Middleware");
await response.WriteAsync(str, 0, str.Length);
await next.Invoke(environment);
};
return appFunc;
}
public class OtherMiddleware : OwinMiddleware
{
public OtherMiddleware(OwinMiddleware next) : base(next) { }
public override async Task Invoke(IOwinContext context)
{
byte[] str = Encoding.UTF8.GetBytes(" Other middleware");
context.Response.Body.Write(str, 0, str.Length);
await this.Next.Invoke(context);
}
}
}
You need to put the AppFunc in the class so it can use the using,
Or you can use full namespace for Func, IDictionary and Task
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
// Use this
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
public class Startup
{
// Or this
using AppFunc = Func<IDictionary<string, object>, Task>;
...
}
For me it was low .NET Target Framework version 2.0 of application. Changed to 4.7 (it seems minimal is 3.5).
You need to make sure you added the reference System.Runtime.CompileServices to your project as you see in here: https://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx the delegate is part of mscorlib assembly.

The name 'AjaxControlToolkit' does not exist in the current context

This code is written in wcf Service1.svc.cs
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class enggcollegelist : ICRUD
{
public List<string> autobranches(string brname)
{ List<string> lstbranches = new List<string>();
connection = new SqlConnection(ConnectionString);
command = new SqlCommand("select branchname from tblenggbranchnames "+"where branchname LIKE '%'+#branches+'%' ",connection);
connection.Open();
command.Parameters.AddWithValue("#branches",brname);
resultReader = command.ExecuteReader();
while (resultReader.Read())
{
string items =AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(resultReader["branchname"].ToString());
lstbranches.Add(resultReader["branchname"].ToString());
}
connection.Close();
return lstbranches;
}
In above code "AjaxControlToolkit" is not accepting.
I have downloaded ajax toolkit and installed and also add reference in toolkit.
But same problem exits.

failed to initialize DTE object

I am following a code sample in this link.
I hit a snag right on the second line:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using EnvDTE;
namespace TwinCAT_Automation_Interface
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
//Creating TwinCAT Projects via templates (Recommended)
Type myType = System.Type .GetTypeFromProgID ("VisualStudio.DTE.12.0");
dynamic myDTE = System.Activator.CreateInstance (myType); //error right here
}
}
The error says:
Error 1 A field initializer cannot reference the non-static field,
method, or property 'TwinCAT_Automation_Interface.Main.myType'
What exactly am I doing wrong? It's the same code snippet; I just modify it a bit. Please help!!!!
OK, I got it fixed by changing it to the following:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using EnvDTE;
namespace TwinCAT_Automation_Interface
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
public void myMethod()
{
//Creating TwinCAT Projects via templates (Recommended)
Type myType = System.Type .GetTypeFromProgID ("VisualStudio.DTE.12.0");
dynamic myDTE = System.Activator.CreateInstance (myType); // dynamic linking for DTE-object
}
}
}
The explanation is in this link. It is a compiler error.
It is a compiler error. See question for link to the answer.

How can i using GetObjectByKey in mvc 5 using entity framword 6

I am using mvc 5 and ef 6 to build a project. I was simplify the retrieval code by adding some methods to partial class entity context. This is how i do it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Data.Entity.Core;
namespace MyShop.Models
{
public partial class DataEntities
{
public T GetById<T>(object id) where T : class
{
EntityKey key = CreateKey<T>(id);
return (T)GetObjectByKey(key);
}
private EntityKey CreateKey<T>(object id)
{
var type = typeof(T);
return new EntityKey("MyEntities." + "." + type.Name, "Id", id);
}
}
But it error at GetObjectByKey though i was add entityframwork 6.dll in my project, and i tried add some references but it don't work.
Can you help me fix the error.
Thanks you for read.
Phuong

Resources