I'm using a stored procedure to import an Excel data into SQL Server in an ASP.NET MVC application. The problem is when I run the application and upload the file, I got the above error and the cursor point on foreach (var a in empDetails).
This is my controller:
public ActionResult ExcelUpload()
{
return View();
}
[HttpPost]
public ActionResult UploadExcel(Réception_camions objEmpDetail, HttpPostedFileBase FileUpload)
{
Réception_phosphateEntities objEntity = new Réception_phosphateEntities();
string data = "";
if (FileUpload != null)
{
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
if (filename.EndsWith(".xlsx"))
{
string targetpath = Server.MapPath("~/DetailFormatInExcel/");
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var empDetails = from a in excelFile.Worksheet<Réception_camions>(sheetName) select a;
// The error occurs in this line:
// Invalid cast from 'System.DateTime' to 'System.TimeSpan'
foreach (var a in empDetails)
{
if (a.Date_d_arrivée != null )
{
DateTime Date_d_arrivée = (a.Date_d_arrivée);
int Id_qualité = Convert.ToInt32(a.Id_qualité);
int result = PostExcelData(a.Date_d_arrivée, a.heure_d_arrivée, a.Poids_cam,/* myBirthdate,*/ a.Id_cam, a.Id_qualité /*a.PostelCode, a.EmailId*/);
if (result <= 0)
{
data = "Hello User, Found some duplicate values! Only unique employee number has inserted and duplicate values(s) are not inserted";
ViewBag.Message = data;
continue;
}
else
{
data = "Successful upload records";
ViewBag.Message = data;
}
}
else
{
data = a.Date_d_arrivée + "Some fields are null, Please check your excel sheet";
ViewBag.Message = data;
return View("ExcelUpload");
}
}
}
else
{
data = "This file is not valid format";
ViewBag.Message = data;
}
return View("ExcelUpload");
}
else
{
data = "Only Excel file format is allowed";
ViewBag.Message = data;
return View("ExcelUpload");
}
}
else
{
if (FileUpload == null)
{
data = "Please choose Excel file";
}
ViewBag.Message = data;
return View("ExcelUpload");
}
}
public int PostExcelData(DateTime Date_d_arrivée, TimeSpan heure_d_arrivée, Decimal Poids_cam, int Id_cam, int Id_qualité)
{
Réception_phosphateEntities DbEntity = new Réception_phosphateEntities();
var InsertExcelData = DbEntity.usp_InsertNewEmployeeDetails(Date_d_arrivée, heure_d_arrivée, Poids_cam, Id_cam, Id_qualité );
return InsertExcelData;
}
And this is my stored procedure for the table Réception_camions:
ALTER PROCEDURE [dbo].[usp_InsertNewEmployeeDetails]
(#Date_d_arrivée DATETIME = NULL,
#heure_d_arrivée TIME(7) = NULL,
#Poids_cam DECIMAL(18, 2) = null,
#Id_cam INT = NULL,
#Id_qualité INT = NULL)
AS
BEGIN
INSERT INTO Réception_camions([Date d'arrivée], [heure d'arrivée], Poids_cam,
Id_cam, Id_qualité)
VALUES (#Date_d_arrivée, #heure_d_arrivée, #Poids_cam,
#Id_cam, #Id_qualité)
END
I'm blocked please if someone can help me.
Related
I am using the following code in window service to download zip file with particular format from email attachments:
Method to get Emails:
public void GetdownloadfromGmail()
{
try
{
ConfigDetails ConfigDetails = new ConfigDetails();
DataTable SecTable = ConfigDetails.GetConfigTableCol(Constant.Seccurity);
using (IDbConnection con = Connections.Getsynchconnection())
{
try
{
con.Open();
ConnectionState state = con.State;
con.Close();
if (state == ConnectionState.Open)
{
SentmailCount = 0;
}
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Error(ex.Message.ToString());
if (SentmailCount == 0)
{
string ContentMessage = "SqlConnection is Not Open :" + ex.Message.ToString();
Process SharedProc = new Process();
string EmailID = SharedProc.GetReceipientmailid(new Context(new MailContext()), "", 3);
string[] Receipients = EmailID.Split(',');
//time being profile,pwd is hard coded
GmailClient.GmailClient gc = new GmailClient.GmailClient();
/*Sending attachment(s) with the mail*/
gc.SMTPHost = SecTable.Rows[0]["SmtpHost"].ToString();
gc.SMTPPortNumber = Convert.ToInt32(SecTable.Rows[0]["SmtpPort"].ToString());
bool IsEnableSsl = Convert.ToBoolean(SecTable.Rows[0]["IsEnableSsl"].ToString());
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(SecTable.Rows[0]["Username"].ToString(), SecTable.Rows[0]["Password"].ToString());
System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(SecTable.Rows[0]["Username"].ToString(), SecTable.Rows[0]["DisplayName"].ToString());
gc.sendMail("Connection", Receipients, ContentMessage, null, "", credentials, address, true, IsEnableSsl);
SentmailCount = 1;
}
return;
}
}
Common.Synch.Factory.LogHelpFactory.log.Info("Start Download Mails From Mailbox");
//ConfigDetails ConfigDetails = new ConfigDetails();
//time being profile,pwd is hard coded
// DataTable SecTable = ConfigDetails.GetConfigTableCol(Constant.Seccurity);
if (SecTable.Columns["UserName"] == null && SecTable.Columns["Password"] == null)
{
throw (new Exception("Invalid Profile settings"));
}
using (GmailClient.GmailClient gc = new GmailClient.GmailClient())
{
gc.UseSSL = true;
/*Part to fetch mails from gmail; List<MailMessage> will have all the mails fetched which can be used later to send mails.
The attachments get downloaded as the mails are read.
The MailMessage only includes the basic header information along with the number of attachments processed.
Once all emails are fetched, the client disconnects automatically*/
//Following property will not delete the email from gmail server if set to False, but deletes if it set to True
gc.SMTPHost = SecTable.Rows[0]["IncomingEmailHost"].ToString();
gc.SMTPPortNumber = Convert.ToInt32(SecTable.Rows[0]["IncomingEmailPort"].ToString());
gc.DeleteProcessedMails = Convert.ToBoolean(SecTable.Rows[0]["DeleteEmail"].ToString());
ConfigDetails = new ConfigDetails();
TempPath = ConfigDetails.GetPath(Constant.TempFolder);
//Default AttachmentPath is the path of dll directory. Howeve it can be set exclusilvely as below.
gc.AttachmentPath = TempPath + "\\";
string strUname = SecTable.Rows[0]["Username"].ToString();
string strPwd = SecTable.Rows[0]["Password"].ToString();
gc.Connect(strUname, strPwd);
gc.CopyProcessedMails = Convert.ToBoolean(SecTable.Rows[0]["CopyProcessedEmail"].ToString()); ;
gc.CopyMailTargetFolder = Convert.ToString(SecTable.Rows[0]["CopyMailTargetFolder"].ToString()); ;
Common.Synch.Factory.LogHelpFactory.log.Info("Test ");
if (gc.IsConnected)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Connected");
List<MailMessage> mails = gc.GetMailList();
Common.Synch.Factory.LogHelpFactory.log.Info("Unread Mail Count:" + mails.Count.ToString()); try
{
foreach (MailMessage Mail in mails)
{
try
{
isDeleted = false;
if (null != Mail.Subject)
Common.Synch.Factory.LogHelpFactory.log.Info(Mail.Subject.ToString());
else
Common.Synch.Factory.LogHelpFactory.log.Info(Mail.FromEmail + " (no subject)");
GetMaiilboxtotable(Mail);
//if (isDeleted)
//{
//Mail.UnRead = false;
//Mail.Delete();
//}
}
catch (Exception Ex)
{
//if (Ex.Message == "Could not save attachment to a file")
//{
Common.Synch.Factory.LogHelpFactory.log.Info("Error while processing email:" + Ex.Message.ToString());
Common.Synch.Factory.LogHelpFactory.log.Info("Subject:" + Mail.Subject + ", From:" + Mail.FromName);
//Mail.UnRead = false;
//Mail.Delete();
//}
}
}
}
//if (ListofMails.Count > 0)
//{
//OutlookClient.MovFolderselection();
//}
catch (Exception Ex)
{
//if (ListofMails != null)
//{
// Marshal.ReleaseComObject(ListofMails);
//}
//ListofMails = null;
////OutlookClient.Dispose();
mails = null;
gc.Dispose();
Common.Synch.Factory.LogHelpFactory.log.Error("SearchMails(GetMailFromGmail) failed : ", Ex);
}
finally
{
if (m_MailTable.Rows.Count > 0)
{
SaveEmail();
Common.Synch.Factory.LogHelpFactory.log.Info("Save Email Complete");
}
int Sleeptime = Convert.ToInt32(ConfigDetails.GetResourceSleeptime(Constant.InboundProcess));
if (Sleeptime == 0)
{
Sleeptime = 10000;
}
ConfigDetails = null;
try
{
Thread.Sleep(Sleeptime);
}
catch (ThreadAbortException ex)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Error on thread.Sleep:" + ex.Message.ToString());
}
try
{
this.DownLoadCompleteEventArgs(this, new DownLoadCompleteEventArgs("DownLoad Complete"));
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Error while invoking the thread:" + ex.Message.ToString());
}
Common.Synch.Factory.LogHelpFactory.log.Info("End Download Mails From Inbox");
}
}
// Log
}
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Error(ex.Message.ToString());
}
}
Method to save extracted files in database:
public void GetMaiilboxtotable(MailMessage Message)
{
Common.Synch.Common.DeleteFile(TempPath);
try
{
if (Initalize())
{
if (Message.Attachments != null && Message.AttachmentsCount > 0)
{
for (int Count = 0; Count <= Message.AttachmentsCount - 1; Count++)
{
//if (Message.Attachments[Count].AttachmentAttachmentFileName.Substring(Message.Attachments[Count].AttachmentAttachmentFileName.Length - 3, 3).ToUpper() == "MSG")
//{
// Message.Attachments[Count].SaveAsFile(TempPath + "Temp.msg");
// outlookApp = new OutLook.ApplicationClass();
// MsgMail = (OutLook.MailItem)outlookApp.CreateItemFromTemplate(TempPath + "Temp.msg", Type.Missing);
// GetMaiilboxtotable(MsgMail);
// outlookApp = null;
// MsgMail = null;
//}
if (Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "ZIP" ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "XML" ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "XLS" ||
(Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "DAT"
&& Message.Attachments[Count].AttachmentFileName.Substring(0, 2).ToUpper() == "HJ") ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "BIN")
{
if (m_MailTable.Columns.Count <= 0)
{
CreateMailTable();
}
isDeleted = true;
DataRow MailRows = m_MailTable.NewRow();
MailRows["MailID"] = Message.FromEmail;
MailRows["MsgDate"] = Message.ReceivedDate;
MailRows["MsgSubject"] = (null == Message.Subject ? string.Empty : Message.Subject);
MailRows["CreateDateTime"] = DateTime.Now;
//string GwAttachmentName = Message.Attachments[Count].AttachmentFileName;
Message.Attachments[Count].DownloadAttachment();// SaveAsFile(TempPath + Message.Attachments[Count].AttachmentFileName);
MailRows["AttachmentName"] = Message.Attachments[Count].AttachmentFileName;
ConvertBinary ConvertBinary = new ConvertBinary();
MailRows["AttachmentFile"] = ConvertBinary.ConverTOBinaryFile(TempPath + "\\" + Message.Attachments[Count].AttachmentFileName);
ConvertBinary.Dispose();
ConvertBinary = null;
//Marshal.ReleaseComObject(synchGwAttachment);
m_MailTable.Rows.Add(MailRows);
//Log
Common.Synch.Factory.LogHelpFactory.log.Info("Add Mail to MailBox Temp Table -" + Message.Attachments[Count].AttachmentFileName);
}
}
}
}
}
catch (Exception ex)
{
Message = null;
Common.Synch.Factory.LogHelpFactory.log.Info(Message.Subject + ":" + ex.ToString());
}
}
Attachment structure is:
In attachment we are sending bin files of objects and these objects further extracted and saved in database.
Problem:
Some times we are receiving large files, so while extracting service hang and stop processing in between. Could you provide me some suggestions and ideas to overcome this issue.
Please let me know if you need more information, I will try my best to provide.
Thanks in advance.
You are using DataTables.
A DataTable is an in-memory copy of relational data.
So all the data you are going to save have to fit into memory.
If you have a lot of records, big records or both this will not do.
I suggest to:
decompress the file inside a temp folder on local file system
insert into the database one file at a time using a SqlCommand
Use parameters in your INSERT command (ie insert into mytable (col1, col2) values (#col1, # col2))
I want to send image files to SQL Server using C#.
The below code is working and saving files and their paths into the database. I need the same data in my API endpoint's response. I've created a custom response class, called RegistrationResponse.
I'm beginner in this so I'm looking for help.
public async Task<RegistrationResponse> PostFormData(HttpRequestMessage request)
{
object data = "";
NameValueCollection col = HttpContext.Current.Request.Form;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/images");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
//read file data
foreach (MultipartFileData dataItem in provider.FileData)
{
try
{
string description = string.Empty;
string userId = string.Empty;
String fileName = string.Empty;
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key.ToString().ToLower() == "userid")
{
userId = val;
}
else if (key.ToString().ToLower() == "description")
{
description = val;
}
}
}
String name = dataItem.Headers.ContentDisposition.FileName.Replace("\"", "");
fileName = userId + Path.GetExtension(name);
File.Move(dataItem.LocalFileName, Path.Combine(root, fileName));
using (var db = new AlumniDBEntities())
{
//saving path and data in database table
Post userPost = new Post();
userPost.Files = fileName;
userPost.Description = description;
userPost.UserID = Convert.ToInt32(userId);
userPost.CreatedDate = DateTime.Now;
db.Posts.Add(userPost);
db.SaveChanges();
data = db.Posts.Where(x => x.PostID ==
userPost.PostID).FirstOrDefault();
string output = JsonConvert.SerializeObject(data);
}
}
catch (Exception ex)
{
return Request.CreateResponse(ex);
}
}
return Request.CreateResponse(HttpStatusCode.Created);
});
var response = new RegistrationResponse
{
success = true,
status = HttpStatusCode.OK,
message = "Success",
data = data
};
return response;
}
I have implemented Citrus Payment gatway request/Response pages I am struck with Enquiry API integration,Where i have to implement it in code ?what is the page name i have to give ?
this is the guide given to me by citrus to implement enquiry api ..
http://developers.citruspay.com/api/miscellaneous/Enquiry.html#/
Request.aspx page code -
{
string formPostUrl = "https://sandbox.citruspay.com/sslperf/xyzdoman";
string secret_key = "xxxxxxxxxxxxxxx";
//Need to change with your Vanity URL Key from the citrus panel
string vanityUrl = "xxxxxyy";
//Should be unique for every transaction
string merchantTxnId = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");
//Need to change with your Order Amount
string orderAmount = "10";
string currency = "INR";
string data = vanityUrl + orderAmount + merchantTxnId + currency;
//Need to change with your Return URL
string returnURL = "http://www.xxxxxyy.com/Response.aspx";
//Need to change with your Notify URL
string notifyUrl = "http://www.xxxxxyy.com/Response.aspx";
System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
string securitySignature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();
%>
Response.aspx page code
{
string secret_key = "xxxxxxxxxxxxxxxxxxxxx";
string data="";
string txnId=Request["TxId"];
string txnStatus=Request["TxStatus"];
string amount=Request["amount"];
string pgTxnId=Request["pgTxnNo"];
string issuerRefNo=Request["issuerRefNo"];
string authIdCode=Request["authIdCode"];
string firstName=Request["firstName"];
string lastName=Request["lastName"];
string pgRespCode=Request["pgRespCode"];
string zipCode=Request["addressZip"];
string resSignature=Request["signature"];
bool flag = true;
if (txnId != null) {
data += txnId;
}
if (txnStatus != null) {
data += txnStatus;
}
if (amount != null) {
data += amount;
}
if (pgTxnId != null) {
data += pgTxnId;
}
if (issuerRefNo != null) {
data += issuerRefNo;
}
if (authIdCode != null) {
data += authIdCode;
}
if (firstName != null) {
data += firstName;
}
if (lastName != null) {
data += lastName;
}
if (pgRespCode != null) {
data += pgRespCode;
}
if (zipCode != null) {
data += zipCode;
}
System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
string signature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();
if(resSignature !=null && !signature.Equals(resSignature)) {
flag = false;
}
if (flag) {
%>
Your Unique Transaction/Order Id : <%=txnId%><br/>
Transaction Status : <%=txnStatus%><br/>
<% } else { %>
<label width="125px;">Citrus Response Signature and Our (Merchant) Signature Mis-Mactch</label>
<% } %>
this is my javascript code :
var fileURL = "file://" + mFileListURL[0].fullPath;
var options = new FileUploadOptions();
options.fileKey = "recFile";
var imagefilename = Number(new Date()) + ".jpg";
options.fileName = imagefilename;
options.mimeType = "image/jpeg";
var params = new Object();
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURL,"http://mywebserver/UploadFoto.asmx/SaveImage",
function(r) {
alert("It's OK!");
alert("Response = " + r.response);
}, function(error) {
alert("An error has occurred: Code = "
+ error.code);
}, options);
and this server side code:
[WebMethod]
[GenerateScriptType(typeof(String))]
[ScriptMethod]
public String SaveImage()
{
HttpContext context = HttpContext.Current;
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
foreach (string key in files)
{
HttpPostedFile file = files[key];
string fileName = file.FileName;
if (fileName != null && fileName != "")
{
String fileStored = System.IO.Path.Combine(context.Server.MapPath("~/public/"), fileName);
file.SaveAs(fileStored);
}
}
}
return "Filestored OK";
}
Now, image upload is done but I get no returned string, no response from server, no error code. I used Json response also but nothing (image is upload, no response, no string returned).
What's wrong?
Thanks. IngD
try this
function(r)
{
alert("It's OK!");
alert("Sent = " + r.bytesSent);
}
WebMethod Must be static
[WebMethod]
[GenerateScriptType(typeof(String))]
[ScriptMethod]
public static String SaveImage()
{
HttpContext context = HttpContext.Current;
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
foreach (string key in files)
{
HttpPostedFile file = files[key];
string fileName = file.FileName;
if (fileName != null && fileName != "")
{
String fileStored = System.IO.Path.Combine(context.Server.MapPath("~/public/"), fileName);
file.SaveAs(fileStored);
}
}
}
return "Filestored OK";
}
public ViewResult Index(string currentFilter, string searchString, int? page)
{
if (Request.HttpMethod == "GET")
{
searchString = currentFilter;
}
else
{
page = 1;
}
ViewBag.CurrentFilter = searchString;
var connString = ConfigurationManager.ConnectionStrings["ApplicantDB"].ConnectionString;
List<Applicant> instructors = new List<Applicant>();
using (var conn = new SqlConnection(connString))
{
conn.Open();
var query = new SqlCommand("SELECT TOP 50 APPLICANT_ID, APPLICANT_Lastname, APPLICANT_FirstName, APPLICANT_MiddleName, APPLICANT_Address, APPLICANT_City"+
" FROM APPLICANT", conn);
var reader = query.ExecuteReader();
int currentPersonID = 0;
Applicant currentInstructor = null;
while (reader.Read())
{
var personID = Convert.ToInt32(reader["APPLICANT_ID"]);
if (personID != currentPersonID)
{
currentPersonID = personID;
if (currentInstructor != null)
{
instructors.Add(currentInstructor);
}
currentInstructor = new Applicant();
currentInstructor.APPLICANT_ID = Convert.ToInt32(reader["APPLICANT_ID"].ToString());
currentInstructor.APPLICANT_Lastname = reader["APPLICANT_Lastname"].ToString();
currentInstructor.APPLICANT_FirstName = reader["APPLICANT_FirstName"].ToString();
currentInstructor.APPLICANT_MiddleName = reader["APPLICANT_MiddleName"].ToString();
currentInstructor.APPLICANT_Address = reader["APPLICANT_Address"].ToString();
currentInstructor.APPLICANT_City = reader["APPLICANT_City"].ToString();
}
if (!String.IsNullOrEmpty(searchString))
{
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
}
}
if (currentInstructor != null)
{
instructors.Add(currentInstructor);
}
reader.Close();
conn.Close();
}
int pageSize = 10;
int pageNumber = (page ?? 0);
return View(instructors.ToPagedList(pageNumber, pageSize));
}
Error in this Line
if (!String.IsNullOrEmpty(searchString))
{
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
}
This is the first time i encountered this type of error . .
I wasted almost 2 hours in this kind of error
I hope someone can help me in this situation. . advance thank you for those who are willing to help. . So much appreciated :) KUDOS !!
As the error says, you are trying to assign single object to list.
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
If there can be only one result you need to use SingleOrDefault() and if there are multiple records, use FirstOrDefault() which extracts first record from result set.
instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper())).FirstOrDefault();
You probably want the first applicant in the list.
currentInstructor = instructors
.AsQueryable()
.Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper()) || s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()))
.FirstOrDefault();