Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Paint Net custom Watermark effect with CodeLab

How to make custom Watermark effect in  Paint Net with CodeLab 

 

intro How to make custom Watermark effect in  Paint Net with CodeLab

In this tutorial, we will create a custom watermark plugin for Paint Net  using the CodeLab tool.

Pre-conditions :

The Paint Net application is already installed on your personal computer.


Solving : 


Watch on YouTube 

https://youtu.be/6dXUK-AAYkg 


Step 1 - Download the CodeLab plugin for Paint Net.

Download the CodeLab plugin from the website shown in the image. It is a free development environment for writing Paint Net effect plugins in C Sharp.

Open CodeLab official page

The download link is located in the middle of the page, as shown in the image below.


Step 2 - Unzip CodeLab archive.

Locate downloaded CodeLab zip archive.

Locate downloaded CodeLab zip archive

Unzip CodeLab archive.

Unzip CodeLab archive

Step 3 - Install CodeLab plugin

Open unzipped folder of CodeLab plugin.

Open unzipped folder of CodeLab plugin

Run CodeLab installer file.

Run CodeLab installer file

In the CodeLab Installer wizard, enable the license agreement checkbox. It would be nice if you read it, of course.

enable the license agreement checkbox

Click the Install button in the bottom-right corner of the CodeLab installation wizard.

Click the Install button in the bottom-right corner of the CodeLab installation wizard

Wait until the installation is finished. Click the OK button in the dialog.

Wait until the installation is finished. Click the OK button in the dialog.

Click the Close button.

Click the Close button


Step 4 - open CodeLab plugin in Paint Net.

Launch Paint Net. In the menu bar, click Effects, then select Advanced, and finally click CodeLab.

open CodeLab plugin in Paint Net

You will see the CodeLab Editor. In my case, it is CodeLab version 6.13. 

You will see the CodeLab Editor.

Step 5 - Implement the custom Watermark effect code.

In the CodeLab Editor, enable the Show output errors checkbox in the bottom-left corner.

In the CodeLab Editor, enable the Show output errors checkbox in the bottom-left corner

In CodeLab Editor, click on the File menu item, then click on the New menu item, then click on the Bitmap Effect menu item.

In CodeLab Editor, click on the File menu item, then click on the New menu item, then click on the Bitmap Effect menu item.


Prepare watermark or logo image, name it PAINT_NET_LOGO.png and place it into Downloads folder on your Windows system.

Prepare watermark or logo image, name it PAINT_NET_LOGO.png and place it into Downloads folder on your Windows system.


Copy and paste the code from the text version of the tutorial into the CodeLab editor. Please find the link to the text version in the video description.

Copy and paste the code from the text version of the tutorial into the CodeLab editor. Please find the link to the text version in the video description.

// Name: Watermark Logo (CPU)

// Submenu: Render

// Author: Custom

// Title: Watermark Logo

#region UICode

IntSliderControl Amount1 = 20;  // [0,500] Margin

IntSliderControl Amount2 = 100; // [10,500] Scale %

IntSliderControl Amount3 = 100; // [0,100] Opacity %

#endregion


private Surface logoSurface = null;


protected override void OnRender(IBitmapEffectOutput output)

{

    // 1. Load the logo once

    if (logoSurface == null)

    {

        string downloadsPath = System.IO.Path.Combine(

            System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile),

            "Downloads", "PAINT_NET_LOGO.png"

        );


        if (System.IO.File.Exists(downloadsPath))

        {

            try {

                using (var sysBmp = new System.Drawing.Bitmap(downloadsPath))

                {

                    logoSurface = Surface.CopyFromBitmap(sysBmp);

                }

            } catch { /* Handle error */ }

        }

    }


    using IEffectInputBitmap<ColorBgra32> sourceBitmap = Environment.GetSourceBitmapBgra32();

    using IBitmapLock<ColorBgra32> sourceLock = sourceBitmap.Lock(new RectInt32(0, 0, sourceBitmap.Size));

    RegionPtr<ColorBgra32> sourceRegion = sourceLock.AsRegionPtr();


    RectInt32 outputBounds = output.Bounds;

    using IBitmapLock<ColorBgra32> outputLock = output.LockBgra32();

    RegionPtr<ColorBgra32> outputSubRegion = outputLock.AsRegionPtr();

    var outputRegion = outputSubRegion.OffsetView(-outputBounds.Location);


    // Calculate dimensions

    float scale = Amount2 / 100f;

    int logoW = (logoSurface != null) ? (int)(logoSurface.Width * scale) : 0;

    int logoH = (logoSurface != null) ? (int)(logoSurface.Height * scale) : 0;

    int startX = Environment.Document.Size.Width - logoW - Amount1;

    int startY = Environment.Document.Size.Height - logoH - Amount1;

    float opacity = Amount3 / 100f;


    for (int y = outputBounds.Top; y < outputBounds.Bottom; ++y)

    {

        if (IsCancelRequested) return;


        for (int x = outputBounds.Left; x < outputBounds.Right; ++x)

        {

            ColorBgra32 bg = sourceRegion[x, y];

            

            // Check if current pixel is within the watermark area

            if (logoSurface != null && x >= startX && x < startX + logoW && y >= startY && y < startY + logoH)

            {

                // Simple Nearest Neighbor scaling for CPU efficiency

                int lx = (int)((x - startX) / scale);

                int ly = (int)((y - startY) / scale);

                

                if (lx < logoSurface.Width && ly < logoSurface.Height)

                {

                    ColorBgra32 fg = logoSurface[lx, ly];

                    // Manual Alpha Blending

                    float alpha = (fg.A / 255f) * opacity;

                    bg.R = (byte)(fg.R * alpha + bg.R * (1 - alpha));

                    bg.G = (byte)(fg.G * alpha + bg.G * (1 - alpha));

                    bg.B = (byte)(fg.B * alpha + bg.B * (1 - alpha));

                }

            }

            outputRegion[x, y] = bg;

        }

    }

}


protected override void OnDispose(bool disposing)

{

    if (disposing) logoSurface?.Dispose();

    base.OnDispose(disposing);

}


Save the script in your Documents folder - I've created a separate folder named WatermarkLogo and saved the code files as WatermarkLogoCPU.cs

Save the script in your Documents folder - I've created a separate folder named WatermarkLogo and saved the code files as WatermarkLogoCPU.cs

Step 6 - Build the custom Watermark effect.

Click the "Build DLL" menu button in the top-left corner of the CodeLab Editor window.

Click the "Build DLL" menu button in the top-left corner of the CodeLab Editor window.

In the "Building" dialog, make the changes shown in the image below and press the "Build" button.

In the "Building" dialog, make the changes shown in the image below and press the "Build" button.

Click the "OK" button in the "Build Finished" dialog box. An archive containing the DLL has been created on your desktop.

Click the "OK" button in the "Build Finished" dialog box. An archive containing the DLL has been created on your desktop.

Step 7 - Install the custom Watermark effect.

Find the WatermarkLogoCPU.zip archive on the Desktop, created by CodeLab plugin.

Find the WatermarkLogoCPU.zip archive on the Desktop, created by CodeLab plugin.

Unzip archive on desktop.

Unzip paint net plugin archive on desktop

Open the unzipped folder and run the install bat script by double-clicking on it.

Open the unzipped folder and run the install bat script by double-clicking on it.

Press Enter once patching is complete.

Press Enter once patching is complete.

Step 8 - Test custom Watermark effect.

After a successful custom plugin installation, restart Paint Net and find our watermark effect in the top menu.

After a successful custom plugin installation, restart Paint Net and find our watermark effect in the top menu.


Set the margin, scale, and opacity in the Watermark Logo dialog window, and then press the OK button.

Set the margin, scale, and opacity in the Watermark Logo dialog window, and then press the OK button.


Step 9 - How to delete a custom Watermark effect.

To delete our custom Watermark Logo effect we need do following steps : 

- first close Paint Net application  

- than find Paint Net folder in Program Files, 

- than find folder Effects 

- find  WatermarkLogoCPU.dll and delete it

After that restart Paint Net application.

delete a custom Watermark effect


Well Done

So we did something useful today instead of  baking brane with mindless scrolling of social networks :) Good job 


C# & ASP.NET: output CSV file with UTF-8 encoding and BOM ( MS Excel friendly )

Trabla: C# & ASP.NET:  output CSV file with UTF-8 encoding and BOM.

Excel correctly opens such CSV files.

Solving:

         /// <summary>
        /// Return CSV utf-8 file
        /// </summary>
        /// <returns></returns>
        public FileResult DownloadCSV( )
        {
           
            string lvCSV = " .... your CSV FILE STRING WITH utf-8 signs like こんにちは世界 ... ";

            string lvFileName = "myfile.csv";

            // UTF8 with BOM (byte order mark)
            UTF8Encoding lvUtf8EncodingWithBOM = new UTF8Encoding(true,true);

            // Byte Order Mark -  \x00EF\x00BB\x00BF
            string lvBOM =
            Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());

            return File( lvUtf8EncodingWithBOM.GetBytes( lvBOM + lvCSV), "text/csv;charset=utf-8", lvFileName);
        }
    }


Unity3D: coroutine and WWW ( example of implementing Web-API call and processing )

Trabla: Unity3D: coroutine and WWW ( example of implementing Web-API call and processing )

Solving:

In this tutorial we will implement simple wrapper for www calls and processing it.
Calling of API will be so easy, e.g.

  api.xgSignIn (this, lvLogin, lvPassword);

where this - object which implements handler method 

Naming convention:
I will use prefix X<ClassName>  e.g. XServiceModel.
I will use prefix XI<InterfaceName> e.g. XIServiceCallbackHandler
I will use prefix xg<MethodName> e.g.  void xgHandleServiceCallback(  XServiceEventModel serviceEvent );

1. Create C# script   XServiceEventModel.cs  with following code:

using UnityEngine;
using System.Collections;

public class XServiceEventModel {

    public int id { get; set; }
    public string data{ get; set; }
    public string error{ get; set; }

}



2. Create C# script XIServiceCallbackHandler.cs - interface with only one method.
Any view should implement it in order to process WWW callbacks. copy following code:

using UnityEngine;
using System.Collections;

public interface XIServiceCallbackHandler {

    void xgHandleServiceCallback(  XServiceEventModel serviceEvent );

}


3. Create C# script XApiServic.cs - this class is a wrapper of your web-server api.
Use following code:


using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;

public class XApiService : MonoBehaviour {


  

    private const string API_URL     = "http://mysite.com/api/mygame1";
    private const string APP_TOKEN    = "2ba908bb34566e1ba91a5e570d0287";

    #region Event Types


    public const int EVENT_SIGN_IN_SUCCESS     = 10;
    public const int EVENT_SIGN_IN_FAILED     = 11;

    public const int EVENT_RESULTS_SAVE_SUCCESS = 20;
    public const int EVENT_RESULTS_SAVE_FAILED = 21;

  

    #endregion

   
    public void xgSignIn( XIServiceCallbackHandler callbackHandler, string login, string password ){

        string url = API_URL + string.Format ( "/signin?app={0}&login={1}&password={2}", APP_TOKEN, login, password );

        Dictionary<string, string> headers = new Dictionary<string, string> ();
        headers.Add("Accept","application/json");

        StartCoroutine(WaitForRequest(
                                      new WWW( url, null, headers)
                                      ,     callbackHandler
                                      ,     EVENT_SIGN_IN_SUCCESS
                                      ,        EVENT_SIGN_IN_FAILED
                                      ));
    }


    IEnumerator WaitForRequest(WWW www, XIServiceCallbackHandler callbackHandler, int successEventType, int failedEventType )
    {
        yield return www;

        XServiceEventModel lvServiceEvent = new XServiceEventModel ();
       
        lvServiceEvent.id = www.error == null ? successEventType : failedEventType;
        lvServiceEvent.data = www.text;
        lvServiceEvent.error = www.error;

        // Call Callback Handler
        callbackHandler.xgHandleServiceCallback ( lvServiceEvent );

    }

}



3. Example of  view and using previous classes

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class XSignInViewController : MonoBehaviour, XIServiceCallbackHandler {

    public XGameController gameController;
    public XApiService api;

    public Text txtLogin;
    public Text txtPassword;
    public InputField inpLogin;
    public InputField inpPassword;
    public Button btnSignIn;
    public Button btnBack;
    public Text txtMessageBox;


    // Use this for initialization
    void Start () {

        this.inpLogin.textComponent.text = "";
        this.inpLogin.textComponent.text = "";
        this.txtMessageBox.text = "";
       
    }
   
    // Update is called once per frame
    void Update () {
   
    }


    #region Events

   
    // This method is attached in UnityEditor to Button OnClick
    public void xgDoSignIn(){

        string lvLogin = this.inpLogin.textComponent.text;
        string lvPassword = this.inpPassword.textComponent.text;

        // Very easy call of API
        api.xgSignIn (this, lvLogin, lvPassword);
    }

    #endregion


    #region XIServiceCallbackHandler implementation


    public void xgHandleServiceCallback (XServiceEventModel serviceEvent)
    {
        switch (serviceEvent.id)
        {
       
            case XApiService.EVENT_SIGN_IN_SUCCESS:

            // Save User
            string lvLogin = this.inpLogin.textComponent.text;
            string lvPassword = this.inpPassword.textComponent.text;
            var lvToken = Pathfinding.Serialization.JsonFx.JsonReader.Deserialize<XTokenResponseModel> (serviceEvent.data);

            // DO SOME STAFF

            break;

            case XApiService.EVENT_SIGN_IN_FAILED:
            throw new UnityException ("NOT IMPLEMENTED EVENT_SIGN_IN_FAILED");
            break;

            default:
            throw new UnityException ("EVENT NOT FOUND");
        }
    }

    #endregion

  

}




Unity3D: loading and using sprite atlas from Resources

Trabla: Unity3D: loading and using sprite atlas from Resources


Unity3D load sprite atlas from Resources - tutorial 1



Solving:


1. Create sprite atlas ( .png file images, background transparent )


Unity3D load sprite atlas from Resources - tutorial 2


Unity3D load sprite atlas from Resources - tutorial 3
"sprite-atlas.png" File


2. Create new unity2D project

Unity3D load sprite atlas from Resources - tutorial 4


3. Create folder "Resources" in folder "Assets"
and drag-n-drop sprite atlas file into folder "Resources"

Unity3D load sprite atlas from Resources - tutorial 5



4. Select sprite atlas file - set "Sprite Mode" -> "Multiple" + click "Apply"

Unity3D load sprite atlas from Resources - tutorial 6



5. Click "Sprite Editor" - slice sprite in automatic mode - will create separate sprites.

Unity3D load sprite atlas from Resources - tutorial 7

Unity3D load sprite atlas from Resources - tutorial 8
Slice Result



6. Create following UI structure:
Panel
- Text
- Button
- Image

Unity3D load sprite atlas from Resources - tutorial 9

Unity3D load sprite atlas from Resources - tutorial 10



7. Create new C# script , name it "SpriteAtlasController"  and add as component to "Panel"

8. Copy following code into "SpriteAtlasController.cs"

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Add this directive for UI Components e.g. Text, Button etc.
using System.Collections.Generic; 


public class SpriteAtlasController : MonoBehaviour {

public Button btnChangeImage;
public Text txtImageName;
public Image imgImage;

Sprite[] arrSprites;
int spriteIndexInArray = -1;

// Use this for initialization
void Start () {

Debug.Log("Try to load : sprite-atlas ");
arrSprites = Resources.LoadAll<Sprite>("sprite-atlas");
Debug.Log(arrSprites.Length);


foreach (Sprite lvSprite in arrSprites)
{
Debug.Log(lvSprite.name);

}

ChangeImage();

}

// Update is called once per frame
void Update () {

}

// Call this function when button click
public void ChangeImage(){

spriteIndexInArray = spriteIndexInArray < arrSprites.Length - 1 ? spriteIndexInArray + 1 : 0;


Debug.Log ("spriteIndexInArray : " + spriteIndexInArray );

imgImage.sprite = arrSprites[spriteIndexInArray];
txtImageName.text = arrSprites[spriteIndexInArray].name;
}
}




9. Drag-n-drop UI elements to "SpriteAtlasController.cs" script

Unity3D load sprite atlas from Resources - tutorial 11


10. Add OnClick call of method "ChangeImage()" for Button in UI

Unity3D load sprite atlas from Resources - tutorial 12


Hooray!!! :)

Microsoft Visual Studio: open Source Control Explorer from Team Explorer

Trabla: Microsoft Visual Studio : open Source Control Explorer from Team Explorer


Solving:

1. In Team Explorer window click "home" button

Microsoft Visual Studio: open Source Control Explorer from Team Explorer 1


2. Click "Source Control Explorer"

Microsoft Visual Studio: open Source Control Explorer from Team Explorer 2

C# & ASP.NET MVC : create and download csv

Trabla: C# & ASP.NET MVC : create and download csv example

Solving:

....

namespace MyApp.Controllers
{

        public class ReportController: Controller
        {

              
              public ActionResult DownloadCSV()
              {
                    var lvData = GetReportData();
 
                    // Create string with csv data
                    string lvCSV = GetCSV(  lvData  );  

                    var lvFileName =   string.Format(
                                 "report_{0}.csv", 
                                 DateTime.Now.ToString("yyyy/MM/dd")
                     );

                    return File(
                             System.Text.Encoding.UTF8.GetBytes(lvCSV), 
                            "text/csv" , 
                             lvFileName
                     );      

               }

              // List of  Dictionaries with data
              public static IEnumerator<Dictionary<string,string>> GetReportData()
              {
                      List<Dictionary<string,string>> lvData = new List<Dictionary<string,string>>();
                     
                      Dictionary<string, string> lvRow = new Dictionary<string, string>();
                      lvRow.Add( "Name", "Alex" );
                      lvRow.Add( "Age", "29" ); 

                      lvData.Add( lvRow );

                      lvRow = new Dictionary<string, string>();
                      lvRow.Add( "Name", "John" );
                      lvRow.Add( "Age", "30" ); 
             
                      lvData.Add( lvRow );

                      return  lvDat;

              }

               // Converst List of  Dictionaries into string for csv file
               public static string GetCSV( IEnumerator<Dictionary<string,string>> data )
              {
                        string lvDelimiter = ",";

                        StringBuilder lvCSV =  new StringBuilder();

                       // Headers
                       var lvTotalElements = rows.First().Count();
                       var lvIndex = 0;
                       foreach ( var lvItemKey in rows.First().Keys)
                       {
                            lvCSV.Append(lvItemKey);
                            if (lvIndex < lvTotalElements - 1) lvCSV.Append(lvDelimiter);
                            lvIndex++;
                        }

                       lvCSV.Append("\n");

                       // Data Rows

                        foreach( var lvRow in rows)
                       {
                             lvTotalElements = lvRow.Count();
                             lvIndex = 0;
                        foreach( var lvItemValue in lvRow.Values)
                       {
                              lvCSV.Append(lvItemValue);
                             if(lvIndex < lvTotalElements - 1) lvCSV.Append(lvDelimiter);
                             lvIndex++;
                        }


                lvCSV.Append("\n");
            }


            return lvCSV.ToString();

              }

        }

}

C#: get current time string

Trabla: C#: get current time string

Solving:

string lvTimeFormat = "yyyy/MM/dd";
string lvCurrentTime = DateTime.Now.ToString( lvTimeFormat  );

C#: iterate ( loop ) through Dictionary

Trabla: C#: iterate ( loop ) through Dictionary<string,string>

Solving:

// Keys and Values

foreach( var lvItem in lvDictionary ){

      System.Diagnostics.Debug.WriteLine(   lvItem.Key );
      System.Diagnostics.Debug.WriteLine(   lvItem.Value);
}


// Iterate only throw collection of Keys

foreach( var lvItemKey in lvDictionary.Keys ){

      System.Diagnostics.Debug.WriteLine(   lvItemKey );

}

 // Iterate only throw collection of Values

foreach( var lvItemValue in lvDictionary.Values ){

      System.Diagnostics.Debug.WriteLine(  lvItemValue );
    
}


C#: c# analog of java System.out.println | System.out.print

Trabla: C#:  c# analog of java System.out.println | System.out.print

Solving:

In C# you can use:
1) Console.WriteLine | Console.Write
2) System.Diagnostics.Debug.WriteLine | System.Diagnostics.Debug.Write

System.Diagnostics.Debug.WriteLine | System.Diagnostics.Debug.Write
- prints into Output Windows in Visual Studio

Example usage:

string lvMessage = "trololo";
System.Diagnostics.Debug.WriteLine( lvMessage );

Official Docs:
https://msdn.microsoft.com/en-us/library/system.diagnostics.debug.write(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.diagnostics.debug.writeline.aspx

C#: ASP.NET: Console.WriteLine not work ( use Debug.WriteLine )

Trabla: C#: ASP.NET: Console.WriteLine not work

Solving:

In ASP.Net app during debug DO NOT use Console.WriteLine.
Use Debug.WriteLine instead.

System.Diagnostics.Debug.WriteLine( " Hooray!!! " );

C#: ASP.NET: get connection string from Web.config file

Trabla: C#: ASP.NET: get connection string from Web.config file


Solving:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


using Npgsql;

// Add this directive
using System.Configuration;

namespace MyApp.Models{

      public class MyReport{

           /// <summary> 
           /// 
           /// </summary> 
           /// <param name="database"> Database connection string name in Web.config</param> 
           /// <param name="params "></param> 
           /// <returns></returns>
            public static ExecuteReport1( string database, string[] params ){
                  
             string connStr = ConfigurationManager.ConnectionStrings[ database ].ConnectionString;
             
             // Example , Connect to PostgreSQL database via Npgsql
            NpgsqlConnection conn = new NpgsqlConnection(  connStr );
            
            // DO STAFF
             ....

            }

      }

}

Xamarine : Xamarine installation on windows

Trabla: Xamarine : Xamarine installation on windows


Solving:

1. Just go to  download page - https://xamarin.com/download
2. Type some required data
3. Download installer
4. Run it and enjoy installation process :)

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 1

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 2


How to install Xamarine IDE on windows 7 - codingtrabla tutorial 3

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 4

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 5

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 6

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 7

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 8

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 9

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 10

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 11

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 12

How to install Xamarine IDE on windows 7 - codingtrabla tutorial 13