Search This Blog

Thursday, July 30, 2009

Drag and Drop Picturebox on FlowLayoutPanel

Here is code example of re-order picture boxes within a FlowLayoutPanel at runtime.

// add FlowLayoutPanel on a Winform - named flowLayoutPanel1
public partial class TestForm: Form
{
       public TestForm()
        {
            InitializeComponent();
            this.flowLayoutPanel1.AllowDrop = true
        }
        private void AddImageToBlog(System.Drawing.Image image)
        {
            PictureBox pbox = new PictureBox();
            pbox.SizeMode = PictureBoxSizeMode.Zoom;            
            pbox.Height = (_picturebox_height * _ScaleFactor);
            pbox.Width = (_picturebox_width * _ScaleFactor);
            pbox.Visible = true;
            pbox.Image = image;

            pbox.MouseDown += new MouseEventHandler(pbox_MouseDown);
            pbox.DragOver += new DragEventHandler(pbox_DragOver);            
            pbox.AllowDrop = true;
            flpNewBlog.Controls.Add(pbox);
        }
       void pbox_DragOver(object sender, DragEventArgs e)
        {
            base.OnDragOver(e);
            // is another dragable
            if (e.Data.GetData(typeof(PictureBox)) != null)
            {
                FlowLayoutPanel p = (FlowLayoutPanel)(sender as PictureBox).Parent;                 
                //Current Position             
                int myIndex = p.Controls.GetChildIndex((sender as PictureBox));

                //Dragged to control to location of next picturebox
                PictureBox q = (PictureBox) e.Data.GetData(typeof(PictureBox));                
                p.Controls.SetChildIndex(q, myIndex);
            }           
        }
        void pbox_MouseDown(object sender, MouseEventArgs e)
        {
            base.OnMouseDown(e);
            DoDragDrop(sender, DragDropEffects.All);
        }
         void pbox_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }


}

Wednesday, July 22, 2009

Tuesday, July 21, 2009

Clear SQL caches

From Devx.com

When tuning SQL Server applications, a certain degree of hands-on experimenting must occur. Index options, table design, and locking options are items that can be modified to increase performance. When running a test, be sure to have SQL Server start from the same state each time. The cache (sometimes referred to as the buffer) needs to be cleared out. This prevents the data and/or execution plans from being cached, thus corrupting the next test. To clear SQL Server’s cache, run DBCC DROPCLEANBUFFERS, which clears all data from the cache. Then run DBCC FREEPROCCACHE, which clears the stored procedure cache

DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS

Saturday, July 18, 2009

C# code to register Assembly into Global Cache (GAC)

You can make use of System.EnterpriseServices assembly. Follow the following steps:

1) Add Reference >> System.EnterpriseServices
2) In case of C#:
using System.EnterpriseServices.Internal;

3) below in the code, for example on click of a button

Publish objPub=new Publish();

//to add the assembly - use full path with file name
objPub.GacInstall("AssamblyPath");

//to remove the assembly - use full path with the file name
objPub.GacRemove("AssemblyPath");

Moreove make sure, your assembly should be signed using:
sn.exe -k assemblyname //either it is .dll or .exe

Another Code Example:
using System.Text;
using System.Windows.Forms;
using System.EnterpriseServices.Internal;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Publish p = new Publish();
p.GacInstall(@"c:\myassmebly.dll");
}
}
}


Other GAC related links:

- A proper way to install Assemblies to the GAC is documented by Microsoft here http://support.microsoft.com/kb/317540/en-us

- For NSIS and .net - Register a managed .NET DLL in the GAC

Friday, July 17, 2009

VB6 App with C# COM object

VB6 project using C# COM Assembly
-2147024896 (80070002) Automation error The System cannot find file specified

I get this very thing...

from MSDN forum

Question:
i'm having problems running the vb6 app, and the error occurs when i make the form show. i've followed the instructions from the help file and still the problem arises everytime.

here's another weird thing, when i added the interop form to an existing vb6 application, it was ok when run inside the ide. when i compiled this to an .exe file, the error happened. i also tried creating fresh vb6 app and it worked, so any ideas on this issue? thanks.


Answer:
1) Strongly name Assemblies.
   sn -k TestKeyPair.snk
2) Add TestKeyPair.snk to project(s).
3) Edit AssemblyInfo.cs
A) Make assembly is versioned
[assembly: AssemblyVersion("1.0.0.0")]
b) Add [assembly: AssemblyKeyFile("TestKeyPair.snk")]
4) Add Assembly to GAC
gacutil /i MyInterop.dll
- Make sure all Assembly DLLS has been
5) Regasm Assembly and expose COM use /codebase
REGASM MyInterop.dll /tlb:com.MyInterop.tlb /codebase
Better Answer:
1) Strongly name Assemblies.
   sn -k TestKeyPair.snk
2) Add TestKeyPair.snk to project(s).
3) Edit AssemblyInfo.cs
A) Make assembly is versioned
[assembly: AssemblyVersion("1.0.0.0")]
b) Add [assembly: AssemblyKeyFile("TestKeyPair.snk")]
4) Copied all related assemblies local to folder containing VB6 project
5) Run from this folder: tlbexp sampleDLL.dll /out:sampleDLL.tlb
6) run from this folder: regasm sampleDLL.dll /tlb:sampleDLL.tlb
7) Open VB6 project and reference to sampleDLL.tlb is local to project.

Proper Useage related Indexed Views

Hidden Gotcha with Indexed Views NoExpand vs Expand See microsoft article

The NOEXPAND view hint forces the query optimizer to treat the view like an ordinary table with a clustered index - basically I thought this was the main purpose for an indexed View...

Using the NOEXPAND view hint

When SQL Server processes queries that refer to views by name, the definitions of the views normally are expanded until they refer only to base tables. This process is called view expansion. It's a form of macro expansion.

The NOEXPAND view hint forces the query optimizer to treat the view like an ordinary table with a clustered index. It prevents view expansion. The NOEXPAND hint can only be applied if the indexed view is referenced directly in the FROM clause. For example,

SELECT Column1, Column2, ... FROM Table1, View1 WITH (NOEXPAND) WHERE ...

Use NOEXPAND if you want to be sure to have SQL Server process a query by reading the view itself instead of reading data from the base tables. If for some reason SQL Server chooses a query plan that processes the query against base tables when you'd prefer that it use the view, consider using NOEXPAND. You must use NOEXPAND in all versions of SQL Server other than Developer and Enterprise editions to have SQL Server process a query against an indexed view directly. You can see a graphical representation of the plan SQL Server chooses for a statement using the SQL Server Management Studio tool Display Estimated Execution Plan feature. Alternatively, you can see different non-graphical representations using SHOWPLAN_ALL, SHOWPLAN_TEXT, or SHOWPLAN_XML. See SQL Sever books online for a discussion of the different versions of SHOWPLAN.

Using the EXPAND VIEWS query hint

When processing a query that refers to a view by name, SQL Server always expands the views, unless you add the NOEXPAND hint to the view reference. It attempts to match indexed views to the expanded query, unless you specify the EXPAND VIEWS query hint in an OPTION clause at the end of the query. For example, suppose there is an indexed view View1 in the database. In the following query, View1 is expanded based on its logical definition (its CREATE VIEW statement), and then the EXPAND VIEWS option prevents the indexed view for View1 from being used in the plan to solve the query.

SELECT Column1, Column2, ... FROM Table1, View1 WHERE ...
OPTION (EXPAND VIEWS)
Use EXPAND VIEWS if you want to be sure to have SQL Server process a query by accessing data directly from the base tables referenced by the query, instead of possibly accessing indexed views. EXPAND views may in some cases help eliminate lock contention that could be experienced with an indexed view. Both NOEXPAND a

Saturday, July 11, 2009

Detect an Internet Connection

Simple Code to make sure there is an active internet connection.
 using System.Net.Sockets;

private bool ConnectionExists()
{
try
{
TcpClient clnt = new TcpClient("www.google.com", 80);
clnt.Close();
return true;
}
catch (System.Exception)
{
return false;
}
}

Friday, July 10, 2009

Create COM object using C# for VB6 Application

Here is a C# example: Create a COM object with events using C# and implement in a VB6 Application.

Step #1: Define COM interfaces
Need to create two interfaces - 1 class interface and a events interface

Public Class Interface: IMyClass
using System;
using System.Drawing;
using PicasaBloggerUserControls;
using System.Runtime.InteropServices;

namespace MyApp
{
[Guid("xxxxxxxx-yyyy-zzzz-aaaa-bbbbbbbbbbbb")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface
IMyClass
{
void GetDRCUpdate(string url, int majorVer, int minorVer, int RevisionVer, bool GetLatest);
}
}


Public Interface defining the events: IMyClassEvents

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace MyApp
{
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("xxxxxxxx-yyyy-zzzz-aaaa-bbbbbbbbbbbb")]
public interface
IMyClassEvents
{
void DownloadComplete();
void DownloadCancel(bool downloadfailed);
}
}
Step #2
Define Public class using class interface: winformUI

using System.Drawing;
using System.Windows.Forms;
using PicasaBloggerUserControls;
using System.Runtime.InteropServices;

namespace PicasaBloggerUI
{
[Guid(
"xxxxxxxx-yyyy-zzzz-aaaa-bbbbbbbbbbbb")]
[
ComSourceInterfaces("MyApp.PicasaBloggerEventsInterface"),
ClassInterface(ClassInterfaceType.None)
]
[ProgId("winformUI")]


public class winformUI :
IMyClass
{
public event FileDownloadDelegate DRCDownloadComplete;
public delegate void FileDownloadDelegate();

public event FileDownloadCancelDelegate DRCDownloadCancel;
public delegate void FileDownloadCancelDelegate(bool downloadfailed);

private frmDRCUpdate _DRCUpdater;

//ctor
public winformUI()
{
_DRCUpdater = new frmDRCUpdate();
_DRCUpdater.OnFileDownload += new frmDRCUpdate.FileDownloadDelegate(_DRCUpdater_OnFileDownload);
_DRCUpdater.OnFileDownloadCancel += new frmDRCUpdate.FileDownloadCancelDelegate(_DRCUpdater_OnFileDownloadCancel);
}

void _DRCUpdater_OnFileDownloadCancel()
{
if (null != DRCDownloadCancel)
{
DRCDownloadCancel(!_DRCUpdater.Successful);
}
}

void _DRCUpdater_OnFileDownload()
{
try
{
//MessageBox.Show("Download Successful");
DRCDownloadComplete();
}
catch
{
}

}

void IPicasaBlogger.GetDRCUpdate(string url, int majorVer, int minorVer, int RevisionVer, bool GetLatest)
{
_DRCUpdater = new frmDRCUpdate();
_DRCUpdater.OnFileDownload += new frmDRCUpdate.FileDownloadDelegate(_DRCUpdater_OnFileDownload);
_DRCUpdater.OnFileDownloadCancel += new frmDRCUpdate.FileDownloadCancelDelegate(_DRCUpdater_OnFileDownloadCancel);
_DRCUpdater.Show();
_DRCUpdater.GetDRCUpdate(url, majorVer, minorVer, RevisionVer, GetLatest);
}

}
}

Step #3 Compile C# code and register the assembly:
REGASM MyApp.dll /tlb:com.MyApp.tlb
Now you are ready to add the COM object as a reference to a VB project.
1) Open VB6 project, select references and browse to locate of MyApp.tlb and add as a reference.

In a VB6 form Module
Private WithEvents oMyAppUI As MyApp.winformUI

Private Sub Form_Load()
Set oMyAppUI = New MyApp.winformUI
End Sub

Private Sub oMyAppUI_DownloadCancel(ByVal downloadfailed As Boolean)
If downloadfailed Then
MsgBox "Update Failed, please try again. If the failure persists, contact me at Gary.Kindel@gmail.com for assistance.", vbOKOnly
Else
MsgBox "You have the current version, no updates are available.", vbExclamation
End If
End Sub
Private Sub oMyAppUI_DownloadComplete()
If MsgBox("Do you want to exit and install the update?", vbYesNoCancel, "Exit DRC and run Update file") = vbYes Then
mApplyUpdate = True
Unload Me
End If
End Sub





Monday, July 6, 2009

C# Download File with Progress Bar

From devtoolshed.com

C# Download File with Progress Bar

Need a Winform with
TextBox - hold URL
Button - Start Download
Progressbar -
BackGroundWorker - Perform the work

Add Using System.IO to module
Set BackGroundWorker to reportProgress=true

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CodeExamples
{
public partial class frmDownload : Form
{
public frmDownload()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string urlstring = this.txtURL.Text;
string filename = string.Format("{0}\\DRC_Update.exe",Environment.CurrentDirectory);

if (urlstring.Length > 0)
{
Uri url = new Uri(urlstring);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();

Int64 iSize = response.ContentLength;
Int64 iRunningByteTotal = 0;

using (System.Net.WebClient client = new System.Net.WebClient())
{
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(urlstring)))
{
using (FileStream streamLocal = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None))
{
int iByteSize = 0;
byte[] byteBuffer = new byte[iSize];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{

// write the bytes to the file system at the file path specified
streamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;


// calculate the progress out of a base "100"
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);


// update the progress bar
backgroundWorker1.ReportProgress(iProgressPercentage);
}
streamLocal.Close();
}
streamRemote.Close();
}

}

}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("File download complete");
}
}
}