Exemple #1
1
   /// <summary>Draws an item</summary>
   /// <exception cref="Logic::IndexOutOfRangeException">Invalid index</exception>
   /// <exception cref="Logic::InvalidOperationException">Invalid window styles</exception>
   void DualComboBox::ControlRenderer::DrawItem()
   {
      // Ensure ComboBox doesn't hold strings
      if (HasStrings())
         throw InvalidOperationException(HERE, L"Cannot owner-draw DualComboBox with CBS_HASSTRINGS");

      // BACKGROUND
      DrawBackground(Bounds, COLOR_WINDOW);

      // Edit Mode
      if (EditMode || Index == CB_ERR)
      {
         // Create left/right/top/bottom border
         Bounds.DeflateRect(GetSystemMetrics(SM_CXEDGE), GetSystemMetrics(SM_CYEDGE));

         // TEXT
         if (ComboBox->GetCount())
         {
            // Get selected item, if any
            auto sel = ComboBox->GetCurSel();
            ItemData* it = dynamic_cast<DualComboBox*>(ComboBox)->FindItem(sel != CB_ERR ? sel : 0);

            DrawText(it->Left, Bounds, DT_LEFT, COLOR_WINDOWTEXT);
         }
      }
      else
      {
         // Create left/right border
         Bounds.DeflateRect(GetSystemMetrics(SM_CXEDGE), 0);
      
         // TEXT
         DrawText(Item->Left, Bounds, DT_LEFT, COLOR_WINDOWTEXT);
         DrawText(Item->Right, Bounds, DT_RIGHT, COLOR_GRAYTEXT);
      }
   }
fs::path
HOSTFXR_UTILITY::GetAbsolutePathToHostFxr(
    const fs::path & dotnetPath
)
{
    std::vector<std::wstring> versionFolders;
    const auto hostFxrBase = dotnetPath.parent_path() / "host" / "fxr";

    LOG_INFOF(L"Resolving absolute path to hostfxr.dll from '%ls'", dotnetPath.c_str());

    if (!is_directory(hostFxrBase))
    {
        throw InvalidOperationException(format(L"Unable to find hostfxr directory at %s", hostFxrBase.c_str()));
    }

    FindDotNetFolders(hostFxrBase, versionFolders);

    if (versionFolders.empty())
    {
        throw InvalidOperationException(format(L"Hostfxr directory '%s' doesn't contain any version subdirectories", hostFxrBase.c_str()));
    }

    const auto highestVersion = FindHighestDotNetVersion(versionFolders);
    const auto hostFxrPath = hostFxrBase  / highestVersion / "hostfxr.dll";

    if (!is_regular_file(hostFxrPath))
    {
        throw InvalidOperationException(format(L"hostfxr.dll not found at '%s'", hostFxrPath.c_str()));
    }

    LOG_INFOF(L"hostfxr.dll located at '%ls'", hostFxrPath.c_str());
    return hostFxrPath;
}
   /// <summary>Commits the document</summary>
   /// <param name="title">Revision title</param>
   /// <returns></returns>
   BOOL ScriptDocument::OnCommitDocument(const wstring& title)
   {
      WorkerData data(Operation::LoadSaveDocument);
      
      try
      {
         // Feedback
         Console << Cons::UserAction << "Committing script: " << FullPath << ENDL;
         data.SendFeedback(ProgressType::Operation, 0, VString(L"Committing script '%s'", FullPath.c_str()));

         // Get project
         auto proj = ProjectDocument::GetActive();

         // Verify document is part of project
         if (!proj)
            throw InvalidOperationException(HERE, L"No current project");
         else if (!proj->Contains(FullPath))
            throw InvalidOperationException(HERE, L"Document is not a member of current project");
         
         // Commit
         if (proj->Commit(*this, title))
            data.SendFeedback(Cons::Success, ProgressType::Succcess, 0, L"Script committed successfully");
         else
            data.SendFeedback(Cons::Error, ProgressType::Failure, 0, L"Script commit aborted");

         return TRUE;
      }
      catch (ExceptionBase&  e) 
      {
         Console.Log(HERE, e, VString(L"Failed to commit script '%s'", FullPath.c_str()));
         data.SendFeedback(Cons::Error, ProgressType::Failure, 0, L"Failed to commit script");
         return FALSE;
      }
   }
      /// <summary>Populates the library from the string library</summary>
      /// <param name="data">Feedback data</param>
      /// <returns>Number of objects found</returns>
      /// <exception cref="Logic::ArgumentNullException">Worker data is null</exception>
      /// <exception cref="Logic::InvalidOperationException">String library is empty</exception>
      UINT  ScriptObjectLibrary::Enumerate(WorkerData* data)
      {
         REQUIRED(data);

         // Ensure string library exists
         if (StringLib.Files.empty())
            throw InvalidOperationException(HERE, L"String library has not been enumerated");

         // Feedback
         data->SendFeedback(Cons::Heading, ProgressType::Operation, 1, L"Generating script objects from language files");

         // Populate
         Clear();
         Populate(data);

         // DEBUG:
         Console << "Discovered " << (int)Objects.size() << " script objects..." << ENDL;
         
         // Feedback number of conflicts
         if (Objects.size() - Lookup.size() > 1)   // Always 1 less in lookup because old [THIS] intentionally removed
            data->SendFeedback(Cons::Error, ProgressType::Error, 2, VString(L"Unable to process %d script objects", Objects.size()-Lookup.size()-1));
         
         // Feedback object count
         data->SendFeedback(ProgressType::Info, 2, VString(L"Loaded %d script objects", Lookup.size()));
         return Lookup.size();
      }
    void PackingSerializer::ReadConfig(string baseFolder, ExecutionConfig* config) const
    {
        config->generationConfig.baseFolder = baseFolder;
        printf("The current working directory is %s.\n", baseFolder.c_str());
        ScopedFile<ExceptionErrorHandler> file(Path::Append(baseFolder, CONFIG_FILE_NAME), "r");

        int boundariesMode;
        // For scanning and printing doubles, see http://stackoverflow.com/questions/210590/why-does-scanf-need-lf-for-doubles-when-printf-is-okay-with-just-f
        fscanf(file,
                "Particles count: %d\n" \
                "Packing size: " FLOAT_FORMAT " " FLOAT_FORMAT " " FLOAT_FORMAT "\n" \
                "Generation start: %d\n" \
                "Seed: %d\n" \
                "Steps to write: %d\n" \
                "Boundaries mode: %d\n" \
                "Contraction rate: " FLOAT_FORMAT,
                &config->systemConfig.particlesCount,
                &config->systemConfig.packingSize[Axis::X],
                &config->systemConfig.packingSize[Axis::Y],
                &config->systemConfig.packingSize[Axis::Z],
                &config->generationConfig.generationStart,
                &config->generationConfig.seed,
                &config->generationConfig.stepsToWrite,
                &boundariesMode,
                &config->generationConfig.contractionRate);

        config->systemConfig.boundariesMode = static_cast<BoundariesMode::Type>(boundariesMode);

        printf("\nN is %d\ndimensions are %f %f %f\ngeneration mode: %s\nseed %d\nsteps to write intermediate state %d\nboundaries mode is %d\n\n\n",
                config->systemConfig.particlesCount,
                config->systemConfig.packingSize[Axis::X],
                config->systemConfig.packingSize[Axis::Y],
                config->systemConfig.packingSize[Axis::Z],
                config->generationConfig.generationStart == 1 ? "start" : "continue",
                config->generationConfig.seed,
                config->generationConfig.stepsToWrite,
                config->systemConfig.boundariesMode);

        if (config->systemConfig.boundariesMode == BoundariesMode::Trapezoid)
        {
            fscanf(file, "\nAlpha: " FLOAT_FORMAT, &config->systemConfig.alpha);
            if ((config->systemConfig.alpha >= 90.0) || (config->systemConfig.alpha < 0.0))
            {
                printf("Error: alpha must be non-negative and less than 90.0 degrees!\n");
                throw InvalidOperationException("Alpha is negative or less than 90.0 degrees.");
            }
            else
            {
                printf("Alpha is %lf degrees\n", config->systemConfig.alpha);
            }
        }

        int generationMode;
        int numberOfReads = fscanf(file, "\nGeneration mode: %d", &generationMode);
        config->generationConfig.initialParticleDistribution = static_cast<InitialParticleDistribution::Type>(generationMode);
        if (numberOfReads <= 0)
        {
            config->generationConfig.initialParticleDistribution = InitialParticleDistribution::Poisson;
        }
    }
      /// <summary>Extracts column information from a text tag</summary>
      /// <param name="tag">text tag</param>
      /// <exception cref="Logic::InvalidOperation">Not a 'text' tag</exception>
      /// <exception cref="Logic::Language::RichTextException">Invalid tag property</exception>
      void  RichStringParser::SetColumnInfo(const RichTag& tag)
      {
         // Ensure tag is 'text'
         if (tag.Type != TagType::Text)
            throw InvalidOperationException(HERE, VString(L"Cannot extract column info from a '%s' tag", ::GetString(tag.Type).c_str()) );

         // Extract properties direct into output
         for (const Property& p : tag.Properties)
         {
            // Column count
            if (p.Name == L"cols")
            {
               // Verify
               auto cols = _ttoi(p.Value.c_str());
               if (cols < 0 || cols > 3)
                  throw RichTextException(HERE, VString(L"Cannot arrange text in %d columns", cols));
               Output.Columns = static_cast<ColumnType>(cols);
            }
            // Column width
            else if (p.Name == L"colwidth")
               Output.Width = _ttoi(p.Value.c_str());
            // Column spacing
            else if (p.Name == L"colspacing")
               Output.Spacing = _ttoi(p.Value.c_str());
            else
               // Unrecognised
               throw RichTextException(HERE, VString(L"Invalid 'text' tag property '%s'", p.Name.c_str()));
         }
      }
 void PackingSerializer::ReadParticleDiameters(string diametersFilePath, Packing* particles) const
 {
     int numberOfParticles = particles->size();
     Packing& particlesRef = *particles;
     ScopedFile<LogErrorHandler> file(diametersFilePath, "r");
     if (file.Exists())
     {
         printf("Reading particle diameters from a file 'diameters'...\n");
         for (int i = 0; i < numberOfParticles; ++i)
         {
             int result = fscanf(file, "%lf", &particlesRef[i].diameter);
             bool endOfFile = result == EOF;
             bool notLastParticle = i < (numberOfParticles - 1);
             if (endOfFile && notLastParticle)
             {
                 printf("Diameters file is too short. Exiting...\n");
                 throw InvalidOperationException("Diameters file is too short.");
             }
         }
         printf("done.\n");
     }
     else
     {
         printf("Diameter of all particles is 1.0\n");
         for (int i = 0; i < numberOfParticles; ++i)
         {
             particlesRef[i].diameter = 1.0;
         }
     }
 }
Exemple #8
0
      /// <summary>Reads the next character</summary>
      /// <param name="c">Next character</param>
      /// <returns>True if read, false if EOF</returns>
      /// <exception cref="Logic::InvalidOperationException">Stream has been closed (reader has been move-copied)</exception>
      /// <exception cref="Logic::IOException">An I/O error occurred</exception>
      bool  StringReader::ReadChar(WCHAR&  c)
      {
         // Ensure stream has not been moved
         if (Input == nullptr)
            throw InvalidOperationException(HERE, L"Underlying stream has been closed");

         // First Call: Read entire file 
         else if (Buffer == nullptr)
            Buffer = FileStream::ConvertFileBuffer(Input, Length);

         // EOF: Return false
         if (IsEOF())
         {
            c = NULL;
            return false;
         }

         // Increment line number 
         if (c == L'\n')
            LineNum++;

         // Set byte, advance position, return true
         c = Buffer.get()[Position++];
         return true;
      }
Exemple #9
0
 void BrowserCore::CheckBrowserInitialization()
 {
     if (!_isBrowserInitialized)
     {
         throw gcnew InvalidOperationException("Browser is not initialized");
     }
 }
Exemple #10
0
	void NodeVersionLoader::startDownload()
	{
		auto self = shared_from_this();
		checkThread();
		
		auto& item = currentDownloadItem();
		{
			std::lock_guard<std::mutex> lock(downloadQueueMutex);
			--item.retryCount;
		}
		
		state = State::Connecting;
		log.setChannel("Download:" + item.version);
		
		std::string fileName;
		auto ver = item.version;
		try {
			onNeedsDownloadFileName(ver, fileName);
			if (fileName.empty()) {
				MSCThrow(InvalidOperationException("File name is empty."));
			}
		} catch (...) {
			downloadFailed("Failed to determine the downloaded file path.: " +
						   boost::current_exception_diagnostic_information());
			return;
		}
		try {
			file.reset(new std::ofstream(fileName.c_str(),
										 std::ios::out |
										 std::ios::trunc |
										 std::ios::binary));
			
			file->exceptions(std::ios::failbit |
							 std::ios::badbit);
		} catch (...) {
			file.reset();
			downloadFailed("Failed to open the destination file '" + fileName + "'.: " +
						   boost::current_exception_diagnostic_information());
			return;
		}
		
		BOOST_LOG_SEV(log, LogLevel::Info) <<
		"Connecting to the master server.";
		
		socket.async_connect(endpoint, [this, self, &item](const error_code& error) {
			checkThread();
			
			if (disposed) {
				downloadCancelled();
				return;
			}
			if (error) {
				downloadFailed(error.message());
				return;
			}
			
			sendHeader();
		});
	}
Exemple #11
0
      /// <summary>Get full path of the data file</summary>
      /// <returns></returns>
      Path  XFileInfo::GetDataFile() const
      { 
         if (Source == FileSource::Physical)
            throw InvalidOperationException(HERE, L"Physical files have no data file");

         // Generate path
         return Catalog->FullPath.RenameExtension(L".dat"); 
      }
Exemple #12
0
void GetPanelInfo(HANDLE handle, PanelInfo& info)
{
	SetState<bool> state(State::GetPanelInfo, true);

	info.StructSize = sizeof(info);
	if (!Info.PanelControl(handle, FCTL_GETPANELINFO, 0, &info))
		throw gcnew InvalidOperationException("Cannot get panel information.");
}
Exemple #13
0
 bool exists( const char* name ) const
 {
   if( type_ != object_type )
   {
     throw InvalidOperationException( "exist() only valid on object type" );
   }
   return getObject().find( name ) != getObject().end();
 }
DefaultMemoryInputData::DefaultMemoryInputData(int size)
{
	PxU8* buffer = (PxU8*)malloc(sizeof(Byte) * size);

	if (buffer == NULL)
		throw gcnew InvalidOperationException(String::Format("Failed to allocate memory for buffer of size {0} bytes", size));

	_defaultMemoryInputData = new PxDefaultMemoryInputData(buffer, size);
}
Exemple #15
0
void ArrayVariant::addMember(const Variant& member) {
    if (value) {
        if (member.getType().isValid())
            boost::dynamic_pointer_cast<Value>(value)->addMember(member);
        else
            throw InvalidDataTypeException();
    }
    else
        throw InvalidOperationException("Adding a member to an invalid array");
}
Exemple #16
0
 size_t size() const
 {
   if( type_ != array_type )
   {
     throw InvalidOperationException(
         "size() only valid on array type"
         );
   }
   return getArray().size();
 }
Exemple #17
0
	const String& opcodeToString(Opcode op)
	{
		buildOpcodeMaps();

		auto found = _opcode_to_str.find(op);
		if (found == _opcode_to_str.end())
			throw InvalidOperationException(FORMAT("Unknown opcode %u", (UInt32)op));

		return found->second;
	}
Exemple #18
0
	UInt8 getOpcodeArgumentCount(Opcode op)
	{
		buildOpcodeMaps();

		auto found = _opcode_args.find(op);
		if (found == _opcode_args.end())
			throw InvalidOperationException(FORMAT("Unknown opcode %u", (UInt32)op));

		return found->second;
	}
Exemple #19
0
  JsonData& operator [] ( size_t i ) const
  {
    if( type_ != array_type )
    {
      throw InvalidOperationException(
          "operator[ size_t ] only valid on array type"
          );
    }

    return getArray()[ i ];
  }
Exemple #20
0
  JsonData& operator [] ( const std::string& name ) const
  {
    if( type_ != object_type )
    {
      throw InvalidOperationException(
          "operator[ string ] only valid on object type"
          );
    }

    return getObject()[ name ];
  }
Exemple #21
0
  JsonData& operator [] ( const char* name ) const
  {
    if( type_ != object_type )
    {
      throw InvalidOperationException( 
          "operator[ char* ] only valid on object type" 
          );
    }

    return getObject()[ name ];
  }
Exemple #22
0
void ArrayVariant::ValueImplV::addMember(const Variant& member) {
    if (!numMembers) {
        if (member.getType() == memberType)
            members.push_back(member);
        else
            throw DataTypeMismatchException(memberType.getIdentifier(),
                                            member.getType().getIdentifier());
    }
    else
        throw InvalidOperationException("Adding a member to a non-dynamic array");
}
Exemple #23
0
AutoEditorInfo::AutoEditorInfo(intptr_t editorId, bool safe)
{
	StructSize = sizeof(EditorInfo);
	if (!Info.EditorControl(editorId, ECTL_GETINFO, 0, this))
	{
		if (safe)
			EditorID = -1;
		else
			throw gcnew InvalidOperationException(__FUNCTION__ " failed. Ensure current editor.");
	}
}
void FileBlocks::updateSpace(unsigned blockNumber,unsigned occupied){

	int freeSpace = (blockSize) - occupied;

	if(freeSpace < 0)
		throw InvalidOperationException("Overflow in a file Block ");

	unsigned int size = spaceInBlocks.size();
	if (size == blockNumber)
		spaceInBlocks.push_back(freeSpace);

	else
		spaceInBlocks.at(blockNumber) = freeSpace;
}
Exemple #25
0
void ArrayVariant::ValueImplV::resize(size_t numMembers) {
    if (!this->numMembers || (numMembers == this->numMembers)) {
        if (numMembers != members.size()) {
            size_t i = members.size();

            members.resize(numMembers);

            for ( ; i < members.size(); ++i)
                members[i] = memberType.createVariant();
        }
    }
    else
        throw InvalidOperationException("Resizing a non-dynamic array");
}
Exemple #26
0
	void CoreBase::Run()
	{
		if(gThread == nullptr)
			throw InvalidOperationException("The graphics thread must be initialized before calling CoreBase::Run.",
				__FUNCTION__);

		currentLevel = nextLevel;
		
		while(currentLevel != nullptr)
		{
			currentLevel->Run();
			delete currentLevel;
			currentLevel = nextLevel;
		}
	}
   /// <summary>Gets the text of the selected suggestion.</summary>
   /// <returns></returns>
   /// <exception cref="Logic::InvalidOperationException">No item selected</exception>
   /// <exception cref="Logic::NotImplementedException">Command selected</exception>
   wstring SuggestionList::GetSelected() const
   {
      // Ensure exists
      if (GetNextItem(-1, LVNI_SELECTED) == -1)
         throw InvalidOperationException(HERE, L"No item selected");

      // Get selection and format
      switch (SuggestionType)
      {
      case Suggestion::GameObject:   return VString(L"{%s}", Content[GetNextItem(-1, LVNI_SELECTED)].Text.c_str());
      case Suggestion::ScriptObject: return VString(L"[%s]", Content[GetNextItem(-1, LVNI_SELECTED)].Text.c_str());
      case Suggestion::Variable:     return VString(L"$%s", Content[GetNextItem(-1, LVNI_SELECTED)].Text.c_str());
      case Suggestion::Label:        return VString(L"%s:", Content[GetNextItem(-1, LVNI_SELECTED)].Text.c_str());
      case Suggestion::Command:      return Content[GetNextItem(-1, LVNI_SELECTED)].Text;
      default:  return L"Error";
      }
   }
Exemple #28
0
bool Thread::safeWait(double seconds) const {
  bool result = true;
  if (seconds != 0.0) {
    Thread* self = 0;
    try {
      self = &Threads::getInstance().getSelf();
    }
    catch (...) {
      self = 0;
    }
    if (self == this)
      throw InvalidOperationException("Thread::safeWait(): bad wait");
    if (safeIsBusy())
      result = mCleaned.wait(mMutex, seconds);
  }
  return result;
}
Exemple #29
0
    void MasterNodeConnection::didAccept()
	{
		auto self = shared_from_this();
        std::lock_guard<ioMutexType> lock(mutex);

        accepted = true;
		log.setChannel(str(format("Unknown [%s]") % tcpSocket().remote_endpoint()));

        auto headerBuffer = std::make_shared<std::uint32_t>();

        readAsync(asio::buffer(headerBuffer.get(), 4),
        [this, headerBuffer]
        (const boost::system::error_code& error, std::size_t readCount){
            try {
                if (error) {
                    MSCThrow(boost::system::system_error(error));
                }

                std::uint32_t header = *headerBuffer;
				std::shared_ptr<MasterNodeConnectionHandler> h;
				
                if (header == ControlStreamHeaderMagic) {
                    h = std::make_shared<MasterNode>(shared_from_this());
                } else if (header == VersionDownloadRequestMagic) {
                    MSCThrow(NotImplementedException());
				} else if (header == DataStreamMagic) {
					h = std::make_shared<MasterNodeClientStream>(shared_from_this());
                } else {
                    MSCThrow(InvalidOperationException(
                            str(format("Invalid header magic 0x%08x received.") % header)));
                }

                assert(h != nullptr);
				handler = h;

				h->service();

            } catch (...) {
				performShutdownByError(boost::current_exception_diagnostic_information());
            }
        });

    }
// The processPath ends with dotnet.exe or dotnet
// like: C:\Program Files\dotnet\dotnet.exe, C:\Program Files\dotnet\dotnet, dotnet.exe, or dotnet.
// Get the absolute path to dotnet. If the path is already an absolute path, it will return that path
fs::path
HOSTFXR_UTILITY::GetAbsolutePathToDotnet(
     const fs::path & applicationPath,
     const fs::path & requestedPath
)
{
    LOG_INFOF(L"Resolving absolute path to dotnet.exe from '%ls'", requestedPath.c_str());

    auto processPath = requestedPath;
    if (processPath.is_relative())
    {
        processPath = applicationPath / processPath;
    }

    //
    // If we are given an absolute path to dotnet.exe, we are done
    //
    if (is_regular_file(processPath))
    {
        LOG_INFOF(L"Found dotnet.exe at '%ls'", processPath.c_str());

        return processPath;
    }

    // At this point, we are calling where.exe to find dotnet.
    // If we encounter any failures, try getting dotnet.exe from the
    // backup location.
    // Only do it if no path is specified
    if (requestedPath.has_parent_path())
    {
        LOG_INFOF(L"Absolute path to dotnet.exe was not found at '%ls'", requestedPath.c_str());

        throw InvalidOperationException(format(L"Could not find dotnet.exe at '%s'", processPath.c_str()));
    }

    const auto dotnetViaWhere = InvokeWhereToFindDotnet();
    if (dotnetViaWhere.has_value())
    {
        LOG_INFOF(L"Found dotnet.exe via where.exe invocation at '%ls'", dotnetViaWhere.value().c_str());

        return dotnetViaWhere.value();
    }

    const auto programFilesLocation = GetAbsolutePathToDotnetFromProgramFiles();
    if (programFilesLocation.has_value())
    {
        LOG_INFOF(L"Found dotnet.exe in Program Files at '%ls'", programFilesLocation.value().c_str());

        return programFilesLocation.value();
    }

    LOG_INFOF(L"dotnet.exe not found");
    throw InvalidOperationException(format(
        L"Could not find dotnet.exe at '%s' or using the system PATH environment variable."
        " Check that a valid path to dotnet is on the PATH and the bitness of dotnet matches the bitness of the IIS worker process.",
        processPath.c_str()));
}