Tuesday, March 4, 2014

Open MS Office documents within a desktop application

Have you ever had to develop an application where you had to open MS office documents within your desktop form (as a child form)? If yes, you would have found that it almost seems to be an impossible task. A long time back, I too had a similar problem. I do not know with newer technology and versions of Windows and VS, maybe there is an easy way to get it done. But at that time, I had a tough time figuring how to get it done.

What I had to do was
- open a office document
- position the office document as a child window within another windows form so that I can control the parent windows form for closing it, positioning it, etc

If you have already searched the internet, you would see various suggestions like using activex controls and some other solutions that his own issues and limitations.

The way I finally got it done was using Windows API. This worked in Windows XP and I think there must be similar APIs for Windows 7 (may even be the same). I am sorry, but I haven't tried whether it works on it or not on Windows 8.

const UInt32 WS_OVERLAPPED = 0x0;
const UInt32 WS_POPUP = 0x80000000;
const UInt32 WS_CHILD = 0x40000000;
const UInt32 WS_MINIMIZE = 0x20000000;
const UInt32 WS_VISIBLE = 0x10000000;
const UInt32 WS_DISABLED = 0x8000000;
const UInt32 WS_CLIPSIBLINGS = 0x4000000;
const UInt32 WS_CLIPCHILDREN = 0x2000000;
const UInt32 WS_MAXIMIZE = 0x1000000;
const UInt32 WS_CAPTION = 0xC00000; //'/* WS_BORDER | WS_DLGFRAME */
const UInt32 WS_BORDER = 0x800000;
const UInt32 WS_DLGFRAME = 0x400000;
const UInt32 WS_VSCROLL = 0x200000;
const UInt32 WS_HSCROLL = 0x100000;
const UInt32 WS_SYSMENU = 0x80000;
const UInt32 WS_THICKFRAME = 0x40000;
const UInt32 WS_GROUP = 0x20000;
const UInt32 WS_TABSTOP = 0x10000;
const UInt32 WS_MINIMIZEBOX = 0x20000;
const UInt32 WS_MAXIMIZEBOX = 0x10000;

[DllImport("user32.dll", SetLastError = true)] static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); 
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); 
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex); 
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
 
[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hwnd, uint command); 
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter,
string className, string windowTitle);

[DllImport("user32.dll")]
private static extern IntPtr FindWindowEx(
IntPtr parentHwnd,
IntPtr childAfterHwnd,
IntPtr className,
string windowText); 
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); 
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); 
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
        [StructLayout(LayoutKind.Sequential)]
public struct RECT
{public int Left;
public int Top;
public int Right; 
public int Bottom;
} 
public static void InitializeWindow(IntPtr pProcessHandle, IntPtr pCurrentHandle, int pLeft, int pTop, int pWidth, int pHeight) //, bool bRepaint)
{  //postion the window
   MoveWindow(pProcessHandle, pLeft, pTop, pWidth, pHeight, true);
   //set the parent as current application
   SetParent(pProcessHandle, pCurrentHandle)    
   int lStyle = GetWindowLong(pProcessHandle, GWL_STYLE); 
   lStyle = lStyle - (int)(WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
   // Put the modified style back:
   SetWindowLong(pProcessHandle, GWL_STYLE, lStyle);
}
Call "InitializeWindow" to position and setup the application's (MS office application) window as a child window of the current form
 using System.Diagnostics;ProcessStartInfo psInfo = new ProcessStartInfo(FilePath of the MS document);
psInfo.WindowStyle = ProcessWindowStyle.Normal;
 //open the external application
Process ApplicationProcess = Process.Start(psInfo);
ApplicationProcess.WaitForInputIdle(1000);//Initialize the application window
InitializeWindow(ApplicationProcess.MainWindowHandle, this.Handle, 100, 0, 300, 200, true);
 
 

Monday, March 3, 2014

Exception - The underlying connection was closed: An unexpected error occurred on a send.

While connecting to an external web service (using WebRequest), you might get the following error

Exception - The underlying connection was closed: An unexpected error occurred on a send.

The inner exception might be  
"Received an unexpected EOF or 0 bytes from the transport stream"

This might get resolved by setting
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

I think .NET applications use TLS for transport security by default. So when the external server where the web service resides does not support TLS, I would assume, the connection would be tried using SSL3. But in some cases (like it was for me), the connection failed with the above error. It was resolved by forcing SSL3.

Wednesday, May 8, 2013

MVC - Share views for multiple controllers

Moving on to MVC projects and I must start of by saying that it seems like we are back to writing a lot of code on the "view" the way we used to write way back in the ASP days :-) Anyway, the topic I was planning to discuss today was not that.

I had this requirement where the view I had created was just perfect 2 of my controllers. I thought this was a straight forward requirement and went about creating the view in one of the "views/WList/Common.cshtml" folder and then called it from an action within "Controllers/WListController".

 public ActionResult MyAction()
{
return View("Common", WListModel);
}

It worked fine till I tried to created another controller called "Controllers/AnotherController" and tried to return the "Wlist" view in the action result (same code as above). While writing the code, I was not sure how this code in this controller would be able to find the view, but decided to give it a try. It failed as expected because it searched for the view in the "views\Another" folder and could not find it there.

This used to be so easy with a redirect statement :-).

Looking closer at the error raised, I noticed, it actually lists all the folders it searched for the view and realized that it also looks in the "shared" folder. I knew that the shared folder was used for partial views. So would the solution be to create a partial view from "Wlist" view and then render the partial view from 2 other views within "views/Wlist" and "views/Another" folder? But before I try that, I thought maybe I could also just try moving the Common.cshtml to "Shared" folder and try it.  I tried and it worked.

So to conclude, the "view/shared" folder can hold partial and also complete views that you might want to share between multiple controllers.

Tuesday, October 23, 2012

Software architecture that works


Ok, this is not about technical issues I usually write about. But this again is an issue we all (technical folks) face time to time and have to deal with. Recently, at my work place, I heard about a project that has not been meeting deadlines and people dreaded to get into. The reason why that project was not able to deliver was blamed completely on the very "complex" architecture and just that. I have heard and seen this so many times that I always wonder, can projects really fail just because of a complex architecture? Is it just the architect who has the final call on how the product/project would be designed and build? Is he/she not just providing guidance and is it not upto the technical leads to guide the developers and the architect on what can be delivered by looking at the resources available and timelines set for the project? How can no one see that the architecture is complex when they in still in the design phase and later blame it for the failure  after working on it for couple of months or years?

Back when I was introduced to programming and when I used to write code in dbase and Foxpro (some of you might have not even heard about these languages), my approach to tackle a requirements would be to just start writing the code. Given a task, I would start writing the code without really thinking on maintenance or trying to understand the whole picture. But I soon realized my mistakes when I saw my efforts been spend on writing the same piece of code more than once or trying to fit a change that the users suddenly felt is very urgent and should be part of the release. That is when I started appreciating the need for a good design and the need to spend more time designing than just writing code. Now that was easy when I was the designer and the developer on the project. But as I moved onto bigger projects and teams, I realized that this approach of investing time on a good design was never accepted with open arms. But somehow I managed to work through my deliverables and thought when I become the person who leads these projects, I will give more importance to the design :-)

So what exactly do we mean by design or a software architecture. Is it just drawing couple of colorful boxes to link them up with some lines or is there more things that an architect needs to consider. Based on my experience, here are “some” of the important items that I feel affects the design of any software application.


Team dynamics

When I started managing teams and be responsible for the deliverables of some developers, I realized there are other aspects to this whole process. I started understanding the fact that in most of the cases, your "team" is the not the best that you would like to have. 70% to 80% members in your team does not see or care for your vision. Many do not know how to code and some are forced into this project that they never wanted to move into and some others are there just because its part of their “job” and does not care about quality. So now I had to adjust my vision and beliefs again. I realized that the team structure is also a factor you need to consider while designing. In the .Net world, imagine you designing a SOA application and developers have never  heard of such an approach and you hardly have time to explain and teach. Yes, a good developer will be able to grasp and develop under any circumstances if given proper guidance. But remember the 70-80% I talked above earlier.

Time

That brings us to another topic that always affects your design - Time. Time is always a factor to what you can deliver. Most of the time, in a practical world, (I think you would agree too) that all projects you work on had to be delivered even before you started the work. So I learned the hard way that you are always behind schedule and will always be trying to meet unrealiastic deadlines. That usually meant that you have to take shortcuts that would eventually mean more defects and so more time to fix. So its better to manage your time efficiently and to spend it on the most important modules. For me, the most important and easy to design modules in any project are the common libraries that will be used by other modules. If you design them well, you would realize that you have more time to spend on other core functionalities and building them around these common libraries is pretty easy.

Common libraries

That brings me to the next point which is that all good architect must also be responsible to identify the common features or libraries that can be reused. In all projects, things like exception handlers, data access, logging, etc are always needed. Unfortunately most of the time, these are the features that are considered to be least important. So the end result is that the application has no proper error handlers or logging and when the application encounters errors, there is no information available to debug. You also face the risk that each developer might handle exception differently (or will not even handle them) and some errors might be reported more than once and in different ways. This could even affect your user's experience.

Templates

Once the common libraries are taken care of, what to do with other modules and how to fit them in to ensure easy maintenance and ease of writing code for your developers? It can done using templates ..  What I mean by templates is just a default structure of how a class or a function or object would be coded for. Most of the applications we develop are for services that require data to be input by users, saved and retrieved. If you have proper structure or template of how data would be managed and flow between various layers, the developer’s responsibility would reside in just reusing these templates and filling the gaps with properties relevant to that module or web page or form. I have seen that if you have properly commented templates defined on how these items in various layers would be coded for and also explained the process to developers on how to fill the gaps, development is much easier and faster. Also this ensures that all modules follow the same "style" of coding and its easier to maintain. This way a developer coding for a particular module can easily pick up other items in some other module and not have to spend too much time trying to figure out how it is coded.

Performance

This is one of the key factors that most of the architects seem to forget i.e how would the application perform under heavy load. I have seen time and time again, performance is something that is always tackled after couple of months into production release because that is when real users start pumping in data and the screens or pages that used to respond in milliseconds now takes minutes to show results. So someone reviews the code for reasons of slow response and most of the times, it’s the architecture to blame. Now its too late or too expensive to fix these performance issues because that would  mean re-designing most of the things that you just released.

Technical leads

How can all the above be managed? Is this all just the responsibility of the architect? I have seen time and again that most of the architects feel that their responsibility lies in drawing pretty diagrams that explain the architecture using visio or some other tool. When you have to finally translate those diagrams into working code, many of these architects cannot help or would not like to help. So its left up to the Technical leads to translate those design to code and explain the process to their developers. For that task to be done efficiently and effectively, you need good technical leads. If you get some good ones, you can always rely on them to manage the team the right way. They can help the developers whenever they are stuck in some tricky situation, review code and ensure that the architecture is followed and distribute work according to the strength of each of members.

So what exactly works? Is it all of the above for every project? I would think a combination of all of the above does ensure a successful project. But unfortunately its an ideal scenario and you have to pick and choose what can work for you. Try your best to concentrate on these points and I would think you can deliver a successful project. Yes, this is not the complete list. There are lot of other things that can affect a project like how requirements are documented, QA assigned to project, availability of resources, etc. But this article was just to highlight what I think are the key items you need to keep in mind while planning.

Tuesday, May 22, 2012

Error - This version of ADT requires Android SDK Tool in revision or above

This version of ADT requires Android SDK Tool in revision <17> or above
Current version is 8
Please update your SDK tools

If you get above error even after installing latest SDK, quite possible you are not pointing to the right SDK in eclipse

Follow these steps
  • Open Eclipse
  • Select menu Window->Preference
  • Select tab "Android"
  • Select the "SDK location" to the folder where you installed the SDK .. quite possibily c:\program files\Android\android-sdk

Android development - setup DEV environment

 Note this is work in progress and I am just writing down things to maintain the list of items I had to setup for starting up development on Android.

What you need
  • Eclipse (classic recommended)
  • Android SDK
  • Andriod development tools plugin for eclipse (ADT). In some cases, a new revision of ADT will have a dependency on a specific revision of the Android SDK Tools. If such dependencies exist, you will need to update the SDK Tools package of the SDK after installing the new revision of ADT. To update the SDK Tools package, use the Android SDK Manager (explained below)

Step 1. Preparing Your Development Computer
  • First download Eclipse  - classic is recommended)
  • http://www.eclipse.org/downloads/
  • Unzip the downloaded zip folder into a folder where you want to run eclipse from. There is no installation for eclipse

Step 2. Downloading the SDK Starter Package
  • Download the Android SDK from http://developer.android.com/sdk/index.html (installer_r18 ....exe)
  • Install the downloaded file
  • Run Android SDK manager (SDK manager.exe from where you installed SDK)
  • Launching the Android SDK Manager - The Android SDK Manager is the tool that you use to install and upgrade SDK packages in your development environment. You can launch the Android SDK Manager in one of the following ways.
  • If you are developing in Eclipse and have already installed the ADT Plugin, follow these steps to access the Android SDK Manager tool:
    • Open Eclipse
    • Select Window > Android SDK Manager.
  • Launching from the SDK Manager script (Windows only)
For Windows only, the SDK includes a script that invokes the Android SDK Manager. To launch the tool using the script, double-click SDK Manager.exe at the root of the the SDK directory
Setup proxy in Tools -> Options (popup to enter user name and password will come later). Close the ADK manager and open again for it to refresh the tools required

The list will be shown what needs to be downloaded. You could choose extras if you need them. The latest version of Android will be selected by default
Click on "Install <number> packages" button

Step 3: Configuring Eclipse for Plugin
  • Open Eclipse
  • If proxy, then select menu Window -> preference
  • Select General -> Network connections
  • Select active provider = Manual
  • Edit http and https options by selecting one at a time and clicking on edit
  • Enter proxy settings and save
  • Select menu Help -> Install new software
  • Click on Add and enter https://dl-ssl.google.com/android/eclipse/ in URL

Enable windows authentication (IIS) on a Windows 2008 server

Recently, I had to setup an old VS 2005 application on a windows 2008 server. I did everything right and setup the virtual directory for the web site. But when I tried to run the web site in VS, the site would not open up. I found that this was because the virtual directory was not set to accept windows authentication.

In IIS 6, it was pretty straight forward - go to security tab in IIS and edit and enable. But here I was not able to see that option for the virtual directory. All I could see were the options anonymous access, forms authentication and asp.net impersonation.

Long story short, you have to enable that as a feature on a 2008 server.

To do that
  • open control panel and click on "add or remove windows feature"
  • Expand the node - roles->Web server (IIS)
  • right click on web server node and select "Add role services"
  • in the new window that opens up, on the right side, under "role services", select checkbox "security->windows authentication
  • Under "management tools", option, select checkbox "IIS 6 management compatibility"
  • Click on Next and then Install
  • restart server
  • go back to IIS and the virtual directory and check the "IIS authentications" available and you should see "windows authentication" as the new option

Friday, February 3, 2012

Error: Unable to update the EntitySet ' because it has a DefiningQuery and no element exists in the element to support the current operation.

If you get the error while you try to save changes to an entity "Unable to update the EntitySet '<Entity name> because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.", just check the table that the entity is mapped to.

Confirm that the table has a primary key defined.