Pkcs11Exception: Method C_Initialize returned 2147483907 - hsm
I have a simply method to access my HSM with Pkcs11Interop.
This is the function:
static public byte[] findTargetKeySValue(String label, String type, string command)
{
try
{
string pkcs11LibraryPath = #"C:\Program Files\SafeNet\Protect Toolkit 5\Protect Toolkit C SDK\bin\hsm\cryptoki.dll";
Utility.Logger("cryptoki dll path " + pkcs11LibraryPath, command);
using (Pkcs11 pkcs11 = new Pkcs11(pkcs11LibraryPath, Inter_Settings.AppType))
{
// Find first slot with token present
Slot slot = Inter_Helpers.GetUsableSlot(pkcs11);
// Open RW session
using (Session session = slot.OpenSession(SessionType.ReadOnly))
{
// Login as normal user
session.Login(CKU.CKU_USER, Inter_Settings.NormalUserPin);
// Prepare attribute template that defines search criteria
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
if (type == "DES")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES));
else if (type == "DES2")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES2));
else if (type == "DES3")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, label));//PROVAK
List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
var key = foundObjects[0];
byte[] plainKeyValue = null;
List<ObjectAttribute> readAttrsSensitive = session.GetAttributeValue(key, new List<CKA>() { CKA.CKA_SENSITIVE });
if (!readAttrsSensitive[0].GetValueAsBool())
{
Utility.Logger("findTargetKeySValue chiave " + label + " non senstive", command);
List<ObjectAttribute> readAttrs = session.GetAttributeValue(key, new List<CKA>() { CKA.CKA_VALUE });
if (readAttrs[0].CannotBeRead)
throw new Exception("Key cannot be exported");
else
plainKeyValue = readAttrs[0].GetValueAsByteArray();
//Console.WriteLine(ByteArrayToAsciiHEX(plainKeyValue));
session.Logout();
return plainKeyValue;
}
else
{
Utility.Logger("findTargetKeySValue chiave " + label + " senstive", command);
Console.WriteLine("wrap/unwrap");
objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "WRAPPING_KEY")); //WRAPPING_KEY WRK
foundObjects = session.FindAllObjects(objectAttributes);
var wrappingKey = foundObjects[0];
Mechanism m = new Mechanism(CKM.CKM_DES3_ECB);
var wrapped = session.WrapKey(m, wrappingKey, key);
//Console.WriteLine("wrapped " + ByteArrayToAsciiHEX(wrapped));
//Console.WriteLine(ByteArrayToAsciiHEX(session.Decrypt(m, wrappingKey, wrapped)));
var k = session.Decrypt(m, wrappingKey, wrapped);
session.Logout();
return k;
}
}
}
}
catch (Exception e)
{
//Console.WriteLine(e.ToSafeString());
Utility.Logger("findTargetKeySValue " + e.ToSafeString(), command);
return null;
}
}
I have this method called within a socket server when it receives a call from the client.
To test it, I created a little program with a loop. In this loop, it sends about 3 requests every seconds to the server, which use Pkcs11Interop.
Let's call this tester program tester.exe. If I run tester.exe, everything seems to be ok. But, while the first tester.exe is running, I try to execute another instance of tester.exe, I get the error
Net.Pkcs11Interop.Common.Pkcs11Exception: Method C_Initialize returned 2147483907
in this specific line code:
using (Pkcs11 pkcs11 = new Pkcs11(pkcs11LibraryPath, Inter_Settings.AppType))
Why? Which is the problem?
UPDATE:
AppType is
public static AppType AppType = AppType.MultiThreaded;
and the settings init is:
static Inter_Settings()
{
if (AppType == AppType.MultiThreaded)
{
InitArgs40 = new LLA40.CK_C_INITIALIZE_ARGS();
InitArgs40.Flags = CKF.CKF_OS_LOCKING_OK;
InitArgs41 = new LLA41.CK_C_INITIALIZE_ARGS();
InitArgs41.Flags = CKF.CKF_OS_LOCKING_OK;
InitArgs80 = new LLA80.CK_C_INITIALIZE_ARGS();
InitArgs80.Flags = CKF.CKF_OS_LOCKING_OK;
InitArgs81 = new LLA81.CK_C_INITIALIZE_ARGS();
InitArgs81.Flags = CKF.CKF_OS_LOCKING_OK;
}
// Convert strings to byte arrays
SecurityOfficerPinArray = ConvertUtils.Utf8StringToBytes(SecurityOfficerPin);
NormalUserPinArray = ConvertUtils.Utf8StringToBytes(NormalUserPin);
ApplicationNameArray = ConvertUtils.Utf8StringToBytes(ApplicationName);
// Build PKCS#11 URI that identifies private key usable in signature creation tests
Pkcs11UriBuilder pkcs11UriBuilder = new Pkcs11UriBuilder();
pkcs11UriBuilder.ModulePath = Pkcs11LibraryPath;
pkcs11UriBuilder.Serial = TokenSerial;
pkcs11UriBuilder.Token = TokenLabel;
pkcs11UriBuilder.PinValue = NormalUserPin;
pkcs11UriBuilder.Type = CKO.CKO_PRIVATE_KEY;
pkcs11UriBuilder.Object = ApplicationName;
PrivateKeyUri = pkcs11UriBuilder.ToString();
}
UPDATE2:
public class InteropHSM
{
private Pkcs11 _pkcs11 = null;
private Slot _slot = null;
public InteropHSM()
{
string pkcs11LibraryPath = #"C:\Program Files\SafeNet\Protect Toolkit 5\Protect Toolkit C SDK\bin\hsm\cryptoki.dll";
_pkcs11 = new Pkcs11(pkcs11LibraryPath, Inter_Settings.AppType);
_slot = Inter_Helpers.GetUsableSlot(_pkcs11);
}
public byte[] findTargetKeySValue(String label, String type, string command)
{
try
{
//string pkcs11LibraryPath = #"C:\Program Files\SafeNet\Protect Toolkit 5\Protect Toolkit C SDK\bin\hsm\cryptoki.dll";
//Utility.Logger("cryptoki dll path " + pkcs11LibraryPath, command);
//using (Pkcs11 pkcs11 = new Pkcs11(pkcs11LibraryPath, Inter_Settings.AppType))
//{
//Slot slot = Inter_Helpers.GetUsableSlot(_pkcs11);
using (Session session = _slot.OpenSession(SessionType.ReadOnly))
{
// Login as normal user
session.Login(CKU.CKU_USER, Inter_Settings.NormalUserPin);
// Prepare attribute template that defines search criteria
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
if (type == "DES")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES));
else if (type == "DES2")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES2));
else if (type == "DES3")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, label));//PROVAK
List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
var key = foundObjects[0];
byte[] plainKeyValue = null;
List<ObjectAttribute> readAttrsSensitive = session.GetAttributeValue(key, new List<CKA>() { CKA.CKA_SENSITIVE });
if (!readAttrsSensitive[0].GetValueAsBool())
{
Utility.Logger("findTargetKeySValue chiave " + label + " non senstive", command);
List<ObjectAttribute> readAttrs = session.GetAttributeValue(key, new List<CKA>() { CKA.CKA_VALUE });
if (readAttrs[0].CannotBeRead)
throw new Exception("Key cannot be exported");
else
plainKeyValue = readAttrs[0].GetValueAsByteArray();
//Console.WriteLine(ByteArrayToAsciiHEX(plainKeyValue));
session.Logout();
return plainKeyValue;
}
else
{
Utility.Logger("findTargetKeySValue chiave " + label + " senstive", command);
Console.WriteLine("wrap/unwrap");
objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "WRAPPING_KEY")); //WRAPPING_KEY WRK
foundObjects = session.FindAllObjects(objectAttributes);
var wrappingKey = foundObjects[0];
Mechanism m = new Mechanism(CKM.CKM_DES3_ECB);
var wrapped = session.WrapKey(m, wrappingKey, key);
//Console.WriteLine("wrapped " + ByteArrayToAsciiHEX(wrapped));
Console.WriteLine(ByteArrayToAsciiHEX(session.Decrypt(m, wrappingKey, wrapped)));
var k = session.Decrypt(m, wrappingKey, wrapped);
session.Logout();
return k;
}
}
//}
}
catch (Exception e)
{
//Console.WriteLine(e.ToSafeString());
Utility.Logger("findTargetKeySValue " + e.ToSafeString(), command);
return null;
}
}
public static string ByteArrayToAsciiHEX(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-", "");
}
}
Every time is called, the server instance the class above and call the method findTargetKeySValue. If the server receive concurrent requests, it fails the HSM interaction... but I'm getting crazy, the session is different every time, like the specification saiys.
UPDATE3
Thread t = new Thread(() => ih.findTargetKeySValue(label, type, command));
t.Start();
Thread tt = new Thread(() => ih.findTargetKeySValue(label, type, command));
tt.Start();
Thread ttt = new Thread(() => ih.findTargetKeySValue(label, type, command));
ttt.Start();
Thread tttt = new Thread(() => ih.findTargetKeySValue(label, type, command));
tttt.Start();
Thread ttttt = new Thread(() => ih.findTargetKeySValue(label, type, command));
ttttt.Start();
I created this simple snippet to test multithread (findTargetKeySValue is defined above) and it crash with the message "Method C_Initialize returned 2147483907". This code is vendor defined and is CKR_CRYPTOKI_UNUSABLE. I will use this for the next tests.
UPDATE4:
I changed the code in
public InteropHSM()
{
string pkcs11LibraryPath = #"C:\Program Files\SafeNet\Protect Toolkit 5\Protect Toolkit C SDK\bin\hsm\cryptoki.dll";
_pkcs11 = new Pkcs11(pkcs11LibraryPath, Inter_Settings.AppType);
_slot = Inter_Helpers.GetUsableSlot(_pkcs11);
session = _slot.OpenSession(SessionType.ReadOnly);
session.Login(CKU.CKU_USER, Inter_Settings.NormalUserPin);
}
public byte[] findTargetKeySValue(String label, String type, string command)
{
try
{
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
if (type == "DES")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES));
else if (type == "DES2")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES2));
else if (type == "DES3")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, label));//PROVAK
List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
var key = foundObjects[0];
byte[] plainKeyValue = null;
List<ObjectAttribute> readAttrsSensitive = session.GetAttributeValue(key, new List<CKA>() { CKA.CKA_SENSITIVE });
if (!readAttrsSensitive[0].GetValueAsBool())
{
Utility.Logger("findTargetKeySValue chiave " + label + " non senstive", command);
List<ObjectAttribute> readAttrs = session.GetAttributeValue(key, new List<CKA>() { CKA.CKA_VALUE });
if (readAttrs[0].CannotBeRead)
throw new Exception("Key cannot be exported");
else
plainKeyValue = readAttrs[0].GetValueAsByteArray();
//Console.WriteLine(ByteArrayToAsciiHEX(plainKeyValue));
session.Logout();
Console.WriteLine(plainKeyValue);
return plainKeyValue;
}
else
{
Utility.Logger("findTargetKeySValue chiave " + label + " senstive", command);
Console.WriteLine("wrap/unwrap");
objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "WRAPPING_KEY")); //WRAPPING_KEY WRK
foundObjects = session.FindAllObjects(objectAttributes);
var wrappingKey = foundObjects[0];
Mechanism m = new Mechanism(CKM.CKM_DES3_ECB);
var wrapped = session.WrapKey(m, wrappingKey, key);
//Console.WriteLine("wrapped " + ByteArrayToAsciiHEX(wrapped));
Console.WriteLine(ByteArrayToAsciiHEX(session.Decrypt(m, wrappingKey, wrapped)));
var k = session.Decrypt(m, wrappingKey, wrapped);
//session.Logout();
return k;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToSafeString());
Utility.Logger("findTargetKeySValue " + e.ToSafeString(), command);
return null;
}
}
I call it with code from UPDATE3. I'm getting Method C_FindObjectsFinal returned CKR_OPERATION_NOT_INITIALIZED when the code calls
List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes);
You are not using PKCS#11 API correctly in multithreaded application. This is a known issue.
Short answer is that you need to ensure that:
you are using single instance of Pkcs11 class in your application (i.e. loaded during server startup and unloaded during its stop)
you are using new instance of Session class for each cryptographic operation
Long answer is that you need to read "Chapter 6 - General overview" of PKCS#11 v2.20 specification which explains all basic concepts of PKCS#11 API. After you finish this mandatory reading, you can take a look at Pkcs11RsaSignature class in Pkcs11Interop.PDF project for a working code sample of class that can be used in multithreaded environment.
This is how you can fix your code from example 4:
public InteropHSM()
{
string pkcs11LibraryPath = #"C:\Program Files\SafeNet\Protect Toolkit 5\Protect Toolkit C SDK\bin\hsm\cryptoki.dll";
_pkcs11 = new Pkcs11(pkcs11LibraryPath, Inter_Settings.AppType);
_slot = Inter_Helpers.GetUsableSlot(_pkcs11);
session = _slot.OpenSession(SessionType.ReadOnly);
session.Login(CKU.CKU_USER, Inter_Settings.NormalUserPin);
}
public byte[] findTargetKeySValue(String label, String type, string command)
{
try
{
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
if (type == "DES")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES));
else if (type == "DES2")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES2));
else if (type == "DES3")
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, label));//PROVAK
using (var session2 = _slot.OpenSession(SessionType.ReadOnly))
{
List<ObjectHandle> foundObjects = session2.FindAllObjects(objectAttributes);
var key = foundObjects[0];
byte[] plainKeyValue = null;
List<ObjectAttribute> readAttrsSensitive = session2.GetAttributeValue(key, new List<CKA>() { CKA.CKA_SENSITIVE });
if (!readAttrsSensitive[0].GetValueAsBool())
{
Utility.Logger("findTargetKeySValue chiave " + label + " non senstive", command);
List<ObjectAttribute> readAttrs = session2.GetAttributeValue(key, new List<CKA>() { CKA.CKA_VALUE });
if (readAttrs[0].CannotBeRead)
throw new Exception("Key cannot be exported");
else
plainKeyValue = readAttrs[0].GetValueAsByteArray();
Console.WriteLine(plainKeyValue);
return plainKeyValue;
}
else
{
Utility.Logger("findTargetKeySValue chiave " + label + " senstive", command);
Console.WriteLine("wrap/unwrap");
objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "WRAPPING_KEY")); //WRAPPING_KEY WRK
foundObjects = session2.FindAllObjects(objectAttributes);
var wrappingKey = foundObjects[0];
Mechanism m = new Mechanism(CKM.CKM_DES3_ECB);
var wrapped = session2.WrapKey(m, wrappingKey, key);
//Console.WriteLine("wrapped " + ByteArrayToAsciiHEX(wrapped));
Console.WriteLine(ByteArrayToAsciiHEX(session2.Decrypt(m, wrappingKey, wrapped)));
var k = session2.Decrypt(m, wrappingKey, wrapped);
return k;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToSafeString());
Utility.Logger("findTargetKeySValue " + e.ToSafeString(), command);
return null;
}
}
Related
System.Collections.Generic.List`1[System.String]" JSON error
I'm trying to use JSON and I was use PostMan to return Response this error happent System.Collections.Generic.List`1[System.String]"} public ActionResult SendVFCode(string Phone_Number) { var jsonSerialiser = new JavaScriptSerializer(); string error = ""; var SearchData =""; if (Phone_Number == null) { error = "Must enter your phone number"; } else if ( (db.PhoneNumbers.Select(x =>x.Id).Count() < 0) && (db.Assistant.Select(x =>x.Id).Count()) < 0) { error = "There are no data or your account is not activated"; } else { SearchData = db.PhoneNumbers.Include(x => x.Assistant) .Where(x => x.PhoneNumber == Phone_Number && x.Assistant.IsActive == true).Select(xx =>xx.PhoneNumber).ToList().ToString(); } json = new { err = error, ResultSearchData = SearchData }; return Content(jsonSerialiser.Serialize(json)); }
SearchData is not a string. Don't declare it as string and don't try to shove a string into it. It's a List (probably of type List<string> or whatever your Phonenumber type is). var SearchData ="" Should be: List<string> SearchData; And your database call should end in .ToList(), not .ToList().ToString().
Note that ToList() followed with ToString() returns fully-qualified name of the list instead of the list contents, hence you should use List<string> to hold result strings (also the list must be instantiated first before used inside if-block). The correct setup should be like this: public ActionResult SendVFCode(string Phone_Number) { var jsonSerialiser = new JavaScriptSerializer(); string error = ""; var SearchData = new List<string>(); // instantiate list of strings var phoneCount = db.PhoneNumbers.Select(x => x.Id).Count(); var assistantCount = db.Assistant.Select(x => x.Id).Count(); if (Phone_Number == null) { error = "Must enter your phone number"; } else if (phoneCount < 0 && assistantCount < 0) { error = "There are no data or your account is not activated"; } else { // assign list from query results SearchData = db.PhoneNumbers.Include(x => x.Assistant) .Where(x => x.PhoneNumber == Phone_Number && x.Assistant.IsActive == true) .Select(xx => xx.PhoneNumber).ToList(); } var json = new { err = error, ResultSearchData = SearchData }; return Content(jsonSerialiser.Serialize(json)); }
Smack - Request MAM faling
I'm using this code with ejabberd 15 and now is updated to 17.04 and now when I ask for MAM this just fails. private MamQueryResult queryArchive(MamQueryIQ mamQueryIq, long extraTimeout) throws NoResponseException, XMPPErrorException, NotConnectedException { if (extraTimeout < 0) { throw new IllegalArgumentException("extra timeout must be zero or positive"); } final XMPPConnection connection = connection(); MamFinExtension mamFinExtension; PacketCollector finMessageCollector = connection.createPacketCollector(new MamMessageFinFilter( mamQueryIq)); PacketCollector.Configuration resultCollectorConfiguration = PacketCollector.newConfiguration().setStanzaFilter( new MamMessageResultFilter(mamQueryIq)).setCollectorToReset( finMessageCollector); PacketCollector resultCollector = connection.createPacketCollector(resultCollectorConfiguration); try { //this line works fine. send and IQ and the response is received connection.createPacketCollectorAndSend(mamQueryIq).nextResultOrThrow(); //This line trigger an exceptions NoResponseException Message mamFinMessage = finMessageCollector.nextResultOrThrow(connection.getPacketReplyTimeout() + extraTimeout); mamFinExtension = MamFinExtension.from(mamFinMessage); } catch(Exception e) { Log.d(Constants.TAG_DEBUG, e.getMessage(), e); throw e; } finally { resultCollector.cancel(); finMessageCollector.cancel(); } List<Forwarded> messages = new ArrayList<>(resultCollector.getCollectedCount()); for (Message resultMessage = resultCollector.pollResult(); resultMessage != null; resultMessage = resultCollector.pollResult()) { // XEP-313 ยง 4.2 MamResultExtension mamResultExtension = MamResultExtension.from(resultMessage); messages.add(mamResultExtension.getForwarded()); } return new MamQueryResult(messages, mamFinExtension, DataForm.from(mamQueryIq)); }
POST data to web service HttpWebRequest Windows Phone 8
I've been trying without success today to adapt this example to POST data instead of the example GET that is provided. http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx I've replaced the line: request.Method = HttpMethod.Get; With request.Method = HttpMethod.Post; But can find no Method that will allow me to stream in the content I wish to POST. This HttpWebRequest seems a lot cleaner than other ways e.g. sending delegate functions to handle the response. In Mr Wigley's example code I can see POST so it must be possible public static class HttpMethod { public static string Head { get { return "HEAD"; } } public static string Post { get { return "POST"; } }
I wrote this class some time ago public class JsonSend<I, O> { bool _parseOutput; bool _throwExceptionOnFailure; public JsonSend() : this(true,true) { } public JsonSend(bool parseOutput, bool throwExceptionOnFailure) { _parseOutput = parseOutput; _throwExceptionOnFailure = throwExceptionOnFailure; } public async Task<O> DoPostRequest(string url, I input) { var client = new HttpClient(); CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]); client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName); var uri = new Uri(string.Format( url, "action", "post", DateTime.Now.Ticks )); string serialized = JsonConvert.SerializeObject(input); StringContent stringContent = new StringContent( serialized, Encoding.UTF8, "application/json"); var response = client.PostAsync(uri, stringContent); HttpResponseMessage x = await response; HttpContent requestContent = x.Content; string jsonContent = requestContent.ReadAsStringAsync().Result; if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure) { throw new Exception(url + " with POST ends with status code " + x.StatusCode + " and content " + jsonContent); } if (_parseOutput == false){ return default(O); } return JsonConvert.DeserializeObject<O>(jsonContent); } public async Task<O> DoPutRequest(string url, I input) { var client = new HttpClient(); CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]); client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName); var uri = new Uri(string.Format( url, "action", "put", DateTime.Now.Ticks )); string serializedObject = JsonConvert.SerializeObject(input); var response = client.PutAsync(uri, new StringContent( serializedObject, Encoding.UTF8, "application/json")); HttpResponseMessage x = await response; HttpContent requestContent = x.Content; string jsonContent = requestContent.ReadAsStringAsync().Result; if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure) { throw new Exception(url + " with PUT ends with status code " + x.StatusCode + " and content " + jsonContent); } if (_parseOutput == false){ return default(O); } return JsonConvert.DeserializeObject<O>(jsonContent); } } Then when I want to call it, I can use it as following : JsonSend<User, RegistrationReceived> register = new JsonSend<User, RegistrationReceived>(); RegistrationReceived responseUser = await register.DoPostRequest("http://myurl", user);
A first chance exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll
I am writing a windows phone 8 application. I am seeing the following error: A first chance exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll I have zoned the code that causes this error, but i am not able to fix it. Feel free to help me out here public void getTheWholeChapter(string startbooknum, string startchapter) { System.Uri uri = new Uri("http://api.seek-first.com/v1/BibleSearch.php?type=lookup&appid=seekfirst&startbooknum=" + startbooknum + "&startchapter=" + startchapter + "&startverse=1&endbooknum=" + startbooknum + "&endchapter=" + startchapter + "&endverse=5000000&version=KJV"); WebClient client = new WebClient(); OpenReadCompletedEventHandler orceh = new OpenReadCompletedEventHandler(GetTheData); client.OpenReadCompleted += orceh; client.OpenReadAsync(uri); } private void GetTheData(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { StreamReader reader = new StreamReader(e.Result); string stringXML = reader.ReadToEnd().ToString(); ListBox tb = new ListBox(); //tb.IsGroupingEnabled = true; //tb.HideEmptyGroups = true; //tb.LayoutMode = LongListSelectorLayoutMode.List; tb.FontSize = 25; List<TextBlock> listOfVerses = new List<TextBlock>(); //get the deatails from the if (stringXML != "" && stringXML != null) { XDocument root = XDocument.Parse("<Document>" + stringXML.Replace("></a>", "/></a>") + "</Document>"); var ResultsX = from Results in root.Descendants("Result") select Results; foreach (var Result in ResultsX) { listOfVerses.Add(new TextBlock() { Text = Result.Element("Chapter").Value + ":" + Result.Element("Verse").Value + " " + Result.Element("Text").Value, TextWrapping = TextWrapping.Wrap, }); } } tb.ItemsSource = listOfVerses; ((PivotItem)this.chaptersPivot.Items[chaptersPivot.SelectedIndex]).Content = tb; } else { //handle this } //throw new NotImplementedException(); }
AttachAll exception: type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly
Scenario: Trying to call the .AttachAll method on a table in my LinqToSql DataContext object. Here's the relevant simplified snippet: public void Update(Customer cust){ MyDataContext db = new MyDataContext(); db.CustomerInvoices.AttachAll(cust.Invoices); //exception raised here! db.Customer.Attach(cust); } Exception raised by the Compiler: The type arguments for method 'System.Data.Linq.Table(Invoices).AttachAll(TSubEntity)(System.Collections.Generic.IEnumerable(TSubEntity))' cannot be inferred from the usage. Try specifying the type arguments explicitly. Question: What is the proper way to cast the collection properly? Any other solutions besides a cast?
Tf cust.Invoices already refers to instances of the CustomerInvoices table, just doing db.Customers.Attach(cust); db.Update(); should be all you need to do. If CustomerInvoices is a different type from Customer.Invoice, you'll probably need to iterate through the collection, and cast each one.
else if (((CheckBox)item.Cells[2].FindControl("ckbSelect")).Checked == true && ((Label)item.Cells[2].FindControl("lblIsInuse")).Text == "1") { RolePage objTemp = new RolePage(); objTemp = new Helper().GetRolePagebyID(roleId, Convert.ToInt32(item.Cells[0].Text)); rp.RoleId = objTemp.RoleId; rp.PageId = objTemp.PageId; rp.RolePageId = objTemp.RolePageId; rp.CreatedOn = objTemp.CreatedOn; rp.Timestamp = objTemp.Timestamp; //rp.RoleId = roleId; //rp.PageId = Convert.ToInt32(item.Cells[0].Text); //rp.RolePageId =Convert.ToInt32(((Label)item.Cells[2].FindControl("lblRolePageId")).Text.Trim()); rp.IsNew = false; rp.IsDeleted = false; rp.UpdatedOn = DateTime.Now; erp.Add(rp); }
public string Save(Role objRole) { string message = string.Empty; System.Data.Common.DbTransaction trans = null; try { Objdb.Connection.Open(); trans = Objdb.Connection.BeginTransaction(); Objdb.Transaction = trans; if (objRole.RoleId == 0) { Objdb.Roles.InsertOnSubmit(objRole); } else { Objdb.Roles.Attach(objRole, true); Objdb.RolePages.AttachAll(objRole.RolePages.Where(a => a.IsNew == false && a.IsDeleted == false), true); Objdb.RolePages.InsertAllOnSubmit(objRole.RolePages.Where(a => a.IsNew == true && a.IsDeleted == false)); Objdb.RolePages.DeleteAllOnSubmit(objRole.RolePages.Where(a => a.IsNew == false && a.IsDeleted == true)); } Objdb.SubmitChanges(); trans.Commit(); message = "Record saved successfully."; } catch (Exception ex) { trans.Rollback(); message = "Error : " + ex.Message; } return message; }