"Validation failed for one or more entities. ERROR - api

I am creating web API to save the uploaded file in my local storage. When I testing my code it gives an error as ExceptionMessage": "Validation failed for one or more entities. See EntityValidationErrors' property for more details."
Can anyone help to fix this issue. Thanks in advance.
Controller(FileUploadController)
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using System.Web.Http;
using VantageCore.BL;
namespace VantageCoreApi.Controllers.Api
{
public class FileUploadController : ApiController
{
[HttpPost]
[Route("api/FileUpload")]
public async Task<IHttpActionResult> UploadFile(string FileName, int Id)
{
try
{
List<string> ids = new List<string>();
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var referenceId = FileName.Split('_')[0];
foreach (var file in provider.Contents)
{
Guid guid;
ids.Add(Guid.TryParse(await new FileUploadMgt().ReceiveFile(file, FileName, Id), out guid) ? FileName : "Error");
}
return Ok(ids);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
public string SaveFile(byte[] File, string path)
{
string Result = "";
try
{
//LOCAL SERVER PATH
var fs = new BinaryWriter(new FileStream(#"F:\Testfolder" + path, FileMode.Append, FileAccess.Write));
fs.Write(File);
fs.Close();
Result = path;
}
catch (Exception ee)
{
Result = ee.ToString();
}
return Result;
}
}
}
BL (FileUplodMgt.cs)
using System;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net.Http;
using VantageCore.Entity.Model;
using File = VantageCore.Entity.Model.File;
namespace VantageCore.BL
{
public class FileUploadMgt
{
public async Task<string> ReceiveFile(HttpContent receivedFile, string receivedFileName, int Id)
{
if (receivedFile != null)
{
var fileId = Guid.NewGuid();
using (var c = new DBEntities())
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string folder = appSettings["TestPath"];
var fileName = fileId.ToString() + Path.GetExtension(receivedFileName).ToLower();
var file = Path.Combine(folder, fileName);
bool exists = Directory.Exists(folder);
if (!exists) Directory.CreateDirectory(folder);
using (var fs = new BinaryWriter(new FileStream(file, FileMode.Create, FileAccess.Write)))
{
fs.Write(await receivedFile.ReadAsByteArrayAsync());
}
string extention = Path.GetExtension(file);
receivedFileName = Path.GetFileNameWithoutExtension(receivedFileName).Length <= 32
? Path.GetFileNameWithoutExtension(receivedFileName)
: Path.GetFileNameWithoutExtension(receivedFileName).Substring(0, 31) + "~";
var newFile = new File
{
Uid = fileId,
FileExtention = extention,
FileName = receivedFileName,
FileSize = (int)(receivedFile.Headers.ContentLength / 1024),
CreatedDate = DateTime.UtcNow
};
c.Files.Add(newFile);
c.SaveChanges();
}
return fileId.ToString();
}
else
{
return "Error,Invalid file Or file size exceeded";
}
}
}
}

You could try as below to observe the error message when you debug and share it;
try
{
c.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
}
}

Related

Receiving error while fetching mails using Aspose Email dll and Microsoft Graph Client API

Below is the code part along with error being received
Error received
Aspose.Email.AsposeBadServerResponceException: 'Server error Status: ResourceNotFound
Description: Resource could not be discovered.
Details:
GET: https://graph.microsoft.com/v1.0/users/1234outlook.onmicrosoft.com/mailFolders
Authorization: Bearer xxxxxx
Accept: application/json
Code 1
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Aspose.Email.Clients;
using Aspose.Email.Clients.Graph;
using Aspose.Email.Mapi;
using Azure.Identity;
using EASendMail;
using Microsoft.Graph;
namespace Code
{
internal class Graph_API
{
private static string _clientId = ConfigurationManager.AppSettings["ClientId"];
private static string _tenantId = ConfigurationManager.AppSettings["TenantId"];
private static string _secretValue = ConfigurationManager.AppSettings["SecretValue"];
static string _postString(string uri, string requestData)
{
HttpWebRequest httpRequest = WebRequest.Create(uri) as HttpWebRequest;
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = httpRequest.GetRequestStream())
{
byte[] requestBuffer = Encoding.UTF8.GetBytes(requestData);
requestStream.Write(requestBuffer, 0, requestBuffer.Length);
requestStream.Close();
}
try
{
HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
var responseText = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseText);
return responseText;
}
catch (WebException ep)
{
if (ep.Status == WebExceptionStatus.ProtocolError)
{
var responseText = new StreamReader(ep.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseText);
}
throw ep;
}
}
public string GenerateToken()
{
string client_id = _clientId;
string client_secret = _secretValue;
string tenant = _tenantId;
string requestData =
string.Format("client_id={0}&client_secret={1}" +
"&scope=https://graph.microsoft.com/.default&grant_type=client_credentials",
client_id, client_secret);
string tokenUri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant);
string responseText = _postString(tokenUri, requestData);
OAuthResponseParser parser = new OAuthResponseParser();
parser.Load(responseText);
var vv = parser.AccessToken;
return vv;
}
public void Generatemail()
{
interface_class bb = new interface_class();
IGraphClient client = GraphClient.GetClient(bb, _tenantId);
client.Resource = (ResourceType)1;
client.ResourceId = "1234outlook.onmicrosoft.com";
MapiMessage mm = new MapiMessage();
mm.Subject = "EMAILNET-39318 " + Guid.NewGuid().ToString();
mm.Body = "EMAILNET-39318 REST API v1.0 - Create Message";
mm.SetProperty(KnownPropertyList.DisplayTo, "1234outlook.onmicrosoft.com");
mm.SetProperty(KnownPropertyList.SenderName, "1234outlook.onmicrosoft.com");
mm.SetProperty(KnownPropertyList.SentRepresentingEmailAddress, "1234outlook.onmicrosoft.com");
// Create message in inbox folder
MapiMessage createdMessage = client.CreateMessage(Aspose.Email.Clients.Graph.KnownFolders.Inbox, mm);
}
public void FetchMail()
{
try
{
interface_class bb = new interface_class();
using (IGraphClient client = GraphClient.GetClient(bb, _tenantId))
{
client.Resource = (ResourceType)1;
client.ResourceId = "1234outlook.onmicrosoft.com";
FolderInfoCollection folderInfoCol1 = client.ListFolders();
FolderInfo inbox = null;
foreach (FolderInfo folderInfo in folderInfoCol1)
{
if (folderInfo.DisplayName.Equals("Inbox", StringComparison.InvariantCultureIgnoreCase))
{
inbox = folderInfo;
break;
}
}
MessageInfoCollection messageInfoCol = client.ListMessages(inbox.ItemId);
MessageInfo messageInfo = messageInfoCol[0];
MapiMessage message = client.FetchMessage(messageInfo.ItemId);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
--------------
Code file 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Email.Clients;
using Aspose.Email.Clients.Graph;
namespace Code
{
internal class interface_class : ITokenProvider
{
Graph_API obj = new Graph_API();
DateTime expirationDate = DateTime.Today.AddDays(1);
public void Dispose()
{
throw new NotImplementedException();
}
public OAuthToken GetAccessToken()
{
string token = obj.GenerateToken();
return new OAuthToken(token, expirationDate);
}
public OAuthToken GetAccessToken(bool ignoreExistingToken)
{
throw new NotImplementedException();
}
}
}

Are there advantages of using .NET Core's middleware "Health checks" over just a ping in a controller's route?

I'm reading a "Asp.net Core 3 and Angular 9" book and there is an example usage of .NET Core Health check.
It's also described on Microsoft website: https://learn.microsoft.com/en-US/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.0
I can't find a reason to actually use it over just creating a route in some controller which will ping external addresses.
Code in a book goes like this:
Add this in Configure (Startup.cs) method:
app.UseHealthChecks("/hc", new CustomHealthCheckOptions());
ConfigureServices method:
services.AddHealthChecks()
.AddCheck("ICMP_01", new ICMPHealthCheck("www.ryadel.com", 100))
.AddCheck("ICMP_02", new ICMPHealthCheck("www.google.com", 100))
.AddCheck("ICMP_03", new ICMPHealthCheck("www.does-notexist.com", 100));
Create ICMPHealthCheck.cs file:
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
namespace HealthCheck
{
public class ICMPHealthCheck : IHealthCheck
{
private string Host { get; set; }
private int Timeout { get; set; }
public ICMPHealthCheck(string host, int timeout)
{
Host = host;
Timeout = timeout;
}
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
try
{
using (var ping = new Ping())
{
var reply = await ping.SendPingAsync(Host);
switch (reply.Status)
{
case IPStatus.Success:
var msg = String.Format(
"IMCP to {0} took {1} ms.",
Host,
reply.RoundtripTime);
return (reply.RoundtripTime > Timeout)
? HealthCheckResult.Degraded(msg)
: HealthCheckResult.Healthy(msg);
default:
var err = String.Format(
"IMCP to {0} failed: {1}",
Host,
reply.Status);
return HealthCheckResult.Unhealthy(err);
}
}
}
catch (Exception e)
{
var err = String.Format(
"IMCP to {0} failed: {1}",
Host,
e.Message);
return HealthCheckResult.Unhealthy(err);
}
}
}
}
Create CustomHealthCheckOptions.cs file:
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Net.Mime;
using System.Text.Json;
namespace HealthCheck
{
public class CustomHealthCheckOptions : HealthCheckOptions
{
public CustomHealthCheckOptions() : base()
{
var jsonSerializerOptions = new JsonSerializerOptions()
{
WriteIndented = true
};
ResponseWriter = async (c, r) =>
{
c.Response.ContentType =
MediaTypeNames.Application.Json;
c.Response.StatusCode = StatusCodes.Status200OK;
var result = JsonSerializer.Serialize(new
{
checks = r.Entries.Select(e => new
{
name = e.Key,
responseTime = e.Value.Duration.TotalMilliseconds,
status = e.Value.Status.ToString(),
description = e.Value.Description
}),
totalStatus = r.Status,
totalResponseTime =
r.TotalDuration.TotalMilliseconds,
}, jsonSerializerOptions);
await c.Response.WriteAsync(result);
};
}
}
}
So it just pings 3 addresses and I can't see advantages of using Microsoft.AspNetCore.Diagnostics.HealthChecks library. Is that wrong example?

Issue with API Deleting for Team Foundation Server TFS

Hello can anyone tell me how to delete files using the API for TFS? Below is what I have but I can not get it to work any help would really be appreciated.
string[] InLocalDirectory = Directory.GetFiles(LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path), "*", SearchOption.AllDirectories);
// Source Control
List<string> InSourceControl = new List<string>();
ItemSet SetOfItem = _ServerVersionControl.GetItems(_ServerPath, VersionSpec.Latest, RecursionType.Full);
foreach (Item GotItem in SetOfItem.Items)
{
ItemType TypeOfItem = GotItem.ItemType;
if (TypeOfItem == ItemType.File)
{
string LocalPath = _WorkspaceLocal.GetLocalItemForServerItem(GotItem.ServerItem);
InSourceControl.Add(LocalPath);
}
}
List<int> ToDeleteById = new List<int>();
foreach (string SourceFile in InSourceControl)
{
if (!IsIgnored(SourceFile) && !InLocalDirectory.Contains(SourceFile))
{
// Delete Source Control File
Item DeleteItem = _ServerVersionControl.GetItem(SourceFile);
ToDeleteById.Add(DeleteItem.ItemId);
// Update Local XML Directory
DataXml.Delete(SourceFile);
}
}
WorkItemStore wis = _CollectionTeamProject.GetService<WorkItemStore>();
wis.DestroyWorkItems(ToDeleteById);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
namespace ConsoleAppX
{
class Program
{
static void Main(string[] args)
{
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
VssConnection connection = new VssConnection(new Uri("https://tfsuri"), creds);
TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>();
TfvcItem ti = tfvcClient.GetItemAsync("ProjectName", "$/FilePath","FileName").Result;
TfvcChange tchange = new TfvcChange(ti,VersionControlChangeType.Delete);
List<TfvcChange> change = new List<TfvcChange> { tchange };
TfvcChangeset tchangeset = new TfvcChangeset();
tchangeset.Changes = change;
tfvcClient.CreateChangesetAsync(tchangeset);
}
}
}
To delete a file, you need to use the VersionControlServer class to get an existing Workspace or create a new workspace. The workspace has a PendDelete method to create pending changes in the workspace. Then use the Workspace.Checkin method to commit them to source control:
https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.versioncontrol.client.workspace.aspx
I tried the penddelete before I tried the last way of doing it. But even when I manually go and delete a file and it hits the _WorkspaceLocal.PendDelete(SourceFile); line and is inserted for deletion it does not pick up on the line if (changes.Count() > 0) and then never check in.
string[] InLocalDirectory = Directory.GetFiles(LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path), "*", SearchOption.AllDirectories);
// Source Control
List<string> InSourceControl = new List<string>();
ItemSet SetOfItem = _ServerVersionControl.GetItems(_ServerPath, VersionSpec.Latest, RecursionType.Full);
foreach (Item GotItem in SetOfItem.Items)
{
ItemType TypeOfItem = GotItem.ItemType;
if (TypeOfItem == ItemType.File)
{
string LocalPath = _WorkspaceLocal.GetLocalItemForServerItem(GotItem.ServerItem);
InSourceControl.Add(LocalPath);
}
}
List<int> ToDeleteById = new List<int>();
foreach (string SourceFile in InSourceControl)
{
if (!IsIgnored(SourceFile) && !InLocalDirectory.Contains(SourceFile))
{
// Delete Source Control File
Item DeleteItem = _ServerVersionControl.GetItem(SourceFile);
ToDeleteById.Add(DeleteItem.ItemId);
// Update Local XML Directory
DataXml.Delete(SourceFile);
// Set for Deletion
_WorkspaceLocal.PendDelete(SourceFile);
}
}
string ConflictMessage = "";
Conflict[] conflicts = _WorkspaceLocal.QueryConflicts(new string[] { _LocalPath }, true);
foreach (Conflict conflict in conflicts)
{
if (conflict != null)
{
try
{
if (conflict.CanMergeContent)
{
conflict.Resolution = Resolution.AcceptMerge;
}
else
{
conflict.Resolution = Resolution.AcceptYoursRenameTheirs;
}
ConflictMessage += #"\n\r\n\r" + conflict.GetFullMessage();
_WorkspaceLocal.ResolveConflict(conflict);
}
catch (Exception ex)
{
LogicAppConfig.Insert(AppConfigLogic.TypeOfConfig.Message, "Error Detected Previously:\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.Source + "\r\n\r\n" + ex.StackTrace + "\r\n\r\n" + LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path));
}
}
}
if (!String.IsNullOrEmpty(ConflictMessage))
{
LogicAppConfig.Insert(AppConfigLogic.TypeOfConfig.Message, ConflictMessage);
}
PendingChange[] changes = _WorkspaceLocal.GetPendingChanges();
if (changes.Count() > 0)
{
int ChangeSetId = _WorkspaceLocal.CheckIn(changes, _WorkspaceName + " Deleted by Member Collaboration Utility");
}

Can I implement file download using MVC4's ApiController?

Using regular Controller I could do it by returning FileResult. The same doesn't seem to work with ApiController. Can it be done? Is it even a right thing to do?
Try this.
[HttpGet]
public HttpResponseMessage Get()
{
var file = HttpContext.Current.Server.MapPath("~/Images/accent.png");
var stream = new FileStream(file, FileMode.Open);
var content = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
content.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return content;
}
I have this working thanks to this question.
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
namespace Web.Controllers
{
//usage: /download/report
[RoutePrefix("download")]
public class DownloadController : ApiController
{
[HttpGet("report")]
public HttpResponseMessage Report()
{
using (var service = new Client())
{
var report = service.BuildReport();
return DownloadResponse(report, "Report.csv");
}
}
private static HttpResponseMessage DownloadResponse(string content, string fileName)
{
var downloadContent = new StringContent(content);
var mediaType = new MediaTypeHeaderValue("application/octet-stream");
var disposition= new ContentDispositionHeaderValue("attachment") { FileName = fileName };
downloadContent.Headers.ContentType = mediaType;
downloadContent.Headers.ContentDisposition = disposition;
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = downloadContent
};
return result;
}
}
}

Object reference not set to an instance of an object when using SPGridViewPager

It's my first sharepoint project and eveything looks very confusing.
I need to have a SPGridView with paging.
Here is an entire code of mx webpart:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace FirstSPGridView.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public class VisualWebPart1 : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/FirstSPGridView/SPGridViewWebPartTest/VisualWebPart1UserControl.ascx";
SPGridView _grid;
protected override void CreateChildControls()
{
base.CreateChildControls();
try
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
//Using RunWithElevatedPrivileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(mySite.ID))
{
using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{
_grid = new SPGridView();
_grid.AutoGenerateColumns = false;
_grid.PageSize = 3;
_grid.AllowPaging = true;
_grid.DataSource = SelectData();
Controls.Add(_grid);
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
}
}
});
}
catch (Exception ex)
{ }
}
protected sealed override void Render(HtmlTextWriter writer)
{
try
{
GenerateColumns();
_grid.DataBind();
base.Render(writer);
}
catch (Exception e)
{
throw new NotImplementedException();
}
}
private void GenerateColumns()
{
BoundField clientNameColumn = new BoundField();
clientNameColumn.HeaderText = "Client";
clientNameColumn.DataField = "LastName";
_grid.Columns.Add(clientNameColumn);
BoundField birthDayColumn = new BoundField();
birthDayColumn.HeaderText = "BirthDate";
birthDayColumn.DataField = "BirthDate";
_grid.Columns.Add(birthDayColumn);
}
public DataTable SelectData()
{
var dataGet = new DataTable();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (
var conn =
new SqlConnection(
"Data Source=localhost;Initial Catalog=AdventureWorksDW2008R2;Integrated Security=True")
)
{
var adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("Select TOP 100 LastName,Birthdate FROM DimCustomer");
adapter.SelectCommand.Connection = conn;
conn.Open();
adapter.Fill(dataGet);
}
});
return dataGet;
}
}
}
Everything was working (except paging until I added this code:
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
After that I get an exception on the Render method here:
base.Render(writer);
StackTrace is:
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)\r\n at Microsoft.SharePoint.WebControls.Menu.FindControlByWalking(Control namingContainer, String id)\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.get_GridViewControl()\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.Render(HtmlTextWriter output)\r\n at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)\r\n at System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer)\r\n at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)\r\n at FirstSPGridView.VisualWebPart1.VisualWebPart1.Render(HtmlTextWriter writer)
How can I fix that error?
You must just set ID for _grid.
For example, _grid.ID = "_gridView";