Project doesn`t have access to referenced project in the c# solution - asp.net

I'm trying to access a method from a class which is in another project but in the same solution. The problem i face is that it keeps saying that i'm missing a reference even when i'm using the using namespace of the project.
This code is in project 2 and it is a controller. which is referenced to project 1
namespace WebSvc1.Controllers
{
public class RemunerationController : ApiController
{
[HttpPost]
public void BonusRecipient(BonusRecipients bonusRecipients)
{
XmlSerializer writer = new XmlSerializer(typeof(BonusRecipients));
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"//BonusReipients.xml";
FileStream file = File.Create(path);
writer.Serialize(file, bonusRecipients);
file.Dispose();
file.Close();
}
}
}
And this code is in project 1 which should call the method from the controller in project 2
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json;
using WebApp1.DataContracts;
using WebApp1.Models;
namespace WebApp1.Controllers
{
public class BonusController : Controller
{
// GET: Bonus
public ActionResult Index()
{
return View("View");
}
// POST: Bonus/Allocate
[HttpPost]
public async Task<ActionResult> Allocate(BonusViewModel bonusAllocation)
{
try
{
var employees = await GetEmployees();
List<Employee> recipients = new List<Employee>();
for (int i = 0; i < employees.Count; i++)
{
if (i % bonusAllocation.OneInXEmployees == 0)
{
var recipient = employees[i];
recipients.Add(recipient);
employees.Remove(recipient);
}
}
//BonusRecipient(recipients);
return RedirectToAction("Index", "Home");
}
catch
{
return View("View");
}
}
private async Task<List<Employee>> GetEmployees()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:57652/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await
client.GetAsync($"api/employee");
if (response.IsSuccessStatusCode)
{
string employeeData = await
response.Content.ReadAsStringAsync();
List<Employee> employees =
JsonConvert.DeserializeObject<List<Employee>>(employeeData);
return employees;
}
return new List<Employee>();
}
}
}

Related

Why ModelState is getting false as validation?

My ModelState is getting false everytime i run the code .This is simply a file upload mvc .net core code. Migration is also perfectly executed. However whenever i try to submit the form after uploading an image the form gets reset. Due to which it failed to get store in the database.
Model code (Image.cs)
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace FileUpload.Models
{
public class Image
{
[Key]
public int Iid { get; set; }
[Required]
public string Iname { get; set; }
[Required]
[NotMapped]
public IFormFile Iimg { get; set; }
}
}
Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using FileUpload.Data;
using FileUpload.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO;
namespace FileUpload.Controllers
{
public class ImagesController : Controller
{
private readonly AppDbContext _context;
private readonly IWebHostEnvironment _hostEnvironment;
public ImagesController(AppDbContext context, IWebHostEnvironment hostEnvironment)
{
_context = context;
_hostEnvironment = hostEnvironment;
}
// GET: Images
public async Task<IActionResult> Index()
{
return View(await _context.Images.ToListAsync());
}
// GET: Images/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var image = await _context.Images
.FirstOrDefaultAsync(m => m.Iid == id);
if (image == null)
{
return NotFound();
}
return View(image);
}
// GET: Images/Create
public IActionResult Create()
{
return View();
}
// POST: Images/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Image image)
{
if (ModelState.IsValid)
{
if(image.Iimg != null)
{
string wwwRootPath = _hostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(image.Iimg.FileName);
string ext = Path.GetExtension(image.Iimg.FileName);
image.Iname = fileName + DateTime.Now.ToString("yymmssfff") + ext;
string path = Path.Combine(wwwRootPath + "/Image/" + fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await image.Iimg.CopyToAsync(fileStream);
}
}
_context.Add(image);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(image);
}
}

Error with GetItemQueryIterator when using a custom CosmosSerializer

I'm trying to make use of System.Text.Json serialization for a project I'm working on. When I make use of a custom CosmosSerializer and call GetItemQueryIterator, the ToStream call is being sent a Microsoft.Azure.Cosmos.SqlQuerySpec that cannot be serialized. Here is a sample that should easily reproduce the problem. Any and all help is appreciated!
using Microsoft.Azure.Cosmos;
using System;
using System.IO;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace CosmosTestApp
{
class Program
{
const string endpoint = "<REPLACE>";
const string key = "<REPLACE>";
const string dbName = "test";
const string containerName = "items";
public static async Task Main(string[] args)
{
var options = new CosmosClientOptions()
{
Serializer = new CosmosJsonSerializer()
};
var client = new CosmosClient(endpoint, key, options);
var dbResponse = await client.CreateDatabaseIfNotExistsAsync(dbName);
var db = dbResponse.Database;
var containerDef = new ContainerProperties(containerName, "/id");
var containerResposne = await db.CreateContainerIfNotExistsAsync(containerDef);
var testContainer = containerResposne.Container;
var testDoc = new TestDoc();
var docResponse = await testContainer.CreateItemAsync(testDoc, new PartitionKey(testDoc.Id));
Console.WriteLine($"Created document {docResponse.Resource.Id}");
var query = testContainer.GetItemQueryIterator<TestDoc>("SELECT * FROM c");
while (query.HasMoreResults)
{
var doc = await query.ReadNextAsync();
foreach(var x in doc.Resource)
{
Console.WriteLine($"Retrieved document {x.Id}");
}
}
}
}
internal class CosmosJsonSerializer : CosmosSerializer
{
public override T FromStream<T>(Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
stream.Close();
var item = JsonSerializer.Parse<T>(memoryStream.ToArray());
return item;
}
}
//This errors on the SqlQuerySpec
public override Stream ToStream<T>(T input)
=> new MemoryStream(JsonSerializer.ToUtf8Bytes(input));
}
internal class TestDoc
{
[JsonPropertyName("id")]
public string Id { get; set; } = "1";
public string TestString { get; set; } = "testing CosmosJsonSerializer";
}
}
EDIT: Bug has been filed and confirmed here: https://github.com/Azure/azure-cosmos-dotnet-v3/issues/575

Use asyn method for synchronous Sqlite on createMethod

I'm using Xamarin, also my SQLite tables contain a large amount of data.
Because I want to avoid UIThread problems in OnCreate(), I need to perform database actions asynchronously.
I'm looking for guidance if I am handling this properly.
First method, which I found on the net:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.InventoryPreviewMain);
Thread thread = new Thread(() =>
{
SQLiteConnection db = new SQLiteConnection(dpPath);
var table = db.Query<InventoryPreviewClass>("select * from InventoryPreviewClass where CategoryID =" + Connection.CategoryID + "");
mItems = new List<InventoryPreviewClass>();
foreach (var item in table)
{
mItems.Add(new InventoryPreviewClass() { InventoryItemID = item.InventoryItemID, InventoryItemName = item.InventoryItemName, InventoryItemPrice = item.InventoryItemPrice });
}
MyListViewAdapterInventory adapter = new MyListViewAdapterInventory(this, Resource.Layout.InventoryPreview, mItems);
mlistview.Adapter = adapter;
});
thread.Start();
Second Method, using async
public async void StartTimer()
{
SQLiteConnection db = new SQLiteConnection(dpPath);
var table = db.Query<InventoryPreviewClass>("select * from InventoryPreviewClass where CategoryID =" + Connection.CategoryID + "");
mItems = new List<InventoryPreviewClass>();
foreach (var item in table)
{
mItems.Add(new InventoryPreviewClass() { InventoryItemID = item.InventoryItemID, InventoryItemName = item.InventoryItemName, InventoryItemPrice = item.InventoryItemPrice });
}
MyListViewAdapterInventory adapter = new MyListViewAdapterInventory(this, Resource.Layout.InventoryPreview, mItems);
mlistview.Adapter = adapter;
await Task.Delay(500);
}
Which of two examples are more safe for keeping alive UIthread? Is there any other solution for making this?What is more reccomended to do?
Answer
Use the Cross-platform SQLite Library made by #FrankKruger to create/access SQLite databases for Xamarin mobile apps.
This library has a built-in asynchronous connection, so you'll never need to worry about accessing the database from the UI Thread again!
Xamarin.Android Example
"Second Method"
public async Task StartTimer()
{
mItems = await InventoryPreviewClassDatabase.GetAllInventoryPreviewClassAsync();
MyListViewAdapterInventory adapter = new MyListViewAdapterInventory(this, Resource.Layout.InventoryPreview, mItems);
mlistview.Adapter = adapter;
}
BaseDatabase Class
using System;
using System.Threading.Tasks;
using SQLite;
namespace SampleApp
{
public abstract class BaseDatabase
{
#region Constant Fields
static readonly Lazy<SQLiteAsyncConnection> _databaseConnectionHolder = new Lazy<SQLiteAsyncConnection>(() => GetDatabaseConnection());
#endregion
#region Fields
static bool _isInitialized;
#endregion
#region Properties
static SQLiteAsyncConnection DatabaseConnection => _databaseConnectionHolder.Value;
#endregion
#region Methods
protected static async Task<SQLiteAsyncConnection> GetDatabaseConnectionAsync()
{
if (!_isInitialized)
await Initialize().ConfigureAwait(false);
return DatabaseConnection;
}
static async Task Initialize()
{
await DatabaseConnection.CreateTableAsync<InventoryPreviewClass>().ConfigureAwait(false);
_isInitialized = true;
}
SQLiteAsyncConnection GetDatabaseConnection()
{
var sqliteFilename = "YourDatabaseName.db3";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
return conn;
}
#endregion
}
}
Parent Database Class
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace SampleApp
{
public abstract class InventoryPreviewClassDatabase : BaseDatabase
{
#region Methods
public static async Task<IList<InventoryPreviewClass>> GetAllInventoryPreviewClassAsync()
{
var databaseConnection = await GetDatabaseConnectionAsync().ConfigureAwait(false);
return await databaseConnection.Table<InventoryPreviewClass>().ToListAsync().ConfigureAwait(false);
}
public static async Task<InventoryPreviewClass> GetInventoryPreviewClassByIDAsync(int id)
{
var databaseConnection = await GetDatabaseConnectionAsync().ConfigureAwait(false);
return await databaseConnection.Table<InventoryPreviewClass>().Where(x => x.ID.Equals(id)).FirstOrDefaultAsync().ConfigureAwait(false);
}
public static async Task<int> SaveInventoryPreviewClassAsync(InventoryPreviewClass inventoryPreview)
{
var databaseConnection = await GetDatabaseConnectionAsync().ConfigureAwait(false);
var isObjectInDatabase = await GetInventoryPreviewClassByIDAsync(inventoryPreview.ID).ConfigureAwait(false) != null;
if (isObjectInDatabase)
return await databaseConnection.UpdateAsync(inventoryPreview).ConfigureAwait(false);
return await databaseConnection.InsertAsync(inventoryPreview).ConfigureAwait(false);
}
public static async Task<int> DeleteItemAsync(OpportunityModel opportunity)
{
var databaseConnection = await GetDatabaseConnectionAsync().ConfigureAwait(false);
return await databaseConnection.DeleteAsync(opportunity).ConfigureAwait(false);
}
public static async Task<int> GetNumberOfRowsAsync()
{
var databaseConnection = await GetDatabaseConnectionAsync().ConfigureAwait(false);
return await databaseConnection.Table<InventoryPreviewClass>().CountAsync().ConfigureAwait(false);
}
#endregion
}
}
This code was inspired from this Xamarin.Forms sample app

Web Api with OData v4 throwing exception on $select

I'm using the latest version of WebApi and OData and everything is set up to work right. The only problem is when I try to use $select .
It throws the error bellow
Object of type 'System.Linq.EnumerableQuery`1[System.Web.OData.Query.Expressions.SelectExpandBinder+SelectAll`1[WebApplication1.Controllers.Person]]' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[WebApplication1.Controllers.Person]'.
I looked at the documentation and their suggestion is to use [Queryable] on top of the Get method in the controller or the in WebApiConfig to use config.EnableQuerySupport and neither of these are available options. I'm currently using [EnableQuery]
EDIT
OdataController:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.OData;
using System.Xml.Serialization;
namespace WebApplication1.Controllers
{
public class PeopleController : ODataController
{
// GET api/values
[EnableQuery]
public IQueryable<Person> Get()
{
return new Person[] { new Person()
{
Id = 1,
FirstName = "Testing",
LastName = "2"
}, new Person()
{
Id = 2,
FirstName = "TestTest",
LastName = "3"
} }.AsQueryable();
}
// GET api/values/5
public Person Get(int id)
{
return new Person()
{
Id = 3,
FirstName = "Test",
LastName = "1"
};
}
// POST api/values
public void Post([FromBody]Person value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]Person value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
public class Person
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
WebApiConfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Formatter;
using WebApplication1.Controllers;
namespace WebApplication1
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
var odataFormatters = ODataMediaTypeFormatters.Create();
config.Formatters.InsertRange(0, odataFormatters);
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("People");
config.AddODataQueryFilter();
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "api",
model: builder.GetEdmModel());
}
}
}
UPDATE 2
seems to only throw an error retrieving the data in xml format. Json seems to work
This is a known limitation of the XmlMediaTypeFormatter class from the System.Net.Formatting Nuget package. The implementation of the JSON formatter does support the $select and $expand commands but these are not available when content negotiation determines that XML should be returned.
You should look into implementing OData endpoints (as opposed to WebAPI endpoints) should you need to return XML formatted responses. More information on how this can be done can be found here:
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options
Found a solution. It isn't perfect but it does work!
Maybe it will be useful for someone because I've spent on it few hours of research and trying.
Step #1 create custom xml formatter:
public class CustomXmlFormatter : MediaTypeFormatter
{
private JsonMediaTypeFormatter jFormatter = null;
public CustomXmlFormatter(JsonMediaTypeFormatter jFormatter)
{
SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml"));
this.jFormatter = jFormatter;
}
public override bool CanReadType(Type type)
{
return false;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
using (MemoryStream ms = new MemoryStream())
{
var tsk = jFormatter.WriteToStreamAsync(type, value, ms, content, transportContext);
tsk.Wait();
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
var xDoc = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(ms, new XmlDictionaryReaderQuotas()));
using (XmlWriter xw = XmlWriter.Create(writeStream))
{
xDoc.WriteTo(xw);
}
}
});
}
}
Step #2 register it in startup section:
var formatters = ODataMediaTypeFormatters.Create();
var jsonFormatter = config.Formatters.JsonFormatter;
var customXmlFormatter = new CustomXmlFormatter(jsonFormatter);
customXmlFormatter.AddQueryStringMapping("$format", "cxml", "application/xml");
config.Formatters.Add(customXmlFormatter);
use it as
http://url..../actionName?$format=cxml&$select=ObjectName,ObjectId

Why is ExecuteResult not called?

I'm trying to implement a JSONP response in my ASP.NET MVC 5 web application. I've followed this tutorial:
http://www.ingeniumweb.com/blog/post/using-jsonp-calls-in-asp.net-mvc/1216/
The problem is that the ExecuteResult method is never called:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace subscribe.ActionResults
{
public class JsonpResult : JsonResult
{
object Data = null;
public JsonpResult()
{
}
public JsonpResult(object Data)
{
this.Data = Data;
}
public override void ExecuteResult(ControllerContext ControllerContext)
{
if (ControllerContext != null)
{
HttpResponseBase Response = ControllerContext.HttpContext.Response;
HttpRequestBase Request = ControllerContext.HttpContext.Request;
string callbackfunction = Request["callback"];
if (string.IsNullOrEmpty(callbackfunction))
{
throw new Exception("Callback function name must be provided in the request!");
}
Response.ContentType = "application/x-javascript";
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(string.Format("{0}({1});", callbackfunction, serializer.Serialize(Data)));
}
}
}
}
}
In my controller I have:
public JsonpResult Get(string emailaddress, string callback, string jsonp)
{
var slist = from u in db.subscriptions
select u;
if (!String.IsNullOrEmpty(emailaddress))
slist = slist.Where(s => (s.emailaddress == emailaddress));
if (slist.Count() > 0)
{
JsonpResult result = new JsonpResult(slist.ToList());
return result; //json list of matches
}
else
{
JsonpResult result = new JsonpResult(new List<Subscription>());
return result; //empty json list
}
}

Resources