Tuesday, 10 August 2021

WPF DataGrid Drag & Drop and target Row Indicator effect

I am new to WPF and got a requirement to apply some effect on dragging and I feel it is one good topic to share which can help programmers out there, who wants to achieve same Hence sharing with you all.

So lets see, How you can apply drag & drop effect to WPF data grid. There are many custom paid/licensed wpf data grid controls which helps you to apply such effects with no effort but that is not a option always (as it is paid).

Here we are discussing two effects on data grid with drag & drop features:

  1. Enable Drag & Drop for grid: Below are the events which I used to enable drag & drop, other than these there are other DataGrid events like DragEnter, DragOver and DragLeave which you can make use of for your need.
    i. Enable AllowDrop=”True” and SelectionMode=”Extended” for the grid.
    ii. Add LoadingRow event for dragging rows and indicator line effects. Below mentioned effects code is been handled from this event.
    iii. Add SelectionChanged event to mark selected rows. This event will set Model.IsSelected to true through which we identify this row(s) are selected.
    iv. Add Drop event and the code related to dropping rows goes here, this is where collection source gets modified.
  2. Show the selected rows while dragging: This you can achieve by adding a popup and this is all you need to do:
    i. Design a container control (in my case I added a grid with no header) to show data (selected rows).
    ii. Create a popup and place the above container control within the popup.
    iii. From the code behind On Row_DragOver event bind the container control and display the popup on current mouse position and otherwise hide the popup.
private void PersonGrid_LoadingRow(object sender, DataGridRowEventArgs e){      e.Row.DragOver += Row_DragOver;}private void Row_DragOver(object sender, DragEventArgs e){     if (!popup1.IsOpen)     {           popup1.IsOpen = true;
//bind your container control with selected rows of data.
} Size popupSize = new Size(popup1.ActualWidth, popup1.ActualHeight); popup1.PlacementRectangle = new Rect(e.GetPosition(this), popupSize);}

3.  Show the row indicator line for drop location: To achieve this we need to figure out the drop location based on our data collection index position and then dynamically apply the styling to draw a Row Indicator line and to do this:
i. Create an enum which will help to hold the info for drag position.

public enum DragRowEffect{     None,     Before,     After}

ii. Add the enum in your model.

private DragRowEffect rowEffect;public DragRowEffect RowEffect{       get => rowEffect;       set => SetProperty(ref rowEffect, value); //Prism.Mvvm.BindableBase}

iii. Based on how you are changing the datagrid’s data collection (i.e remove item and then add the dragged back at respective index), set the value of RowEffect for your model On Row_DragOver event.

private void Row_DragOver(object sender, DragEventArgs e){      if (!popup1.IsOpen)
{
popup1.IsOpen = true; //bind your container control with selected rows of data.
}
Size popupSize = new Size(popup1.ActualWidth, popup1.ActualHeight);
popup1.PlacementRectangle = new Rect(e.GetPosition(this), popupSize);
var targetRowIndex = dataContext.PersonCollection.IndexOf((e.OriginalSource as FrameworkElement).DataContext as Person);
if (targetRowIndex < 0)
return;
var selectedItemsIndexes = selectedItems.Select(x => dataContext.PersonCollection.IndexOf(x)).OrderBy(x => x).ToList();
var minIndex = selectedItemsIndexes.Min();
if (targetRowIndex == 0)
dataContext.PersonCollection[targetRowIndex].RowEffect = DragRowEffect.Before;
else if (minIndex > targetRowIndex)
dataContext.PersonCollection[targetRowIndex].RowEffect = DragRowEffect.Before;
else
dataContext.PersonCollection[targetRowIndex].RowEffect = DragRowEffect.After;
}

iv. Override the DataGrid.RowStyle and change the style of the target row’s border based on your Model.RowEffect value.

<DataGrid.RowStyle><Style TargetType="{x:Type DataGridRow}"><Setter Property="SnapsToDevicePixels" Value="true"/><Setter Property="Background" Value="Transparent"/><Setter Property="VerticalAlignment" Value="Center"/><Setter Property="MinHeight" Value="40"/><Style.Triggers><DataTrigger Binding="{Binding RowEffect}" Value="1"><Setter Property="BorderBrush" Value="Blue" /><Setter Property="BorderThickness" Value="0,2,0,0" /></DataTrigger><DataTrigger Binding="{Binding RowEffect}" Value="2"><Setter Property="BorderBrush" Value="Blue" /><Setter Property="BorderThickness" Value="0,0,0,2" /></DataTrigger><Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="LightGray" /></Trigger><Trigger Property="IsSelected" Value="True"><Setter Property="Background" Value="LightGray" /></Trigger><Trigger Property="IsNewItem" Value="True"><Setter Property="Margin" Value="{Binding NewItemMargin, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/></Trigger></Style.Triggers></Style></DataGrid.RowStyle>

if you see here in above code I have applied Style triggers based on model’s RowEffect data to change the backgroud of a row.

That’s all and as a result here is the effect which you will get:

Note: Cursor is not shown in image as it disappear while taking the snapshot because of control movement but it is there.

** Use ctrl for multi select and then ctrl+shift to start dragging multiple selected rows. This behavior your can change based on your code logic.

Download the prototype code from here: https://github.com/binodmahto/FunProjects/tree/main/WPFDragDropDemo

Saturday, 26 June 2021

Defining Custom IP range for Docker Containers

 I feel or I would recommend, it is always good to go with custom subnet IP range for your docker containers and you would need it for many reasons:

  1. What id default IP ranges are not available
  2. You need to add the range/IP to your firewall but don’t know because of it’s dynamic nature. etc.

There are two ways you can do it and I’m saying it two ways because you would need it if you are dealing with docker containers in windows OS.

  1. Define it with Docker-Compose.yaml file.
For Linux:networks:
mycustomnet:
driver: bridge
ipam:
config:
- subnet: 20.5.0.0/24
For Windows:networks:
mycustomnet:
driver: nat
ipam:
config:
- subnet: 20.5.0.0/24

So above definition will create a name subnet under bridge/nat driver and you can use this defined subnet for your containers and your containers will always use IP from the above mentioned range only.

But this is a problem with Windows OS. In windows OS this defined network (in this case mycustomnet) will get disappear with restarting of windows OS. Aah it makes me frustrated when I faced this and unfortunately there is no solution available neither from Docker or Windows (at lease I didn’t find it as of now) and this is where I was forced to choose second approach which preferably I won’t recommend.

2. Define it via Docker Daemon.json

For windows:{"fixed-cidr": "20.5.0.0/16"}For Linux:{"default-address-pools":[
{"base":"20.5.0.0/16","size":24}
]
}

Above settings will change the default network IP range to 20.5.0.0/16 in windows as well as in Linux but in Linux I get extra advantage to mention the /24 range to be used out of /16 by creating a new named subnet. So in linux if you do >>docker network ls then you will see the defined name network as dockerartifacts_service or similar.

Since there is no problem with Linux so I would always recommend the first approach for Linux machine.

Important Note:
If you are doing the second approach for any reason, then don’t forget to delete the existing net and restart the docker engine and to do this you can use powershell command for windows as:

Get-HNSNetwork | Remove-HNSNetwork -Verbose
Restart-Service Docker -Verbose
Verbose will display the result and it is optional in command

WPF Data Binding Best Practices

 I just started learning WPF and today I’m gonna share the WPF basics for two way data bindings and the focus would be on designing your Model and ViewModel.

WPF is based on MVVM design patterns and this is how I see/understand it.

Model should only be responsible for Business & Data logics and it should not have any dependency with UI. Well, I say it as I have seen many articles where people have used INotifyPropertyChanged derived with their Models. I’m not saying it is completely wrong but doesn’t seems to be a best practices as well. Think about a scenario where your Model is shared among multiple services and wpf application.

So what I prefer here to use MVVM with Facade Pattern to separate out the UI dependency with Model.

Another important thing which I noticed with articles flooded over the internet is, Use of DependencyObject override for ViewModel for data binding. I didn’t find it a best practice as well because of the limitations/issues it is giving like:
1. It creates a View dependencies and it never meant to be a source of a binding.
2. Can’t override Equals or GetHashCode (may be less important)
3. Thread affinity problem: a huge issue dealing with multi threading
4. Serialization problem: another problem if you want to serialize anything in ViewModel
5. Difficult to read: I hate this as this implementation makes code too difficult to read/understand specially for people like me, who is learning.
6. Still need INotifyPropertyChanged for CLR properties.

Hence finally here we got two best practices to be followed for WPF data binding:
1. Use Facade for Models and 2. use INotifyPropertyChanged.

Now lets do the programming. A simple application which has a person info, First Name, Last Name and Full Name and how we bind it by following above two best practices.

Model (Person.cs)

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";

public Person() { }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}

As I said, we will not keep any dependency with Model to UI and ViewModel and the reason could be like, this model has too much probably not needed for me or we need to use multiple models together for view model.

Model Facade (ModelFacade.cs =>you name it as you want)

public class ModelFacade
{
public Person Person { get; set; }
public ModelFacade(string firstName, string lastName)
{
Person = new Person
{
FirstName = firstName,
LastName = lastName
};
}
}

Now here we go with ViewModel which will be implementing INotifyPropertyChanged. Also for code extendibility or avoid code duplicity I prefer (actually I recommend it as a best practice) ViewModelBase to separate the INotifyPropertyChanged implementation.

ViewModel (ViewModel.cs) and ViewModelBase (ViewModelBase.cs)

public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}

public class ViewModel : ViewModelBase
{
ModelFacade _model;
public string FirstName
{
get { return _model.Person.FirstName; }
set
{
_model.Person.FirstName = value;
OnPropertyChanged("FirstName");
OnPropertyChanged("FullName");
}
}
public string LastName
{
get { return _model.Person.LastName; }
set
{
_model.Person.LastName = value;
OnPropertyChanged("LastName");
OnPropertyChanged("FullName");
}
}
public string FullName
{
get { return _model.Person.FullName; }
}
public ViewModel()
{
_model = new ModelFacade("Binod", "Mahto");
}
}

View (MainWindow.xaml)

<Window x:Class="WpfAppNet2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppNet2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:ViewModel x:Name="vm"/>
</Window.DataContext>
<Grid Margin="10" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<TextBlock Text="First Name:" Grid.Column="1" Grid.Row="1"/>
<TextBox Text="{Binding Mode=TwoWay, Path=FirstName, UpdateSourceTrigger=PropertyChanged}" Grid.Column="2" Grid.Row="1" Width="100" />
<TextBlock Text="Last Name:" Grid.Column="1" Grid.Row="2"/>
<TextBox Text="{Binding Mode=TwoWay, Path=LastName, UpdateSourceTrigger=PropertyChanged}" Grid.Column="2" Grid.Row="2" Width="100"/>
<TextBlock Text="Full Name:" Grid.Column="1" Grid.Row="4"/>
<TextBlock Text="{Binding FullName}" Grid.Column="2" Grid.Row="4"/>
<TextBlock Text="{Binding Mode=TwoWay, Path=Message}" Grid.Column="2" Grid.ColumnSpan="2" Grid.Row="5"/>
<Button Content="Save Me!" Name="btnSave" Click="btnSave_Click" Grid.Column="1" Grid.Row="6"/>
<TextBox TextWrapping="Wrap" AcceptsReturn="True" Name="txtSavedData" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="7"/>
</Grid>
</Window>

Suggestion: Avoid doing control drag & drop if you really want to use the WPF best of it and follow Grid Rows and Columns based design as I did here otherwise you will never get your code right in UI because of autogenerated margins when you drag and drop controls.

Code Behind. (MainWindow.xaml.cs)

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
txtSavedData.Text = vm.FirstName + "\n" + vm.LastName + "\n" + vm.FullName;
}
}

and here is the output:
1. When it loads:

2. Either change First Name or Last Name, you will the Full Name changing accordingly.

3. Click on save to see the modified state of Model Facade properties.

Now you can easily use the ModelFacase modified state to send the data back from ViewModel to Model for update.

Hope you like it.

Wednesday, 2 June 2021

Configure Apache as a forward proxy on Windows

 We often need a proxy (forward proxy) as an intermediate server to serve the request between the client and the origin server via proxy. Assume a scenario like: client needs to connect to internet or some other sites by using the forward proxy as the client can’t connect to them directly.


Let’s do the setup for Apache as a forward proxy. Below are the steps which you need to follow.

Step 1: We need a Apache server so download it from here.
https://www.apachelounge.com/download/

Apache server is available as binaries in a zip file from the above link.

Step 2: Extract the downloaded zip file in a C/D/E (your choice) drive within a folder called Apache24. i.e. C:\Apache24.

Note: You may give another name instead of Apache24 but in that case you will also have to update the SRVROOT value in httpd.conf file.


Step 3: Now we will install this as a window service to take an advantage of auto start and always keeping up the server up & running. To install this Apache server as window service, open command prompt and point to C:\Apache24\bin run the below command:

C:\Apache24\bin> httpd.exe -k install -n "MyServiceName"

For more options on installation, please visit the link here: http://httpd.apache.org/docs/2.4/platform/windows.html

Step 4: Update the related config/modules for Apache to setup forward proxy. open the file C:\Apache24\conf\httpd.conf in your favorite text editor and update/modify settings as mentioned:

a. Enable related modules by uncommenting them, remove the # character from beginning.

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_module modules/mod_proxy_http.so
LoadModule proxy_module modules/mode_proxy_connect.so
LoadModule proxy_module modules/mod_ssl.so
LoadModule proxy_module modules/mod_xml2enc.so
LoadModule proxy_module modules/mod_proxy_html.so
LoadModule proxy_module modules/mod_proxy_http2.so

Here are short descriptions of each module which will give you idea why you need them.

mod_proxy: implement a proxy/gateway for Apache HTTP Server.
mod_proxy_connect: provides support for the CONNECT HTTP method. This method is mainly used to tunnel SSL requests through proxy servers.
mod_proxy_http: provides the features used for proxying HTTP and HTTPS requests.
mod_proxy_http2: supports HTTP/2 only and works with incoming fronted requests using HTTP/1.1 or HTTP/2.
mod_ssl: provides SSL v3 and TLS v1.x support for the Apache HTTP Server. SSL v2 is no longer supported.
mod_proxy_html: provides an output filter to rewrite HTML links in a proxy situation, to ensure that links work for users outside the proxy.
mod_xml2enc: provides enhanced internationalisation support for markup-aware filter modules such as mod_proxy_html. It can automatically detect the encoding of input data and ensure they are correctly processed by the libxml2 parser, including converting to Unicode (UTF-8) where necessary.

Note: For more details on above module please visit https://httpd.apache.org/docs/2.4/mod/

b. Update the listener information for apache server. (Search the word Listen in httpd.conf file)

Listen 192.89.12.120:8082

Note: You must use IP:Port combination instead of just using either one of them which you can do and the reason behind this is: If only a port number is specified in the Listen directive, the server listens to the given port on all interfaces. If an IP address is given as well as a port, the server will listen on the given port and interface. Multiple Listen directives may be used to specify a number of addresses and ports to listen on. The server will respond to requests from any of the listed addresses and ports. For more detail please visit: https://httpd.apache.org/docs/2.4/bind.html

c. update ServerName as DNS Host Name (FQDN) if not then the IP address of the server (search the word ServerName)

ServerName 192.89.12.120:8082

Note: ServerName gives the name and port that the server uses to identify itself. This can often be determined automatically, but we recommend you specify it explicitly to prevent problems during startup. If your host doesn’t have a registered DNS name, enter its IP address here.

d. Update other details like ServerAdmin emailid, ErrorLog path, LogLevel etc as per your need.

Step 5: Now we will modify/update the proxy server details in C:/Apache24/conf/extra/proxy-html.conf file. So lets open the file using your favorite text editor and follow the below steps:

a. Enable forward proxy using ProxyRequest module by setting it to On.

ProxyRequests On

b. Configure the server address (i.e. internet, origin server etc) where request will be forwarded through this proxy server.

ProxyRemote = http://XXX.XXX.0.25:9400
OR
ProxyRemote * "${ProxyRemote}" -- in this case ProxyRemote is an environment variable which holds the origin server info.

Note: ProxyRemote is optional and needed only if you have remote proxy to redirect. In case if this machine has internet connection and don’t add this setting at all and that will make your proxy server to process the requests (internal or intranet).

c. Now lets enable the proxy routing and at the same time also restrict the forward proxy for specific subnet mask or IP if you need to do so or else ignore the Require IP setup.

<Proxy *>
Require ip 192.12 -- in this case any ip with mask 192.12 will be able to use the proxy
</Proxy>

Step 6: we are done here and it’s time to test your forward proxy setup. To test you can take another machine and setup the manual proxy setting (through internet setting or registry or curl command (if testing through curl command)), set the proxy url as ‘192.89.12.120:8082’ and run the test.

Though above configuration is for setting up the forward proxy in Windows machine but it is almost the same step you need to follow for Linux too. 

Wednesday, 12 May 2021

C# 9.0 record types

Hello Friends,

In C# 9.0, there is a new type 'record' has been introduced and believe me, I was very excited when I see this feature. As a programmer I got many situation where I had to do a lot to compare two class objects to check if they both have same values, cloning a class and used to think why can’t be this made simpler.

And here we go, Now C# 9.0 has introduced record types to fulfil the need of value based equality, comparisons with reference variables. So the difference between a class and record type are:

1. Both are reference type but record type equality is determined by the equality of values of the data members where as class does the comparison with reference.

Yeah and that is all the difference I see between a class and record type. ❤

I was playing a bit to figure out what we can do with record type and below code shows all interesting stuff or need which we want as a programmer. So let’s go one by one.

  1. Is record type supports interface inheritance: Yes It does.
  2. public interface IHuman
        {
            string Family { get; }
        }
    
        public record Person : IHuman
        {
            public string Family => "Hominidae";
            public string FirstName { get; init; } 
            public string LastName { get; init; } 
        }
    Note: record type too support init-only feature of C# 9.0 which is equivalent to ReadOnly. In above code I have mentioned init only setter property for FirstName and LastName which means these values must be initialized while object initialization and can’t be modified after that.

  3. Is record type support inheritance: Yes It does.
  4. public record Actor : Person
    {
    public int Age { get; set; }
    public Gender Gender { get; init; }
    public void PrintActorDetails()
    {
    Console.WriteLine($"Name:{FirstName} {LastName}, Age:{Age}, Gender:{Gender}");
    }
    }
    Also you can introduced new record types with inheritance simply with a line of code:

    public record Bollywood(string Industry) : Actor;
    This means, the new Bollywood record type has a new member called Industry which is required while creating a new object of record type Bollywood. Interesting Isn’t it. I ❤ it.

  5. Can we clone the object of record type: Aha, it supports C# 9.0 ‘with’ expression which allows to easily clone the object.

  6. var actor1 = new Actor { FirstName = "Varun", LastName="Dhawan", Age=30, Gender=Gender.Male };
    var actor2 = actor1 with { FirstName = "Akshay", LastName= "Kumar" };

  7. It really compares values: Yes it does.

  8. var actor1 = new Actor { FirstName = "Varun", LastName="Dhawan", Age=30, Gender=Gender.Male };
    var actor2 = actor1 with { Age = 30 };
    Console.WriteLine(actor1.Equals(actor3));// results true.

  9. Last but not the list, Everyone would love it for tracing (no more serializing).
  10. var bollyActor = new Bollywood("Bollywood") { Age = 30, FirstName = "Kiara", LastName = "Advani", Gender = Gender.Female };
    Console.WriteLine(bollyActor);

Above code will result output as:

 Bollywood { Family = Hominidae, FirstName = Kiara, LastName = Advani, Age = 30, Gender = Female, Industry = Bollywood } 

Hope you enjoyed reading! Thank You.

Sunday, 23 June 2019

Printing zpl and pdf documents through C#

Hi Friends,

 We have seen ways to print a pdf through C# but printing zpl on zebra printers doesn't seems to work like pdf but here I'm demonstrating a way which can print zpl (*.zpl, on zebra printers) and pdf (*.pdf) or other documents types. This also could be a best option as it doesn't depend on any other third party libraries (open source or paid).

public class BasePrintUtility { private static bool SendRawBytesToPrinter(string szPrinterName, string printerFileName, IntPtr pBytes, Int32 dwCount) { Int32 dwError = 0, dwWritten = 0; IntPtr hPrinter = new IntPtr(0); DOCINFOA di = new DOCINFOA(); bool bSuccess = false; // Assume failure unless you specifically succeed. di.pDocName = printerFileName; di.pDataType = "RAW"; // Open the printer. if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero)) { // Start a document. if (StartDocPrinter(hPrinter, 1, di)) { // Start a page. if (StartPagePrinter(hPrinter)) { // Write your bytes. bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten); EndPagePrinter(hPrinter); } EndDocPrinter(hPrinter); } ClosePrinter(hPrinter); } // If you did not succeed, GetLastError may give more information // about why not. if (bSuccess == false) { dwError = Marshal.GetLastWin32Error(); } return bSuccess; } // Structure and API declarions: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class DOCINFOA { [MarshalAs(UnmanagedType.LPStr)] public string pDocName; [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile; [MarshalAs(UnmanagedType.LPStr)] public string pDataType; } [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd); [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool ClosePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di); [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool EndDocPrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool StartPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool EndPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten); public bool SendDocumentToPrinter(string filePath, PrintSettings printSettings) { // Open the file. FileInfo fileInfo = new FileInfo(filePath); Byte[] bytes = null; bool bSuccess = false; // Your unmanaged pointer. IntPtr pUnmanagedBytes = new IntPtr(0); int nLength; using (FileStream fs = fileInfo.OpenRead()) { //FileStream fs = new FileStream(szFileName, FileMode.Open); // Create a BinaryReader on the file. BinaryReader br = new BinaryReader(fs); // Dim an array of bytes big enough to hold the file's contents. bytes = new Byte[fs.Length]; nLength = Convert.ToInt32(fs.Length); // Read the contents of the file into the array. bytes = br.ReadBytes(nLength); } // Allocate some unmanaged memory for those bytes. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); // Copy the managed byte array into the unmanaged array. Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength); // Send the unmanaged bytes to the printer. for (int i = 0; i < printSettings.Copies; i++) { bSuccess = SendRawBytesToPrinter(printSettings.PrinterName, fileInfo.Name, pUnmanagedBytes, nLength); } // Free the unmanaged memory that you allocated earlier. Marshal.FreeCoTaskMem(pUnmanagedBytes); return bSuccess; } public bool SendDocumentToPrinter(byte[] content, int copies, string printerName, string fileName) { bool status = false; IntPtr pUnmanagedBytes; int nLength = content.Length; // Allocate some unmanaged memory for those bytes. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); // Copy the managed byte array into the unmanaged array. Marshal.Copy(content, 0, pUnmanagedBytes, nLength); // Send the unmanaged bytes to the printer. for (int i = 0; i < copies; i++) { status = SendRawBytesToPrinter(printerName, fileName, pUnmanagedBytes, nLength); } // Free the unmanaged memory that you allocated earlier. Marshal.FreeCoTaskMem(pUnmanagedBytes); return status; } }

isn't it simple.

Note: This is not optimized code and just  a sample. You must optimize it as your need before using it.

Source: https://github.com/andyyou/SendToPrinter/blob/master/Printer/RawPrinterHelper.cs


Thanks.

Friday, 9 November 2018

Calling Python from SQL Server

Hi Friends,

This post is about executing python script from sql server using the python environment you have and the solution is 'xp_cmdshell'.

It is very simple and easy actually just one line and this is:


EXEC master..xp_cmdshell N'C:\Python\ENV-Python3.7\Scripts\python.exe C:\P21\git\pythonpricingprototype\helloworld.py param[0] param[1]'

In the above code,
 the first path 'C:\Python\ENV-Python3.7\Scripts\python.exe' is for python.exe from the python environment you have/created.
 and the second path 'C:\P21\git\pythonpricingprototype\helloworld.py' is for the script which you need to execute.
then comes the parameters which you need to pass to python script.

Here is the python script helloworld.py for me.

import sys import numpy from __init__ import Logger def main(name): print(name) if __name__ == '__main__': Logger.debug('In Main') main(sys.argv[1]) Logger.debug(sys.argv[1])

beauty of this is, it will resolve all your dependent scripts and packages automatically. As example I have __init__.py for logging related setting and initialization within the same folder ' C:\P21\git\pythonpricingprototype' and one package 'numpy' installed through pip for my python environment 'ENV-Python3.7.

Simple isn't it, but you need to make sure your python code shouldn't be a demon to kill the sql server process while running this through sql server.

** I still need to explore little more on this but if you have something which people should know please share it.

Thanks

Friday, 2 November 2018

Calling Python from C#

"Calling Python script from C#" doesn't seems to be a challenge or tough task. Even there are many articles available on internet which will tell you how to do that, but still I had to struggle a lot when I was doing this based on my need hence thought, it is better to share it with you all.

I had a full fledged Python project dependent on packages like Numpy, Pandas etc and I had to consume it through C# (a web api service). Technically from the C# I had a web api REST service endpoint which was processing data through python script/project.

My struggle was to resolve the other dependent script available in project and packages installed through pip. It took good amount of time to figure out the efficient way to solve this problem. During this I also researched about IronPython which allows you to fill the gap between .net and python but it didn't helped me and instead it was more problematic while resolving package like numpy, panda etc. Also I was not convinced to use IronPython just to execute python script from C# (.net).



Enough of talk, let's come to the solution. Below are steps which I followed to solve the problem

1. Created Main script (Main.py) which is an entry point to python from C#. something like this (sample):

import mypackage from __init__ import Logger def Main(requestid, data): try: #Code...calling other scripts/logics etc except Exception as e: Logger.error(e) if __name__ == '__main__': try: Logger.debug('calling Main with paramaeters requestid:%s and\n data:%s' % (sys.argv[1], sys.argv[2])) Main(sys.argv[1], sys.argv[2]) Logger.debug('Main Ends') except Exception as e: Logger.error(e)


Above code was a sample code which will get executed from C# and then this script will take care of executing other script. in .Net word this acts as a Main method of console application.

2. Made sure all the dependent python packages are installed through pip for the python environment (which is being used)

3. C# code to execute the script. This uses System.Diagnostics.ProcessStartInfo class to execute the python.exe and run the script main.py with arguments.

using System.Diagnostics;

//**C# code **//
 private dynamic CallPython(string requestId, string data)
        {
            // full path of python interpreter 
            string python = @"C:\Python\ENV-Python3.7\Scripts\python.exe";

            // python app to call 
            string myPythonApp = @"Main.py";

            // Create new process start info 
            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
            myProcessStartInfo.WorkingDirectory = @"C:\Project\git\pythonpricingprototype";

            // make sure we can read the output from stdout 
            myProcessStartInfo.UseShellExecute = false;
            myProcessStartInfo.RedirectStandardOutput = true;

            // start python app with 3 arguments  
            // 1st arguments is pointer to itself,  
            // 2nd and 3rd are actual arguments we want to send 
            myProcessStartInfo.Arguments = myPythonApp + " " + requestId + " " + data;
            string result;
            using (Process myProcess = Process.Start(myProcessStartInfo))
            {
                using (StreamReader reader = myProcess.StandardOutput)
                {
                    result = reader.ReadToEnd();
                    myProcess.WaitForExit();
                }
            }

            return result;
        }




Explanation: There are three important line of code which plays the responsibility of resolving and running all dependent python packages/scripts.

  • Python Interpreter (exe) path. : You must point to the path of python.exe available for the python environment where you have all dependent package installed.
    In my case it was: C:\Python\ENV-Python3.7\Scripts\python.exe
  • Main script (entry point) name.
    In my case: Main.py
  • Python project working directory: This was the the most important thing to resolve the all your other scripts (in project). In short it is the project root folder path where the Main.py and other *.py files are available.
    In my case: C:\Project\git\pythonpricingprototype
  • then executing the command which is equivalent to:
    >>>main.py 12345 somedata
Rest all codes in C# are simple and good enough for self explanatory but instead if needed feel free to reach out to me.

That's all. Thanks for reading. Feel free to provide your valuable feedback.