Saturday, December 31, 2011

C# in java

I Like to post though it avail at code project.
for your refernce with parameter
==========================================

    public class Sum
    {
        public int add(int a, int b)
        {
            return a + b;
        }
    }
===========================================
save as Sum.cs and compile it to module
using cmd:

>csc /t:module sum.cs

Create Java File to test
===========================================
public class test{
public native int add(int a,int b);
 static {
        System.loadLibrary("JSample");
    }
   
    public static void main (String[] args) {
       System.out.println(new test().add(10,15));
    }
}
==========================================
save it as test.java compile as
>javac test.java
create native header file
>javah -jni test
it will create test.h
==========================================
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class test */

#ifndef _Included_test
#define _Included_test
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     test
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_test_add
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif
==========================================

create win32 project using visual studio (I used VS2010)
Choose project name as JSample

include header and C#.net module
write header for manged C++ conversion
==============================================
#using <mscorlib.dll>
#using "Sum.netmodule"
using namespace System;
public __gc class SumC
{
public:
    Sum __gc *t;
    SumC()
    {
        t = new Sum();          
    }
    int callCSharpSum(int a,int b)
    {
        return  t->add(a,b);
    }
};
===========================================
save it as sum.h

create sum.cpp file
============================================
#include <jni.h>
#include "test.h"
#include "sum.h"

JNIEXPORT jint JNICALL Java_test_add
    (JNIEnv *, jobject, jint a, jint b)
{
    SumC* t = new SumC();  
    return t->callCSharpSum(a ,b );
}
=============================================
optimze compliler to build /clr:oldSyntax
Include Jdk/Include directory path
build the project.
we will Get JSample DLL

run the project
with C#.net module,Native DLL file and class file at the same folder.

>java test
25
================================================
Hope it helps

find the link

https://docs.google.com/open?id=0B8j-6CFq6hsGY2EzOWRmMGMtZDBjOS00NTgwLTgxYjQtMzhhODk2OWM2N2Vj


Regards
..arun@darkside..

Trace to Log File

 private readonly FileStream _obj = new FileStream("log.txt", FileMode.OpenOrCreate);

At form Load use this

  var objt = new TextWriterTraceListener(_obj);
   Trace.Listeners.Add(objt);
    Trace.AutoFlush = true;


 

Saturday, October 15, 2011

Block the paste by CUT, COPY event in .Net

private void timer1_Tick(object sender, EventArgs e)
{
    try
    {
        var f = Process.GetProcessesByName("cmd"); 
//to avoid copy cmd by command prompt
        foreach (var process in f)
        {
            process.Kill();
            Clipboard.Clear();
        }
        Clipboard.Clear();
    }
    catch (Exception)
    {

        Clipboard.Clear();
    }    }

Friday, September 9, 2011

Often I Prefer single instance application on Form

    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>


        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetForegroundWindow(IntPtr hWind);

        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWind, int cmd);


        [STAThread]
        private static void Main()
        {
            bool mutexWasCreated;
            var mut = new Mutex(true, "{..arun@darkside..}", out mutexWasCreated);
            if (mutexWasCreated)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                mut.ReleaseMutex();
            }
            else
            {
                Process current = Process.GetCurrentProcess();
                for (int index = 0; index < Process.GetProcessesByName(current.ProcessName).Length; index++)
                {
                    Process process = Process.GetProcessesByName(current.ProcessName)[index];
                    if (process.Id == current.Id) continue;
                    SetForegroundWindow(process.MainWindowHandle);
                    ShowWindowAsync(process.MainWindowHandle, 9);
                    break;
                }
            }
        }
    }

often I Like to Scroll at Bottom

Autoscroll (TextBox, ListBox, ListView) [C#]

This example demonstrates how to programatically autoscroll WinForm controls TextBox, ListBox, ListView, TreeView and DataGridView.
Autoscroll to the end of box or view is useful, for example, in situations when you use one of these components as the output log window. Usually you add the items to the box or view and you want to be sure that the last added item is visible without the necessary to do it manually.
Though it's not difficult to solve this problem, .NET doesn't provide any unified way how to do it.

TextBox autoscroll

[C#]
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();

ListBox autoscroll

[C#]
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.SelectedIndex = -1;

ListView autoscroll

[C#]
listView1.EnsureVisible(listView1.Items.Count - 1);

TreeView autoscroll

[C#]
treeView1.Nodes[treeView1.Nodes.Count - 1].EnsureVisible();

DataGridView autoscroll

[C#]
dataGridView1.FirstDisplayedCell =
  dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0]; 
 
Found at http://www.csharp-examples.net/autoscroll/

Hide Show Panel at RunTime

 if (hideToolStripMenuItem.Text != @"Hide")
            {
                if (hideToolStripMenuItem.Text != @"Show") return;
                splitContainer1.Panel2.Visible = true;
                splitContainer1.Panel2Collapsed = false;
                hideToolStripMenuItem.Text = @"Hide";
                return;
            }
            splitContainer1.Panel2.Visible = false;
            splitContainer1.Panel2Collapsed = true;
            hideToolStripMenuItem.Text = @"Show";

Pdf embedded Resource displaying at Run Time

                Stream sr = Assembly.GetExecutingAssembly().GetManifestResourceStream("P2PC.ppc.pdf");
                if (sr == null) return;
                var reader = new BufferedStream(sr);
                tempfile = Path.GetTempFileName() + ".pdf";
                var data = new byte[reader.Length];
                reader.Read(data, 0, (int) reader.Length);
                File.WriteAllBytes(tempfile, data);
                axAcroPDF1.Visible = true;
                axAcroPDF1.LoadFile(tempfile);

to delete...

axAcroPDF1.Visible = false;
            if (tempfile != null) File.Delete(tempfile);

Cross Thread Exception in Same thread in WinForm Controls

recently i came across problem over rich text box control,on updating string 

richTextBox1.Text += "Client Started" + Environment.NewLine;

Is replaced by

Invoke(new Action(() => richTextBox1.Text += "Client Started" + Environment.NewLine));

Note: if You're using .net 2.0runtime build declare 
public delegate void Action();//do not return the value
write it outside of a class.













Thursday, July 14, 2011

Date Time Picker

Simple User Defined datetime picker value.from a string.

dateTimePicker1.Value = DateTime.ParseExact(da, "dd/MM/yyyy", CultureInfo.InvariantCulture);