Search Results

Search found 37183 results on 1488 pages for 'string conversion'.

Page 56/1488 | < Previous Page | 52 53 54 55 56 57 58 59 60 61 62 63  | Next Page >

  • String.substring(index) has stoped my thread in debug mode.

    - by Arkaha
    Hello! I work with j2me polish 2.0.7, in eclipse 3.4.2, with wtk2.5.2_01. I create control which draws text: normal, bold, and italic. The code below is parsing raw text, and search for * and _ symbols, if found than add to draw vector the text and the drawer, and it's just stops after getting second time to the line 58: String test = new String(raw_text_buff.substring(iter)); it stops in raw_text_buff.substring(iter), ONLY in debug mode.. raw text is: bla bla bla *1000* bla bla Full code: private String raw_text = "bla bla bla *1000* bla bla"; Vector draw_items = null; private void prepareText() { char open_char = 0; int open_pos = 0; Object []param = null; StringBuffer sb = new StringBuffer(); String raw_text_buff = new String(raw_text); int iter = 0; boolean was_reset = false; while(true) { char c = raw_text_buff.charAt(iter); if(iter == raw_text_buff.length() || c == '*' || c == '_') { if(sb.length() > 0) { BmFont viewer = null; String str = sb.toString(); if(open_char == '*' && null != bm_strong) { viewer = bm_strong.getViewer(str); }else if(open_char == '_' && null != bm_italic) { viewer = bm_italic.getViewer(str); }else if(null != bm_normal) { viewer = bm_normal.getViewer(str); }else { } param = new Object[2]; param[0] = str; param[1] = viewer; if(null == draw_items) draw_items = new Vector(); draw_items.addElement(param); sb = new StringBuffer(); if(open_char == 0 && (c == '*' || c=='_')) open_char = c; else open_char = 0; String test = new String(raw_text_buff.substring(iter)); // stucks here. raw_text_buff = test; iter = 0; was_reset = true; }else { open_char = c; } if(iter == raw_text_buff.length()) break; }else { sb.append(c); } ++iter; } } What I'm doing wrong?

    Read the article

  • Basic Custom String Class for C++

    - by wdow88
    Hey all, I'm working on building my own string class with very basic functionality. I am having difficulty understand what is going on with the basic class that I have define, and believe there is some sort of error dealing with the scope occurring. When I try to view the objects I created, all the fields are described as (obviously bad pointer). Also, if I make the data fields public or build an accessor method, the program crashes. For some reason the pointer for the object is 0xccccccccc which points to no where. How can a I fix this? Any help/comments are much appreciated. //This is a custom string class, so far the only functions are //constructing and appending #include<iostream> using namespace std; class MyString1 { public: MyString1() { //no arg constructor char *string; string = new char[0]; string[0] ='\0'; std::cout << string; size = 1; } //constructor receives pointer to character array MyString1(char* chars) { int index = 0; //Determine the length of the array while (chars[index] != NULL) index++; //Allocate dynamic memory on the heap char *string; string = new char[index+1]; //Copy the contents of the array pointed by chars into string, the char array of the object for (int ii = 0; ii < index; ii++) string[ii] = chars[ii]; string[index+1] = '\0'; size = index+1; } MyString1 append(MyString1 s) { //determine new size of the appended array and allocate memory int newsize = s.size + size; MyString1 MyString2; char *newstring; newstring = new char[newsize+1]; int index = 0; //load the first string into the array while (string[index] != NULL) { newstring[index] = string[index]; index++; } //load the second string while (s.string[index] != NULL) { newstring[index] = s.string[index]; index++; } //null terminate newstring[newsize+1] = '\0'; delete string; //generate the object for return MyString2.string=newstring; MyString2.size=newsize; return MyString2; } private: char *string; int size; }; int main() { MyString1 string1; MyString1 string2("Hello There"); MyString1 string3("Buddy"); string2.append(string3); return 0; }

    Read the article

  • How to read and write a STL C++ string?

    - by cambr
    #include<string> ... string in; //How do I store a string from stdin to in? // //gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to //char* gets (char*)' // //scanf("%s",in) also gives some weird error Similarly, how do I write out in to stdout or to a file??

    Read the article

  • How can I determine if a composite format string is invalid?

    - by Tinister
    Per the documentation, String.Format will throw a FormatException if either (A) the format string is invalid or (B) the format string contains an index that cannot be found in the args array. I want to be able to determine which (if either) of those conditions fail on any arbitrary string and array of arguments. Is there anything that can do that for me? Thanks!

    Read the article

  • ASP.NET MVC2 Implementing Custom RoleManager problem

    - by ile
    To create a custom membership provider I followed these instructions: http://stackoverflow.com/questions/2771094/asp-net-mvc2-custom-membership and these: http://mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx So far, I've managed to implement custom membership provider and that part works fine. RoleManager still needs some modifications... Project structure: SAMembershipProvider.cs: public class SAMembershipProvider : MembershipProvider { #region - Properties - private int NewPasswordLength { get; set; } private string ConnectionString { get; set; } public bool enablePasswordReset { get; set; } public bool enablePasswordRetrieval { get; set; } public bool requiresQuestionAndAnswer { get; set; } public bool requiresUniqueEmail { get; set; } public int maxInvalidPasswordAttempts { get; set; } public int passwordAttemptWindow { get; set; } public MembershipPasswordFormat passwordFormat { get; set; } public int minRequiredNonAlphanumericCharacters { get; set; } public int minRequiredPasswordLength { get; set; } public string passwordStrengthRegularExpression { get; set; } public override string ApplicationName { get; set; } public override bool EnablePasswordRetrieval { get { return enablePasswordRetrieval; } } public override bool EnablePasswordReset { get { return enablePasswordReset; } } public override bool RequiresQuestionAndAnswer { get { return requiresQuestionAndAnswer; } } public override int MaxInvalidPasswordAttempts { get { return maxInvalidPasswordAttempts; } } public override int PasswordAttemptWindow { get { return passwordAttemptWindow; } } public override bool RequiresUniqueEmail { get { return requiresUniqueEmail; } } public override MembershipPasswordFormat PasswordFormat { get { return passwordFormat; } } public override int MinRequiredPasswordLength { get { return minRequiredPasswordLength; } } public override int MinRequiredNonAlphanumericCharacters { get { return minRequiredNonAlphanumericCharacters; } } public override string PasswordStrengthRegularExpression { get { return passwordStrengthRegularExpression; } } #endregion #region - Methods - public override void Initialize(string name, NameValueCollection config) { throw new NotImplementedException(); } public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); } public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new NotImplementedException(); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); } public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); } public override MembershipUser GetUser(string username, bool userIsOnline) { throw new NotImplementedException(); } public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); } protected override void OnValidatingPassword(ValidatePasswordEventArgs e) { base.OnValidatingPassword(e); } public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); } public override bool UnlockUser(string userName) { throw new NotImplementedException(); } public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } public override bool ValidateUser(string username, string password) { AccountRepository accountRepository = new AccountRepository(); var user = accountRepository.GetUser(username); if (string.IsNullOrEmpty(password.Trim())) return false; if (user == null) return false; //string hash = EncryptPassword(password); var email = user.Email; var pass = user.Password; if (user == null) return false; if (pass == password) { //User = user; return true; } return false; } #endregion protected string EncryptPassword(string password) { //we use codepage 1252 because that is what sql server uses byte[] pwdBytes = Encoding.GetEncoding(1252).GetBytes(password); byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(pwdBytes); return Encoding.GetEncoding(1252).GetString(hashBytes); } } SARoleProvider.cs public class SARoleProvider : RoleProvider { AccountRepository accountRepository = new AccountRepository(); public override bool IsUserInRole(string username, string roleName) { return true; } public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { int rolesCount = 0; IQueryable<RoleViewModel> rolesNames; try { // get roles for this user from DB... rolesNames = accountRepository.GetRolesForUser(username); rolesCount = rolesNames.Count(); } catch (Exception ex) { throw ex; } string[] roles = new string[rolesCount]; int counter = 0; foreach (var item in rolesNames) { roles[counter] = item.RoleName.ToString(); counter++; } return roles; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } } AccountRepository.cs public class RoleViewModel { public string RoleName { get; set; } } public class AccountRepository { private DB db = new DB(); public User GetUser(string email) { return db.Users.SingleOrDefault(d => d.Email == email); } public IQueryable<RoleViewModel> GetRolesForUser(string email) { var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID where user.Email == email select new RoleViewModel { RoleName = role.Name }); return result; } } webconfig <membership defaultProvider="SAMembershipProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="SAMembershipProvider" type="SA_Contacts.Membership.SAMembershipProvider, SA_Contacts" connectionStringName ="ShinyAntConnectionString" /> </providers> </membership> <roleManager defaultProvider="SARoleProvider" enabled="true" cacheRolesInCookie="true"> <providers> <clear/> <add name="SARoleProvider" type="SA_Contacts.Membership.SARoleProvider" connectionStringName ="ShinyAntConnectionString" /> </providers> </roleManager> AccountController.cs: public class AccountController : Controller { SAMembershipProvider provider = new SAMembershipProvider(); AccountRepository accountRepository = new AccountRepository(); public AccountController() { } public ActionResult LogOn() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOn(string userName, string password, string returnUrl) { if (!ValidateLogOn(userName, password)) { return View(); } var user = accountRepository.GetUser(userName); var userFullName = user.FirstName + " " + user.LastName; FormsAuthentication.SetAuthCookie(userFullName, false); if (!String.IsNullOrEmpty(returnUrl) && returnUrl != "/") { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } private bool ValidateLogOn(string userName, string password) { if (String.IsNullOrEmpty(userName)) { ModelState.AddModelError("username", "You must specify a username."); } if (String.IsNullOrEmpty(password)) { ModelState.AddModelError("password", "You must specify a password."); } if (!provider.ValidateUser(userName, password)) { ModelState.AddModelError("_FORM", "The username or password provided is incorrect."); } return ModelState.IsValid; } } In some testing controller I have following: [Authorize] public class ContactsController : Controller { SAMembershipProvider saMembershipProvider = new SAMembershipProvider(); SARoleProvider saRoleProvider = new SARoleProvider(); // // GET: /Contact/ public ActionResult Index() { string[] roleNames = Roles.GetRolesForUser("[email protected]"); // Outputs admin ViewData["r1"] = roleNames[0].ToString(); // Outputs True // I'm not even sure if this method is the same as the one below ViewData["r2"] = Roles.IsUserInRole("[email protected]", roleNames[0].ToString()); // Outputs True ViewData["r3"] = saRoleProvider.IsUserInRole("[email protected]", "admin"); return View(); } If I use attribute [Authorize] then everything works ok, but if I use [Authorize(Roles="admin")] then user is always rejected, like he is not in role. Any idea of what could be wrong here? Thanks in advance, Ile

    Read the article

  • Compatibility of Enum Vs. string constants

    - by Yosi
    I was recently told that using Enum: public enum TaskEndState { Error, Completed, Running } may have compatibility/serialization issues, and thus sometimes it's better to use const string: public const string TASK_END_STATE = "END_STATE"; public const string TASK_END_STATE_ERROR = "TASK_END_STATE_ERROR"; public const string TASK_END_STATE_COMPLETE = "TASK_END_STATE_COMPLETE"; public const string TASK_END_STATE_RUNNING = "TASK_END_STATE_RUNNING"; Can you find practical use case where it may happen, is there any guidelines where Enum's should be avoided? Edit: My production environment has multiple WFC services (different versions of the same product). A later version may/or may not include some new properties as Task end state (this is just an example). If we try to deserialize a new Enum value in an older version of a specific service, it may not work.

    Read the article

  • Removing the last digits in string [migrated]

    - by Ruriko
    I have a string that looks like this: [APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834 I want to remove the digits at the end of the string, basically the 16 digits at the end of the string. In the end it should look like this: [APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC) This is my code that I have written so far var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834"; var n=str.substr(1,74); document.write(n); The problem is the string will be different so each will have different amount of characters. So how I remove the digits at the end of the string in javascript?

    Read the article

  • Sorting a string array in C++ no matter of A or a and with å, ä ö?

    - by Chris_45
    How do you sort an array of strings in C++ that will make this happen in this order: mr Anka Mr broWn mr Ceaser mR donK mr ålish Mr Ätt mr önD //following not the way to get that order regardeless upper or lowercase and å, ä, ö //in forloop... string handle; point1 = array1[j].find_first_of(' '); string forename1(array1[j].substr(0, (point1))); string aftername1(array1[j].substr(point1 + 1)); point2 = array1[j+1].find_first_of(' '); string forename2(array1[j+1].substr(0, (point2))); string aftername2(array1[j+1].substr(point2 + 1)); if(aftername1 > aftername2){ handle = array1[j]; array1[j] = array1[j+1]; array1[j+1] = handle;//swapping } if(aftername1 == aftername2){ if(forname1 > forname2){ handle = array1[j]; array1[j] = array1[j+1]; array1[j+1] = handle; } }

    Read the article

  • how to split string with some seperator but without removing that seperator in Java?

    - by sag
    Hi, I m facing problem in splitting string. Actually i want to split a string with some seperator but without loosing that seperator. when we use somestring.split(String seperator) method in java it splits the string but removes the seperator part from string.It should not happen. I want result like below: Example::string1="Ram-sita-laxman"; seperator="-"; string1.split(seperator); output : [Ram, sita, laxman] but i want the result like :[Ram, -sita, -laxman] is there a way to get output like this?

    Read the article

  • How do I convert a number (as a String) to an array of bytes in Java?

    - by user1795595
    I'm creating a method specific method for a java project i'm working on. The UML given specifies the return type to be of static byte[] that accepts the arguments (String, byte) So far, looks like this: public static byte[] convertNumToDigitArray(String number, byte numDigits) { } This method is supposed to convert a number (as a String) to an array of bytes. The ordering must go from most to least significant digits. For example, if the number String is “732” then index 0 of the array should contain 7. The last argument (numDigits) should match the length of the string passed in. How do I do this?

    Read the article

  • PHP get values from SimpleXMLElement array

    - by seanp2k
    I have this: [1]=> object(SimpleXMLElement)#6 (1) { ["@attributes"]=> array(14) { ["name"]=> string(5) "MySQL" ["acknowledged"]=> string(1) "1" ["comments"]=> string(1) "1" ["current_check_attempt"]=> string(1) "1" ["downtime"]=> string(1) "0" ["last_check"]=> string(19) "2010-05-01 17:57:00" ["markdown_filter"]=> string(1) "0" ["max_check_attempts"]=> string(1) "3" ["output"]=> string(42) "CRITICAL - Socket timeout after 10 seconds" ["perfdata_available"]=> string(1) "1" ["service_object_id"]=> string(3) "580" ["state"]=> string(8) "critical" ["state_duration"]=> string(6) "759439" ["unhandled"]=> string(1) "0" } } (I used var_dump($child) to generate that) How do I get the 'name' attribute out of there as a string? Here is my code: $xml = simplexml_load_string($results); foreach($xml->data->list as $child) { var_dump($child); echo $child->getName() . ": " . $child->name . "<br />"; }

    Read the article

  • Retrieve the full ASP.NET Form Buffer as a String

    - by Rick Strahl
    Did it again today: For logging purposes I needed to capture the full Request.Form data as a string and while it’s pretty easy to retrieve the buffer it always takes me a few minutes to remember how to do it. So I finally wrote a small helper function to accomplish this since this comes up rather frequently especially in debugging scenarios or in the immediate window. Here’s the quick function to get the form buffer as string: /// <summary> /// Returns the content of the POST buffer as string /// </summary> /// <returns></returns> public static string FormBufferToString() { HttpRequest Request = HttpContext.Current.Request; if (Request.TotalBytes > 0) return Encoding.Default.GetString(Request.BinaryRead(Request.TotalBytes)); return string.Empty; } Clearly a simple task, but handy to have in your library for reuse. You probably don’t want to call this if you have a massive inbound form buffer, or if the data you’re retrieving is binary. It’s probably a good idea to check the inbound content type before calling this function with something like this: var formBuffer = string.Empty; if (Request.ContentType.StartsWith("text/") || Request.ContentType == "application/x-www-form-urlencoded") ) { formBuffer = FormBufferToString(); } to ensure you’re working only on content types you can actually view as text. Now if I can only remember the name of this function in my library – it’s part of the static WebUtils class in the West Wind Web Toolkit if you want to check out a number of other useful Web helper functions.© Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  

    Read the article

  • Using a random string to authenticate HMAC?

    - by mrwooster
    I am designing a simple webservice and want to use HMAC for authentication to the service. For the purpose of this question we have: a web service at example.com a secret key shared between a user and the server [K] a consumer ID which is known to the user and the server (but is not necessarily secret) [D] a message which we wish to send to the server [M] The standard HMAC implementation would involve using the secret key [K] and the message [M] to create the hash [H], but I am running into issues with this. The message [M] can be quite long and tends to be read from a file. I have found its very difficult to produce a correct hash consistently across multiple operating systems and programming languages because of hidden characters which make it into various file formats. This is of course bad implementation on the client side (100%), but I would like this webservice to be easily accessible and not have trouble with different file formats. I was thinking of an alternative, which would allow the use a short (5-10 char) random string [R] rather than the message for autentication, e.g. H = HMAC(K,R) The user then passes the random string to the server and the server checks the HMAC server side (using random string + shared secret). As far as I can see, this produces the following issues: There is no message integrity - this is ok message integrity is not important for this service A user could re-use the hash with a different message - I can see 2 ways around this Combine the random string with a timestamp so the hash is only valid for a set period of time Only allow each random string to be used once Since the client is in control of the random string, it is easier to look for collisions I should point out that the principle reason for authentication is to implement rate limiting on the API service. There is zero need for message integrity, and its not a big deal if someone can forge a single request (but it is if they can forge a very large number very quickly). I know that the correct answer is to make sure the message [M] is the same on all platforms/languages before hashing it. But, taking that out of the equation, is the above proposal an acceptable 2nd best?

    Read the article

  • Regex to check if exact string exists

    - by Jayrox
    I am looking for a way to check if an exact string match exists in another string using Regex or any better method suggested. I understand that you tell regex to match a space or any other non-word character at the beginning or end of a string. However, I don't know exactly how to set it up. Search String: t String 1: Hello World, Nice to see you! t String 2: Hello World, Nice to see you! String 3: T Hello World, Nice to see you! I would like to use the search string and compare it to String 1, String 2 and String 3 and only get a positive match from String 1 and String 3 but not from String 2. Requirements: Search String may be at any character position in the Subject. There may or may not be a white-space character before or after it. I do not want it to match if it is part of another string; such as part of a word. For the sake of this question: I think I would do this using this pattern: /\bt\b/gi /\b{$search_string}\b/gi Does this look right? Can it be made better? Any situations where this pattern wouldn't work? Additional info: this will be used in PHP 5

    Read the article

  • (Java) Get value of string loaded into dynamic-type object?

    - by Michael
    I'm very new to Java (~10 days), so my code is probably pretty bad, but here's what I've got: ArgsDataHolder argsData = new ArgsDataHolder(); // a class that holds two // ArrayList's where each element // representing key/value args Class thisArgClass; String thisArgString; Object thisArg; for(int i=2; i< argsString.length; i++) { thisToken = argsString[i]; thisArgClassString = getClassStringFromToken(thisToken).toLowerCase(); System.out.println("thisArgClassString: " + thisArgClassString); thisArgClass = getClassFromClassString(thisArgClassString); // find closing tag; concatenate middle Integer j = new Integer(i+1); thisArgString = getArgValue(argsString, j, "</" + thisArgClassString + ">"); thisArg = thisArgClass.newInstance(); thisArg = thisArgClass.valueOf(thisArgString); argsData.append(thisArg, thisArgClass); } The user basically has to input a set of key/value arguments into the command prompt in this format: <class>value</class>, e.g. <int>62</int>. Using this example, thisArgClass would be equal to Integer.class, thisArgString would be a string that read "62", and thisArg would be an instance of Integer that is equal to 62. I tried thisArg.valueOf(thisArgString), but I guess valueOf(<String>) is only a method of certain subclasses of Object. For whatever reason, I can't seem to be able to cast thisArg to thisArgClass (like so: thisArg = (thisArgClass)thisArgClass.newInstance();, at which point valueOf(<String>) should become accessible. There's got to be a nice, clean way of doing this, but it is beyond my abilities at this point. How can I get the value of the string loaded into a dynamically-typed object (Integer, Long, Float, Double, String, Character, Boolean, etc.)? Or am I just overthinking this, and Java will do the conversion for me? :confused:

    Read the article

  • How can I create a Base64-Encoded string from an GDI+ Image in C++?

    - by Schnapple
    I asked a question recently, How can I create an Image in GDI+ from a Base64-Encoded string in C++?, which got a response that led me to the answer. Now I need to do the opposite - I have an Image in GDI+ whose image data I need to turn into a Base64-Encoded string. Due to its nature, it's not straightforward. The crux of the issue is that an Image in GDI+ can save out its data to either a file or an IStream*. I don't want to save to a file, so I need to use the resulting stream. Problem is, this is where my knowledge breaks down. This first part is what I figured out in the other question // Initialize GDI+. GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); // I have this decode function from elsewhere std::string decodedImage = base64_decode(Base64EncodedImage); // Allocate the space for the stream DWORD imageSize = decodedImage.length(); HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize); LPVOID pImage = ::GlobalLock(hMem); memcpy(pImage, decodedImage.c_str(), imageSize); // Create the stream IStream* pStream = NULL; ::CreateStreamOnHGlobal(hMem, FALSE, &pStream); // Create the image from the stream Image image(pStream); // Cleanup pStream->Release(); GlobalUnlock(hMem); GlobalFree(hMem); (Base64 code) And now I'm going to perform an operation on the resulting image, in this case rotating it, and now I want the Base64-equivalent string when I'm done. // Perform operation (rotate) image.RotateFlip(Gdiplus::Rotate180FlipNone); IStream* oStream = NULL; CLSID tiffClsid; GetEncoderClsid(L"image/tiff", &tiffClsid); // Function defined elsewhere image.Save(oStream, &tiffClsid); // And here's where I'm stumped. (GetEncoderClsid) So what I wind up with at the end is an IStream* object. But here's where both my knowledge and Google break down for me. IStream shouldn't be an object itself, it's an interface for other types of streams. I'd go down the road from getting string-Image in reverse, but I don't know how to determine the size of the stream, which appears to be key to that route. How can I go from an IStream* to a string (which I will then Base64-Encode)? Or is there a much better way to go from a GDI+ Image to a string?

    Read the article

  • Helping linqtosql datacontext use implicit conversion between varchar column in the database and tab

    - by user213256
    I am creating an mssql database table, "Orders", that will contain a varchar(50) field, "Value" containing a string that represents a slightly complex data type, "OrderValue". I am using a linqtosql datacontext class, which automatically types the "Value" column as a string. I gave the "OrderValue" class implicit conversion operators to and from a string, so I can easily use implicit conversion with the linqtosql classes like this: // get an order from the orders table MyDataContext db = new MyDataContext(); Order order = db.Orders(o => o.id == 1); // use implicit converstion to turn the string representation of the order // value into the complex data type. OrderValue value = order.Value; // adjust one of the fields in the complex data type value.Shipping += 10; // use implicit conversion to store the string representation of the complex // data type back in the linqtosql order object order.Value = value; // save changes db.SubmitChanges(); However, I would really like to be able to tell the linqtosql class to type this field as "OrderValue" rather than as "string". Then I would be able to avoid complex code and re-write the above as: // get an order from the orders table MyDataContext db = new MyDataContext(); Order order = db.Orders(o => o.id == 1); // The Value field is already typed as the "OrderValue" type rather than as string. // When a string value was read from the database table, it was implicity converted // to "OrderValue" type. order.Value.Shipping += 10; // save changes db.SubmitChanges(); In order to achieve this desired goal, I looked at the datacontext designer and selected the "Value" field of the "Order" table. Then, in properties, I changed "Type" to "global::MyApplication.OrderValue". The "Server Data Type" property was left as "VarChar(50) NOT NULL" The project built without errors. However, when reading from the database table, I was presented with the following error message: Could not convert from type 'System.String' to type 'MyApplication.OrderValue'. at System.Data.Linq.DBConvert.ChangeType(Object value, Type type) at Read_Order(ObjectMaterializer1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader2.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at Example.OrdersProvider.GetOrders() at ... etc From the stack trace, I believe this error is happening while reading the data from the table. When presented with converting a string to my custom data type, even though the implicit conversion operators are present, the DBConvert class gets confused and throws an error. Is there anything I can do to help it not get confused and do the implicit conversion? Thanks in advance, and apologies if I have posted in the wrong forum. cheers / Ben

    Read the article

  • SQL: empty string vs NULL value

    - by Jacek Prucia
    I know this subject is a bit controversial and there are a lot of various articles/opinions floating around the internet. Unfortunatelly, most of them assume the person doesn't know what the difference between NULL and empty string is. So they tell stories about surprising results with joins/aggregates and generally do a bit more advanced SQL lessons. By doing this, they absolutely miss the whole point and are therefore useless for me. So hopefully this question and all answers will move subject a bit forward. Let's suppose I have a table with personal information (name, birth, etc) where one of the columns is an email address with varchar type. We assume that for some reason some people might not want to provide an email address. When inserting such data (without email) into the table, there are two available choices: set cell to NULL or set it to empty string (''). Let's assume that I'm aware of all the technical implications of choosing one solution over another and I can create correct SQL queries for either scenario. The problem is even when both values differ on the technical level, they are exactly the same on logical level. After looking at NULL and '' I came to a single conclusion: I don't know email address of the guy. Also no matter how hard i tried, I was not able to sent an e-mail using either NULL or empty string, so apparently most SMTP servers out there agree with my logic. So i tend to use NULL where i don't know the value and consider empty string a bad thing. After some intense discussions with colleagues i came with two questions: am I right in assuming that using empty string for an unknown value is causing a database to "lie" about the facts? To be more precise: using SQL's idea of what is value and what is not, I might come to conclusion: we have e-mail address, just by finding out it is not null. But then later on, when trying to send e-mail I'll come to contradictory conclusion: no, we don't have e-mail address, that @!#$ Database must have been lying! Is there any logical scenario in which an empty string '' could be such a good carrier of important information (besides value and no value), which would be troublesome/inefficient to store by any other way (like additional column). I've seen many posts claiming that sometimes it's good to use empty string along with real values and NULLs, but so far haven't seen a scenario that would be logical (in terms of SQL/DB design). P.S. Some people will be tempted to answer, that it is just a matter of personal taste. I don't agree. To me it is a design decision with important consequences. So i'd like to see answers where opion about this is backed by some logical and/or technical reasons.

    Read the article

  • [C#] How to convert string encoded in windows-1250 to unicode ?

    - by Deveti Putnik
    Hi! I am receiving from some dll (which is wrapper for some external data source) strings in Windows-1250 codepage and I would like to insert them correctly (as unicode) to table in SQL Server Database. Since particular row in database which should hold that data is of NVarchar type, I only needed to convert it in my C# code to unicode and pass it as parameter. Everything is well and nice, but I stumbled on conversion step. I tried the following but that doesn't work: private static String getUnicodeValue(string string2Encode) // { Encoding srcEncoding = Encoding.GetEncoding("Windows-1250"); UnicodeEncoding dstEncoding = new UnicodeEncoding(); byte[] srcBytes = srcEncoding.GetBytes(string2Encode); byte[] dstBytes = dstEncoding.GetBytes(string2Encode); return dstEncoding.GetString(dstBytes); } When I insert this returned string to table, I don't get correct letters like Ð, d, C, c, C or c. Please, help! :)

    Read the article

  • What to look for in estimating a PowerBuilder Conversion Project?

    - by tekiegreg
    Hi there, I've been trying to do a spec for a PowerBuilder 9 to 11.5 migration of a relatively complex application. Granted PowerBuilder is not really my specialty I'm having issues trying to justify an estimate for this part of the project (and the PowerBuilder people I've been talking with have had some personal issues lately and are out of communication). These are some of the metrics that we have seen and can evaluate: -PBL Files -Main Windows -Data Windows -Functions (no we don't have the source available on this project) What metrics in particular are helpful and how long would any given "unit" such as a Data Window take?

    Read the article

< Previous Page | 52 53 54 55 56 57 58 59 60 61 62 63  | Next Page >