Sunday 28 April 2024

Write a program to check if a number is divisible by 3 and 5

 number = int(input("Which number do you want to check? "))

if number % 3 == 0 and number % 5 == 0:

  print("This number is divisible by 3 and 5.")

elif number % 3 == 0 and number % 5 != 0:

  print("This number is divisible by 3 but not 5.")

elif number % 3 != 0 and number % 5 == 0:

  print("This number is divisible by 5 but not 3.")  

else:

  print("This number is not divisible by 3 or 5.")

Friday 2 February 2024

To use the code you provided to increase the touch area of an ImageButton in an Android Activity, follow these steps

 To use the code you provided to increase the touch area of an ImageButton in an Android Activity, follow these steps:


1. Copy the provided `setupTouchDelegate` method and add it to your Activity class.


```java

public class YourActivity extends AppCompatActivity {

    // Your existing code


    public void setupTouchDelegate(View parentView, ImageButton btnImgBack) {

        // The code you provided

    }

}

```


2. In your Activity's `onCreate` method, find the parent view (e.g., RelativeLayout, LinearLayout, etc.) that contains the ImageButton you want to increase the touch area for.


```java

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_activity_layout);


    // Find the parent view

    View parentView = findViewById(R.id.parent_view_id);

}

```


3. In the same `onCreate` method, find the ImageButton you want to increase the touch area for.


```java

// Find the ImageButton

ImageButton btnImgBack = findViewById(R.id.btn_img_back_id);

```


4. Call the `setupTouchDelegate` method with the parent view and ImageButton you found in steps 2 and 3.


```java

// Use the setupTouchDelegate method to increase the touch area

setupTouchDelegate(parentView, btnImgBack);

```


Here's the complete example:


```java

public class YourActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.your_activity_layout);


        // Find the parent view

        View parentView = findViewById(R.id.parent_view_id);


        // Find the ImageButton

        ImageButton btnImgBack = findViewById(R.id.btn_img_back_id);


        // Use the setupTouchDelegate method to increase the touch area

        setupTouchDelegate(parentView, btnImgBack);

    }


    public void setupTouchDelegate(View parentView, ImageButton btnImgBack) {

        // The code you provided

    }

}

```

Make sure to replace `YourActivity`, `your_activity_layout`, `parent_view_id`, and `btn_img_back_id` with the appropriate names for your Activity and views.

===================================================================

How to increase touch area in Activity Android java?

public void IncreaseTouchArea(View parentView, ImageButton btnImgBack) {

    // Create a Rect object to store the desired touch area

    final Rect touchArea = new Rect();

    // Get the current touch area (bounds) of the button

    btnImgBack.getHitRect(touchArea);

    // Increase the touch area by the desired amount (e.g., 200dp)

    int extraPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,getApplicationContext().getResources().getDisplayMetrics());

    touchArea.top -= extraPadding;

    touchArea.bottom += extraPadding;

    touchArea.left -= extraPadding;

    touchArea.right += extraPadding;

    // Create a TouchDelegate and set it on the parent view

    parentView.setTouchDelegate(new TouchDelegate(touchArea, btnImgBack));

}


===================================================================


Error maxTag: java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #5,5,main] that has not called Looper.prepare()

 The error message you are encountering, java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #5,5,main] that has not called Looper.prepare(), typically occurs when you try to update the UI from a background thread without using the proper mechanism.

In Android, UI updates should be performed on the main (UI) thread. In your case, it seems like you're trying to update the UI directly from the doInBackground method of an AsyncTask, which runs on a background thread.

To fix this issue, you should move the UI-related code to the onPostExecute method of the AsyncTask. This method is called on the main thread after the background processing is complete. Here's an example:


private class RFIDScanTask extends AsyncTask<Void, Void, Void> {


    @Override

    protected Void doInBackground(Void... voids) {

        // Simulate RFID scanning logic

        for (int i = 0; i < 10; i++) {

            if (isCancelled()) {

                // Break out of the loop if the task is cancelled

                break;

            }


            // Perform RFID scanning here


            // Simulate delay

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }


        return null;

    }


    @Override

    protected void onPostExecute(Void aVoid) {

        // RFID scanning completed

        isScanning = false;


        // Update UI from the main thread

        updateUIAfterScanning();

    }

}


private void updateUIAfterScanning() {

    runOnUiThread(new Runnable() {

        @Override

        public void run() {

            // Update UI elements here

            stopScanning();

        }

    });

}

In this example, I've introduced the updateUIAfterScanning method, which is called from the onPostExecute method. This method uses runOnUiThread to ensure that the UI updates are performed on the main thread.

Make sure to replace the stopScanning method call with the actual UI updates you want to perform after the RFID scanning is complete.

If you're not using an AsyncTask or have a different threading mechanism, the key is to ensure that any UI updates are done on the main (UI) thread.

Wednesday 1 November 2023

How to implemnet Dependency Injection in ASP.NET MVC 4? Explain with example.

Dependency Injection (DI) is a software design pattern that promotes loosely coupled code by allowing dependencies to be injected into a class from the outside, rather than being created or managed within the class. In ASP.NET MVC 4, you can implement DI using various DI containers such as Unity, Ninject, or Simple Injector. Here, I'll provide an example using Unity for dependency injection.

 

Step 1: Create an ASP.NET MVC 4 Project If you haven't already, create a new ASP.NET MVC 4 project in Visual Studio.

 

Step 2: Install Unity Container You need to install the Unity NuGet package to your project. Open the Package Manager Console and run:

-----------------------------------------------------------------------------------------------------------------------------

Install-Package Unity.Mvc4

-----------------------------------------------------------------------------------------------------------------------------

Step 3: Create a Dependency Let's assume you have a service that you want to inject into your controller. First, create an interface and a class for this service:

-----------------------------------------------------------------------------------------------------------------------------

// IService.cs

public interface IService

{

    string GetData();

}


// Service.cs

public class Service : IService

{

    public string GetData()

    {

        return "Hello from Service!";

    }

}

Step 4: Configure Dependency Injection In your Global.asax.cs file, configure Unity to manage the dependencies. Add the following code to the Application_Start method:

-----------------------------------------------------------------------------------------------------------------------------

protected void Application_Start()

{

    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);


    // Configure Unity Container

    var container = new UnityContainer();

    container.RegisterType<IService, Service>();


    // Set the Unity DependencyResolver

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));

}

This code sets up the Unity container and tells it that when someone asks for an IService, it should provide an instance of the Service class.

Step 5: Inject the Dependency Now, you can inject the dependency into your controller. Here's an example:

-----------------------------------------------------------------------------------------------------------------------------

public class HomeController : Controller

{

    private readonly IService _service;


    // Constructor injection

    public HomeController(IService service)

    {

        _service = service;

    }


    public ActionResult Index()

    {

        string data = _service.GetData();

        return View(data);

    }

}

By using constructor injection, the IService is automatically injected when an instance of HomeController is created.

Step 6: Use the Dependency in a View In your view (Index.cshtml), you can display the data from the injected service:

-----------------------------------------------------------------------------------------------------------------------------

@model string


<!DOCTYPE html>

<html>

<head>

    <title>Dependency Injection Example</title>

</head>

<body>

    <h1>@Model</h1>

</body>

</html>

When you run the application, the text from the Service will be displayed on the Index page.

This is a basic example of implementing Dependency Injection in ASP.NET MVC 4 using the Unity container. It promotes better separation of concerns and testability by allowing you to easily switch out dependencies and mock them during unit testing.


Tuesday 24 October 2023

Hosting ASP.NET Web API REST Service On IIS 10

 To make any application accessible to the end-user, we need to host it on a server. So, in this article, we will learn how to host ASP.NET Web API REST Service in IIS 10. The following steps are required to host any application. 

I hope, you have learned how to create and publish ASP.NET Web API REST Service. Now, let's start hosting Web API REST Service in IIS 10.

Step 1 Install IIS
 
Before hosting any application, make sure that IIS (Internet Information Services) is installed on your Hosting Server. If it is not installed or enabled, then follow the below steps.
  • Click on Windows icon at the bottom left corner and find the "Control Panel" menu and click on it.

  • In the "Control Panel", find the "Program and Features" option from the displayed list.

  • This shows the list of installed programs. Find and click the "Turn Windows feature on or off" option from the left pane, as shown in the following image.

     
  • Now, in the next popup, find Internet Information Services (IIS) and check on it.
  • Click "Next" button and then "Finish". It takes a few minutes to install IIS.
  • After installing IIS, restart your machine.
Note - I have Windows 10 OS and the above process is for Windows 10 PC. The steps might differ depending on your Operating System version.
 
Step 2 Install .NET Framework
 
Although Visual Studio is not required on your hosting Server, it must have .NET Framework installed, as per the .NET framework used to develop the application. If it is not installed, then please install the appropriate .NET Framework available on Microsoft official website.
 
I assume, you have installed the .NET framework on your Hosting Server.
 
Step 3 Move the published code on Hosting Server
 
Copy the "Published files" and paste those on respective Servers where you want to host the Web API REST Service. In our last article, we published Web API REST Service in the E drive of my Server, as shown in the following image .
 
Step 4 Open IIS Manager
 
Now, open the IIS Manager from Windows menu or in any other ways you have known.

 
The above image is of IIS 10 Manager of my Windows 10 machine. The view as well as options might be different on your machine depending on the OS version.

Step 5 Add Website
 
Right click on "Site" in IIS and click on add new website, as shown in the following screenshot.
 

After clicking on "Add Website" option, it displays the following configuration window.
 
 
 
I hope you understood the preceding configuration by highlighted text.
 
Step 6 Define Site Name & Application Pool
 
Define the site name which will be useful to uniquely identify the site within the IIS Server. After specifying the site name, choose the Application Pool from available pools. You can even create a custom application pool with any desired name. Currently, our IIS Manager has the following Application Pools.

 
Choose the application pool depending on your application configuration. In this article, we are going to choose DefaultAppPool.

Step 7 Browse and select Published Folder path
 
Now, choose the physical location of published code files by clicking on "Browse" button, as shown in the following image. 
 
 
 
Now, click on "OK" button.
 
Step 8 Define IP address & Port
 
Choose one IP address from the list of available IP addresses and define the unique port number for the application, which will be unique within the defined IP address.

Step 9 Choose Protocol & Host name (optional )
 
Choose the protocol for your application i.e HTTP or HTTPS which requires port 443 to be open and choose the Host name which will be used publicly to access the application. After defining all the configurations, the web site configuration window will look like this.
 
 
Now, click on OK button. It will create and add the application in IIS.
 


Step 10 Browse the URL with REST Client
 
Browse the hosted application using REST client with base URL along with API, Controller name, and Action method name, with pattern defined in routing template inside the webapiconfig.cs file.
 
We can browse applications using the browser but then, we can only test the GET method. So, to test all types of Action Methods, we are using  advanced REST client which is a developer extension tool in Firefox browser.
 
Our hosted Web API REST Service includes these two methods, as given below.
  • GetAllEmployees (GET )
  • GetEmployeeById  (POST ) which takes id as input parameter
Browse GetAllEmployees method using Advanced REST client which has used HTTP GET verb.
 


In the preceding screenshot, the GetAllEmployees hosted Web API REST method is returning all the employee lists.
 
Now, browse GetEmployeeById method using Advanced REST client which uses HTTP POST verb and takes id as input parameter.
 
 
 
From the above desired output, it's clear that our Web API REST Service is hosted on IIS successfully.

Note
  • Download the Zip file of the Published code to learn and start quickly.
  • This article is just guideline to show how to host Web API REST Service on IIS .
  • Optimize the speed by setting debug as false etc., from web.config file as per your skills. 
  • In this article, the optimization is not covered in depth.
  • Configure the authentication in IIS as per your REST Service .

For more information: https://www.c-sharpcorner.com/article/hosting-asp-net-web-api-rest-service-on-iis-10/

Wednesday 18 October 2023

Pinging a Reader with C#

 Here's a handy way to determine if a reader is connected to the network or not. It uses the .NET Ping and PingOptions classes, so make sure to add the following namespace to your project.

 

using System.Net.NetworkInformation;

//Then, you can write a method like this, that returns true if the reader is connected and false if it is not.

private bool ReaderIsAvailable(string address)
{
    Ping pingSender = new Ping();
    PingOptions options = new PingOptions();
    options.DontFragment = true;
    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    byte[] buffer = Encoding.ASCII.GetBytes(data);
    int timeout = 120;
    PingReply reply = pingSender.Send(address, timeout, buffer, options);
    if (reply.Status == IPStatus.Success)
        return true;
    else
        return false;
}

Finally, this is how you would call the method.

if (ReaderIsAvailable("SpeedwayR-10-25-32"))
{
    // Reader is connected to the network.
    // Start reading some tags!
}
else
{
    // Reader is not connected to the network.
    // Handle it here.
}

Sunday 8 October 2023

Android – Can’t make spinner’s scrollbar always visible (Android)

 I have such a problem – I want to make spinner's scrollbar always visible.

But for spinner function

setScrollbarFadingEnabled(false);

causes crash with a NullExceptionPointer during drawing the GUI.

XML tags can't solve this problem too – it seems that spinner just ignore them.

Maybe there are another ways to move? For example, using of the custom scrollbar? If yes, how can I do this?

---------------------------------------------------------------------------------------------------------------

As I've been asked, here is LogCat error message for simple project with just a spinner in it:

AndroidRuntime(2252): FATAL EXCEPTION: main
AndroidRuntime(2252): java.lang.NullPointerException
AndroidRuntime(2252): at android.view.View.onDrawScrollBars(View.java:5836)
AndroidRuntime(2252): at android.view.View.draw(View.java:6799)
AndroidRuntime(2252): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
AndroidRuntime(2252): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
AndroidRuntime(2252): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
AndroidRuntime(2252): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
AndroidRuntime(2252): at android.view.View.draw(View.java:6796)
AndroidRuntime(2252): at android.widget.FrameLayout.draw(FrameLayout.java:352)
AndroidRuntime(2252): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
AndroidRuntime(2252): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
AndroidRuntime(2252): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
AndroidRuntime(2252): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
AndroidRuntime(2252): at android.view.View.draw(View.java:6796)
AndroidRuntime(2252): at android.widget.FrameLayout.draw(FrameLayout.java:352)
AndroidRuntime(2252): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2078)
AndroidRuntime(2252): at android.view.ViewRoot.draw(ViewRoot.java:1433)
AndroidRuntime(2252): at android.view.ViewRoot.performTraversals(ViewRoot.java:1175)
AndroidRuntime(2252): at android.view.ViewRoot.handleMessage(ViewRoot.java:1753)
AndroidRuntime(2252): at android.os.Handler.dispatchMessage(Handler.java:99)
AndroidRuntime(2252): at android.os.Looper.loop(Looper.java:123)
AndroidRuntime(2252): at android.app.ActivityThread.main(ActivityThread.java:4632)
AndroidRuntime(2252): at java.lang.reflect.Method.invokeNative(Native Method)
AndroidRuntime(2252): at java.lang.reflect.Method.invoke(Method.java:521)
AndroidRuntime(2252): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
AndroidRuntime(2252): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
AndroidRuntime(2252): at dalvik.system.NativeStart.main(Native Method)

Best Solution

Spinner does not have a scrollbar, Hence you are getting NullPointerException.

The popup shown by spinner has a scrollbar. So you need to change the properties of the ListView shown by spinner. But ListView itself is not exposed by Spinner by any public methods.

Even if you get the ListPopupWindow by reflection, a further problem arises, that ListPopupWindow's ListView is only created after you click the Spinner.

But OnClickListener of the Spinner cannot be registered , to set the ListView Properties after the show.

You could create a Custom Spinner with performClick overridden and then get mPopup by reflection. and use mPopup.getListView().setScrollbarFadingEnabled(false)

But If you are going to create a custom Spinner, i believe it is easier to implement the whole popup to