c# – Como e onde fazer hospedagem de site Asp.Net Framework 4.7.2

Obrigado por contribuir com o Stack Overflow em Português!

  • Certifique-se de responder à pergunta. Entre em detalhes sobre a sua solução e compartilhe o que você descobriu.

Mas evite

  • Pedir esclarecimentos ou detalhes sobre outras respostas.
  • Fazer afirmações baseadas apenas na sua opinião; aponte referências ou experiências anteriores.

Para aprender mais, veja nossas dicas sobre como escrever boas respostas.

Closed Port on Metaspoilt framework

so i run the kali linux OS on my PC and i use the metaspoilt framework; but i’m unable to access any ports when i run sudo netdiscover it always outputs that all ports are closed. even though metaspoilt has a port open.

What do I do?

Securing the REST APIs – Security Framework (Technology) V/S Custom

There are many ways to secure the REST APIs, from authentication and authorization view point. Below are the two which I know so far:

  1. Using existing token based IAM solutions like Okta, KeyCloak, Auth0, etc.

    • Pros: Already proven solution, feature rich, easy to start and run
    • Cons: Difficult to customize as per needs as the application grows, application becomes dependent on these third party solutions
  2. Building custom solution using filters, interceptors, and JWT (or opaque tokens)

    • Pros: Easy to customize as per needs as we have full control
    • Cons: Chances of error/leaks increases, amount of code to write and manage increases

Above are the points as per my understanding of securing the REST APIs, using token based authentication and authorization. I want to know –

  1. Which of these (or any other) are widely accepted and used in production environments?
  2. Which from these are best suited for small to mid scale projects?
  3. Is there any other way/solution (token based or anything else) to secure the REST APIs?

entity framework – C# Winforms App ,EF6, DB First with Auto Mapper Generic Repository and UOW context is not updated automatically when database is changed externally

I’ve started to work on a single user c# winforms application, with EF6 db first approach, AutoMapper, Generic Repository and UnitOfWork. They have been previously implemented by others former colleagues . I’m not very experienced with those concepts but I have read a lot of links.
The main issue is now that the single user c# app needs to be updated for multiuser environment. Using the current implementation , the external changes(like update operations) performed on database are not visible inside de controller.

I’ve tried using _unitOfWork.Context.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, _tableRepository.FindAllInContext()); to refresh the context but I think this is not a good option, because if I try to update a table column value after refresh, the action will not be saved in database.

 public interface IDbEntity
    {
        int Id { get; set; }
        bool IsDeleted { get; set; }
    }
 
 public interface IRepository<T, T1>
        where T : class, IDbEntity
        where T1 : class, IDbEntity
    {
        int Add(T1 newEntityViewModel);
        void AddRange(List<T1> newEntities);
        void Remove(int id);
        void RemoveFromDb(int id);
        List<T1> Find(Expression<Func<T1, bool>> predicate);
        T1 FindById(int id);
        List<T1> FindAll();
        T FindByIdInContext(int id);
        int GetNextId();
        List<T> FindAllInContext();
    }
    
    internal class DbRepository<T, T1> : IRepository<T, T1>
        where T : class, IDbEntity
        where T1 : class, IDbEntity
    {
        protected ObjectSet<T> _objectSet;
        protected List<T1> _internalList;
        protected ObjectContext _context;

        public DbRepository(ObjectContext context)
        {
            try
            {
                
                _internalList = new List<T1>();
                _objectSet = context.CreateObjectSet<T>();
                _context = context;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }



        public int Add(T1 newEntityViewModel)
        {
            try
            {
                var entityDto = AutoMapperConfiguration.GetMapperConfiguration().Map<T1, T>(newEntityViewModel);
                _objectSet.AddObject(entityDto);

                _context.SaveChanges();
                
                //check id 
                return entityDto.Id;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }


        public List<T1> Find(Expression<Func<T1, bool>> predicate)
        {
            try
            {
                var listT1 = AutoMapperConfiguration.GetMapperConfiguration().Map<List<T1>>(_objectSet.Where(q => !q.IsDeleted));
                var result = listT1.Where(predicate.Compile()).ToList();

                return result;
            }
            catch (Exception ex)
            {
               log.Error(ex.Message);
                throw;
            }
        }

        public List<T1> FindAll()
        {
            try
            {
                var listT1 = AutoMapperConfiguration.GetMapperConfiguration().Map<List<T1>>(_objectSet.Where(q => !q.IsDeleted));
                return listT1;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }

    }
    
    
    public interface IUnitOfWork
    {
        IRepository<User, User_ViewModel> Users { get; }
        IRepository<Type, Type_ViewModel> Types { get; }
        
        /// and a lot more repositories

        ObjectContext Context { get; }
        void Commit();
    }
    
    
    internal class DbUnitOfWork : IUnitOfWork
    {
        private DbRepository<User, User_ViewModel> _users = null;
        private DbRepository<Type, Type_ViewModel> _types = null;
       
       
       
        private readonly ObjectContext _context;
        private readonly EntityConnection _connectionString;

   
        public ObjectContext Context { get { return _context; } }

        public DbUnitOfWork(EntityConnection connectionString)
        {
            try
            {
                _connectionString = connectionString;
                _context = new ObjectContext(connectionString, true);
                _context.ContextOptions.LazyLoadingEnabled = true;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }

        public IRepository<User, User_ViewModel> Users
        {
            get
            {
                return _users ?? (_users = new DbRepository<User, User_ViewModel>(_context));
            }
        }


        public IRepository<Type, Type_ViewModel> Types
        {
            get
            {
                return _types ?? (_types = new DbRepository<Type, Type_ViewModel>(_context));
            }
        }



        public void Commit()
        {
            try
            {
               _context.SaveChanges();

            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }

    }
    
    DbController.cs
    public partial class DbController
    {
        protected readonly IUnitOfWork _unitOfWork;
        
        protected readonly IRepository<User, User_ViewModel> _userRepository;
        protected readonly IRepository<Type, Type_ViewModel> _typeRepository;
        
        
        public SafeIOController(IUnitOfWork unitOfWork)
        {
           

            _unitOfWork = unitOfWork;
            
            _userRepository = _unitOfWork.Users;
            _typeRepository = _unitOfWork.Types;
            
        }

        public void Save()
        {
            _unitOfWork.Commit();
        }
    }
    Controller_User.cs
    public partial class DbController
    {
       

        public List<User_ViewModel> GetAllUsers()
        {
            try
            {
                
                return _userRepository.FindAll();

            }
            catch (Exception ex)
            {
                _exHandler.LogErrorMessage(Constants_Exception.DB_EXCEPTION_MSG, ex, _exHandler.GetCurrentMethod());
                throw;
            }
        }


        
    }
    
    and then in winforms app 
    
            _unitOfWork = new DbUnitOfWork(connectionString);
            _controller = new DbController(_unitOfWork);

How can I properly implement unitOfWork in order to have the latest information from db inside my context?

fa.functional analysis – Quick derivation of classical probability theory from von Neumann algebraic framework

Watching (the begining of) a lecture on free probability theory by Dimitri Shlyakhtenko https://www.youtube.com/watch?v=F8Urtr39jM0, I’m led to the following question

Question. How can one build classical probability theory (measurable functions on measure space, expectations, etc.) from the framework of “von Neumann algebras” ?

Note. I’d really appreciate a bottom-up answer (not just a dry stack of formal encyclopedic statements, except perhaps when strictly needed). Thanks in advance!

sharepoint framework – Fetching Planner Task through Graph API into webpart

public componentDidMount() {
this.props.context.msGraphClientFactory.getClient().then((client: MSGraphClient): void => {
  client
    .api('me/planner/tasks')
    .version("v1.0")
    .select("*")
    .get((error: any, eventsResponse, rawResponse?: any) => {
      if (error) {
        console.error("message is :" + error);
        return;
      }
      const plannerTask: MicrosoftGraph.Event() = eventsResponse.value;
      this.setState({ events: plannerTask });
    })
  })
  }

Making an API call through Graph Explorer to fetch the Planner Task data into sharepoint webpart in the above function

i am getting an error when fetching the data of “{“Assignments : AssignedBy :User :id”}”

I am fetching data through Graph Explorer as shown below

enter image description here

I am able to fetch the {“CreatedBy : User :id”} but not able to fetch {“Assignments : AssignedBy :User :id”}

I have used that code to fetch the createdBy’s ID and assignedBY’s ID

{this.state.events.map((item, key) =>
            <tr>
              <td id="status">
                {(() => {
                  switch (item.percentComplete) {
                    case 0: return "Not-started";
                    case 50: return "In-Progress";
                    case 100: return "Completed";
                  }
                })()}
              </td>
              <td><a href={"https://tasks.office.com/credentinfotech.com/en-GB/Home/Planner#/plantaskboard?planId=" + item.planId + "&taskId=" + item.id} target="_blank" >{item.title}</a></td>
              <td>{moment(item.startDateTime).format('MM/DD/YYYY ')}</td>
              <td>{moment(item.dueDateTime).format('MM/DD/YYYY')}</td>
              <td>{item.createdBy.user.id}</td>
              <td>{item.assignments.assignedBy.user.id}</td>
              

            </tr>

          )

          }

html – Uploading images to the server using PHP and MVC framework

Good day,

Could someone please assist / advise on how I can upload images to the server with PHP and a custom MVC framework? I am currently able to upload the image name to the database, but not sure what to add in order for the images to be uploaded in a directory on the server.

Below are the code that are in the Image Controller:

<?php
class Images extends Controller {
  public function __construct(){
    if(!isLoggedIn()){
      redirect('users/login');
    }

    $this->postModel = $this->model('Post');
    $this->userModel = $this->model('User');
    $this->imageModel = $this->model('Image');
  }
  public function add(){
    if($_SERVER('REQUEST_METHOD') == 'POST'){
      
      // Sanitize POST array
      $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

      $data = (
 
        'image1' => trim($_POST('image1')),            
        'image1_err' => '',
     
      );

      // Validate data
      if(empty($data('image1'))){
        $data('image1_err') = 'Please enter a image1';
      }

      // Make sure no errors
        if (empty($data('image1_err'))){
        // Validated
        if($this->imageModel->addImage($data)){
          flash('post_message', 'Post Added');
          redirect('posts/added');
        } else {
          die('Something went wrong');
        }
      } else {
        // Load view with errors
        $this->view('posts/add', $data);
      }

    } else {
      $data = (
        'image1' => '',      
      );

      $this->view('posts/add', $data);
    }
  }
}

Below are part of the code in the view that contains the HTML form:


<form action="<?php echo URLROOT; ?>/images/add" method="post">

<div class="wrapper">
  <div class="box">
    <div class="js--image-preview"></div>
    <div class="upload-options">
      <label>
        <input type="file" name="image1" class="image-upload" accept="image/*" />
      </label>
    </div>
  </div>

</div>
<button type="submit">Submit</button>
</form>

I have tried to add the below code to the Controller, but the image name only uploads to the database.

if (! empty($_FILES)) {
    $imagePath = isset($_FILES("file")("name")) ? $_FILES("file")("name") : "Undefined";
    $targetPath = "uploads/";
    $imagePath = $targetPath . $imagePath;
    $tempFile = $_FILES('file')('tmp_name');
    
    $targetFile = $targetPath . $_FILES('file')('name');
    
    if (move_uploaded_file($tempFile, $targetFile)) {
        echo "true";
    } else {
        echo "false";
    }
}

Any assistance would be appreciated.

entity framework – Como devo testar um repositorio EF core com xunit

Actualmente estou a testar um repositorio da seguinte forma:

public class SomethingTest
{
    (Fact)
    public async void GetKeyValuesAsync_NotNull()
    {

        // Arrange
        var categoryRepository = CreateRepository();
        var fixture = new Fixture().Customize(new AutoMoqCustomization());
        var categoryModel = fixture.Build<Category>()
                        .Without(x => x.Property)
                        .Create();

        // Act
        var categoryCreated = await categoryRepository.CreateAsync(categoryModel);
        var result = await categoryRepository.GetKeyValuesAsync();

        //Assert
        Assert.NotNull(result);
    }

    private CategoryRepository CreateRepository()
    {
        var services = new ServiceCollection();
        services.AddDbContext<TokensContext>(x => { x.UseInMemoryDatabase(databaseName: "StoreMemoryContext", new InMemoryDatabaseRoot()); });
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        var serviceProvider = services.BuildServiceProvider();
        var mockLocalizationService = new Mock<ILocalizationService>();
        var mockNormalizationService = new Mock<INormalizationService>();
        var mockLogger = new Mock<ILogger<CategoryRepository>>();
        return new CategoryRepository(serviceProvider,
                                    mockLocalizationService.Object,
                                    mockNormalizationService.Object,
                                    mockLogger.Object);


    }
}

Eu acredito que a forma como estou a alterar a memoria de sql para UseInMemoryDatabase não é a mair correcta, mas não sei como consigo alterar de outra forma

Error generated for warning
‘Microsoft.EntityFrameworkCore.Infrastructure.ManyServiceProvidersCreatedWarning’:
More than twenty ‘IServiceProvider’ instances have been created for
internal use by Entity Framework. This is commonly caused by injection
of a new singleton service instance into every DbContext instance. For
example, calling UseLoggerFactory passing in a new instance each
time–see https://go.microsoft.com/fwlink/?linkid=869049 for more
details. Consider reviewing calls on ‘DbContextOptionsBuilder’ that
may require new service providers to be built. This exception can be
suppressed or logged by passing event ID
‘CoreEventId.ManyServiceProvidersCreatedWarning’ to the
‘ConfigureWarnings’ method in ‘DbContext.OnConfiguring’ or
‘AddDbContext’.

Best Python GUI framework for Windows development

I would like to make some GUI in Windows OS. There is a few Python GUI framework options like wxPython pyQt etc. Which is best for Windows development specifically in terms of ease of use for end users (I want to make the GUI into a .exe file), compatibility with Windows, looks native etc.

Basically I’m looking for a .NET alternative since I don’t know C# or .NET

sharepoint framework – Fetching the Outlook Task’s Data into Webpart using Graph Api call

I am using render function to make Graph Api call

I have created a function _outlookTask to fetch the outlook task’s data

How to make Graph Api call with Selecting the HTTP method as GET and then, select beta as the API version in my function

public render(): void {
this.context.msGraphClientFactory
  .getClient()
.then((graphclient:MSGraphClient): void=>{
  graphclient
  .api('/me/outlook/tasks')
  .get((error,user:MicrosoftGraph.OutlookItem,rawResponse?:any)=>{
  this.domElement.innerHTML = `
 <div>
 <div id="spListContainer">
 </div>
  </div>`;
 this._OutlookTask(tasks.value)
})
 })

}

private _OutlookTask(tasks: MicrosoftGraph.Message()): void {
let html: string = '';
for (let index = 0; index < tasks.length; index++) {
  html += `<p class="${styles.description}">Tasks Through Outlook  ${index + 1} - 
${escape(tasks(index).subject)}</p>`;
}

// Add the emails to the placeholder
const listContainer: Element = this.domElement.querySelector('#spListContainer');
listContainer.innerHTML = html;

}