EF - I can not assign values to foreign keys via Create - entity-framework

I'm a fairly green beginner (1 year training altogether) in C#.
My assignment was to create tables in a DB through Visual Studio 2010 - I did via EF. Now I want to write a simple Console program to fill those tables with values. In SQL MS they look right. In the last few lines of my code, I get the error msg that the CreateBestellung()-method only takes two arguments though. That'll be the two columns I created in this table. But how do I assign values to the foreign key fields? Couldn't find anything about this so far.
private static void bestellungAnlegen(playgroundEntities context)
{
Console.Clear();
Console.WriteLine("Neue Bestellung anlegen");
int kdId = -1;
int wrId = -1;
int anzahl = 0;
int id = -1;
// Validierung der Werte
do
{
Console.Write("Kunden ID: ");
if (int.TryParse(Console.ReadLine(), out kdId))
{
kdId = int.Parse(Console.ReadLine());
}
} while (kdId == -1);
do
{
Console.Write("Waren ID: ");
if (int.TryParse(Console.ReadLine(), out kdId))
{
kdId = int.Parse(Console.ReadLine());
}
} while (wrId == -1);
do
{
Console.Write("Anzahl: ");
if (int.TryParse(Console.ReadLine(), out anzahl))
{
if (anzahl >= 0)
{
anzahl = int.Parse(Console.ReadLine());
}
else anzahl = 0;
}
} while (anzahl == 0);
Bestellung neueBestellung =
Bestellung.CreateBestellung(id, anzahl, kdId, wrId);
context.Bestellungen.AddObject(neueBestellung);
}

This can only be a wild (but educated) guess. I think the method call should be
Bestellung neueBestellung = Bestellung.CreateBestellung(id, anzahl);
followed by
neueBestellung.kdId = kdId;
neueBestellung.wrId = wrId;

Related

Writing Test class for Currency Conversion Trigger

I need little assistance in writing a test class for this trigger that converts the record currency to org currency. Can anyone please assist/guide? Please.
trigger convertToEuro on CustomObject(before update) {
List<CurrencyType> currencyTypeList = [select id,IsoCode,ConversionRate from CurrencyType where isActive = true] ;
Map<String , Decimal> isoWithRateMap = new Map<String, Decimal>();
for(CurrencyType c : currencyTypeList) {
isoWithRateMap.put(c.IsoCode , c.ConversionRate) ;
}
for(CustomObject ce: trigger.new){
if(ce.CurrencyIsoCode != 'EUR' && isoWithRateMap.containsKey(ce.CurrencyIsoCode)){
ce.Amount_Converted__c = ce.ffps_iv__Amount__c/ isoWithRateMap.get(ce.CurrencyIsoCode);
}
}
}
#isTest(seealldata=false)
public class testConvertToEuro{
#testSetup
static void setupTest(){
List<CurrencyType> liCT = New List<CurrencyType>();
List<CustomObject> liCO = New List<CustomObject>();
Integer iCounter = 0;
liCT.add(new CurrencyType(IsoCode='EUR',ConversionRate=1,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='USD',ConversionRate=2,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='XXX',ConversionRate=3,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='YYY',ConversionRate=4,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='ZZZ',ConversionRate=5,isActive=TRUE));
for(Integer i=0; i<251; i++){
CustomObject co = New CustomObject(
CurrencyIsoCode = liCT[iCounter].IsoCode;
ffps_iv__Amount__c = liCT[iCounter].ConversionRate + .01;
);
if(iCounter < liCT.size() -1){
iCounter += 1;
}
else{
iCounter = 0;
}
}
insert liCT;
insert liCO;
}
static testmethod void runTest(){
setupTest();
List<CustomObject> liCustomObjectsToUpdate = New List<CustomObject>();
for(CustomObject co : [SELECT Id, ffps_iv__Amount__c, Amount_Converted__c from CustomObject]){
co.ffps_iv__Amount__c -= .01;
liCustomObjectsToUpdate.add(co);
}
test.startTest();
Update liCustomObjectsToUpdate;
test.stopTest();
System.assertEquals([SELECT Id, Amount_Converted__c FROM CustomObject LIMIT 1][0].Amount_Converted__c, 1);
}
}
I can't test this code without adding your custom object so it might have some errors. Please let me know what errors you are getting. If you want help debugging, you should provide the exact code being used and the exact error message.
It follows the basic pattern for testing update triggers:
Insert test data
Retrieve test data
Update records
Assert that the trigger generated the desired result

Dynamics CRM plugin -Pre Operation Update

I created a plug-in that calculates the pricing of the quote based on custom fields whenever update done on the quote entity.I executed the plugin on pre-opertaion update of the quote entity.I tried to debbug my plugin, it retrives null values.For example the value of the field "edm_CashAmount" contains 5000 but the code retrieved null. Kindly advise on the below. Thanks in advance.
namespace CRMPlugins.Plugins
{
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk.Messages;
public class PrequoteUpdate : Plugin
{
public PrequoteUpdate()
: base(typeof(PrequoteUpdate))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "quote", new Action<LocalPluginContext>(ExecutePrequoteUpdate)));
}
protected void ExecutePrequoteUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
Entity entity = null;
if (localContext.PluginExecutionContext.InputParameters.Contains("Target") && localContext.PluginExecutionContext.InputParameters["Target"] is Entity)
{
entity = (Entity)localContext.PluginExecutionContext.InputParameters["Target"];
}
else
{
return;
}
decimal instotal = 0;
Quote quote = entity.ToEntity<Quote>();
using (GeneratedEntities orgContext = new GeneratedEntities(localContext.OrganizationService))
{
var installements = (from b in orgContext.edm_installementSet
where b.GetAttributeValue<Guid>("edm_quote") == quote.QuoteId
select b);
foreach (var c in installements)
{
if (c.edm_Amount != null)
{
instotal += (decimal)c.new_Decimal;
}
}
}
decimal cash = 0;
if (quote.edm_CashAmount != null)
{
cash = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_cashamount").Value);
}
decimal check = 0;
if (quote.edm_CheckAmount != null)
{
check = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_checkamount").Value);
}
decimal credit = 0;
if (quote.edm_CreditCardAmount != null)
{
credit = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_creditcardamount").Value);
}
decimal gift = 0;
if (quote.new_GiftCard != null)
{
gift = Convert.ToDecimal(quote.GetAttributeValue<Money>("new_giftcard").Value);
}
decimal total = 0;
if (quote.TotalLineItemAmount != null)
{
total = Convert.ToDecimal(quote.GetAttributeValue<Money>("totallineitemamount").Value);
}
decimal currentbalane = 0;
if (quote.edm_CurrentBalane != null)
{
currentbalane = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_currentbalane").Value);
}
decimal DiscAmount = 0;
if (quote.DiscountAmount != null)
{
DiscAmount = Convert.ToDecimal(quote.GetAttributeValue<Money>("discountamount").Value);
}
decimal totalafterdiscount = total - DiscAmount;
decimal tax = (totalafterdiscount * 10) / 100;
decimal totalwithvat = totalafterdiscount + tax;
decimal paidamount = cash + check + credit + gift + instotal;
decimal remainingamount = totalwithvat - paidamount;
quote["edm_cashamount_1"] = new Money(tax);
quote["edm_totaltax"] = new Money(tax);
quote["edm_paidamount"] = new Money(paidamount);
quote["edm_remainingamount"] = new Money(remainingamount);
quote["edm_total"] = new Money(totalwithvat);
quote["edm_totalinstallements"] = new Money(instotal);
quote["edm_checkamount_1"] = new Money(totalwithvat);
}
}
}
for update plugins, if the value has not been changed then it will not appear in the target entity. Therefore you should create a pre entity image an include these values, or you can create a post entity image to see the state of the entity after the changes will be applied

android cardview only show the last result the right amount of times

i'm new to android and java.
i made a cardview and populated it with a simple loop like so:
private ArrayList<DataObject> getTheData(){
ArrayList res = new ArrayList<DataObject>();
for (int index = 0; index < 5; index++){
DataObject obj = new DataObject("shit","happen");
res.add(index,obj);
}
return res;
}
it worked. now i created a database and want to populate it with this data. so i have this:
public ArrayList<DataObject> getData() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList res = null;
try {
res = new ArrayList<DataObject>();
String selectQuery = "SELECT * FROM quotes a LEFT JOIN authors b ON b.author_id=a.quote_author";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Log.d("CHECKDB",cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")));
Log.d("CHECKDB2",cursor.getString(cursor.getColumnIndex("quote_text")));
DataObject obj = new DataObject(
cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")),
cursor.getString(cursor.getColumnIndex("quote_text"))
);
res.add(obj);
} while (cursor.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
return res;
}
the log show all the results, but when i run the app i get the last result the right amount of times. in this case 4 quotes in my database, so i see 4 but the last one 4 times.
please , since i'm new to it, good explanations will be appreciated.
the issue was that my dataobject attributes were set to static

Can I drag items from Outlook into my SWT application?

Background
Our Eclipse RCP 3.6-based application lets people drag files in for storage/processing. This works fine when the files are dragged from a filesystem, but not when people drag items (messages or attachments) directly from Outlook.
This appears to be because Outlook wants to feed our application the files via a FileGroupDescriptorW and FileContents, but SWT only includes a FileTransfer type. (In a FileTransfer, only the file paths are passed, with the assumption that the receiver can locate and read them. The FileGroupDescriptorW/FileContents approach can supply files directly application-to-application without writing temporary files out to disk.)
We have tried to produce a ByteArrayTransfer subclass that could accept FileGroupDescriptorW and FileContents. Based on some examples on the Web, we were able to receive and parse the FileGroupDescriptorW, which (as the name implies) describes the files available for transfer. (See code sketch below.) But we have been unable to accept the FileContents.
This seems to be because Outlook offers the FileContents data only as TYMED_ISTREAM or TYMED_ISTORAGE, but SWT only understands how to exchange data as TYMED_HGLOBAL. Of those, it appears that TYMED_ISTORAGE would be preferable, since it's not clear how TYMED_ISTREAM could provide access to multiple files' contents.
(We also have some concerns about SWT's desire to pick and convert only a single TransferData type, given that we need to process two, but we think we could probably hack around that in Java somehow: it seems that all the TransferDatas are available at other points of the process.)
Questions
Are we on the right track here? Has anyone managed to accept FileContents in SWT yet? Is there any chance that we could process the TYMED_ISTORAGE data without leaving Java (even if by creating a fragment-based patch to, or a derived version of, SWT), or would we have to build some new native support code too?
Relevant code snippets
Sketch code that extracts file names:
// THIS IS NOT PRODUCTION-QUALITY CODE - FOR ILLUSTRATION ONLY
final Transfer transfer = new ByteArrayTransfer() {
private final String[] typeNames = new String[] { "FileGroupDescriptorW", "FileContents" };
private final int[] typeIds = new int[] { registerType(typeNames[0]), registerType(typeNames[1]) };
#Override
protected String[] getTypeNames() {
return typeNames;
}
#Override
protected int[] getTypeIds() {
return typeIds;
}
#Override
protected Object nativeToJava(TransferData transferData) {
if (!isSupportedType(transferData))
return null;
final byte[] buffer = (byte[]) super.nativeToJava(transferData);
if (buffer == null)
return null;
try {
final DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer));
long count = 0;
for (int i = 0; i < 4; i++) {
count += in.readUnsignedByte() << i;
}
for (int i = 0; i < count; i++) {
final byte[] filenameBytes = new byte[260 * 2];
in.skipBytes(72); // probable architecture assumption(s) - may be wrong outside standard 32-bit Win XP
in.read(filenameBytes);
final String fileNameIncludingTrailingNulls = new String(filenameBytes, "UTF-16LE");
int stringLength = fileNameIncludingTrailingNulls.indexOf('\0');
if (stringLength == -1)
stringLength = 260;
final String fileName = fileNameIncludingTrailingNulls.substring(0, stringLength);
System.out.println("File " + i + ": " + fileName);
}
in.close();
return buffer;
}
catch (final Exception e) {
return null;
}
}
};
In the debugger, we see that ByteArrayTransfer's isSupportedType() ultimately returns false for the FileContents because the following test is not passed (since its tymed is TYMED_ISTREAM | TYMED_ISTORAGE):
if (format.cfFormat == types[i] &&
(format.dwAspect & COM.DVASPECT_CONTENT) == COM.DVASPECT_CONTENT &&
(format.tymed & COM.TYMED_HGLOBAL) == COM.TYMED_HGLOBAL )
return true;
This excerpt from org.eclipse.swt.internal.ole.win32.COM leaves us feeling less hope for an easy solution:
public static final int TYMED_HGLOBAL = 1;
//public static final int TYMED_ISTORAGE = 8;
//public static final int TYMED_ISTREAM = 4;
Thanks.
even if
//public static final int TYMED_ISTREAM = 4;
Try below code.. it should work
package com.nagarro.jsag.poc.swtdrag;
imports ...
public class MyTransfer extends ByteArrayTransfer {
private static int BYTES_COUNT = 592;
private static int SKIP_BYTES = 72;
private final String[] typeNames = new String[] { "FileGroupDescriptorW", "FileContents" };
private final int[] typeIds = new int[] { registerType(typeNames[0]), registerType(typeNames[1]) };
#Override
protected String[] getTypeNames() {
return typeNames;
}
#Override
protected int[] getTypeIds() {
return typeIds;
}
#Override
protected Object nativeToJava(TransferData transferData) {
String[] result = null;
if (!isSupportedType(transferData) || transferData.pIDataObject == 0)
return null;
IDataObject data = new IDataObject(transferData.pIDataObject);
data.AddRef();
// Check for descriptor format type
try {
FORMATETC formatetcFD = transferData.formatetc;
STGMEDIUM stgmediumFD = new STGMEDIUM();
stgmediumFD.tymed = COM.TYMED_HGLOBAL;
transferData.result = data.GetData(formatetcFD, stgmediumFD);
if (transferData.result == COM.S_OK) {
// Check for contents format type
long hMem = stgmediumFD.unionField;
long fileDiscriptorPtr = OS.GlobalLock(hMem);
int[] fileCount = new int[1];
try {
OS.MoveMemory(fileCount, fileDiscriptorPtr, 4);
fileDiscriptorPtr += 4;
result = new String[fileCount[0]];
for (int i = 0; i < fileCount[0]; i++) {
String fileName = handleFile(fileDiscriptorPtr, data);
System.out.println("FileName : = " + fileName);
result[i] = fileName;
fileDiscriptorPtr += BYTES_COUNT;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
OS.GlobalFree(hMem);
}
}
} finally {
data.Release();
}
return result;
}
private String handleFile(long fileDiscriptorPtr, IDataObject data) throws Exception {
// GetFileName
char[] fileNameChars = new char[OS.MAX_PATH];
byte[] fileNameBytes = new byte[OS.MAX_PATH];
COM.MoveMemory(fileNameBytes, fileDiscriptorPtr, BYTES_COUNT);
// Skip some bytes.
fileNameBytes = Arrays.copyOfRange(fileNameBytes, SKIP_BYTES, fileNameBytes.length);
String fileNameIncludingTrailingNulls = new String(fileNameBytes, "UTF-16LE");
fileNameChars = fileNameIncludingTrailingNulls.toCharArray();
StringBuilder builder = new StringBuilder(OS.MAX_PATH);
for (int i = 0; fileNameChars[i] != 0 && i < fileNameChars.length; i++) {
builder.append(fileNameChars[i]);
}
String name = builder.toString();
try {
File file = saveFileContent(name, data);
if (file != null) {
System.out.println("File Saved # " + file.getAbsolutePath());
;
}
} catch (IOException e) {
System.out.println("Count not save file content");
;
}
return name;
}
private File saveFileContent(String fileName, IDataObject data) throws IOException {
File file = null;
FORMATETC formatetc = new FORMATETC();
formatetc.cfFormat = typeIds[1];
formatetc.dwAspect = COM.DVASPECT_CONTENT;
formatetc.lindex = 0;
formatetc.tymed = 4; // content.
STGMEDIUM stgmedium = new STGMEDIUM();
stgmedium.tymed = 4;
if (data.GetData(formatetc, stgmedium) == COM.S_OK) {
file = new File(fileName);
IStream iStream = new IStream(stgmedium.unionField);
iStream.AddRef();
try (FileOutputStream outputStream = new FileOutputStream(file)) {
int increment = 1024 * 4;
long pv = COM.CoTaskMemAlloc(increment);
int[] pcbWritten = new int[1];
while (iStream.Read(pv, increment, pcbWritten) == COM.S_OK && pcbWritten[0] > 0) {
byte[] buffer = new byte[pcbWritten[0]];
OS.MoveMemory(buffer, pv, pcbWritten[0]);
outputStream.write(buffer);
}
COM.CoTaskMemFree(pv);
} finally {
iStream.Release();
}
return file;
} else {
return null;
}
}
}
Have you looked at https://bugs.eclipse.org/bugs/show_bug.cgi?id=132514 ?
Attached to this bugzilla entry is an patch (against an rather old version of SWT) that might be of interest.
I had the same problem and created a small library providing a Drag'n Drop Transfer Class for JAVA SWT. It can be found here:
https://github.com/HendrikHoetker/OutlookItemTransfer
Currently it supports dropping Mail Items from Outlook to your Java SWT application and will provide a list of OutlookItems with the Filename and a byte array of the file contents.
All is pure Java and in-memory (no temp files).
Usage in your SWT java application:
if (OutlookItemTransfer.getInstance().isSupportedType(event.currentDataType)) {
Object o = OutlookItemTransfer.getInstance().nativeToJava(event.currentDataType);
if (o != null && o instanceof OutlookMessage[]) {
OutlookMessage[] outlookMessages = (OutlookMessage[])o;
for (OutlookMessage msg: outlookMessages) {
//...
}
}
}
The OutlookItem will then provide two elements: filename as String and file contents as array of byte.
From here on, one could write it to a file or further process the byte array.
To your question above:
- What you find in the file descriptor is the filename of the outlook item and a pointer to an IDataObject
- the IDataObject can be parsed and will provide an IStorage object
- The IStorageObject will be then a root container providing further sub-IStorageObjects or IStreams similar to a filesystem (directory = IStorage, file = IStream
You find those elements in the following lines of code:
Get File Contents, see OutlookItemTransfer.java, method nativeToJava:
FORMATETC format = new FORMATETC();
format.cfFormat = getTypeIds()[1];
format.dwAspect = COM.DVASPECT_CONTENT;
format.lindex = <fileIndex>;
format.ptd = 0;
format.tymed = TYMED_ISTORAGE | TYMED_ISTREAM | COM.TYMED_HGLOBAL;
STGMEDIUM medium = new STGMEDIUM();
if (data.GetData(format, medium) == COM.S_OK) {
// medium.tymed will now contain TYMED_ISTORAGE
// in medium.unionfield you will find the root IStorage
}
Read the root IStorage, see CompoundStorage, method readOutlookStorage:
// open IStorage object
IStorage storage = new IStorage(pIStorage);
storage.AddRef();
// walk through the content of the IStorage object
long[] pEnumStorage = new long[1];
if (storage.EnumElements(0, 0, 0, pEnumStorage) == COM.S_OK) {
// get storage iterator
IEnumSTATSTG enumStorage = new IEnumSTATSTG(pEnumStorage[0]);
enumStorage.AddRef();
enumStorage.Reset();
// prepare statstg structure which tells about the object found by the iterator
long pSTATSTG = OS.GlobalAlloc(OS.GMEM_FIXED | OS.GMEM_ZEROINIT, STATSTG.sizeof);
int[] fetched = new int[1];
while (enumStorage.Next(1, pSTATSTG, fetched) == COM.S_OK && fetched[0] == 1) {
// get the description of the the object found
STATSTG statstg = new STATSTG();
COM.MoveMemory(statstg, pSTATSTG, STATSTG.sizeof);
// get the name of the object found
String name = readPWCSName(statstg);
// depending on type of object
switch (statstg.type) {
case COM.STGTY_STREAM: { // load an IStream (=File)
long[] pIStream = new long[1];
// get the pointer to the IStream
if (storage.OpenStream(name, 0, COM.STGM_DIRECT | COM.STGM_READ | COM.STGM_SHARE_EXCLUSIVE, 0, pIStream) == COM.S_OK) {
// load the IStream
}
}
case COM.STGTY_STORAGE: { // load an IStorage (=SubDirectory) - requires recursion to traverse the sub dies
}
}
}
}
// close the iterator
enumStorage.Release();
}
// close the IStorage object
storage.Release();

How to get latest files in C#

I have some files with same name but with different dates.
Basically we are finding the files with most recent dates
The file patterns are
<FileNames><YYYYMMDD><FileExtension>
e.g. test_20100506.xls indicates
<FileNames> = test_
<YYYYMMDD> = 20100506
<FileExtension> = .xls
Now in the source folder, the files are
standardization_20100503.xls,
standardization_20100504.xls,
standardization_20100305.xls,
replacement_20100505.xls
As can be seen that, standardization_.xls are 3 in numbers but
replacement_.xls is only 1.
The output will be a list of file names whose content will be
standardization_20100504.xls and replacement_20100505.xls
Because among all the standardization_.xls is the most recent one and replacement_.xls is also the same.
I have tried with my own logic but somehow failed.
My idea is as under
private static void GetLatestFiles(ref List<FileInfo> validFiles)
{
List<FileInfo> validFilesTemp = new List<FileInfo>();
for (int i = 0; i < validFiles.Count; i++)
{
for (int j = i+1; j < validFiles.Count; j++)
{
string getFileTextX = ExtractText(validFiles[i].Name);
string getFileTextY = ExtractText(validFiles[j].Name);
if (getFileTextX == getFileTextY)
{
int getFileDatesX = Convert.ToInt32(ExtractNumbers(validFiles[i].Name));
int getFileDatesY = Convert.ToInt32(ExtractNumbers(validFiles[j].Name));
if (getFileDatesX > getFileDatesY)
{
validFilesTemp.Add(validFiles[i]);
}
else
{
validFilesTemp.Add(validFiles[j]);
}
}
}
}
validFiles.Clear();
validFiles = validFilesTemp;
}
The ExtractNumbers is:
public static string ExtractNumbers(string expr)
{
return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
}
and the ExtractText is
public static string ExtractText(string expr)
{
return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[\\d]"));
}
I am using c#3.0 and framework 3.5
Use this regex to Get the date out of the full file name.
#"_([0-9]*)\."
Then Convert it to DateTime if you want as
DateTime dt;
dt = new DateTime();
dt = DateTime.ParseExact(MyString, "yyyyMMdd",null);
Use dt.CompareTo(dt1).Equals(1) to compare if the date is earlier or later.
class Program
{
static void Main()
{
var files =
from file in Directory.GetFiles(#"c:\somedirectory")
let name = Path.GetFileNameWithoutExtension(file)
let tokens = name.Split('_')
where tokens.Length > 1
let date = DateTime.ParseExact(tokens[1], "yyyyMMdd", CultureInfo.InvariantCulture)
orderby date descending
select file;
foreach (var item in files)
{
Console.WriteLine(item);
}
}
}