Categories
.NET C#.NET VB.NET/VB WPF

Self Hosted Web Service: WebServiceHost

So today I learn about WebServiceHost. Just a normal class but it does a lot for me today. This host the web service within you Desktop/Windows Service application. i.e. you don’t need to install any Web server or other stuff, just create a Service Contract Class and use WebServiceHost to host it within your application. 

I need this as part of my project, because I have to pass some server information to my application. I initially create a Seperete web application for this, but why maintain another application and increase setup time when I can host it within. I need it for just one particular value to be pass in JSON format to my client side. However one thing I must tell here is that the Host server application must be running as Administrative privilege or the service won’t start. For Windows Service run application as “LocalSystem” rather than default LocalService to keep it working.

It solve lot of problem and architectural issue I had in my project.  

Categories
.NET C#.NET VB.NET/VB WPF

WPF ComboBox: DataBinding with DataTable

Well it seems easy thing, but it took a while for me to get it working. Frankly I still don’t know why it works this way, but at least it works. With WPF I was expecting something as easy as giving DataTable object to ComboBox by it’s property and define the Data Field and Value field as in ASP.NET dropdownlist and it will bind, but this was not the case or at least the syntax is little different. So it goes like

ComboBox cb = new ComboBox(); /// You might already have object of it, so I just create it for sake of understanding here.
cb.ItemSource = MyDataTable.Rows; /// Yup, DataTable will not bind but it's rows collection will.
cb.DisplayMemberPath = ".[" + YourColumnNameVariable + "]"; ///in other other ".[columnname]" is what is expected;
cb.SelectedValuePath = ".[" + YourColumnNameVariable2 + "]"; ///in other other ".[columnname]" is what is expected;

This is all we need to do to get it working.

Categories
C#.NET Concept/algorithm Programming VB.NET/VB

MDI Window: C# way

So how can we make MDI Parent and Child Window in C#. The answer I found was that there is nothing inbuilt for it. So, I have two choice, either I modify the Window class and add MDI [Multiple Document Interface] coding in them or I found a alternative interface. 

It took less than 5 minute to decide that I can go with alternative interface after googling, the interface is TAB. Yup, much like your browser, they use TABs too, we create tab in  web portal, browser and lot of other things. So, they are perfect replacement for MDI window needs. The logic is as simple as, 

1. Create a TabControl on Main window.

2. Add couple of function, that search for TabItem in Tabcontrol if they exists or not, if exists focus them or add a new Tab Dynamically. Same logic on deletion of tab.

3. Create User Control from your Common custom Interface class and default UserControl object. Add these user control on Tab content when adding new tab.

I again didn’t keep the URL, but there is good example on it is available on MSDN and few other tutorial site. I try to post main component of logic below

namespace MyCommonLibrary
{
    /// 
    /// Deletgate for Tab Closing
    /// 
    /// 
    /// 
    public delegate void CloseTab(ITabbedWindow sender, EventArgs e);

    /// 
    /// Delegate to reload Tab Data.
    /// 
    /// 
    /// 
    public delegate void ReloadTabData(ITabbedWindow sender, EventArgs e);

    /// 
    /// Interface for Tabbed Windows Style MDI.
    /// 
    public interface ITabbedWindow
    {
        /// 
        /// Event for Closing Tab handle
        /// 
        event CloseTab CloseInitiated;

        /// 
        /// Event to reload Tab Data
        /// 
        event ReloadTabData Reload;

        /// 
        /// Name of the Tab Window
        /// 
        string TabName { get; set; }

        /// 
        /// Title of the Tab Window
        /// 
        string TabTitle { get; set; }

        /// 
        /// If Tab is loaded fully.
        /// 
        bool IsAllowRefresh { get; set; }


        void ReloadData();
    }
}

Above one is my common Interface which I use to implement in my User Control. After this all I have to do is add below function in my Parent window which has TabControl added to it.

#region Tab Functions
 #region Tab Functions

        public void AddChildWindow(ITabbedWindow childWndow)
        {
            if (childWindows.ContainsKey(childWndow.TabName))
            {
                foreach (TabItem tabItem in MDIContainer.Items)
                {
                    if (tabItem.Name == childWndow.TabName)
                    {                        
                        tabItem.Focus();
                        if (childWndow.IsAllowRefresh)
                        {
                            childWndow.CloseInitiated += new CloseTab(childWndow_CloseInitiated);
                            tabItem.Content = childWndow;
                        }
                        ITabbedWindow uc = tabItem.Content as ITabbedWindow;
                        try
                        {
                            if (uc != null )
                            {
                                uc.ReloadData();
                            }
                        }
                        catch { }
                        break;
                    }
                }
            }
            else
            {
                TabItem tabItem = new TabItem();
                tabItem.Name = childWndow.TabName;
                tabItem.Header = childWndow.TabTitle;
                tabItem.Content = childWndow;

                childWndow.CloseInitiated += new CloseTab(childWndow_CloseInitiated);

                MDIContainer.Items.Add(tabItem);
                MDIContainer.SelectedItem = tabItem;
                ITabbedWindow uc = tabItem.Content as ITabbedWindow;
                try
                {
                    if (uc != null)
                    {
                        uc.ReloadData();
                    }
                }
                catch { }
                
                childWindows.Add(childWndow.TabName, childWndow.TabTitle);
            }
        }

        public void RefreshTabContent(string mTabName)
        {
            foreach (TabItem tabItem in MDIContainer.Items)
            {
                if (tabItem.Name == mTabName)
                {
                    tabItem.Focus();
                    ITabbedWindow uc = tabItem.Content as ITabbedWindow;
                    try
                    {
                        if (uc != null)
                        {
                            uc.ReloadData();
                        }
                    }
                    catch { }
                    break;
                }
            }
        }

        void childWndow_CloseInitiated(ITabbedWindow sender, EventArgs e)
        {
            foreach (TabItem tabItem in MDIContainer.Items)
            {
                if (tabItem.Name == sender.TabName)
                {
                    MDIContainer.Items.Remove(tabItem);
                    childWindows.Remove(sender.TabName);
                    break;
                }
            }
        }
        #endregion

I just paste the portion where I control Tab, but it goes to code behind of mainwindow.xaml. One thing to note here is I use a SortedDictionary object to store the name of Tab in it for searching and retrieval of it. Rest is clear I guess.

 

Categories
.NET ASP.NET C#.NET VB.NET/VB

ASP.NET: Why my cookie is not saving

Funny, today after years I thought to finally use Cookies in one of my project. It is probably my first attempt to use Cookie in ASP.NET in last 5 yrs. WOW, that is amazing. Anyways, I just notice one thing and thought it might help any first timer, so here is the key note I want to share. In ASP.NET if you want to read Cookie, use REQUEST.Cookies, but if you want to add new Cookie use RESPONSE.Cookies. This is very minor difference and I really waste 30 minutes before I release I was using Request.Cookies to add new cookie, but it won’t get added that way.

Categories
Article ASP.NET Bookmarked C#.NET PHP Programming VB.NET/VB

WKHTMLTOPDF: A Free PDF solution

As any other developer we often find it difficult to get a Website to print something accurately, specially when printing labels for mailing as they are outside the default print area for most browser and no client want to adjust or memorize the print setting to adjust them manually. Also it doesn’t make sense to relay on client to do adjustments.

So the only universal solution I found is.. of course PDF files. But how do I create PDF. Well easy enough use some library. I did that I use iTextPDF very good Library that works for my C# project well for couple of years. But then what is the problem now? Well iTextPDF is now have commercial license at ridiculous pricing in fact it is now most expensive to any other paid software. Yet another Open Source project going paid on success. 

Also, there is a problem with library like iTextPDF that they need you to draw each and every element programmatically more often or not. And you find yourself caught in a web of long written code. I remember one of my report’s PDF generation code goes 1000 lines. I hate it. So, the best solution is to Generate PDF from a HTML source. We can handle HTML much better way and rather easily with our skills as web programmer. And even a designer in team can change PDF design giving time for programmer for other work. 

In this regard I look for free alternative of iTEXTPDF, which does have HTML parser to generate PDF from HTML file, and my search for now ends on http://code.google.com/p/wkhtmltopdf/ (wkhtmltopdf ) project. A Simple Executable that I can call from a my code to execute and it does the parsing. 

It is not really a good idea to call it through web page, but we should create a Windows service and use it there, but I have successfully test it to work on web server with quite a load and at least with my limitation to access Windows Service I can live with it running through HTML page, after all my PDF is just 1-2 page and it works fine. Will post code for it some other day. But do try it if you want a good and quick solution to your problem.

Categories
.NET Automation C#.NET VB.NET/VB

Excel Automation Add-In for Office 64bit Check List

After days of research, hit and trail; today I finally got a working 64bit Excel Automation Add-In. I am using Visual Studio 2010 [.NET 4.0 client profile framework]. 

1. Create a Project using Visual Studio Office 2010 template “Excel 2010 Add-In”. [I opt for this as I need Ribbon UI too, if you don’t need that you can use Class library project as well]

2. Create a New class and follow this article from Eric ( Excel Automation AddIn in Visual studio ). This article covers 95% of stuff you need it to work. Thanks Eric your article is still valid after 3 yrs and new version than those mention there.

3. Make sure you, have a Signed Assembly. I am not sure if it is really true, but when I was manually registering my assembly in failed cases, it warn me to sign them, though it says “registration succeed”.

4. Good thing is I am creating Add-IN using 32bit machine, and even though my addin works for 64bit. I do not define any specific CPU, just use ANYCPU flag where applicable.

5. Make sure you do not check “Make COM Visible” under Advance setting of your Assembly properties. Again I am not sure, if it is true, but it works when I have it OFF.

6. Do not check “Register for COM” under the BUILD Tab of Project property in Visual Studio. We need to manually register using 64bit regasm through our Setup or command line as you like.

7. [Guess not important or relevant], I have by default Sign for ClickOnce mainfest enable. Actually it is enable for Template project by Visual studio. I keep it that way, doesn’t harm to have it.

8. Make sure to create a good GUID for Class definition as define in article. There is another GUID used in Assembly information, I try to match them and it didn’t work. When it works they have different GUID. Though have it same or different should make difference according to me.

9. I define a ProgID on top of my class like

[ProgId("EVA.Excel")]
[Guid("A4C56D50-D25D-41BA-AE3E-9BE5A56736D3")]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class Sound

{

}

I guess that is all what I make changes and have it working. Best of luck.

 

 

Categories
.NET ASP.NET C#.NET VB.NET/VB WPF

GDI+ Generic Error

I see lot of people asking about GDI+ Generic Error. Since this is “generic” error nobody can tell what is wrong with code. So did a work around and get it working. I had this error quite a time in early days of my programming and just found same error in one of junior’s code. Well from my experience I can say one thing. GDI+ Generic error 99.9% means “developer miss a detail or overlooked something”. Most common reason of error are negligence of

1. Path should be physical path

2. All folder should present before you create file.

3. Previous files should be in write mode if case of overriding files.

4. Make sure permission are for writing to User of process.

5. Do not include any special character which windows do not permit in folder name or file name.

6. FILE FORMAT has nothing to do with this error most often.

7. Recheck permission if you try all above.

8. Recheck Path again :).

Point #7 and #8 are most important solution and always works for me.