Exception Devart.Data.Linq on a server "Devart.Data.Oracle.Linq.Provider" - linq

I am trying to deploy my application on Windows server 2007 32 Bit.
My application gave me this Exception
Error on opening DbConnection. bei Devart.Data.Linq.LinqCommandExecutionException.CanThrowLinqCommandExecutionException
(String message, Exception e)
bei Devart.Data.Linq.Provider.k.a.g()
bei Devart.Data.Linq.Provider.k.a.b(IConnectionUser A_0)
bei Devart.Data.Linq.Provider.k.b(IConnectionUser A_0)
bei Devart.Data.Linq.Provider.DataProvider.ExecuteQuery(CompiledQuery compiledQuery, Object[] parentArgs, Object[] userArgs, Object lastResult)
bei Devart.Data.Linq.Provider.DataProvider.ExecuteAllQueries(CompiledQuery compiledQuery, Object[] userArguments)
bei Devart.Data.Linq.Provider.DataProvider.CompiledQuery.Devart.Data.Linq.Provider.ICompiledQuery.Execute(IProvider provider, Object[] userArgs)
bei Devart.Data.Linq.DataQuery`1.i()
bei System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
bei System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
while executing this line in my program
var list = clientCustomers.ToList();
Code
public Repository(String Connection, String EventPackageName, String EventScopeName)
{
this.connectionDict = this.getConnectionInfo(Connection);
//this.context = new DataContext(connection);//old way
this.context = new DataContext(Connection, new Devart.Data.Oracle.Linq.Provider.OracleDataProvider());
this.eventContext = new EventPacDataContext(Connection);
this.eContext = new Context.EventPacDataContext(Connection, new Devart.Data.Oracle.Linq.Provider.OracleDataProvider());
this.eventPackageName = EventPackageName;
this.eventScopeName = EventScopeName;
this.clientUserName = this.connectionDict["User Id"];
}
/// <summary>
/// Collect all Customers from VIEW
/// </summary>
/// <returns>IQueryable<Customer></returns>
public IQueryable<Customer> GetCustomers()
{
try
{
var result = from p in this.context.YDEVQUALIBASICs
join extended in this.context.YDEVQUALIBASICEXTENDEDs on
p.ACCOUNTID equals extended.ACCOUNTID
select
new Customer
{
Base = new Customer
{
CustomerId = p.CUSTOMERID.ToString(),
CustomerNo = p.CUSTOMERNO.ToString(),
Geburtsdatum = p.DETGEBURTSDATUM.GetValueOrDefault(new DateTime(1900, 1, 1)),
Email = p.DETEMAIL,
BusinessArea = p.ACCBUSINESSAREA,
ContractType = p.ACCCONTRACTTYPE,
ContractTariff = p.ACCCONTRACTARIFF,
SubscribeChannel = p.DETANMELDEKANAL,
PaymentMethod = p.CUSCOLLECTIONIDENT,
CustomerAddress = new Address
{
City = p.CUSCITY,
Street = p.CUSSTREET,
ExtendedInfo = p.CUSEHNR,
StreetNumber = p.CUSHNR,
LCountry = p.CUSCOUNTRYL,
SCountry = p.CUSCOUNTRYS,
ZipCode = p.CUSZIPCODE
},
AccountPerson = new Person
{
Salutation = p.ACCANREDE,
Title = p.ACCAKADEM,
Branche = p.ACCBRANCHE,
Lastname = p.ACCTOMERNAME1,
Firstname = p.ACCTOMERNAME2,
Name3 = p.ACCTOMERNAME3
}
},
CustomerPerson = new Person
{
Salutation = p.CUSANREDE,
Title = p.CUSAKADEM,
Branche = p.CUSBRANCHE,
Lastname = p.CUSTOMERNAME1,
Firstname = p.CUSTOMERNAME2,
Name3 = p.CUSTOMERNAME3
},
InternGeolocChecked = extended.DETINTERNGEOLOCCHECKED,
InternGeolocStatus = extended.DETINTERNGEOLOCSTATUS,
};
return result;
}
catch (ReflectionTypeLoadException ex)
{
StringBuilder sb = new StringBuilder();
foreach (Exception exSub in ex.LoaderExceptions)
{
sb.AppendLine(exSub.Message);
if (exSub is FileNotFoundException)
{
FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
{
sb.AppendLine("Fusion Log:");
sb.AppendLine(exFileNotFound.FusionLog);
}
}
sb.AppendLine();
}
string errorMessage = sb.ToString();
//Display or log the error based on your application.
logger.Fatal("Aha: " + errorMessage);
return null;
}
catch (Exception ex)
{
logger.Fatal("Customer failed: " + ex.Message + ex.StackTrace);
throw new DataAccessException("Customer failed", ex);
}
}

When deploying applications written with the help of LinqConnect you should register run-time assemblies Devart.Data.Oracle.dll, Devart.Data.dll, Devart.Data.Oracle.Linq.dll and Devart.Data.Linq.dll at Global Assembly Cache (GAC) or place them in the folder of your application.
When deploying ASP.NET applications it is also necessary to have Devart.Data.Oracle.Web.dll and App_Licenses.dll assemblies available.
If all required assemblies are available for your project, please perform the following steps:
Make sure that Oracle Client Software is installed on your computer;
Specify the name of Oracle Home explicitly in the Home connection string parameter.
Place the content of the ORACLE_HOME variable on the first position in the PATH variable of your operating system;
Make sure that capacity (x86 or x64) of your application and the capacity of your Oracle Client are the same.
If after these steps the issue still persists, please contact us with more details for this issue, e.g.:
the full stack trace of the exception;
the connection string;
the version of the Oracle Client;
the version of the Oracle server;
the definitions of the database tables and corresponding entity classes, etc.

Related

Reading a list from SharePoint instance through code

I'm trying to access a SharePoint instance using SharePoint Online Client Components SDK (sharepointclientcomponents_16-6518-1200_x64-en-us.msi) through .Net 6 console application.
My Code:
internal class SpMain
{
public static void GetApprovedAppsByView(
string siteUrl, NetworkCredential credentials, string listName, string viewName, string camlQuery)
{
try
{
using var context = new ClientContext(siteUrl);
context.Credentials = credentials;
var list = context.Web.Lists.GetByTitle(listName);
var view = list.Views.GetByTitle(viewName);
var query = new CamlQuery();
context.Load(view);
if (context.HasPendingRequest)
{
context.ExecuteQuery();
}
query.ViewXml = $"<View><Query>{view.ViewQuery}{camlQuery}</Query></View>";
var items = list.GetItems(query);
context.Load(items);
if (context.HasPendingRequest)
{
context.ExecuteQuery();
}
foreach (var listItem in items)
{
Console.WriteLine(listItem["Title"]);
}
}
catch (Exception ex)
{
Console.WriteLine("Error Message: " + ex.Message);
}
}
}
I'm calling this function like:
// Target Page: https://dummy.company.com/commy/cotrev/Lists/DevCMRL/DaMemos.aspx
const string siteUrl = "https://dummy.company.com/commy/cotrev/";
const string listName = "DevCMRL";
const string viewName = "DaMemos";
const string query = "*";
var credentials = new NetworkCredential("sp_testUser", "AwesomePassword", "myDomain");
SpMain.GetApprovedAppsByView(siteUrl, credentials, listName, viewName, query);
Console.ReadKey();
But I keep getting Bad Request at the first context.ExecuteQuery();. The credentials are correct. I think I have the Url, List, & View names set up incorrectly. And also, CamlQuery is completely wrong for sure. But this is something new for me and the docs at Microsoft are talking about SharePoint Online only.
Given the Target URL of the page with the actual List, how should I set the correct parameters?

Crystal Report ExportToStream Failing with Object Reference not set to an instance

I have a very simple app that takes in No parameters in the attempt to return PDF.
The crystal Reports were authored using CR IX and I had to update the web service code to use Crystal Report for Visual studio 13. I am able to set parameters, as well as being able to login and verify that login credentials are correct.
public string TestReport()
{
try
{
var p = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("Product", "03R95-01"),
new KeyValuePair<string, string>("Product_Rev", "E-V001")
};
var reportParameters = new ParameterField[2];
var rpt = InitializeReport("testReport", p);
var s = rpt.ExportToStream(ExportFormatType.PortableDocFormat);
return "Stream exists";
}
catch (Exception ex)
{
return $"{ex.Message}|{ex.StackTrace}";
}
}
The Initialize Report method is:
private ReportDocument InitializeReport(string svrId, string reportName, List<KeyValuePair<string, string>> parameters)
{
var uid = "userId";
var pwd = "pwd";
var svr = "serverId";
var db = "DBNAME";
var reportFolder = "c:\\CrystalTest\\ReportFolder";
var reportFile = Path.Combine(reportFolder, $"{reportName}.rpt");
var rpt = new ReportDocument
{
FileName = reportFile
};
rpt.Load(reportFile);
var conInfo = new ConnectionInfo
{
UserID = uid,
Password = pwd,
ServerName = svr,
DatabaseName = db
};
foreach (Table t in rpt.Database.Tables)
{
try
{
var loginInfo = t.LogOnInfo;
loginInfo.ConnectionInfo = conInfo;
t.ApplyLogOnInfo(loginInfo);
if(!t.TestConnectivity())
{
throw new Exception($"{t.Name} failed login");
}
}
catch (Exception ex)
{
throw;
}
}
rpt.VerifyDatabase();
return rpt;
}
I have verified that an error is thrown when userid/pass combinations are incorrect.
I get the following error when I run this.
Object reference not set to an instance of an object.| at
CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext
reqContext) at
CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions
options) at
CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType
formatType) at ICEWS4.maintenance.TestReport() in
C:\CrystalTest.cs:line 724
I learned of the fix.
I had CR for VS 13 SP 29.
The Runtime installed on the server was 13 SP 23
I was told by SAP to update to SP 30.
After updating my code, and installing the runtime, I was able to export to PDF as desired.

How to register a new user in ASP.NET MVC application by passing the data into a Web API?

In my ASP.NET MVC 5 application, I want to make the Admin User add a new user. Upon signing in, the registration form fields (registration view) with new user values are captured in AccountController of the ASP.NET MVC 5 application as follows, and which then calls the API and the data must be transferred there:
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Register(AccountRegistration register)
{
string baseAddress = ConfigurationManager.AppSettings["ApiBaseUrl"];
//var client = new HttpClient();
//client.BaseAddress = new Uri("api/Account/Register");
//client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string accessToken = this.ControllerContext.HttpContext.Request.Cookies["auth_key"].Values["token"];
using (var client = new HttpClient())
{
var form = new Dictionary<string, string>
{
{ "firstname", register.FirstName.Trim()},
{ "lastname", register.LastName.Trim()},
{ "email", register.Email.Trim()},
{ "phone", register.PhoneNo.Trim()},
{ "password", register.Password.Trim()},
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
var res = client.PostAsync(baseAddress + "/api/Account/Register", new StringContent(JsonConvert.SerializeObject(register), Encoding.UTF8, "application/json"));
res.Wait();
var taskResponse = res.Result;
var data = taskResponse.Content.ReadAsAsync<object>(new[] { new JsonMediaTypeFormatter() }).Result;
}
return View();
}
Here is my Web API AccountController code:
[HttpPost]
public IHttpActionResult Register([FromBody]UserRegister register)
{
DBAccess dblayer = new DBAccess();
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
UserManager<IdentityUser> _manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new TachusApi.DBContext.AuthDbContext()));
string pHash = _manager.PasswordHasher.HashPassword(register.Password);
dblayer.SaveAdmin(register, pHash);
return Ok("Success");
}
catch (Exception)
{
return Ok("Something went wrong.");
}
}
And here is the DBAccess.cs method which is called from this API's Register method to actually save the data into the database.
#region Save Admin
public void SaveAdmin(UserRegister user, string passwordHash)
{
SqlConnection conn = null;
SqlCommand command = null;
int retValue;
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
command = conn.CreateCommand();
command.CommandText = "Sp_Add_Admin";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#Email", user.Email);
command.Parameters.AddWithValue("#PasswordHash", passwordHash);
command.Parameters.AddWithValue("#FirstName", user.FirstName);
command.Parameters.AddWithValue("#LastName", user.LastName);
command.Parameters.AddWithValue("#PhoneNumber", user.PhoneNumber);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
#endregion
My problem is that I have all the values of Register.cshtml (User Registration View) available on both the Register and SaveAdmin methods of the API except the phone number. I think I have some ambiguity in the model classes that I have created. I want the data to be stored in the database using a stored procedure I created.
When I run the code and the API is called, I am getting exception. Is there any one who can suggest me the best way to manage my code so that I can save the data into the database?

Adding reminder to event fails in Android

I have a method which adds an reminder to an event, but it fails:
FATAL EXCEPTION: main
android.database.sqlite.SQLiteException
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:184)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
at android.content.ContentResolver.insert(ContentResolver.java:864)
at de.appwege.droid.medwege.navigationdrawer.TerminFragment.insertReminder(TerminFragment.java:848)
The method in question:
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
What I am missing here? both eventID and minutes are defined...
Recently, I also faced same issue. Finally, I found the solution.
First of all, you have to find all logged in gmail id from the device and then select any one gmail account and find its calendar id. After that you have to pass that id to the event query like this....
values.put(Events.CALENDAR_ID, calendarId);
at last call you function
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD,
CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
See below method for finding email id's...
public static Hashtable listCalendarId(Context context) {
try {
if (haveCalendarReadWritePermissions((Activity) context)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()) {
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String, String> calendarIdTable = new Hashtable<>();
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName, calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Error updating Sharepoint List item, when called from web service

I'm using ajax to call a webservice which updates a sharepoint list.
It works when I call the code from unit tests, but running the code in a browser causes an exception:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
at Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context)
at Microsoft.SharePoint.SPContext.get_Current()
at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration, Boolean bPublish, Boolean bCheckOut, Boolean bCheckin, Guid newGuidOnAdd, Int32& ulID, Object& objAttachmentNames, Object& objAttachmentContents, Boolean suppressAfterEvents)
at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents)
at Microsoft.SharePoint.SPListItem.Update()
My code to update the list item is:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb(path))
{
SPList userProfile = web.Lists[userList];
SPQuery qry = new SPQuery
{
Query =
"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" +
accountName +
"</Value></Eq></Where><ViewFields><FieldRef Name='ID' /><FieldRef Name='Title' /><FieldRef Name='LastUpdated' /><FieldRef Name='Reason' /></ViewFields>"
};
SPListItemCollection spListItemCollection = userProfile.GetItems(qry);
if (spListItemCollection.Count == 1)
{
//edit user
SPListItem item = spListItemCollection[0];
item["Updated"] = DateTime.Now;
item["Reason"] = updateReason;
item.Update();
}
}
}
});
It errors on item.Update();
Try adding this:
HttpContext context = HttpContext.Current;
if (HttpContext.Current != null)
{
if (context.Items["HttpHandlerSPWeb"] == null)
context.Items["HttpHandlerSPWeb"] = site.RootWeb;
if (context.Items["Microsoft.Office.ServerContext"] == null)
context.Items["Microsoft.Office.ServerContext"] = ServerContext.GetContext(site);
}
The problem was with security. The following line needs to be added (although not ideal)
web.AllowUnsafeUpdates = true;
I also removed the line
SPSecurity.RunWithElevatedPrivileges(delegate()
and changed the SPSite and SPWeb to not use "using".

Resources