void ExtractAlphaChannelsInterface::__ChannelList_EditCompleted( Edit& sender )
{
   try
   {
      String s = sender.Text();
      s.Trim();

      SortedArray<int> list;
      ExtractAlphaChannelsInstance::ParseChannelList( list, s );

      s.Clear();
      for ( size_type i = 0; ; )
      {
         s.Append( String( list[i] ) );
         if ( ++i == list.Length() )
            break;
         s.Append( ',' );
      }

      instance.channelList = s;
      sender.SetText( s );
   }

   ERROR_CLEANUP(
      sender.SetText( instance.channelList );
      sender.SelectAll();
      sender.Focus()
   )
}
  void SensorRegistry::UnregisterSensor(Sensor* pSensor)
  {
    if (pSensor != NULL)
    {
      if (pSensor->GetIdentifier().GetScope() != "Karto/System")
      {
        Log(LOG_DEBUG, String("Unregistering sensor: [") + pSensor->GetIdentifier().ToString() + "]");
      }

      if (m_pSensorRegistryPrivate->m_SensorMap.find(pSensor->GetIdentifier()) != m_pSensorRegistryPrivate->m_SensorMap.end())
      {
        m_pSensorRegistryPrivate->m_SensorMap.erase(pSensor->GetIdentifier());

        m_pSensorRegistryPrivate->m_Sensors.Remove(pSensor);
      }
      else
      {
        String errorMessage;
        errorMessage.Append("Cannot unregister sensor: not registered: [");
        errorMessage.Append(pSensor->GetIdentifier().ToString());
        errorMessage.Append("]");

        throw Exception(errorMessage);
      }
    }
  }
void DrizzleIntegrationInterface::UpdateInputDataItem( size_type i )
{
   TreeBox::Node* node = GUI->InputData_TreeBox[i];
   if ( node == 0 )
      return;

   const DrizzleIntegrationInstance::DataItem& item = m_instance.p_inputData[i];

   node->SetText( 0, String( i+1 ) );
   node->SetAlignment( 0, TextAlign::Right );

   node->SetIcon( 1, Bitmap( String( item.enabled ? ":/browser/enabled.png" : ":/browser/disabled.png" ) ) );
   node->SetAlignment( 1, TextAlign::Left );

   String fileText;
   if ( GUI->FullPaths_CheckBox.IsChecked() )
      fileText.Append( item.path );
   else
      fileText.Append( File::ExtractNameAndSuffix( item.path ) );

   node->SetText( 2, fileText );
   node->SetAlignment( 2, TextAlign::Left );
   if ( !GUI->FullPaths_CheckBox.IsChecked() )
      node->SetToolTip( 2, item.path );
}
  void SensorRegistry::RegisterSensor(Sensor* pSensor)
  {
    if (pSensor != NULL)
    {
      if (pSensor->GetIdentifier().GetScope() != "Karto/System")
      {
        Validate(pSensor);

        Log(LOG_DEBUG, String("Registering sensor: [") + pSensor->GetIdentifier().ToString() + "]");
      }

      if ((m_pSensorRegistryPrivate->m_SensorMap.find(karto::Identifier(pSensor->GetIdentifier())) != m_pSensorRegistryPrivate->m_SensorMap.end()))
      {
        String errorMessage;
        errorMessage.Append("Cannot register sensor: already registered: [");
        errorMessage.Append(pSensor->GetIdentifier().ToString());
        errorMessage.Append("]");

        throw Exception(errorMessage);
      }

      m_pSensorRegistryPrivate->m_SensorMap[karto::Identifier(pSensor->GetIdentifier())] = pSensor;
      m_pSensorRegistryPrivate->m_Sensors.Add(pSensor);
    }
  }
Example #5
0
void JSBModule::WriteClassDeclaration(String& source)
{

    source += "static void jsb_declare_classes(JSVM* vm)\n{\n";

    source += "duk_context* ctx = vm->GetJSContext();\n";

    for (unsigned i = 0; i < classes_.Size(); i++)
    {
        JSBClass* klass = classes_.At(i);

        if (klass->isNumberArray())
            continue;

        source.AppendWithFormat("   js_class_declare(vm, \"%s\", jsb_constructor_%s);\n", klass->GetName().CString(), klass->GetName().CString());

        if (klass->hasProperties())
        {
            source.AppendWithFormat("js_class_push_propertyobject(vm, \"%s\");\n", klass->GetName().CString());


            Vector<String> pnames;
            klass->GetPropertyNames(pnames);

            for (unsigned j = 0; j < pnames.Size(); j++)
            {
                JSBProperty* prop = klass->GetProperty(pnames[j]);

                source.Append("duk_push_object(ctx);\n");

                if (prop->getter_ && !prop->getter_->Skip())
                {
                    source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, 0);\n",
                                            klass->GetName().CString(), prop->getter_->name_.CString());
                    source.Append("duk_put_prop_string(ctx, -2, \"get\");\n");
                }
                if (prop->setter_ && !prop->setter_->Skip())
                {
                    source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, 1);\n",
                                            klass->GetName().CString(), prop->setter_->name_.CString());
                    source.Append("duk_put_prop_string(ctx, -2, \"set\");\n");
                }

                pnames[j][0] = tolower(pnames[j][0]);
                source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", pnames[j].CString());

            }

            source.Append("duk_pop(ctx);\n");

        }
    }

    source += "\n}\n\n";

}
/// Save account information to a file
void GameEconomicGameClient::SaveConfiguration(Configuration &configuration)
{
    /// Get Resource
    ResourceCache * cache = GetSubsystem<ResourceCache>();
    FileSystem * fileSystem = GetSubsystem<FileSystem>();

    String configFileName;

    /// Set directory and path for network file
    configFileName.Append(fileSystem->GetProgramDir().CString());
    configFileName.Append("");
    configFileName.Append("Configuration.xml");


    /// Check if the account file information exist
    if(fileSystem->FileExists(configFileName.CString()))
    {
        fileSystem->Delete(configFileName.CString());
    }

    cout << "It got here "<<endl;

    File saveFile(context_, configFileName.CString(), FILE_WRITE);

    XMLFile * preferencefileconfig  = new XMLFile(context_);

    XMLElement configElem = preferencefileconfig   -> CreateRoot("Configuration");
    XMLElement GameModeConfigurationElement = configElem.CreateChild("GameModeConfiguration");
    XMLElement VideoConfigurationElement= configElem.CreateChild("VideoConfiguration");

    /// Set true false
    if(configuration.GameModeForceTablet==true)
    {
        GameModeConfigurationElement.SetAttribute("GameModeForceTablet", "true");
    }
    else
    {
        GameModeConfigurationElement.SetAttribute("GameModeForceTablet", "false");
    }

    /// Convert video bloom to float
    String VideoBloomParamValue1String(configuration.VideoBloomParam1);
    String VideoBloomParamValue2String(configuration.VideoBloomParam2);

    /// Copy values testing
    VideoConfigurationElement.SetAttribute("BloomParam1",VideoBloomParamValue1String);
    VideoConfigurationElement.SetAttribute("BloomParam2",VideoBloomParamValue2String);

    preferencefileconfig->Save(saveFile);

    return;
}
Example #7
0
String PixInsightVersion::AsString( bool withCodename )
{
   Initialize();
   String v = String().Format( "PixInsight %s%02d.%02d.%02d.%04d",
               LE() ? "LE " : "", Major(), Minor(), Release(), Build() );
   if ( BetaRelease() != 0 )
      v.Append( String().Format( " %s%d", (BetaRelease() < 0) ? "RC" : "beta ", Abs( BetaRelease() ) ) );
   if ( withCodename )
      v.Append( ' ' + Codename() );
   if ( Confidential() )
      v.Append( " (confidential)" );
   return v;
}
void JSClassWriter::GenerateNonStaticFunctionsSource(String& source, String& packageName)
{
    source.AppendWithFormat("js_class_get_prototype(ctx, \"%s\", \"%s\");\n", packageName.CString(), klass_->GetName().CString());

    for (unsigned i = 0; i < klass_->functions_.Size(); i++)
    {
        JSBFunction* function = klass_->functions_.At(i);

        if (function->Skip())
            continue;

        if (function->IsConstructor() || function->IsDestructor())
            continue;

        if (function->IsStatic())
            continue;

        if (function->FirstDefaultParameter() != -1)
        {
            source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, DUK_VARARGS);\n", klass_->GetName().CString(), function->GetName().CString());
        }
        else
        {
            source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, %i);\n", klass_->GetName().CString(), function->GetName().CString(), (int)function->GetParameters().Size());
        }

        String scriptName = function->GetName();
        scriptName[0] = tolower(scriptName[0]);
        source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", scriptName.CString());

    }
    source.Append("duk_pop(ctx);\n");
}
String BonkEnc::Utilities::LocalizeNumber(Int64 number)
{
	String	 nString = String::FromInt(number);
	String	 retVal;
	String	 separator;

	char	*buffer_a = new char [256];
	wchar_t	*buffer_w = new wchar_t [256];

	if (Setup::enableUnicode)	GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, buffer_w, 256);
	else				GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, buffer_a, 256);

	if (Setup::enableUnicode)	separator = buffer_w;
	else				separator = buffer_a;

	delete [] buffer_a;
	delete [] buffer_w;

	for (Int i = 0; i < nString.Length(); i++)
	{
		if ((nString.Length() - i) % 3 == 0 && i > 0) retVal.Append(separator);

		retVal[retVal.Length()] = nString[i];
	}

	return retVal;
}
Example #10
0
String  ParameterProcess::ToString ()
{
  String  statusStr ("");

  statusStr.Append (curStatus);

  String  class0Name;
  String  class1Name;

  if  (!class0)
    class0Name = "NoName";
  else
    class0Name = class0->Name ();

  if  (!class1)
    class1Name = "NoName";
  else
    class1Name = class1->Name ();
    

  statusStr << "\t" << processNum
            << "\t" << jobId 
            << "\t" << class0Name
            << "\t" << class1Name
            << "\t" << cParm
            << "\t" << gammaParm
            << "\t" << aParm
            << "\t" << highestAccuracy;
            
  
  return  statusStr;
} /* ToString */
Example #11
0
String Version::AsString()
{
   String v = String().Format( "PCL %02d.%02d.%02d.%04d", Major(), Minor(), Release(), Build() );
   if ( BetaRelease() != 0 )
      v.Append( String().Format( " beta %d", BetaRelease() ) );
   return v;
}
  Sensor* SensorRegistry::GetSensorByName(const Identifier& rName)
  {
    if (m_pSensorRegistryPrivate->m_SensorMap.find(rName) != m_pSensorRegistryPrivate->m_SensorMap.end())
    {
      Sensor* pSensor = m_pSensorRegistryPrivate->m_SensorMap[rName];

      assert(pSensor != NULL);

      return pSensor;
    }

    String errorMessage;
    errorMessage.Append("Sensor not registered: [");
    errorMessage.Append(rName.ToString());
    errorMessage.Append("]");
    throw Exception(errorMessage);
  }
void DecimalFormatRenderer::InsertFiller(String  &sScale, String &strDecPlaces )
{
	StartTrace(DecimalFormatRenderer.InsertFiller);

	for ( long lIdx = strDecPlaces.Length(); lIdx < sScale.AsLong(0L) ; lIdx++) {
		strDecPlaces.Append("0");
		Trace("scale [ " << strDecPlaces << "] index [ " << lIdx << " ]");
	}
}
Example #14
0
bool Information::ShowPopup(Form * parent)
{
	String titleid = L"IDS_FORM_";
	titleid.Append(__type);
	String title = Utils::GetString(titleid);
	//                IDS_INFORMATION_DICTIONARY
	String textid = L"IDS_INFORMATION_";
	textid.Append(__type);
	String text = Utils::GetString(textid);

	__pParentForm = parent;
	result result = Construct(L"IDP_INFORMATION");

	SetTitleText(title);

	__chkNoShowMore = static_cast<CheckButton *> (GetControl("IDC_NOSHOWMORE"));
	if (__chkNoShowMore)
	{
		bool checked = false;
		SetupCheckbox(checked);
		__chkNoShowMore->SetSelected(checked);
	}

	EditArea *peaText = static_cast<EditArea *> (GetControl("IDC_TEXT"));
	if (peaText)
	{
		peaText->SetText(text);
		peaText->SetEnabled(false);
		peaText->SetCursorPosition(0);
	}

	Button *pbtnCancel = static_cast<Button *> (GetControl("IDC_BTN_CANCEL"));
	if (pbtnCancel)
	{
		pbtnCancel->AddActionEventListener(*this);
		pbtnCancel->SetActionId(ID_BTN_CANCEL);
	}

	SetShowState(true);
	Show();
	return result;
}
Example #15
0
result
UserProfileForm::OnInitializing(void)
{
	BaseForm::OnInitializing();

	AppResource* pAppResource = Application::GetInstance()->GetAppResource();
	__pLeftItemBitmap = pAppResource->GetBitmapN(L"facebook_icon1.png");

	ButtonItem  buttonLeftItem;
	buttonLeftItem.Construct(BUTTON_ITEM_STYLE_ICON,NULL);
	buttonLeftItem.SetIcon(BUTTON_ITEM_STATUS_NORMAL, __pLeftItemBitmap);

	Header* pHeader = GetHeader();
	pHeader->SetStyle(HEADER_STYLE_TITLE);
	pHeader->SetButton(BUTTON_POSITION_LEFT, buttonLeftItem);
	pHeader->SetTitleText(L"Your Profile Page");


	result r = E_SUCCESS;

	//Read Access Token

	Registry reg;
	r = reg.Construct(L"/Home/FacebookReg.ini", false );
	String token;
	String section = L"Facebook";
	String entry = L"AccessToken";
	r = reg.GetValue(section, entry , token);
	if(r == E_SUCCESS)
		AppLog("token is %ls",token.GetPointer());
	else
		AppLog("Reading failed: %s", GetErrorMessage(r));
	__accessToken =token;

	String profileurl;
	profileurl.Append(L"https://graph.facebook.com/me?");
	profileurl.Append(L"access_token=");
	profileurl.Append(__accessToken);
	SendRequestGet(profileurl);

	return r;
}
Example #16
0
void Client::OnConnectionAttemptFailed()
{
    // Provide a reason why the connection failed.
    String address = LoginProperty("address").GetString();
    String port = LoginProperty("port").GetString();
    String protocol = LoginProperty("protocol").GetString();

    String failReason = "Could not connect to host";
    if (!address.Empty())
    {
        failReason.Append(" " + address);
        if (!port.Empty())
            failReason.Append(":" + port);
        if (!protocol.Empty())
            failReason.Append(" with " + protocol.ToUpper());
    }

    SetLoginProperty("LoginFailed", failReason);
    DoLogout(true);
}
Example #17
0
static String _StrToString(const char* str)
{
    String r;

    while (str)
    {
        MI_Char c = *str++;
        r.Append(&c, 1);
    }

    return r;
}
bool RegExpFilterFieldsParameterMapper::getValueWithSlotname(const char *key, String const &strSlotname, Context & ctx, ValueType & value,
		ROAnything script) {
	StartTrace1(RegExpFilterFieldsParameterMapper.getValueWithSlotname, "key [" << NotNull(key) << "] slotname [" << strSlotname << "]");
	String strNewKey = key;
	if (Lookup(_CombineKeyName, 1L) != 0) {
		strNewKey.Append(getDelim()).Append(strSlotname);
	}
	Anything slotnameBuffer = strSlotname, combinedKeyBuffer = strNewKey;
	Context::PushPopEntry<Anything> aSlotnameEntry(ctx, "CurrentSlotname", slotnameBuffer, _CurrentSlotname);
	Context::PushPopEntry<Anything> aCombinedEntry(ctx, "CombinedKey", combinedKeyBuffer, _CombinedKeyName);
	return doGetValue(strNewKey, value, ctx, script);
}
void JSClassWriter::GenerateSource(String& sourceOut)
{
    String source = "";

    if (klass_->IsNumberArray())
        return;

    WriteFunctions(source);

    String packageName = klass_->GetModule()->GetPackage()->GetName();

    source.AppendWithFormat("static void jsb_class_define_%s(JSVM* vm)\n{\n", klass_->GetName().CString());
    source.Append("duk_context* ctx = vm->GetJSContext();\n");

    GenerateStaticFunctionsSource(source, packageName);

    GenerateNonStaticFunctionsSource(source, packageName);

    source.Append("}\n");

    sourceOut += source;

}
/// Insert into a Market
bool GameEconomicServer::insertDBMarket(MarketInformation &TempMarket)
{
    /// get db
    connectorDB * connectionDB = GetSubsystem<connectorDB>();

    /// temporary user
    MarketInformation TemporaryDBMarket;

    /// Copy specific Markets
    TemporaryDBMarket.MarketName = TempMarket.MarketName.Trimmed();
    TemporaryDBMarket.MarketFee=TempMarket.MarketFee;
    TemporaryDBMarket.MarketSystem=TempMarket.MarketSystem;
    TemporaryDBMarket.Bidding=TempMarket.Bidding;
    TemporaryDBMarket.UniqueID=TempMarket.UniqueID;
    TemporaryDBMarket.AlienRace = TempMarket.AlienRace;
    TemporaryDBMarket.AlienAllianceAligned = TempMarket.AlienAllianceAligned;


    if(TemporaryDBMarket.MarketName.Empty()
            ||TemporaryDBMarket.UniqueID.Empty())
    {
        cout << "Cannot create prepared statement for insertDBMarket(MarketInformation &TempMarket)";
        return false;
    }


    ///StateStart
    String PreparedStatement = String("INSERT INTO Markets (`MarketName`,`MarketSystem`, `MarketFee`,`MarketAlienRace`,`MarketAlienAllianceAligned`, `MarketBidding`, `MarketUniqueID`) VALUES (");


    /// Copy information to statement
    PreparedStatement.Append("'"+TemporaryDBMarket.MarketName+"'");
    PreparedStatement.Append(","+String(TemporaryDBMarket.MarketSystem)+"");
    PreparedStatement.Append(","+String(TemporaryDBMarket.MarketFee)+"");
    PreparedStatement.Append(","+String(TemporaryDBMarket.AlienRace)+"");
    PreparedStatement.Append(","+String((unsigned int)TemporaryDBMarket.AlienAllianceAligned)+"");
    PreparedStatement.Append(","+String(TemporaryDBMarket.Bidding)+"");;
    PreparedStatement.Append(",'"+TemporaryDBMarket.UniqueID+"");

    /// Create the rest of the statement
    PreparedStatement.Append(");");

    string mysqlpreparedstatement =string(PreparedStatement.CString());

    /// attempt to write
    if(!connectionDB ->executeQuery(mysqlpreparedstatement))
    {
        return false;
    }

    return true;
}
void HTTPPostRequestBodyParserTest::ReadMultiPartPost()
{
	StartTrace(HTTPPostRequestBodyParserTest.ReadMultiPartPost);
	std::iostream *is = coast::system::OpenStream("MultiPartBody.txt", 0);

	t_assertm(is != 0, "expected 'MultiPartBody.txt' to be there");
	if ( is ) {
		MIMEHeader mh;
		t_assertm(mh.ParseHeaders(*is, 4096, 4096), "expected global header parsing to succeed");
		assertEqual(586L, mh.GetParsedHeaderLength());
		HTTPPostRequestBodyParser sm(mh);
		t_assert(sm.Parse(*is));
		Anything expected;
		Anything result = sm.GetContent();

		delete is;

		t_assert(!GetConfig().IsNull());
		assertAnyEqual(GetConfig()["MultiPartResult"], result);
	}
	// This sequence takes advantage of the String::SubString
	// feature to return the whole remainder of the string starting
	// from the first occurrence the substring-pattern has been found.
	// This relieves us from the need to create an expected result file
	// which we would use to verify the results.

	is =  coast::system::OpenStream("MultiPartBody.txt", 0);
	if ( is ) {
		MIMEHeader mh;
		t_assertm(mh.ParseHeaders(*is, 4096, 4096), "expected global header parsing to succeed");
		assertEqual(586L, mh.GetParsedHeaderLength());
		HTTPPostRequestBodyParser sm(mh);
		t_assert(sm.Parse(*is));
		String unparsedContent = sm.GetUnparsedContent();
		delete is;

		is =  coast::system::OpenStream("MultiPartBody.txt", 0);
		if (is) {
			char c;
			String tmp;
			while ((!!(*is).get(c))) {
				tmp.Append(c);
			}
			String final;
			final = tmp.SubString(unparsedContent);
			assertEqual(final, unparsedContent);
			delete is;
		}
	}
Example #22
0
String  ParameterJob::ToString ()
{
  String  statusStr ("");

  statusStr.Append (curStatus);


  statusStr << "\t" << processNum
            << "\t" << jobId 
            << "\t" << cParm
            << "\t" << gammaParm
            << "\t" << aParm
            << "\t" << accuracy;
            
  
  return  statusStr;
} /* ToString */
Example #23
0
bool JSVM::ExecuteFile(File *file)
{
    if (!file)
        return false;

    String source;

    file->ReadText(source);
    source.Append('\n');

    duk_push_string(ctx_, file->GetFullPath().CString());
    if (duk_eval_raw(ctx_, source.CString(), 0,
        DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
    {
        SendJSErrorEvent(file->GetFullPath());

        duk_pop(ctx_);
        return false;
    }

    duk_pop(ctx_);

    return true;
}
Example #24
0
bool JSVM::ExecuteScript(const String& scriptPath)
{
    String path = scriptPath;
    if (!path.StartsWith("Scripts/"))
        path = "Scripts/" + path;

    if (!path.EndsWith(".js"))
        path += ".js";

    SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));

    if (file.Null())
    {
        return false;
    }

    String source;

    file->ReadText(source);
    source.Append('\n');

    duk_push_string(ctx_, file->GetFullPath().CString());
    if (duk_eval_raw(ctx_, source.CString(), 0,
                     DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
    {
        if (duk_is_object(ctx_, -1))
            SendJSErrorEvent(path);

        duk_pop(ctx_);
        return false;
    }

    duk_pop(ctx_);

    return true;
}
/// Main program execution code
void GameEconomicGameClient::Start()
{
    /// Initialize
    Init(context_);

    /// Execute base class startup
    GameEconomicApp::Start();

    ResourceCache* cache = GetSubsystem<ResourceCache>();
    XMLFile* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
    FileSystem * filesystem = GetSubsystem<FileSystem>();
    GameStateHandlerComponent * gamestatehandlercomponent_ = GetSubsystem<GameStateHandlerComponent>();

    /// Set aApplication
    gamestatehandlercomponent_->SetApplication(applicationPtr);

    /// Get ui
    UI* ui = GetSubsystem<UI>();

    /// create variables (urho3d)
    String additionresourcePath;

    /// Append Resource path
    additionresourcePath.Append(filesystem->GetProgramDir().CString());
    additionresourcePath.Append("Resources/");

    /// add resource path to last
    cache -> AddResourceDir(additionresourcePath);

    /// Load COnfiguration
    GameConfig = new Configuration();

    LoadConfiguration(*GameConfig);

    /// Turn on networking
    if(LoadNetworkConfig(NetConfig)==false)
    {
        /// Set up network configuration
        NetConfig.hostport = 3632;
        NetConfig.hostserver = String("127.0.0.1");
        NetConfig.hostidentity = Unauthenticated;
    }

    /// Set up default network status
    NetOnline = NetDisconnected;
    NetStats = NetworkOffline;

    /// Set the loaded style as default style
    uiRoot_->SetDefaultStyle(style);

    CreateCursor();

    ui->GetCursor()->SetVisible(true);

    /// Initialize Console
    InitializeConsole();

    GetSubsystem<Input>()->Update();

    /// Enable OS cursor
    /// Configure rudimentary state handler
    gamestatehandlercomponent_ ->SetUIState(UI_NONE);

    GetSubsystem<Input>()->SetMouseVisible(true);

    /// load account
    ///LoadAccount();

    /// Create test value
    testvalue=121;

    /// Debug output context and testvalue
    cout << "Debug: ExistenceClient Class Test Value " << testvalue << " context_ " << &context_ << endl;

    /// Finally subscribe to the update event. Note that by subscribing events at this point we have already missed some events
    /// like the ScreenMode event sent by the Graphics subsystem when opening the application window. To catch those as well we
    /// could subscribe in the constructor instead.
    SubscribeToEvents();

    /// Randomize timer
    srand (time(NULL));

    cout << "Debig: Existence App Existence " << applicationPtr ->GetTestString()<< endl;

    /// Create test value

    cout << "Debig: Existence App Existence " << applicationPtr ->GetTestString()<< endl;

    touchenabled_=false;

    /// Network related
    SubscribeToEvent(E_NETWORKMESSAGE, HANDLER(GameEconomicGameClient, HandleNetworkMessage));
    SubscribeToEvent(E_SERVERCONNECTED, HANDLER(GameEconomicGameClient, HandlerServerConnected));
    SubscribeToEvent(E_SERVERDISCONNECTED, HANDLER(GameEconomicGameClient, HandlerServerDisconnected));
    SubscribeToEvent(E_CONNECTFAILED, HANDLER(GameEconomicGameClient, HandlerServerConnectionFailed));

    ResourcesManager = new ResourceManager(context_);
    ActivitiesManager = new ActivityManager(context_);

    gamestatehandlercomponent_->Start();

    return;
}
Example #26
0
void
UserProfileForm::OnTransactionReadyToRead(HttpSession& httpSession, HttpTransaction& httpTransaction, int availableBodyLen)
{

	AppLogDebug("OnTransactionReadyToRead,..availableBodyLen=%d",availableBodyLen);
	count++;

	HttpResponse* pHttpResponse = httpTransaction.GetResponse();

	if(pHttpResponse->GetHttpStatusCode() == HTTP_STATUS_OK)
	{
		__pBuffer = pHttpResponse->ReadBodyN();
	}
	if(__pProfileName==NULL)
	{
		ParseJsonData();
		Label *pLabel = new Label();
		String labelText(L"Welcome ");
		labelText.Append(*__pProfileName);
		AppLog("labelText is =%ls",labelText.GetPointer());
		pLabel->Construct(Rectangle(05, 50, 500, 100), labelText);
		AddControl(*pLabel);
		Draw();
		Show();

		__pSession->CloseTransaction(httpTransaction);
		delete __pSession;
		__pSession = null;
	}

	//Get Profile Picture

	String imageurl;
	imageurl.Append(L"https://graph.facebook.com/me");
	imageurl.Append(L"/picture?");
	imageurl.Append(L"access_token=");
	imageurl.Append(__accessToken);
	SendRequestGet(imageurl);

	__pProfileImage = new Image();
	__pProfileImage->Construct();

	Bitmap *pBitmap;
	pBitmap=__pProfileImage->DecodeN(*__pBuffer,IMG_FORMAT_JPG,BITMAP_PIXEL_FORMAT_ARGB8888,150,150);
	Label *pImageLabel = new Label();
	pImageLabel->Construct(Rectangle(150,150, 150, 150),"");
	pImageLabel->SetBackgroundBitmap(*pBitmap);
	AddControl(*pImageLabel);

	Button* pGetFriends = new Button();
	pGetFriends->Construct(Rectangle(30,330, 350, 70), L"Get Friends");
	pGetFriends->SetActionId(ID_BUTTON_FRIENDS_CLICKED);
	pGetFriends->AddActionEventListener(*this);
	AddControl(*pGetFriends);

	Button* pLogout = new Button();
	pLogout->Construct(Rectangle(30,430, 350, 70), L"Logout");
	pLogout->SetActionId(ID_BUTTON_LOGOUT_CLICKED);
	pLogout->AddActionEventListener(*this);
	AddControl(*pLogout);
	Draw();
	Show();

}
void JSPackageWriter::GenerateSource()
{
    String source = "// This file was autogenerated by JSBind, changes will be lost\n\n";

    String defineGuard = package_->GetPlatformDefineGuard();

    if (defineGuard.Length())
    {
        source += ToString("%s\n\n", defineGuard.CString());        
    }

    source += "#include <Duktape/duktape.h>\n";
    source += "#include <AtomicJS/Javascript/JSVM.h>\n";
    source += "#include <AtomicJS/Javascript/JSAPI.h>\n";

    source += "\n\nnamespace Atomic\n{\n";

    String packageLower = package_->GetName().ToLower();

    for (unsigned i = 0; i < package_->modules_.Size(); i++)
    {
        JSBModule* module = package_->modules_.At(i);

        if (module->GetDotNetModule())
            continue;

        String moduleGuard = module->GetModuleDefineGuard();

        if (moduleGuard.Length())
        {
            source += ToString("\n%s\n", moduleGuard.CString());
        }

        String moduleLower = module->GetName().ToLower();

        source.AppendWithFormat("\nextern void jsb_package_%s_preinit_%s (JSVM* vm);", packageLower.CString(), moduleLower.CString());
        source.AppendWithFormat("\nextern void jsb_package_%s_init_%s (JSVM* vm);", packageLower.CString(), moduleLower.CString());

        if (moduleGuard.Length())
        {
            source += ToString("\n#endif\n", moduleGuard.CString());
        }

    }

    source += "\n\nstatic void jsb_modules_setup_prototypes(JSVM* vm)\n{\n";

    source += "   // It is important that these are in order so the prototypes are created properly\n";
    source += "   // This isn't trivial as modules can have dependencies, so do it here\n\n";

    WriteProtoTypeSetup(source);

    source += "\n}\n";

    source.AppendWithFormat("\n\nstatic void jsb_package_%s_preinit(JSVM* vm)\n{", packageLower.CString());


    source.Append("\n    // Create the global package object\n");
    source.Append("    duk_context* ctx = vm->GetJSContext();\n");
    source.Append("    duk_push_object(ctx);\n");
    source.AppendWithFormat("    duk_put_global_string(ctx, \"%s\");\n", package_->GetName().CString());

    for (unsigned i = 0; i < package_->modules_.Size(); i++)
    {
        JSBModule* module = package_->modules_.At(i);

        if (module->GetDotNetModule())
            continue;

        String moduleGuard = module->GetModuleDefineGuard();

        if (moduleGuard.Length())
        {
            source += ToString("\n%s\n", moduleGuard.CString());
        }

        if (module->Requires("3D"))
            source += "\n#ifdef ATOMIC_3D";

        String moduleLower = module->GetName().ToLower();

        source.AppendWithFormat("\n   jsb_package_%s_preinit_%s(vm);", packageLower.CString(), moduleLower.CString());

        if (module->Requires("3D"))
            source += "\n#endif //ATOMIC_3D\n";

        if (moduleGuard.Length())
        {
            source += ToString("\n#endif\n", moduleGuard.CString());
        }

    }

    source += "\n}\n\n";

    source.AppendWithFormat("\n\nvoid jsb_package_%s_init(JSVM* vm)\n{", packageLower.CString());

    source.AppendWithFormat("\n\n   jsb_package_%s_preinit(vm);\n", packageLower.CString());

    source += "\n\n   jsb_modules_setup_prototypes(vm);\n";

    for (unsigned i = 0; i < package_->modules_.Size(); i++)
    {
        JSBModule* module = package_->modules_.At(i);

        if (module->GetDotNetModule())
            continue;

        String moduleLower = module->GetName().ToLower();

        String moduleGuard = module->GetModuleDefineGuard();

        if (moduleGuard.Length())
        {
            source += ToString("\n%s\n", moduleGuard.CString());
        }

        if (module->Requires("3D"))
            source += "\n#ifdef ATOMIC_3D";

        source.AppendWithFormat("\n   jsb_package_%s_init_%s(vm);", packageLower.CString(), moduleLower.CString());
        
        if (module->Requires("3D"))
        {
            source += "\n#endif //ATOMIC_3D\n";
        }

        if (moduleGuard.Length())
        {
            source += ToString("\n#endif\n", moduleGuard.CString());
        }

    }

    source += "\n}\n\n";

    // end Atomic namespace
    source += "\n}\n";

    if (defineGuard.Length())
    {
        source += "\n#endif\n";
    }

    JSBind* jsbind = package_->GetSubsystem<JSBind>();

    String filepath = jsbind->GetDestNativeFolder() + "/JSPackage" + package_->name_ + ".cpp";

    File file(package_->GetContext());
    file.Open(filepath, FILE_WRITE);
    file.Write(source.CString(), source.Length());
    file.Close();

    for (unsigned i = 0; i < package_->modules_.Size(); i++)
    {
        if (package_->modules_[i]->GetDotNetModule())
            continue;

        JSModuleWriter writer(package_->modules_[i]);
        writer.GenerateSource();
    }

}
void SecurityModuleTest::EncodeDecodeTest() {
	Encoder encoder("encoder");

	int i;

	String EmptySt;
	String EncodedString;
	String DecodedString;
	String OriginalString;

	// Test 1:
	// checkif all HEX-values can be en-/decoded
	// check for identity of original and decoded string
	// check the lengths

	// setup original
	for (i = 0; i < 256; i++) {
		OriginalString.Append((char) i);
	}

	// encode decode with standard encoder (cleartext)
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	// assert strings are equal
	t_assert( memcmp( (const char *)OriginalString, (const char *)DecodedString, OriginalString.Length() ) == 0);
	t_assert( OriginalString.Length() == DecodedString.Length());

	assertEqual( OriginalString, DecodedString);
	assertEqual( OriginalString.Length(), DecodedString.Length());

	// Test 2
	// reset strings
	EncodedString = EmptySt;
	DecodedString = EmptySt;

	// encode decode with standard encoder (cleartext)
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	// check whether the Strings are identical
	assertCharPtrEqual( OriginalString, DecodedString);
	assertEqual(1, (long)( OriginalString == DecodedString ));

	// Test 3
	// reset strings
	OriginalString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	EncodedString = EmptySt;
	DecodedString = EmptySt;

	// encode decode with standard encoder (cleartext)
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	// check whether the Strings are identical
	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);
	assertCharPtrEqual( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", EncodedString);

	//Test 4
	// Only Unprintable Chars, unscrambled
	OriginalString = EmptySt;
	EncodedString = EmptySt;
	DecodedString = EmptySt;

	for (i = 0; i < 10; i++) {
		OriginalString.Append((char) i);
	}

	// encode decode with standard encoder (cleartext)
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	// check whether the Strings are identical
	t_assert( (memcmp( (const char *)OriginalString, (const char *)DecodedString, OriginalString.Length() ) == 0));
	t_assert( OriginalString.Length() == DecodedString.Length());

	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);

	assertCharPtrEqual( "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09", EncodedString);

	// One Printable Char, unscrambled
	OriginalString = "M";
	EncodedString = EmptySt;
	DecodedString = EmptySt;

	// check whether the Strings are identical
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);
	assertCharPtrEqual( "M", EncodedString);

	// One Unprintable Char, unscrambled
	OriginalString = EmptySt;
	OriginalString.Append((char) 5);

	OriginalString = OriginalString;
	EncodedString = EmptySt;
	DecodedString = EmptySt;
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);

	// String::IntPrintOn:  05     -> \x05
	// coast::urlutils::urlEncode: \x05   -> %5Cx05
	// coast::urlutils::urlEncode: %5Cx05 -> %255Cx05
	assertCharPtrEqual( "\x05", EncodedString);

	// Only Printable Chars, scrambled
	OriginalString = "ABC";
	EncodedString = EmptySt;
	DecodedString = EmptySt;
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);
	// w\"ABC\"
	assertCharPtrEqual( "ABC", EncodedString);

	// a particularly nasty sequence of non-printables and printables
	OriginalString = "Anfang%252B+%2BEnde";
	EncodedString = EmptySt;
	DecodedString = EmptySt;

	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	assertEqual( OriginalString, DecodedString);
	assertEqual( OriginalString, EncodedString);

	// Only Unprintable Chars, scrambled
	OriginalString = EmptySt;
	for (i = 0; i < 3; i++) {
		OriginalString.Append((char) i);
	}
	EncodedString = EmptySt;
	DecodedString = EmptySt;
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);

	assertCharPtrEqual( "\x00\x01\x02", EncodedString);

	// One Printable Char, scrambled
	OriginalString = "M";
	OriginalString = OriginalString;
	EncodedString = EmptySt;
	DecodedString = EmptySt;
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);
	assertCharPtrEqual( "M", EncodedString);

	//           1         2         3         4         5         6
	// 0123456789012345678901234567890123456789012345678901234567890123456789
	// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-$

	// One Unprintable Char, scrambled
	OriginalString = EmptySt;
	OriginalString.Append((char) 5);

	OriginalString = OriginalString;
	EncodedString = EmptySt;
	DecodedString = EmptySt;
	encoder.DoEncode(EncodedString, OriginalString);
	encoder.DoDecode(DecodedString, EncodedString);

	assertCharPtrEqual( OriginalString, DecodedString);
	t_assert( OriginalString == DecodedString);

	assertCharPtrEqual( "\x05", EncodedString);
}
void GameEconomicGameClient::LoadConfiguration(Configuration &configuration)
{
    /// Grab resources
    FileSystem * fileSystem = GetSubsystem<FileSystem>();

    /// Set all defaults
    bool success=false;

    configuration.GameModeForceTablet=false;

    configuration.VideoBloomParam1=0.9f;
    configuration.VideoBloomParam2=0.6f;

    /// Create String
    String configFileName;

    /// Set directory and path for network file
    configFileName.Append(fileSystem->GetProgramDir().CString());
    configFileName.Append("");
    configFileName.Append("Configuration.xml");

    /// If file does not exist exit function with null structure
    if (!fileSystem->FileExists(configFileName))
    {
        cout << "Configuration file not found.. Using defaults.. " << endl;

        return;
    }

    /// Flag file for loading and load
    File loadFile(context_, configFileName, FILE_READ);

    XMLFile * configurationXML = new XMLFile(context_);

    configurationXML -> Load(loadFile);

    XMLElement configElem = configurationXML->GetRoot();

    /// If no configuration is set or no root
    if (configElem.IsNull())
    {
        cout << "Configuration file not found.. Using defaults.. " << endl;

        return;
    }

    /// Basic Config
    XMLElement GameModeConfigurationElem = configElem.GetChild("GameModeConfiguration");

    /// If no network server element return false;
    if (!GameModeConfigurationElem.IsNull())
    {
        if (GameModeConfigurationElem.HasAttribute("GameModeForceTablet")) configuration.GameModeForceTablet = GameModeConfigurationElem.GetBool("GameModeForceTablet");
    }

    /// Basic Config
    XMLElement VideoConfigurationElem = configElem.GetChild("VideoConfiguration");

    /// If no network server element return false;
    if (!VideoConfigurationElem.IsNull())
    {
        if (VideoConfigurationElem.HasAttribute("BloomParam1")) configuration.VideoBloomParam1= VideoConfigurationElem.GetFloat("BloomParam1");
        if (VideoConfigurationElem.HasAttribute("BloomParam2")) configuration.VideoBloomParam2= VideoConfigurationElem.GetFloat("BloomParam2");
    }


    return;
}
/// Insert into a Transaction
bool GameEconomicServer::insertDBMarketTransaction(TransactionInformation &TempTransaction)
{
    /// get db
    connectorDB * connectionDBMarketTransaction = GetSubsystem<connectorDB>();

    /// temporary user
    TransactionInformation TemporaryDBMarketTransaction;

    /// Copy specific Transactions
    TemporaryDBMarketTransaction.TradeGood = TempTransaction.TradeGood;
    TemporaryDBMarketTransaction.AskingPrice=TempTransaction.AskingPrice;
    TemporaryDBMarketTransaction.TimeLimit=TempTransaction.TimeLimit;
    TemporaryDBMarketTransaction.LastBid=TempTransaction.LastBid;
    TemporaryDBMarketTransaction.LastBidder=TempTransaction.LastBidder;
    TemporaryDBMarketTransaction.Bids=TempTransaction.Bids;
    TemporaryDBMarketTransaction.Seller=TempTransaction.Seller.Trimmed();
    TemporaryDBMarketTransaction.UniqueID=TempTransaction.UniqueID.Trimmed();
    TemporaryDBMarketTransaction.Market=TempTransaction.Market.Trimmed();


    if(TemporaryDBMarketTransaction.Seller.Empty()
            ||TemporaryDBMarketTransaction.UniqueID.Empty()
            ||TemporaryDBMarketTransaction.Market.Empty())
    {
        cout << "Cannot create prepared statement for insertDBMarketTransaction(TransactionInformation &TempTransaction)";
        return false;
    }


    ///State Start
    String PreparedStatement = String("INSERT INTO MarketTransactions (`TransactionResourceType`, `TransactionResourceQuanity`, `TransactionAskingPrice`, `TransactionEndTime`, `TransactionLastBid`, `TransactionLastBidder`, `TransactionBids`, `TransactionSeller`, `TransactionUniqueID`, `TransactionMarket`) VALUES ( ");


    /// Copy information to statement
    PreparedStatement.Append(""+String(TemporaryDBMarketTransaction.TradeGood.ResourceType)+"");
    PreparedStatement.Append(","+String(TemporaryDBMarketTransaction.TradeGood.Quantity)+"");
    PreparedStatement.Append(","+String(TemporaryDBMarketTransaction.AskingPrice)+"");
    PreparedStatement.Append(","+String(TemporaryDBMarketTransaction.TimeLimit)+"");
    PreparedStatement.Append(","+String(TemporaryDBMarketTransaction.LastBid)+"");;
    PreparedStatement.Append(",'"+TemporaryDBMarketTransaction.LastBidder+"");
    PreparedStatement.Append(","+String(TemporaryDBMarketTransaction.Bids)+"");;
    PreparedStatement.Append(",'"+TemporaryDBMarketTransaction.Seller+"");
    PreparedStatement.Append(",'"+TemporaryDBMarketTransaction.UniqueID+"");
    PreparedStatement.Append(",'"+TemporaryDBMarketTransaction.Market+"");

    /// Create the rest of the statement
    PreparedStatement.Append(");");

    string mysqlpreparedstatement =string(PreparedStatement.CString());

    /// attempt to write
    if(!connectionDBMarketTransaction ->executeQuery(mysqlpreparedstatement))
    {
        return false;
    }

    return true;
}