I have asked a previous question on SO with regards to the Sony Camera API and I did get some help but I am still having a problem. I found the following library https://github.com/kazyx/kz-remote-api that someone made to use with the Sony Camera API but I had to make changes to it to work with a WPF app as it was optimized for windows store apps.
I am now resorting to do everything myself but I am unsure if I need to attach a Camera API file to my solution and if I do where can I find the exact file because the one the API file that I downloaded only has files for Android and iOS in which won't help me.
I finally got my thing working and I tried to put it in such a manner so that it is easily understandable. If anyone would like my Sony Library that I wrote that please let me know as I also tried the Kazyx library and that didn't work for me.
My code is below.
private string cameraURL;
private bool recModeActive;
public void ControlCamera(string cameraResp)
{
cameraURL = string.Format("{0}/{1}", GetCameraURL(cameraResp), GetActionType(cameraResp));
}
private string CameraRequest(string cameraUrl, string cameraRequest)
{
Uri urlURI = new Uri(cameraURL);
HttpWebRequest cameraReq = (HttpWebRequest)WebRequest.Create(cameraURL);
cameraReq.Method = "POST";
cameraReq.AllowWriteStreamBuffering = false;
cameraReq.ContentType = "application/json; charset=utf-8";
cameraReq.Accept = "Accept-application/json";
cameraReq.ContentLength = cameraRequest.Length;
using (var cameraWrite = new StreamWriter(cameraReq.GetRequestStream()))
{
cameraWrite.Write(cameraRequest);
}
var cameraResp = (HttpWebResponse)cameraReq.GetResponse();
Stream cameraStream = cameraResp.GetResponseStream();
StreamReader cameraRead = new StreamReader(cameraStream);
string readCamera = cameraRead.ReadToEnd();
return readCamera;
}
public string GetCameraURL(string cameraResp)
{
string[] cameraXML = cameraResp.Split('\n');
string cameraURL = "";
foreach (string cameraString in cameraXML)
{
string getCameraURL = "";
if (cameraString.Contains("<av:X_ScalarWebAPI_ActionList_URL>"))
{
getCameraURL = cameraString.Substring(cameraString.IndexOf('>') + 1);
cameraURL = getCameraURL.Substring(0, getCameraURL.IndexOf('<'));
}
}
return cameraURL;
}
public string GetActionType(string cameraResp)
{
string[] cameraXML = cameraResp.Split('\n');
string actionType = "";
foreach (string cameraString in cameraXML)
{
string getType = "";
if (cameraString.Contains("<av:X_ScalarWebAPI_ServiceType>"))
{
getType = cameraString.Substring(cameraString.IndexOf('>') + 1);
actionType = getType.Substring(0, getType.IndexOf('<'));
if (actionType == "camera")
{
break;
}
}
}
return actionType;
}
public string StartRecMode()
{
string startRecMode = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "startRecMode",
#params = new List<string> { },
id = 1,
version = "1.0"
});
recModeActive = true;
return CameraRequest(cameraURL, startRecMode);
}
public string TriggerCamera()
{
string _triggerCamera = JsonConvert.SerializeObject(new Camera.StillCapture
{
method = "actTakePicture",
#params = new List<string> { },
id = 1,
version = "1.0"
});
return CameraRequest(cameraURL, _triggerCamera);
}
public string EchoRequest()
{
string _echoRequest = JsonConvert.SerializeObject(new Camera.TestCameraComm
{
method = "getEvent",
#params = new List<bool> { true },
id = 1,
version = "1.0"
});
return CameraRequest(cameraURL, _echoRequest);
}
public string StopRecMode()
{
string stopRecMode = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "stopRecMode",
#params = new List<string> { },
id = 1,
version = "1.0"
});
recModeActive = false;
return CameraRequest(cameraURL, stopRecMode);
}
public string SetImageQuality()
{
string qualityReq = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "setStillSize",
#params = new List<string> { "4:3", "20M"},
id = 1,
version = "1.0"
});
recModeActive = false;
return CameraRequest(cameraURL, qualityReq);
}`
Related
I need to get (not download) the content from 10.000~ manifest files within a project in Azure DevOps, but I don't manage to achieve this. I have found several ways to retrieve the content from one file at a time, but in this context, it is neither an efficient nor sustainable solution. I have managed to retrieve all files of a particular file type by checking if the file path ends with the name of the file, then using the TfvcHttpClientBase.GetItemsBatch method. However, this method does not return the item's content.
Program.cs
using Microsoft.TeamFoundation.SourceControl.WebApi;
AzureRest azureRest = new AzureRest();
var tfvcItems = azureRest.GetTfvcItems();
List<TfvcItemDescriptor> itemDescriptorsList = new List<TfvcItemDescriptor>();
foreach(var item in tfvcItems)
{
//Example manifest file .NET
if (item.Path.EndsWith("packages.config"))
{
var itemDescriptor = new TfvcItemDescriptor()
{
Path = item.Path,
RecursionLevel = VersionControlRecursionType.None,
Version = "",
VersionOption = TfvcVersionOption.None,
VersionType = TfvcVersionType.Latest
};
itemDescriptorsList.Add(itemDescriptor);
}
}
TfvcItemDescriptor[] itemDescriptorsArray = itemDescriptorsList.ToArray();
var itemBatch = azureRest.GetTfvcItemsBatch(itemDescriptorsArray);
foreach(var itemList in itemBatch)
{
foreach(var itemListList in itemList)
{
Console.WriteLine("Content: " + itemListList.Content); //empty/null
Console.WriteLine("ContentMetadata: " + itemListList.ContentMetadata); //not empty/null
}
}
AzureRest.cs
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
public class AzureRest
{
const string ORG_URL = "https://org/url/url";
const string PROJECT = "Project";
const string PAT = "PersonalAccessToken";
private string GetTokenConfig()
{
return PAT;
}
private string GetProjectNameConfig()
{
return PROJECT;
}
private VssConnection Authenticate()
{
string token = GetTokenConfig();
string projectName = GetProjectNameConfig();
var credentials = new VssBasicCredential(string.Empty, token);
var connection = new VssConnection(new Uri(ORG_URL), credentials);
return connection;
}
public List<TfvcItem> GetTfvcItems()
{
var connection = Authenticate();
using (TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>())
{
var tfvcItems = tfvcClient.GetItemsAsync(scopePath: "/Path", recursionLevel: VersionControlRecursionType.Full, true).Result;
return tfvcItems;
}
}
public List<List<TfvcItem>> GetTfvcItemsBatch(TfvcItemDescriptor[] itemDescriptors)
{
TfvcItemRequestData requestData = new TfvcItemRequestData()
{
IncludeContentMetadata = true,
IncludeLinks = true,
ItemDescriptors = itemDescriptors
};
var connection = Authenticate();
using (TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>())
{
var tfvcItems = tfvcClient.GetItemsBatchAsync(requestData).Result;
return tfvcItems;
}
}
}
}
For reference:
I have tested the codes you shared and when debugging at "itemDescriptorsList" and have found that there is no content specified in it, so that's why you cannot get the txt content.
You should first check and add the content property into the "itemDescriptorsList".
I'm trying to find executable files for games; however some are nested (For example Ark: Survival Evolved) (A:\Steam Games\steamapps\common\ARK\ShooterGame\Binaries\Win64\ShooterGame.exe)
I've spent ages trying to find a way to only find the executables which are relevant.
This link shows games when we don't search recursively. It finds most, but not all .exe's
This link shows games searching recursively, but also shows a bunch of binaries/redist exes.
Initially I tried excluding "bin","binary","binaries","redist" folders but that then didn't give me Ark: Survival Evolved for example.
I also considered filtering the .exe's based on their size, but Aperture Tag has a QC_Eyes.exe at 3055KB, but Tomb Raider II.exe is 892KB.
Here's the method I'm using to find the steam installation directory, and check the libraryfolders.vdf file for where the library locations are. For now I'm just writing to console so that I can see what the outputs are.
If anyone has any tips on how I can find the right files for the right games it would be much appreciated. Thanks
public void SearchSteam()
{
steamGameDirs.Clear();
string steam32 = "SOFTWARE\\VALVE\\";
string steam64 = "SOFTWARE\\Wow6432Node\\Valve\\";
string steam32path;
string steam64path;
string config32path;
string config64path;
RegistryKey key32 = Registry.LocalMachine.OpenSubKey(steam32);
RegistryKey key64 = Registry.LocalMachine.OpenSubKey(steam64);
foreach(string k32subKey in key32.GetSubKeyNames())
{
using (RegistryKey subKey = key32.OpenSubKey(k32subKey))
{
steam32path = subKey.GetValue("InstallPath").ToString();
config32path = steam32path + "/steamapps/libraryfolders.vdf";
if (File.Exists(config32path))
{
string[] configLines = File.ReadAllLines(config32path);
foreach(var item in configLines)
{
Console.WriteLine("32: " + item);
}
}
}
}
foreach(string k64subKey in key64.GetSubKeyNames())
{
using (RegistryKey subKey = key64.OpenSubKey(k64subKey))
{
steam64path = subKey.GetValue("InstallPath").ToString();
config64path = steam64path + "/steamapps/libraryfolders.vdf";
string driveRegex = #"[A-Z]:\\";
if (File.Exists(config64path))
{
string[] configLines = File.ReadAllLines(config64path);
foreach (var item in configLines)
{
Console.WriteLine("64: " + item);
Match match = Regex.Match(item, driveRegex);
if(item != string.Empty && match.Success)
{
string matched = match.ToString();
string item2 = item.Substring(item.IndexOf(matched));
item2 = item2.Replace("\\\\", "\\");
steamGameDirs.Add(item2);
}
}
steamGameDirs.Add(steam64path + "\\steamapps\\common\\");
}
}
}
foreach(string item in steamGameDirs)
{
string GameTitle;
string[] Executables = new string[0];
string[] steamGames = Directory.GetDirectories(item);
foreach (var dir in steamGames)
{
string title = dir.Substring(dir.IndexOf("\\common\\"));
string[] titlex = title.Split('\\');
title = titlex[2].ToString();
GameTitle = title;
Console.WriteLine("Title: " + GameTitle);
Console.WriteLine("Directory: " + dir);
string[] executables = Directory.GetFiles(dir, "*.exe", SearchOption.AllDirectories);
int num = 0;
foreach (var ex in executables)
{
//add "ex" to Executables[] if poss
Console.WriteLine(ex);
num++;
}
}
}
}
I've managed to do what I can, so first I detect where steam is installed through the registry, then I check /steamapps/libraryfolders.vdf for where the users libraries are, then check those libraries for any "top level" executables. The program then lets the user select their own exe if one isn't found in the top directory.
Seems like the best solution for now as the steamfiles module isn't currently active.
public void SearchSteam()
{
steamGameDirs.Clear();
string steam32 = "SOFTWARE\\VALVE\\";
string steam64 = "SOFTWARE\\Wow6432Node\\Valve\\";
string steam32path;
string steam64path;
string config32path;
string config64path;
RegistryKey key32 = Registry.LocalMachine.OpenSubKey(steam32);
RegistryKey key64 = Registry.LocalMachine.OpenSubKey(steam64);
if (key64.ToString() == null || key64.ToString() == "")
{
foreach (string k32subKey in key32.GetSubKeyNames())
{
using (RegistryKey subKey = key32.OpenSubKey(k32subKey))
{
steam32path = subKey.GetValue("InstallPath").ToString();
config32path = steam32path + "/steamapps/libraryfolders.vdf";
string driveRegex = #"[A-Z]:\\";
if (File.Exists(config32path))
{
string[] configLines = File.ReadAllLines(config32path);
foreach (var item in configLines)
{
Console.WriteLine("32: " + item);
Match match = Regex.Match(item, driveRegex);
if (item != string.Empty && match.Success)
{
string matched = match.ToString();
string item2 = item.Substring(item.IndexOf(matched));
item2 = item2.Replace("\\\\", "\\");
item2 = item2.Replace("\"", "\\steamapps\\common\\");
steamGameDirs.Add(item2);
}
}
steamGameDirs.Add(steam32path + "\\steamapps\\common\\");
}
}
}
}
foreach(string k64subKey in key64.GetSubKeyNames())
{
using (RegistryKey subKey = key64.OpenSubKey(k64subKey))
{
steam64path = subKey.GetValue("InstallPath").ToString();
config64path = steam64path + "/steamapps/libraryfolders.vdf";
string driveRegex = #"[A-Z]:\\";
if (File.Exists(config64path))
{
string[] configLines = File.ReadAllLines(config64path);
foreach (var item in configLines)
{
Console.WriteLine("64: " + item);
Match match = Regex.Match(item, driveRegex);
if(item != string.Empty && match.Success)
{
string matched = match.ToString();
string item2 = item.Substring(item.IndexOf(matched));
item2 = item2.Replace("\\\\", "\\");
item2 = item2.Replace("\"", "\\steamapps\\common\\");
steamGameDirs.Add(item2);
}
}
steamGameDirs.Add(steam64path + "\\steamapps\\common\\");
}
}
}
}
Attached the code so others can see how I've done it. I know it's not the best but it's working
The keydata seems to be in the appinfo.vdf file. So a somewhat working code to get the correct EXE file for steam games is as follows. Where the game is an EA game with a pointer to an URL or there is no data in the appinfo.vdf a fallback to your previous solution could be used. If anyone got a good parser of the appinfo.vdf the code would be better and not as hacky as the "IndexOf" solution.
GetSteamPath() in the below code can be updated to fetch from registry.
I am going to use that code to fix those petchy steam links that goes back to that anonymous globe-url icon.
(Written in .Net 5.0 - seems IndexOf for .4.7.2 is quirky. doesnt like \x00 I think)
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace SteamAppsParser
{
class Program
{
static void Main(string[] args)
{
var libs = GetSteamLibs();
var apps = GetSteamApps(libs);
}
static List<AppInfo> GetSteamApps(List<string> steamLibs)
{
var apps = new List<AppInfo>();
foreach (var lib in steamLibs)
{
var appMetaDataPath = Path.Combine(lib, "SteamApps");
var files = Directory.GetFiles(appMetaDataPath, "*.acf");
foreach (var file in files)
{
var appInfo = GetAppInfo(file);
if (appInfo != null)
{
apps.Add(appInfo);
}
}
}
return apps;
}
static AppInfo GetAppInfo(string appMetaFile)
{
var fileDataLines = File.ReadAllLines(appMetaFile);
var dic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var line in fileDataLines)
{
var match = Regex.Match(line, #"\s*""(?<key>\w+)""\s+""(?<val>.*)""");
if (match.Success)
{
var key = match.Groups["key"].Value;
var val = match.Groups["val"].Value;
dic[key] = val;
}
}
AppInfo appInfo = null;
if (dic.Keys.Count > 0)
{
appInfo = new AppInfo();
var appId = dic["appid"];
var name = dic["name"];
var installDir = dic["installDir"];
var path = Path.GetDirectoryName(appMetaFile);
var libGameRoot = Path.Combine(path, "common", installDir);
if (!Directory.Exists(libGameRoot)) return null;
appInfo.Id = appId;
appInfo.Name = name;
appInfo.Manifest = appMetaFile;
appInfo.GameRoot = libGameRoot;
appInfo.InstallDir = installDir;
appInfo.SteamUrl = $"steam://runsteamid/{appId}";
//if (appInfo.Name.StartsWith("Sid Meier"))
appInfo.Executable = GetExecutable(appInfo);
}
return appInfo;
}
static string _appInfoText = null;
static string GetExecutable(AppInfo appInfo)
{
if (_appInfoText == null)
{
var appInfoFile = Path.Combine(GetSteamPath(), "appcache", "appinfo.vdf");
var bytes = File.ReadAllBytes(appInfoFile);
_appInfoText = Encoding.UTF8.GetString(bytes);
}
var startIndex = 0;
int maxTries = 50;
var fullName = "";
do
{
var startOfDataArea = _appInfoText.IndexOf($"\x00\x01name\x00{appInfo.Name}\x00", startIndex);
if (startOfDataArea < 0 && maxTries == 50) startOfDataArea = _appInfoText.IndexOf($"\x00\x01gamedir\x00{appInfo.Name}\x00", startIndex); //Alternative1
if (startOfDataArea < 0 && maxTries == 50) startOfDataArea = _appInfoText.IndexOf($"\x00\x01name\x00{appInfo.Name}\x00", startIndex); //Alternative2
if (startOfDataArea > 0)
{
startIndex = startOfDataArea + 10;
int nextLaunch = -1;
do
{
var executable = _appInfoText.IndexOf($"\x00\x01executable\x00", startOfDataArea);
if (executable>-1 && nextLaunch == -1)
{
nextLaunch = _appInfoText.IndexOf($"\x00\x01launch\x00", executable);
}
if ((nextLaunch <= 0 || executable < nextLaunch) && executable > 0)
{
if (executable > 0)
{
executable += 10;
string filename = "";
while (_appInfoText[executable] != '\x00')
{
filename += _appInfoText[executable];
executable++;
}
if (filename.Contains("://"))
{
//EA or other external
return filename; //Need to use other means to grab the EXE here.
}
fullName = Path.Combine(appInfo.GameRoot, filename);
startOfDataArea = executable + 1;
startIndex = startOfDataArea + 10;
}
}
else
{
break;
}
}
while (!File.Exists(fullName) && maxTries-- > 0);
}
else
{
return null;
}
} while (!File.Exists(fullName) && maxTries-- > 0);
if (File.Exists(fullName)) return fullName;
return null;
}
static List<string> GetSteamLibs()
{
var steamPath = GetSteamPath();
var libraries = new List<string>() { steamPath };
var listFile = Path.Combine(steamPath, #"steamapps\libraryfolders.vdf");
var lines = File.ReadAllLines(listFile);
foreach (var line in lines)
{
var match = Regex.Match(line, #"""(?<path>\w:\\\\.*)""");
if (match.Success)
{
var path = match.Groups["path"].Value.Replace(#"\\", #"\");
if (Directory.Exists(path))
{
libraries.Add(path);
}
}
}
return libraries;
}
static string GetSteamPath()
{
return #"C:\Spill\Steam";
}
class AppInfo
{
public string Id { get; internal set; }
public string Name { get; internal set; }
public string SteamUrl { get; internal set; }
public string Manifest { get; internal set; }
public string GameRoot { get; internal set; }
public string Executable { get; internal set; }
public string InstallDir { get; internal set; }
public override string ToString()
{
return $"{Name} ({Id}) - {SteamUrl} - {Executable}";
}
}
}
}
I have used json code to call the controller/action method and convert the json format inside the project,everything worked in my localhost and my server which i had, but it was not working in some other server like US server, I don't know why it throws.
Is it cause Network or IIS confirguration or code issue? If Firewall or port issue means how to change their settings?
I have attached the code which I tried,
Class :
public class Jsonget
{
public static string jsonconvert(string url)
{
string currentsite = HttpContext.Current.Request.Url.Authority;
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
wc.Encoding = UTF8Encoding.UTF8;
var uri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);
var requestType = uri.Scheme;
string jsonurl = requestType + "://" + currentsite + url;
var jsondata = wc.DownloadString(jsonurl);
string jsonresult = "{\"results\":" + jsondata.ToString() + "}";
return jsonresult;
}
}
Index.cshtml:
jsonurl = Url.Action("GetallPrograms", "Admin", new { Name = "testprogram" });
getjsonresult = Jsonget.jsonconvert(jsonurl);
Newtonsoft.Json.Linq.JObject programList = Newtonsoft.Json.Linq.JObject.Parse(getjsonresult);
foreach (var pgm in programList["results"])
{
<p>#((string)pgm["ProgramName"])</p>
}
AdminController:
public JsonResult GetallPrograms(string Name)
{
var programList = new List<CustomAttribute>();
BaseController bc = new BaseController();
try
{
var Exist_programs = (from n in bc.db.Programs where n.Name == Name select n).ToList();
foreach (var exist in Exist_programs)
{
programList.Add(new CustomAttribute
{
ProgramName = exist.ProgramName,
Id = exist.Id.ToString()
});
}
}
catch
{
programList.Add(new CustomAttribute
{
ProgramName ="",
Id = ""
});
}
return Json(programList, JsonRequestBehavior.AllowGet);
}
Please give suggestion to fix this?
I am rather new to the whole programming with C# and I stumbled upon a small problem that I just cannot solve.
I start up the software the code below is programmed into and it is working well until it reaches the SaveChanges call and it throws an error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I have already attempted to inspect EntityValidationErrors, but it doesn't want to show me any errors at all. So I am turning to you all to find some answers.
//
// GET: /Installningar/FoxImportTidning
public async Task<ActionResult> FoxImportTidning()
{
Tidning tidning = new Tidning();
SaveTidningToDatabase("C:/Backup/Prenback/backuptidning.xls");
return View();
}
//
// POST: /Installningar/FoxImportTidning
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FoxImportTidning(Tidning Id)
{
if (ModelState.IsValid)
{
db.Entry(Id).State = EntityState.Modified;
await db.SaveChangesAsync();
Main.PopulateGlobalInst();
ViewBag.SaveMsg = "Sparat!";
return RedirectToAction("Main", "Main", new { Id = Id.Id });
}
return View(Id);
}
private ApplicationDbContext databas6 = new ApplicationDbContext();
private string SaveTidningToDatabase(string filePath)
{
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
using (OleDbCommand cmd = new OleDbCommand("Select * from [backuptidning$]", excelConnection))
{
excelConnection.Open();
var tidningLista = new List<Tidning>();
databas6.Tidnings.Clear();
databas6.SaveChanges();
using (OleDbDataReader dReader = cmd.ExecuteReader())
do
{
while (dReader.Read())
{
Object[] tidninginfo = new Object[45];
int id = Convert.ToInt32(dReader[0]);
string namn = Convert.ToString(dReader[1]);
string datadir = Convert.ToString(dReader[2]);
string adr1 = Convert.ToString(dReader[3]);
string adr2 = Convert.ToString(dReader[4]);
string regnr = Convert.ToString(dReader[5]);
string tel = Convert.ToString(dReader[6]);
string pg = Convert.ToString(dReader[7]);
string bg = Convert.ToString(dReader[8]);
string villkor = Convert.ToString(dReader[9]);
int sista_nr = Convert.ToInt32(dReader[10]);
int faktavg = Convert.ToInt32(dReader[11]);
int vilande = Convert.ToInt32(dReader[12]);
int listlopnr = Convert.ToInt32(dReader[13]);
int faktnr = Convert.ToInt32(dReader[14]);
decimal moms = Convert.ToDecimal(dReader[15]);
int avipriskod = Convert.ToInt32(dReader[16]);
DateTime? inbetdat = null;
try
{
inbetdat = Convert.ToDateTime(dReader[17]);
}
catch { }
int period = Convert.ToInt32(dReader[18]);
string avityp = Convert.ToString(dReader[19]);
DateTime? sistavidat = null;
try
{
sistavidat = Convert.ToDateTime(dReader[20]);
}
catch { }
DateTime? fromdatum = null;
try
{
fromdatum = Convert.ToDateTime(dReader[21]);
}
catch { }
DateTime? tomdatum = null;
try
{
tomdatum = Convert.ToDateTime(dReader[22]);
}
catch { }
int fromprennr = Convert.ToInt32(dReader[23]);
int tomprennr = Convert.ToInt32(dReader[24]);
string databasversion = Convert.ToString(dReader[25]);
int nummerperiod = Convert.ToInt32(dReader[26]);
int nolastyear = Convert.ToInt32(dReader[27]);
int nonextyear = Convert.ToInt32(dReader[28]);
string dubbelnummer = Convert.ToString(dReader[29]);
bool skrivetik = Convert.ToBoolean(dReader[30]);
bool utrmomsavdrag = Convert.ToBoolean(dReader[31]);
bool buntning = Convert.ToBoolean(dReader[32]);
int pren = Convert.ToInt32(dReader[33]);
int betalare = Convert.ToInt32(dReader[34]);
int kredit = Convert.ToInt32(dReader[35]);
int fornyanr = Convert.ToInt32(dReader[36]);
string landskod = Convert.ToString(dReader[37]);
DateTime? nästsist = null;
try
{
nästsist = Convert.ToDateTime(dReader[38]);
}
catch { }
string fax = Convert.ToString(dReader[39]);
string epost = Convert.ToString(dReader[40]);
string hemsida = Convert.ToString(dReader[41]);
string bic = Convert.ToString(dReader[42]);
string iban = Convert.ToString(dReader[43]);
string faktkoll = Convert.ToString(dReader[44]);
var tidning = new Tidning();
tidning.Id = id;
tidning.Namn = namn;
tidning.Datadir = datadir;
tidning.Adr1 = adr1;
tidning.Adr2 = adr2;
tidning.Regnr = regnr;
tidning.Tel = tel;
tidning.Pg = pg;
tidning.Bg = bg;
tidning.Villkor = villkor;
tidning.Sista_nr = sista_nr;
tidning.FaktAvg = faktavg;
tidning.Vilande = vilande;
tidning.Listlopnr = listlopnr;
tidning.Faktnr = faktnr;
tidning.Moms = moms;
tidning.AviPriskod = avipriskod;
tidning.InbetDatum = inbetdat;
tidning.Period = period;
tidning.AviTyp = (AviTyp)Enum.Parse(typeof(AviTyp), avityp, true);
tidning.SistAviDatum = sistavidat;
tidning.FromDatum = fromdatum;
tidning.TomDatum = tomdatum;
tidning.FromPrennr = fromprennr;
tidning.TomPrennr = tomprennr;
tidning.Databasversion = databasversion;
tidning.Nummerperiod = nummerperiod;
tidning.Nolastyear = nolastyear;
tidning.Nonextyear = nonextyear;
tidning.Dubbelnummer = dubbelnummer;
tidning.Skrivetik = skrivetik;
tidning.Utrmomsavdrag = utrmomsavdrag;
tidning.Buntning = buntning;
tidning.Pren = pren;
tidning.Betalare = betalare;
tidning.Kredit = kredit;
tidning.Fornyanr = fornyanr;
tidning.Landskod = landskod;
tidning.NastSist = nästsist;
tidning.Fax = fax;
tidning.Epost = epost;
tidning.Hemsida = hemsida;
tidning.Bic = bic;
tidning.Iban = iban;
tidning.Faktkoll = faktkoll;
tidningLista.Add(tidning);
}
} while (dReader.NextResult());
databas6.Tidnings.AddRange(tidningLista);
databas6.SaveChanges(); //<--- This is where it goes wrong
excelConnection.Close();
return ("hej"); //<--- Do not mind this one
}
}
}
If you need any further information, just tell me and I will provide it. The main thing I want is to get this working and this is not the only code giving me this problem, but if this one can be solved, then maybe the other ones can be solved the same way.
This error is caused when you are trying to add invalid data to your database table.
e.g. you are adding string of 100 chars to the table column but in table definition your column has maxlength of 50. in that case value you are adding is invalid as per the column definitions and this error occur.
you should log what properties are causing the error. for that you can use below code:
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
throw;
}
You can catch these errors easily ,using the watch window, without writing much code.
Kindly find the very good solution in the following link
https://stackoverflow.com/a/40732784/3397630
I really inspired in the way that answer was given, with the very good screenshots . Sharing it here with the hope it will be helpful to you and the others.
thanks
KArthik
I'm trying to access Amazon MWS API from my .Net application, using Products API Section Client Library - C# (https://developer.amazonservices.com/doc/products/products/v20111001/cSharp.html/138-8219342-3408216)
Everything works fine, except for GetMyFeesEstimate calls.
I use this method from example:
public GetMyFeesEstimateResponse InvokeGetMyFeesEstimate()
{
// Create a request.
GetMyFeesEstimateRequest request = new GetMyFeesEstimateRequest();
string sellerId = "example";
request.SellerId = sellerId;
string mwsAuthToken = "example";
request.MWSAuthToken = mwsAuthToken;
FeesEstimateRequestList feesEstimateRequestList = new FeesEstimateRequestList();
request.FeesEstimateRequestList = feesEstimateRequestList;
return this.client.GetMyFeesEstimate(request);
}
And I add item to FeesEstimateRequestList like this:
feesEstimateRequestList.FeesEstimateRequest.Add(new FeesEstimateRequest
{
MarketplaceId = marketplaceId,
IdType = "ASIN",
IdValue = "B0078LENZC",
PriceToEstimateFees = new PriceToEstimateFees { ListingPrice = new MoneyType { Amount = 30.49M, CurrencyCode = "GBP" }, Shipping = new MoneyType { Amount = 3.5M, CurrencyCode = "GBP" }, Points = new Points { PointsNumber = 0 } },
Identifier = "request_" + Guid.NewGuid().ToString(),
IsAmazonFulfilled = false
});
But constantly get MalformedInput error with no message describing what is wrong:
<ErrorResponse
xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<Error>
<Type>Sender</Type>
<Code>MalformedInput</Code>
</Error>
<RequestId>f79b9147-90d7-4ea2-b51c-d6c37c6a1bd0</RequestId>
</ErrorResponse>
Have someone any ideas how to make it work?
I have found solution:
Due to my OS regional settings, decimal separator in price had being set to comma, instead of dot when converting parameters to string.
I have to modify method putValue of MwsAQCall class like this:
private void putValue(object value)
{
if (value==null)
{
return;
}
if (value is IMwsObject)
{
parameterPrefix.Append('.');
(value as IMwsObject).WriteFragmentTo(this);
return;
}
string name = parameterPrefix.ToString();
if (value is DateTime)
{
parameters.Add(name, MwsUtil.GetFormattedTimestamp((DateTime)value));
return;
}
string valueStr = value.ToString();
if (value is decimal)
{
valueStr = valueStr.Replace(",", ".");
}
if (valueStr==null || valueStr.Length==0)
{
return;
}
if (value is bool)
{
valueStr = valueStr.ToLower();
}
parameters.Add(name, valueStr);
}