Example #1
0
bool ComparePropertyStrings(const String& lhs, const String& rhs)
{
    int spaceLhs = lhs.Find(' ');
    int spaceRhs = rhs.Find(' ');
    if (spaceLhs != String::NPOS && spaceRhs != String::NPOS)
        return String::Compare(lhs.CString() + spaceLhs, rhs.CString() + spaceRhs, true) < 0;
    else
        return String::Compare(lhs.CString(), rhs.CString(), true) < 0;
}
Example #2
0
void DatabaseDemo::HandleInput(const String& input)
{
    // Echo input string to stdout
    Print(input);
    row_ = 0;
    if (input == "quit" || input == "exit")
        engine_->Exit();
    else if (input.StartsWith("set") || input.StartsWith("get"))
    {
        // We expect a key/value pair for 'set' command
        Vector<String> tokens = input.Substring(3).Split(' ');
        String setting = tokens.Size() ? tokens[0] : "";
        if (input.StartsWith("set") && tokens.Size() > 1)
        {
            if (setting == "maxrows")
                maxRows_ = Max(ToUInt(tokens[1]), 1U);
            else if (setting == "connstr")
            {
                String newConnectionString(input.Substring(input.Find(" ", input.Find("connstr")) + 1));
                Database* database = GetSubsystem<Database>();
                DbConnection* newConnection = database->Connect(newConnectionString);
                if (newConnection)
                {
                    database->Disconnect(connection_);
                    connection_ = newConnection;
                }
            }
        }
        if (tokens.Size())
        {
            if (setting == "maxrows")
                Print(ToString("maximum rows is set to %d", maxRows_));
            else if (setting == "connstr")
                Print(ToString("connection string is set to %s", connection_->GetConnectionString().CString()));
            else
                Print(ToString("Unrecognized setting: %s", setting.CString()));
        }
        else
            Print("Missing setting paramater. Recognized settings are: maxrows, connstr");
    }
    else
    {
        // In this sample demo we use the dbCursor event to loop through each row as it is being fetched
        // Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object,
        //   unless the dbCursor event handler has instructed to filter out the fetched row from the final result
        DbResult result = connection_->Execute(input, true);

        // Number of affected rows is only meaningful for DML statements like insert/update/delete
        if (result.GetNumAffectedRows() != -1)
            Print(ToString("Number of affected rows: %d", result.GetNumAffectedRows()));
    }
    Print(" ");
}
Example #3
0
   String
   Utilities::GetHostNameFromReceivedHeader(const String &sReceivedHeader)
   {
      /*
         sFirstPart now contains the following
         received =  "Received"    ":"            ; one per relay
         ["from" domain]           ; sending host
         ["by"   domain]           ; receiving host
         ["via"  atom]             ; physical path
         *("with" atom)             ; link/mail protocol
         ["id"   msg-id]           ; receiver msg id
         ["for"  addr-spec]        ; initial form
         ";"    date-time         ; time received

         http://cr.yp.to/immhf/envelope.html
         In theory, the value of a Received field is tokenizable.
         In practice, SMTP servers put all sorts of badly formatted information into Received lines. 
         Hence: We only do a quick search
      */

      int iFromPos = sReceivedHeader.Find(_T("from "));
      if (iFromPos == -1)
      {
         return "";
      }

      int startPos = iFromPos + 5;
      int endPos = sReceivedHeader.Find(_T(" "), startPos );
      if (endPos == -1)
      {
         assert(0);
         return "";
      }

      int length = endPos - startPos;

      if (length == -1)
      {
         assert(0);
         return "";
      }

      String hostName = sReceivedHeader.Mid(startPos, length);

      if (!StringParser::IsValidDomainName(hostName))
      {
         return "";
      }

      return hostName;

   }
Example #4
0
   std::vector<String>
   StringParser::SplitString(const String &sInput, const String &sSeperators)
   {
      // Previously, this code used boost::tokenizer to split
      // the contents of string, but I did some tests and it
      // showed that the below code was 50% faster. Not so 
      // unexpected since tokenizer is much more advanced.

      std::vector<String> vecResult;
      int iBeginning = 0;
      int iEnd = sInput.Find(sSeperators);

      if (iEnd == -1)
      {
         // The separator was not found in the string. 
         // We should put the entire string in the result.
         if (!sInput.IsEmpty())
            vecResult.push_back(sInput);

      }

      int iSeperatorLen = sSeperators.GetLength();

      while (iEnd >= 0)
      {
         int iSubStrLength = iEnd - iBeginning;
         
         String sSubString;
         sSubString = sInput.Mid(iBeginning, iSubStrLength);
         
         vecResult.push_back(sSubString);

         // Skip to the position where the next substring
         // can start
         iBeginning = iEnd + iSeperatorLen;
         iEnd = sInput.Find(sSeperators, iBeginning);   
      }

      if (iBeginning > 0)
      {
         String sSubString = sInput.Mid(iBeginning);
         if (!sSubString.IsEmpty())
            vecResult.push_back(sSubString);
      }

      return vecResult;
    
  
   }
Example #5
0
   void LoadFiltersFromGlobalString( const IsoString& globalKey )
   {
      filters.Clear();

      String s = PixInsightSettings::GlobalString( globalKey  );
      if ( !s.IsEmpty() )
      {
         for ( size_type p = 0; ; )
         {
            size_type p1 = s.Find( '(', p );
            if ( p1 == String::notFound )
               break;

            size_type p2 = s.Find( ')', p1 );
            if ( p2 == String::notFound )
               break;

            String extStr = s.Substring( p1, p2-p1 );
            if ( !extStr.IsEmpty() )
            {
               StringList extLst;
               extStr.Break( extLst, ' ', true );
               if ( !extLst.IsEmpty() )
               {
                  FileFilter filter;

                  for ( StringList::const_iterator i = extLst.Begin(); i != extLst.End(); ++i )
                  {
                     size_type d = i->Find( '.' );
                     if ( d != String::notFound )
                        filter.AddExtension( i->Substring( d ) );
                  }

                  if ( !filter.Extensions().IsEmpty() )
                  {
                     String desc = s.Substring( p, p1-p );
                     desc.Trim();
                     filter.SetDescription( desc );

                     filters.Add( filter );
                  }
               }
            }

            p = p2 + 1;
         }
      }
   }
// Initialises the range from a unicode range in string form.
bool UnicodeRange::Initialise(const String& unicode_range)
{
	// Check for a 'U+' at the start.
	if (unicode_range.Length() < 2 ||
		unicode_range[0] != 'U' ||
		unicode_range[1] != '+')
		return false;

	// Check if there's a '-' sign; if so, we've got a range.
	String::size_type separator_index = unicode_range.Find("-", 2);
	if (separator_index != String::npos)
	{
		const char* end = unicode_range.CString() + separator_index;
		min_codepoint = strtoul(unicode_range.CString() + 2, (char **) &end, 16);

		end = unicode_range.CString() + unicode_range.Length();
		max_codepoint = strtoul(unicode_range.CString() + separator_index + 1, (char **) &end, 16);

		return min_codepoint <= max_codepoint;
	}

	// No range! Check if we have any wildcards.
	String::size_type wildcard_index = unicode_range.Find("?", 2);
	if (wildcard_index != String::npos)
	{
		String range_min(unicode_range.CString() + 2, unicode_range.CString() + wildcard_index);
		String range_max(range_min);

		for (String::size_type i = 0; i < unicode_range.Length() - wildcard_index; ++i)
		{
			range_min += "0";
			range_max += "F";
		}

		const char* end = range_min.CString() + range_min.Length();
		min_codepoint = strtoul(range_min.CString(), (char**) &end, 16);
		end = range_max.CString() + range_max.Length();
		max_codepoint = strtoul(range_max.CString(), (char**) &end, 16);

		return true;
	}

	const char* end = unicode_range.CString() + unicode_range.Length();
	min_codepoint = strtoul(unicode_range.CString() + 2, (char**) &end, 16);
	max_codepoint = min_codepoint;

	return true;
}
   VirusScanningResult 
   CustomVirusScanner::Scan(const String &executablePath, int virusReturnCode, const String &sFilename)
   {
      LOG_DEBUG("Running custom virus scanner...");


      String sPath = FileUtilities::GetFilePath(sFilename);

      String sCommandLine;

      if (executablePath.Find(_T("%FILE%")) >= 0)
      {
         sCommandLine = executablePath;
         sCommandLine.Replace(_T("%FILE%"), sFilename);
      }
      else
         sCommandLine.Format(_T("%s %s"), executablePath, sFilename);

      unsigned int exitCode = 0;
      ProcessLauncher launcher(sCommandLine, sPath);
      launcher.SetErrorLogTimeout(20000);
      if (!launcher.Launch(exitCode))
      {
         return VirusScanningResult("CustomVirusScanner::Scan", "Unable to launch executable.");
      }

      String sDebugMessage = Formatter::Format("Scanner: {0}. Return code: {1}", sCommandLine, exitCode);
      LOG_DEBUG(sDebugMessage);

      if (exitCode == virusReturnCode)
         return VirusScanningResult(VirusScanningResult::VirusFound, "Unknown");
      else
         return VirusScanningResult(VirusScanningResult::NoVirusFound, Formatter::Format("Return code: {0}", exitCode));

   }
Example #8
0
	void GenerateCmd()
	{
		String cmdBuild("-");
		if (rebuild) cmdBuild << 'a';
		if (blitz) cmdBuild << 'b';
		if (!umk && msgonfail) cmdBuild << 'e';
		if (silent) cmdBuild << 'l';
		if (map) cmdBuild << 'm';
		cmdBuild << cmdBuildMode;
		if (shared) cmdBuild << 's';
		else if (sharedbuild) cmdBuild << 'S';
		if (verbose) cmdBuild << 'v';
		if (savetargetdir) cmdBuild << 'k';
		switch (exportproject) {
			case 1: cmdBuild << 'x'; break;
			case 2: cmdBuild << 'X'; break;
		}
		if (makefile) cmdBuild << 'M';
		int numThreads = ~threads;
		if (umk && !IsNull(numThreads) && numThreads > 0)
			cmdBuild << 'H' << numThreads;
		String output;
		if (outoption) {
			output = TrimBoth(~out);
			if (output.Find(" ") >= 0)
				output = String().Cat() << "\"" << output << "\"";
		}
		cmd <<= TrimRight(Format("%s %s %s %s%s %s",
			cmdAssembly, cmdPackage, cmdMethod, cmdBuild, cmdMainConfig, output));
	}
Example #9
0
   SPF::Result
   SPF::Test(const String &sSenderIP, const String &sSenderEmail, String &sExplanation)
   {
      USES_CONVERSION;
      String sDomain = StringParser::ExtractDomain(sSenderEmail);

      int family;
      if (sSenderIP.Find(_T(":")) > 0)
         family=AF_INET6;
      else
         family=AF_INET;

      // Convert the IP address from a dotted string
      // to a binary form. We use the SPF library to
      // do this.

      char BinaryIP[16];
      if (SPFStringToAddr(T2A(sSenderIP),family,BinaryIP)==NULL)
         return Neutral;

      String sSPFBestGuess = IniFileSettings::Instance()->GetSPFDefaultPolicy();
      String sSPFBestGuessA = IniFileSettings::Instance()->GetSPFDefaultPolicyA();

      int result1 = SPFSetBestGuess(T2A(sSPFBestGuess), T2A(sSPFBestGuessA)); // policy, policy if only A

      if (result1 != 0)
      {
          LOG_DEBUG("SPFDefaultPolicy NOT Set OK. Invalid SPF string specified?");
      }
      else
      {
          LOG_DEBUG("Set OK. SPFDefaultPolicy: " + sSPFBestGuess + " SPFDefaultPolicyA: " + sSPFBestGuessA);
      }
          
      
      String sPolicyOverride = IniFileSettings::Instance()->GetSPFPolicyOverride();
      LOG_DEBUG("SPFPolicyOverride Set: " + sPolicyOverride);

      const char* explain;
      int result=SPFQuery(family,BinaryIP,T2A(sSenderEmail),T2A(sPolicyOverride),NULL,NULL,&explain); // ipv4/6, binIP, sender, policy over-ride, HELO, explaination

      if (explain != NULL)
      {
         sExplanation = explain;
         SPFFree(explain);
         LOG_DEBUG("SPF Explaination: " + sExplanation);
      }

      if (result == SPF_Fail)
      {
         // FAIL
         return Fail;
      }
      else if (result == SPF_Pass)
      {
         return Pass;
      }

      return Neutral;
   }
Example #10
0
String GetExeFilePath()
{
	static String exepath;
	ONCELOCK {
		const char *exe = procexepath_();
		if(*exe)
			exepath = exe;
		else {
			String x = Argv0__;
			if(IsFullPath(x) && FileExists(x))
				exepath = x;
			else {
				exepath = GetHomeDirFile("upp");
				Vector<String> p = Split(FromSystemCharset(Environment().Get("PATH")), ':');
				if(x.Find('/') >= 0)
					p.Add(GetCurrentDirectory());
				for(int i = 0; i < p.GetCount(); i++) {
					String ep = NormalizePath(AppendFileName(p[i], x));
					if(FileExists(ep))
						exepath = ep;
				}
			}
		}
	}
	return exepath;
}
Example #11
0
static inline String TrimClassName(String clss)
{
	int f = clss.Find('$');
	if(f >= 0)
		clss.Trim(f);
	return clss;
}
Example #12
0
String GetExeFileTypeAssociation(const String ext) {

	String buff = GetWinRegString("", GetWinRegString("", ext, HKEY_CLASSES_ROOT) + String("\\Shell\\Open\\Command"), HKEY_CLASSES_ROOT);
	buff = buff.Left(buff.Find(".exe")+4);
	if(buff.Left(1) == "\"") return buff.Right(buff.GetCount() - 1);
	else return buff;
}
Example #13
0
void PropertiesWindow::OnEndEdit(int mode)
{
	if (_Item)
	{
		for (int i = 0; i < _Properties.GetCount(); ++i)
		{
			String param = _Properties.GetKey(i);
			if (param.Find("Color") >= 0) // if color found
			{
				Color r = _Properties[i].GetData();
				_Item->Set(param, Encode64(StoreAsString(r)));
				continue;
			}
			String value = AsString(_Properties[i].GetData());
			_Item->Set(param, value);
		}

		if (mode)
		{
			_Options.EndEdit();
			_Options.ClearCursor();
			_Item->Set("Type", _Headers.Get(0, 1));
			Generate(_Item, _Index);
		}

		WhenChildZ.Execute();
	}
}
Example #14
0
//-----------------------------------------------------------------------------------------------------------------------------------------------------
VOID Configuration::LoadConfigFile(LPCTSTR Filename)
{
  TextStream T(File::Open(Filename, FileMode::OPEN));

  while(!T.EndOfStream())
  {
    String L = T.ReadLine();
    if (L.BeginsWith("#"))
      continue;

    String::Iterator i = L.Find('=');
    if (i != L.End())
    {
      String Name = L.Substr(L.Begin(), i);
      String Value = L.Substr(i+1, L.End());

      if (m_Schema.Contains(Name))
      {
        Item I = m_Schema.Get(Name);
        if ((I.m_Source & ConfigurationSource::FILE) == 0)
          continue;
        I.m_Present = TRUE;
      }

      m_ConfigValues.Add(Name,Value);
    }
  }
}
static void AddSuggestion(std::vector<String>& matches, const String& word, const String& suggestion)
{
	if (suggestion.Find(word) != 0)
		return;

	matches.push_back(suggestion);
}
   /// Resolves IP addresses for the recipient servers. This will either be a MX 
   /// lookup, or a A lookup, if SMTP relaying is used.
   bool 
   ExternalDelivery::_ResolveRecipientServer(shared_ptr<ServerInfo> &serverInfo, vector<shared_ptr<MessageRecipient> > &vecRecipients, vector<String> &saMailServers)
   {
      DNSResolver resolver;

      // Resolve the specified hosts.
      bool dnsQueryOK = false;

      if (serverInfo->GetFixed())
      {
         String relayServer = serverInfo->GetHostName();

         LOG_APPLICATION("SMTPDeliverer - Message " + StringParser::IntToString(_originalMessage->GetID()) + ": Relaying to host " + relayServer + ".");      

         vector<String> mailServerHosts;
         if (relayServer.Find(_T("|")) > 0)
            mailServerHosts = StringParser::SplitString(relayServer, "|");
         else
            mailServerHosts.push_back(relayServer);

         boost_foreach(String host, mailServerHosts)
         {
            // The actual resolution of these host names to IP addresses,
            // are taken care of by TCPConnection::Connect.
            saMailServers.push_back(host);
         }
   IMAPResult
   IMAPCommandStore::ExecuteCommand(shared_ptr<IMAPConnection> pConnection, shared_ptr<IMAPCommandArgument> pArgument)
   {


      String sTag = pArgument->Tag();
      String sCommand = pArgument->Command();

      if (!pConnection->IsAuthenticated())
         return IMAPResult(IMAPResult::ResultNo, "Authenticate first");

      if (!pConnection->GetCurrentFolder())
         return IMAPResult(IMAPResult::ResultNo, "No folder selected.");


      shared_ptr<IMAPStore> pStore = shared_ptr<IMAPStore>(new IMAPStore());
      pStore->SetIsUID(false);

      String sResponse; 
      long lMailNoStart = 6;
      long lMailNoEnd = sCommand.Find(_T(" "), lMailNoStart);
      long lMailNoLen = lMailNoEnd - lMailNoStart;
      String sMailNo = sCommand.Mid(lMailNoStart, lMailNoLen);
      String sShowPart = sCommand.Mid(lMailNoEnd);

      pArgument->Command(sShowPart);

      IMAPResult result = pStore->DoForMails(pConnection, sMailNo, pArgument);

      if (result.GetResult() == IMAPResult::ResultOK)
         pConnection->SendAsciiData(pArgument->Tag() + " OK STORE completed\r\n");

      return result;
   }
Example #18
0
static String TranslateHTMLBreakTags( const String& s )
{
   String r;
   for ( size_type p0 = 0; ; )
   {
      size_type p = s.FindIC( "<br", p0 );
      if ( p == String::notFound )
      {
         r.Append( s.Substring( p0 ) );
         break;
      }

      if ( p != p0 )
         r.Append( s.Substring( p0, p-p0 ) );

      r.Append( '\n' );

      size_type p1 = s.Find( '>', p+1 );
      if ( p1 == String::notFound )
         break;
      p0 = p1 + 1;
   }

   return r;
}
Example #19
0
static String GetNamespace( const String& dbName, const char* collection, const MetaClass* metaClass )
{
	String ns ( dbName );
	ns += ".";

	if ( collection )
	{
		ns += collection;
		return ns;
	}

	std::string defaultCollection;
	if ( metaClass->GetProperty( "defaultCollection", defaultCollection ) )
	{
		ns += defaultCollection.c_str();
		return ns;
	}

	String metaClassName ( metaClass->m_Name );
	for ( size_t startIndex = 0, foundIndex = Invalid<size_t>(); ( foundIndex = metaClassName.Find( ':', startIndex ) ) != Invalid<size_t>(); )
	{
		metaClassName.Remove( foundIndex, 1 );
	}

	ns += metaClassName;
	return ns;
}
Example #20
0
asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declarationIn)
{
    if (!compiled_ || !object)
        return 0;

    String declaration = declarationIn.Trimmed();
    // If not a full declaration, assume void with no parameters
    if (declaration.Find('(') == String::NPOS)
        declaration = "void " + declaration + "()";

    asIObjectType* type = object->GetObjectType();
    if (!type)
        return 0;

    HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
    if (i != methods_.End())
    {
        HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
        if (j != i->second_.End())
            return j->second_;
    }

    asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
    methods_[type][declaration] = function;
    return function;
}
Example #21
0
static String GetHostFromAddress( const String& address )
{
	int posAt = address.Find('@') ;
	if (posAt == -1)
		return address ;

	return address.Mid(posAt+1) ;
}
Example #22
0
void DrawMnemonicText(Draw& w, int x, int y, const String& s, Font font, Color color,
                      int mnemonic, bool menumark)
{
	int apos = HIWORD(mnemonic);
	int q;
	if(apos && apos < s.GetLength())
		q = apos - 1;
	else {
		q = s.Find(ToUpper(mnemonic));
		if(q < 0)
			q = s.Find(ToLower(mnemonic));
	}
	w.DrawText(x, y, s, font, color);
	if(q < 0) return;
	FontInfo f = font.Info();
	w.DrawRect(x + GetTextSize(~s, font, q).cx, y + f.GetAscent() + 1, f[s[q]], 1,
	           menumark ? SColorMenuMark() : SColorMark());
}
Example #23
0
void BaseSetupDlg::OnUpp()
{
    if(new_base) {
        String s = ~upp;
        int f = s.Find(';');
        if(f >= 0) s.Trim(f);
        base <<= GetFileTitle(s);
    }
}
   bool
   SQLScriptRunner::ExecuteScript(shared_ptr<DALConnection> connectionObject, const String &sFile, String &sErrorMessage)
   {
      SQLScriptParser oParser(connectionObject->GetSettings(), sFile);
      if (!oParser.Parse(sErrorMessage))
      {
         sErrorMessage = "Parsing of SQL script failed: " + sFile + "\r\nError:" + sErrorMessage;
         return false;
      }

      if (oParser.GetNoOfCommands() == 0)
      {
         sErrorMessage = "Found no SQL commands in file : " + sFile;
         return false;
      }

      // 30 minute timeout per statement. Should hopefully never be needed.
      connectionObject->SetTimeout(60 * 30);

      for (int i = 0; i < oParser.GetNoOfCommands(); i++)
      {
         String sCommand = oParser.GetCommand(i);

         if (sCommand.StartsWith(_T("@@@")))
         {
            // Remove leading @@@.
            sCommand = sCommand.Mid(3);

            // Remove trailing @@@
            sCommand = sCommand.Mid(0, sCommand.Find(_T("@@@")));

            MacroParser parser(sCommand);
            Macro macro = parser.Parse();

            if (macro.GetType() == Macro::Unknown)
            {
               sErrorMessage = "Parsing of SQL script failed. Unknown macro. " + sFile + "\r\nMacro:" + sCommand;
               return false;
            }

            shared_ptr<IMacroExpander> macroExpander = connectionObject->CreateMacroExpander();
            if (!macroExpander->ProcessMacro(connectionObject, macro, sErrorMessage))
               return false;
         }
         else
         {
            if (connectionObject->TryExecute(SQLCommand(sCommand), sErrorMessage, 0, 0) != DALConnection::DALSuccess)
            {
               return false;
            }
         }
      }

      connectionObject->SetTimeout(30);

      return true;
   }
Example #25
0
String FormatNest(String nest)
{
	int q = nest.Find("@");
	if(q >= 0) {
		nest.Trim(q);
		nest << "[anonymous]";
	}
	return nest;
}
Example #26
0
///////////////////////////////////////////////////////////////////////////////
// Checks if a file name matches this joker.
///////////////////////////////////////////////////////////////////////////////
bool Joker::Matches(const String& fileName) const
{
	int empty = 0;

	int leftIndex = 0;
	if( m_left.GetLength() > 0 )
	{
		leftIndex = fileName.Find(m_left, 0);
		if( leftIndex != 0 )
		{
			return false;
		}
	}
	else
	{
		empty = 1;
	}

	int rightIndex = 0;
	if( m_right.GetLength() > 0 )
	{
		rightIndex = fileName.Find(m_right, leftIndex + m_left.GetLength());
		if( rightIndex < 0 )
		{
			return false;
		}
		int wantedIndex = fileName.GetLength() - m_right.GetLength();
		if( rightIndex != wantedIndex )
		{
			return false;
		}
	}
	else
	{
		empty |= 2;
	}

	if( empty == 3 && m_str != "*" )
	{
		// Exact match
		return m_str == fileName;
	}
	return true;
}
Example #27
0
Vector<AndroidVirtualDevice> AndroidSDK::FindVirtualDevices() const
{
	Vector<AndroidVirtualDevice> avdes;
	
	String out;
	if(Sys(NormalizeExePath(AndroidPath()) + " list avd", out) == 0) {
		Vector<String> lines = Split(out, "\n");
		
		AndroidVirtualDevice avd;
		for(int i = 0; i < lines.GetCount(); i++) {
			Vector<String> line = Split(lines[i], ":");
			if(line.GetCount() == 2) {
				String tag  = line[0];
				String data = line[1];
				if(data.StartsWith(" "))
					data.Remove(0);
				if(tag.Find("Name") > -1) {
					if(!avd.GetName().IsEmpty() && avd.GetName() != data)
						avdes.Add(avd);
					avd.SetName(data);
				}
				else
				if(tag.Find("Device") > -1)
					avd.SetDeviceType(data);
				else
				if(tag.Find("Path") > -1)
					avd.SetPath(data);
				else
				if(tag.Find("Target") > -1)
					avd.SetTarget(data);
				else
				if(tag.Find("Tag/ABI") > -1)
					avd.SetAbi(data);
				
				// TODO: implement all possible tags
			}
		}
		
		if(!avd.GetName().IsEmpty())
			avdes.Add(avd);
	}
	
	return avdes;
}
Example #28
0
   DALConnection::ExecutionResult
   PGConnection::TryExecute(const SQLCommand &command, String &sErrorMessage, __int64 *iInsertID, int iIgnoreErrors) 
   {
      String SQL = command.GetQueryString();

      try
      {
         // PG_query-doc:
         // Zero if the query was successful. Non-zero if an error occurred.
         // 
         AnsiString sQuery;
         if (!Unicode::WideToMultiByte(SQL, sQuery))
         {
            ErrorManager::Instance()->ReportError(ErrorManager::Critical, 5106, "PGConnection::TryExecute", "Could not convert string into multi-byte.");
            return DALConnection::DALUnknown;
         }

         PGresult *pResult = PQexec(m_pDBConn, sQuery);

         bool bIgnoreErrors = SQL.Find(_T("[IGNORE-ERRORS]")) >= 0;

         if (!bIgnoreErrors)
         {
            DALConnection::ExecutionResult result = CheckError(pResult, SQL, sErrorMessage);
            if (result != DALSuccess)
            {
               if (pResult != 0)
                  PQclear(pResult);

               return result;
            }
         }

         ExecStatusType iExecResult = PQresultStatus(pResult);
         
         // Check if a value has been returned. Will only occur if we've
         // inserted a value.
         if (iInsertID > 0 && iExecResult == PGRES_TUPLES_OK)
         {
            // pick the ID from the first row.
            char *pRetVal = PQgetvalue(pResult, 0, 0);
            *iInsertID = pRetVal ? _atoi64(pRetVal) : 0;
         }

         if (pResult != 0)
            PQclear(pResult);
        
      }
      catch (...)
      {
         sErrorMessage = "Source: PGConnection::TryExecute, Code: HM5084, Description: An unhanded error occurred while executing: " + SQL;
         return DALConnection::DALUnknown;
      }

      return DALConnection::DALSuccess;
   }
void ShaderVariation::SaveByteCode(const String& binaryShaderName)
{
    ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
    FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();

    // Filename may or may not be inside the resource system
    String fullName = binaryShaderName;
    if (!IsAbsolutePath(fullName))
    {
        // If not absolute, use the resource dir of the shader
        String shaderFileName = cache->GetResourceFileName(owner_->GetName());
        if (shaderFileName.Empty())
            return;
        fullName = shaderFileName.Substring(0, shaderFileName.Find(owner_->GetName())) + binaryShaderName;
    }
    String path = GetPath(fullName);
    if (!fileSystem->DirExists(path))
        fileSystem->CreateDir(path);

    SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
    if (!file->IsOpen())
        return;

    file->WriteFileID("USHD");
    file->WriteShort((unsigned short)type_);
    file->WriteShort(3);

    file->WriteUInt(parameters_.Size());
    for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
    {
        file->WriteString(i->second_.name_);
        file->WriteUByte((unsigned char)i->second_.register_);
        file->WriteUByte((unsigned char)i->second_.regCount_);
    }

    unsigned usedTextureUnits = 0;
    for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
    {
        if (useTextureUnit_[i])
            ++usedTextureUnits;
    }
    file->WriteUInt(usedTextureUnits);
    for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
    {
        if (useTextureUnit_[i])
        {
            file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
            file->WriteUByte((unsigned char)i);
        }
    }

    unsigned dataSize = byteCode_.Size();
    file->WriteUInt(dataSize);
    if (dataSize)
        file->Write(&byteCode_[0], dataSize);
}
Example #30
0
   bool
   MailImporter::GetRootLevelDirectory_(const String &fullPath, String &rootLevel)
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Takes an input parameter such as C:\DataDir\Account\Sub1\Sub2\Test.eml and
   // returns the root of that hierarcy, such as C:\Datadir\Account in this case.
   //---------------------------------------------------------------------------()
   {
      // The file must be located in the data directory. Make sure this is the case.
      const String dataDirectory = IniFileSettings::Instance()->GetDataDirectory();

      if (!fullPath.StartsWith(dataDirectory))
         return false;

      int currentTrimPosition = dataDirectory.GetLength() + 1;

      const String publicFolderName = IMAPConfiguration::GetPublicFolderDiskName();

      // Is the file located in the public folder?
      if (fullPath.FindNoCase(publicFolderName, currentTrimPosition) == currentTrimPosition)
      {
         // The file is located in the public folder.
         currentTrimPosition += publicFolderName.GetLength() + 1;
      }
      else
      {
         // The file is either located in the queue folder or in an account folder.
         int slashPosition = fullPath.Find(_T("\\"), currentTrimPosition);
         if (slashPosition < 0)
            return false;

         int accountSlashPosition = fullPath.Find(_T("\\"), slashPosition+1);

         if (accountSlashPosition > 0)
         {
            // The file is locate din the queue folder.
            currentTrimPosition = accountSlashPosition+1;
         }
      }

      rootLevel = fullPath.Mid(0, currentTrimPosition);
      return true;
   }