Fun with Waves in Matlab – Wave Equation Modeling

Dev

Setup

Matlab is cool. Math is cool. Enough said.
Amazing how all this beauty is held inside such a seemingly simple formula, the wave equation.
{ \partial^2 u \over \partial t^2 } = c^2 \nabla^2 u
This is the basics of the setup. It is a rectangular pool that can simulate perturbations based on the above wave equation. The model implements finite differences for its solution on the 2D mesh. e.g. (f_x = (f_i – f_[i-1]) / da)

Details of Model

The inner oscillations are a result of model error. I wasn’t sure if this error was from the size of the impulse or the size of the mesh. The variables needed to be isolated. I doubled the size of the mesh points in each direction. To keep the impulse size the same, the input was now a 2×2 impulse instead of a 1×1. As seen, the inner oscillations have a higher frequency compared to before. This means the model error of inner oscillation frequency is dependent on the mesh size.
I wondered what happens in real life when something gets dropped into a big bowl of water. It turns out that there is one big oscillation followed by medium sized ripples. Running the simulation with a bigger impulse and a very fine mesh, I obtain similar results. As shown, you can see one big oscillation followed by medium-sized ripples.
In addition to the medium-sized ripples, you can still see little oscillations of high frequency. As shown previously, these depend on the step size.
In real life, there are a discrete number of water molecules to move up and down. There aren’t infinitely many points in the mesh.
Maybe these frequencies that depend on the step size show up in real life too. Or maybe not.

Boundary Value Manipulation

Any Dirichlet boundary conditions* can be imposed by reassigning the boundary to its fixed value after every iteration. I wanted to see what happened on the shape of a guitar. It is interesting how there is sort of a mirror of the source in the front of the guitar. There was only one impulse applied to this shape, even though it looks like there is a smaller impulse on the top of the guitar.

*A Dirichlet boundary condition is a fancy word for a boundary that doesn’t move, like a wall that has a jump rope tied to it – or a guitar bridge with guitar strings tied to it.

Fun Experiment DOUBLE SLIT!! xD

Applying more Dirichlet boundary values to form two slits for waves to come out. Look at that beautiful diffraction pattern!! (:

 
Until next time

Climbing The Legendary Snake Dike, located on Half Dome in Yosemite Valley

Sport

half_dome_from_glacier_point_yosemite_np_-_diliffFrom a few weeks after I got hooked on climbing, before I even knew how to climb outside or set up a single pitch top rope safely, let alone lead a multipitch route safely, I had my eyes set on Snake Dike. Snake Dike is the name of a particularly popular and awesome climb up Half Dome in Yosemite. It always seemed so far away, one of those things that’s just fun to think about but “isn’t something I could do, at least not safely”. It has been sitting on my Life Bucket List for a long time. It now goes down as one of the best climbing adventures of my life.

Thanks Ted and Jesse. I will remember this adventure forever.

The Overview

The logistics mattered greatly for a trip of this size, even for the option of giving up and heading back, we had to plan carefully and thoroughly.

We were considering only going as a party of two, as we couldn’t find a fourth person with skills necessary. Two people is faster than three and going slow can be dangerous on a route as long as this one. However, we decided to go as three, and boy did it turn out to be a great choice. As all the pitches are easy for a follower and difficult for a leader (extreme runouts), sending up a second follower is no big deal. In some ways, it probably made the trip easier as we could distribute our gear and make the trip lighter per person. Four would be the best for a big trip, but three turned out to be better than two in this case.

Our schedule came out something like this:

  • 5pm Arrived in Yosemite, battled logistics and massive amounts of tourists to find friends and a place to sleep for the night without getting fined
  • 7pm Carbed up and hydrated up
  • 8pm Packed for next day
  • 9pm Put in earplugs, wore eyemask, and slept
  • 4am Woke and ate
  • 5am Began 6 mile approach hike
  • 9am Arrived at base of climb
  • 10am Began climb
  • 5pm Summited Half Dome
  • 6pm Began 9 mile descent hike
  • 11pm Mentally and physically started to break down, rested for a half hour or so
  • 2am Arrived back at camp – we brushed some of our teeth then stumbled into our tents and fell asleep instantly

The Departure

Getting to Yosemite from the bay is a pain in the ass. If you leave after 7pm to avoid traffic, you arrive too late and are too tired to alpine start the next day. The best way is to leave the bay before 1pm, which means leaving the office around 12pm, gathering in a carpool, then taking off.

We’ve found the best compromise to be one of the following:

  1. Taking a half day of vacation on Friday
  2. Working extra earlier in the week
  3. Working remotely Friday afternoon if your type of work will allow that (not recommended for the driver)

The Arrival

Once in Yosemite, the next challenge arises. All the campsites are full, and the only way you could have possibly gotten one is if you booked a reservation site last year or have been sitting in the first come line since 4am to pick up your location when the office opens at 6am.

We’ve found the following strategies workable:

  1. Book sites a year ago
  2. Make friends. If they let you stay with them, definitely make the offer to pay for the whole campsite for their generosity
    1. Speaking Chinese has saved our asses twice and has also let me run into some awesome Chinese climbers visiting the US and Yosemite. It’s amazing how quickly you can genuinely bond with someone over language.
  3. Camp in a tent with a wilderness permit
  4. Camp illegally Arrive extremely early for breakfast and rest yours eyes before having that breakfast. And leave very early before the rangers come by. If possible, do it next to cars that are parked for the night so you blend in. Take all responsibility for getting a ticket, still be respectful, and don’t park anywhere stupid.
    1. Sadly, I most often do this one – Having a car with a trunk that fits a bed comfortably comes in very handy. Make sure to still load your food into a bear box when doing this.

After you have found your campsite, attempt to boulder Midnight Lightning, probably the most famous problem in the world, both because the number of great climbers who have been shutdown on it (stout V8) and because of its location in the middle of Camp 4 Yosemite. You haven’t truly joined the climbing world until you make the dyno move for the lightning bolt hold. The legendary lightning bolt chalk emblem was drawn on shortly after the first ascent and is continually redrawn by the community.

20

The Ascent

untitled_clipping_103016_044403_pm

We are up. We are doing this. Ted, Jesse, and I are beaming with eagerness, anxiety, and happiness. The photo below was taken as the sun was still coming up. We were hiking to Curry Village, then hiking to the trailhead. That is Half Dome we are looking at.

untitled_clipping_103016_052028_pm

After reaching Curry Village and being told by a group of leather-clad, alcohol infused climbers of another era, “You have too many cams. You won’t need those,” we asked them for directions and were pointed along our way and given drunken smiles and wishes of good luck.

img_3490_103016_052351_pm

Looking up the gorgeous Merced River with a granite summit peeking in the background.

untitled_clipping_103016_054739_pm

Coming up on Vernal Fall

untitled_clipping_103016_054839_pm

For Ted a few years ago, this was the end of his family adventure. For us three boys, it was about 7am, and after stopping for a picture, we stormed on!

untitled_clipping_103016_052553_pm

Ted and Jesse standing next to Nevada Fall, the second of the two awesome falls on the way to Snake Dike.

untitled_clipping_103016_054528_pm

All of our dreams are coming true!! It’s Half Dome!!!!

untitled_clipping_103016_052839_pm

Arriving in the meadow underneath Half Dome. I brought along these purifying droplets to cure the water. I bought them under the description they were lightweight and perfectly treated the water without side affects like altering the taste, causing health discomfort, or taking valuable time to filter. We weren’t sure if they actually worked as the actual description on the dropper didn’t say anything about killing parasites or bacteria, just about cleaning contaminated RV water containers. Not having experience with filling up and curing wild water, we decided that there was a good chance I bought the wrong product. We cleverly decided to fill our first emptied water reservoir with creek water but held off on drinking it or applying the drops just yet. That way, we would have a supply of water if we absolutely needed it later.

untitled_clipping_103016_053708_pm

Following the Cairns and looking back across our hike. Look at all that. It goes on for miles and miles. Gorgeous. I would like to backpack it someday.

untitled_clipping_103016_055157_pm

At this point in the trip, I was ecstatic about my real approach shoes. Well they are actually trail running shoes. But they were infinitely better (AND SAFER!) than tennis shoes. I was going up this slab granite with ease! They the Adidas Terrex if interested. I tested a variety of shoes and the slab grip abilities. These were the best performers and the most comfortable. They noticeably out performed the popular trail running shoe Salomon Speedcross in grip and control.

This is my least favorite part of climbing, that point where the terrain is challenging and there is little safety margin, apart from not making a mistake. We were considering roping up and placing gear if it got a little worse, but it was very manageable. If you are planning on climbing the runouts of Snake Dike, you better be able to get safely past this fairly easy approach.

untitled_clipping_103016_055826_pm

Looking up at the base of the climb. This is the first pitch. Technically, the hardest move on the climb is moving across the sheet of glass underneath the roof. There is a small crack smaller than finger tips for the hands. In my mind it wasn’t quite the crux of Snake Dike though, because it was a well protected move. It was not runout. But it was the hardest point in climbing skill needed and the most likely place to take a fall. Jesse led this pitch and also led what I believe was the true crux on pitch 2, a slopey mantle after a long traverse and runout. Great work Jesse!

Ted and I both Stephen Kinged the first pitch. This means you are too impatient for the belayer to start taking slack, so once you are safely on belay, you clip in to the rope as you quickly and aggressively ascend. Once at the crux, we waited for Jesse to pull up the rest of the slack. I went across first. I quickly found myself away from the comfort of top rope. As I was several moves into the sheet of glass crux, Ted’s rope came taut against the back of my calves as my own top rope pulled me laterally to the traversing piece of gear. It would have been a fairly bad fall, and I was not at all on the comfort of top rope. I knew I HAD to make the move. I could not lift a foot one at a time safely to clear the rope. I was mentally preparing to jump off the rock, over Ted’s rope, and grab for Ted’s rope with my hands in the event I started to slip (he was still safe at the last piece if I put full tension on his rope). With my plan in place. I eyeballed the sheet of glass I had to go across for any irregularities. There were slight microridges that would give me a slight advantage in friction. I carefully placed my toes on each one. One foot slipped out at the second step, but the front foot held. I quickly shifted weight and reached for the slight widening in the crimp. I now had a secure hand. I made it!

Ted quickly followed and wondered what all the fuss was about. Ted is about 6’4″. At least.

untitled_clipping_103016_060622_pm

We made it! Pitch one complete! Notice the super awesome adjustable orange personal anchor. What a great personal. I was constantly looking for not so subtle ways to show it off and fish Jesse and Ted for compliments. Jesse and Ted both reluctantly acknowledged multiple times that yes, it was a decent personal and that I should be very proud of myself.

img_20160806_113200_103016_061110_pm

This was the start of pitch 2, Jesse on lead. In my opinion, this was the crux of the climb. The visual was also epic. Watching Jesse go around this feature with the Sierras in the background, I couldn’t help but ask Ted to belay as I snapped pictures. Gorgeous.

He is placing some gear in this questionable crack feature here, but then has to make a wide traverse to exceptionally solid bolts (thank god). After the bolts, it’s about a 15ft runout (not long by Snake Dike standards, but still scary) to a very technical friction slab traverse. In my opinion, those two friction steps with a move that’s like a friction mantle are the hardest in the entire climb. And it’s funny because with slab, the followers just get to skip along as if it’s easy climbing: both because any fall gets cut short from the top rope, and because any amount of upward helping force from the rope helps considerably in moving forward. Big props to Jesse “Captain Granite” Scarborough for sending this!! There are more slab runouts to go, 6 pitches to be exact, all featuring some amount of friction slab climbing, but this pitch gets my vote for the crux.

untitled_clipping_103016_062049_pm

Here I found myself thinking, “Holy shit. Nice lead Jesse.”

untitled_clipping_103016_081249_pm

A very happy Jesse waiting for me at the anchor. This is awesome! We are climbing Snake Dike! Look at the view! Wow!

untitled_clipping_103016_062152_pm

Pitch 3, first of the LONG runout pitches. I think this was rated 5.3 or something like that. But this wasn’t a gym climb. At that time, I was leading 5.11 in the gym and had numerous well-bolted outdoor 5.10’s and 5.11’s under my belt. However, I knew it wasn’t going to be a cake walk.

It was about 60′ between bolts at the most extreme situations, and it was consistently 30′ between bolts.

Even a mistake as little as 15′ past a bolt equates to a 30′ fall, almost certainly ending in a broken leg or worse. Best case, I would lose a lot of skin and have to descend and hike four hours just to get cell phone service. Worse case, I would die. This is something I hate this route for. Why can’t they just put in a few more bolts and make it safe? People have died on this route. Anyways, I highly recommend practicing slab climbing and working your way up to this. It’s easy and comfortable, but not at all what you think of when you think of “it’s only a 5.3!”

I was definitely scare and intimidated, but I knew it was well within my skill level to do safely. The climb wasn’t especially risky. It’s about as risky as walking on a curb with lava on both sides. I could do it, even with making a lot of minor mistakes. As long as I avoided catastrophic mistakes, I would be fine. What I specifically avoided was making moves onto questionable holds (things that could break), keeping three points of contact if i suspected breakage/slipppage, and moving deliberately. Thankfully the extreme popularity of the route leads itself to bomber holds. The only thing to watch is slipping out.

untitled_clipping_103016_063831_pm

Giving Ted and Jesse a thumbs up! Chalking up, enjoying the climb and view, and not thinking about the fact the first bolt was still much higher.

Just in case my parents are reading and freaking out, this is similar to skiing a narrow Blue Square (medium difficulty) run right on the face of a cliff. It is only dangerous if you mess up enough to cross the threshold. Otherwise it’s just a normal Blue Square that’s taken slow and steady.

untitled_clipping_103016_064412_pm

Check out Jesse’s sweet redundant, independent, and equalized anchor. Bomber!

This is the top of the final pitch. There’s this mysterious giant crack. I hung out squeezed in it as Ted followed Jesse up.

We actually roped up again for an additional pitch, mainly due to me freaking out that it was harder than what we just climbed and that we should stay roped for a bit.

untitled_clipping_103016_081055_pm

Looking back on Ted, Jesse, and the Yosmite Valley. El Cap is the very vertical cliff in the distant valley behind.

untitled_clipping_103016_083256_pm

Errr, maybe let’s rope up again guys. This is pretty steep!!

untitled_clipping_103016_064717_pm

At this point it was somewhat safe to switch to other shoes. Notice how it’s still steep as all @#$%. Being the complete wuss I am, I took a breather and stayed in my rock climbing shoes for a good deal further. No reason to take dumb risks. It’s fairly hikeable, but one slip and you aren’t falling down to get back up: you are falling down and sliding/tumbling down Half Dome to become another statistic.

untitled_clipping_103016_065543_pm

Here are two friends we met on the way. I forgot their names (Jesse or Ted do you remember?). Bryce and Angela maybe… They were great. Very friendly, strong, and experienced climbers. We ended up throwing Bryce a rope for safety when he stalled out on one of the slab pitches. It was rated 5.2, and I was on the slow struggle bus leading it. The whole pitch was a runout. Ted and Jesse of course skipped up it blindly. It was reassuring seeing a strong of a climber as Bryce also struggle and ask us to toss a rope. After he grabbed it, of course he then made the move easily. The old hard to lead, insanely easy to top rope principle of slab.

We asked Bryce and another group about the water curing droplets. He had the exact same ones and told us they were effective and popular for killing giardia and cysts.

 

untitled_clipping_103016_075330_pm

Jesse at the top of Yosemite Valley. He facetimed with his mom for a bit at the top haha. What an epic day and epic view. Jimmy Chin would be proud!

untitled_clipping_103016_081507_pm

The obligatory shot off the visor of Half Dome. Jesse is laying right on the edge.

13912549_10154152214013387_1031464548391101129_n_103016_082855_pm

Irina insisted on photoshopping this for me. 5 minutes later, she sent me a picture with everyone standing by the side removed. Very convincing fake background. Awesome work!!

untitled_clipping_103016_081833_pm

Ted sizing up which of the many practically limitless peaks to climb next. (:

The Descent

 

untitled_clipping_103016_075453_pm

Here’s Jesse again, we are descending the north side of Half Dome. This is the cable route for the hikers. Wow I can’t believe normal hikers come up this. If I hiked it, I would definitely bring a climbing harness and anchor along. You have to be a damn solid hiker to make that safely.

We of course personal anchored in to the cables for backup then made our way down. I slipped once and was sure glad I had my personal or I would have died for sure.

Unbelievable that hikers go up and down this with tennis shoes on. Although when you have no backup, you are forced to go more carefully, but still. Insane the amount of people who do it regularly without incident.

untitled_clipping_103016_082009_pm

Gorgeous sunset and shadowing on the north face of Half Dome. Making our way down the cables.

untitled_clipping_103016_075828_pm

It was around 11pm, still hours to go. Getting delirious. I got really sick in the stomach a little bit after this and needed to stop. So thankful Ted and Jesse were there. We stopped to tidy up our ropes and gear that had become loose and uncomfortable along the many downhill miles. Ted and Jesse offered to help carry my gear, but I didn’t want them to do that. We waited for 15 minutes or so while I recovered, having some light water and light snacks.

untitled_clipping_103016_080639_pm

Back at the campsite at 2am. Oh yes! We did it! We high fived quietly, team hugged, then crashed inside our tents. That was epic.

Snake Dike. 22 hours wake to sleep. What an adventure. Would do again.

A Guitarist’s Guide To Overcoming Obnoxious Password Requirements

Dev

Annoyed with site’s complexity requirements?

Are the passwords “password” and “qwe123” no longer cutting it? Are websites not accepting “CorrectHorseBatteryStaple” due to lack of complexity?!?

Here’s a technique I came up with that helps me create memorable passwords that still meet obnoxious complexity requirements.

Pick your favorite guitar scale, in this example I’ll use the pentatonic scale.

minorpentatonic2positions

From here, I imagine the keyboard as a fretboard. I will also press shift when I want to play the upper three strings.

My password is now “farw42FSRQ$!”. I usually call this good, but on some sites where I don’t want to security risk of duplicating a password, I will add the first letter of the site name. So for www.capitalone.com, my password would be “cfarw42FSRQ$!”

You can continue to apply this technique to learning songs as well. All you have to do is visualize the keyboard as a guitar fretboard. Having my password set as the crux riff to the crazy train solo helped me build the muscle memory needed to play that quickly and accurately.

Winter Trip to China Planning

Art

This is an old evernote jot from when I was planning to make my first international trip, to China. I went by myself, and the experience, stories, and perspective I got were magical and fantastic. I spent 2008-2012 studying Chinese, not having enough money to travel, but always thinking it would be cool if I could speak another language. I chose Chinese because of the usefulness of it and because of the musicality of it. At the time, I was very intrigued by what “tonal language” meant.

In the winter of 2012, I stepped off a plane with myself and a backpack in Beijing, barely being able to intelligibly say, “Where’s the bathroom.” I almost fell for a classic 5 minutes off the plane: I reluctantly gave my luggage to an insistent guy. I didn’t want to be rude. Well it turned out I need to be rude shortly after as he had no intentions of helping me with my luggage. Helping me donate my luggage more like :). As a solo traveler with zero foreign experience, I was the target of number of scam attempts, but most were pretty obvious and only financial trickery. One dangerous scam situation occurred later in the trip, but overall, it was a positive and rewarding trip with a plethora of diverse experiences packed into 1.5 months. Rock climbing above the great wall on nearby limestone pinnacles, running 8 miles by myself on the great wall, and climbing the legendary Buddhist mountain 峨眉 were thrill highlights of the trip. The real highlight of the trip was constantly feeling lost and chewing off pieces of the challenge that is the Chinese language, meeting amazing people, understanding a glimpse of select people in another culture through their thoughts and experiences, and experiencing a different way of living life.

Well that’s enough English background, I’m going to tell the specific stories in Chinese then post the old evernote below.

我做了很深的关系,也试试看了真中国化。我总是感觉了得努力奇遇,努力学中文。我看过了也做过了特别多东西。拍了特别多照片。这些是我最喜欢的故事:

哈尔滨旅行社

在哈尔滨的时候,骗人试试骗我。(有点坏的故事)他们告诉我他们是旅游事。但是我觉得不是。感觉他们想绑票我。我测试了:我告诉那个司机,我要跟你一起旅游,先请我客那个饭店吗?我选择了哪个饭店(很重要!)。我选了特别贵的俄罗斯饭店。他们请我客了。在饭店里面,我跟我的骗人练习很多中文。我们热闹得聊。我去卫生间的时候,服务员陪我。里面的时候,服务员告诉我:小心,我感觉你的朋友不是朋友,想骗你。他决定我的疑心。我非常感谢他告诉我因为我不太确定。以后,他们骗人问问我请进出他们的车。我就说了刚忙事,就走。

长城攀岩

我在北京的时候,我很想试试攀岩。其实我在美国攀岩一些次,但是觉得不那么好的。去中国的时候,我感觉他们的大石头好神秘了。感觉想攀岩了。这个故事很重要因为我现在很喜欢攀岩,也很喜欢中文。

我们去北京的北面,爬了二十分钟左右去大石头。我的攀岩旅行社教练帮我攀岩了。今天,我还跟他聊天,也还跟我中国攀岩做的朋友聊天。

还有很多的故事:我过一会儿要写

爬峨眉山
九寨沟
长城马拉松
挖大佛得鼻子
上大连大学电脑科学课

这是很久的想法。2012/09/06在我的evernote写了。

----

This Winter break, I am planning a trip to China with the goal of intensive language and culture immersion. And by intense, all I really mean is that I want to feel uncomfortable, but in a good way you know? A good learning environment. I am favoring northern China for the trip because of the Harbin winter culture, Beijing Capital, and of course the sexy Beijing accent.

目標:

  1. 學習地道口語 (練習很多普通話!)
  2. 过地道生活,了解地道文化
  3. 認識生活朋友

Goals:

  1. Learn authentic oral Chinese and practice my Beijing accent.
  2. Experience daily Chinese life and culture
  3. Make lifelong friends

Thoughts:

  1. Classical Chinese music
    1. Play Pipa
    2. Play GuZheng
    3. Go to concert
  2. Tourist Attractions
    1. Harbin
      1. Ice and Snow Festival (哈尔滨冰雪大世界)
      2. Manchurian Tiger Garden (东北虎园)
      3. Yabuli Ski Field (雅布力滑雪场)
      4. Sun Island (太阳岛)
      5. Russian-Built Saint Sophia Cathedral (中央大街)
    2. Beijing
      1. Great Wall(长城)
      2. Forbidden City(紫禁城 or 故宫)
      3. Summer Palace(颐和园)
      4. Imperial Palace(圆明园)
      5. Temple of Heaven(天坛)
      6. Tian’anmen Square(天安门广场)
      7. Hutong (less modern, small streets, lots of classical shops)

http://www.beijingholiday.com/bus-tour/2-days-classic-beijing-bus-tour.html has some bus tours.

Where to Sleep?

http://www.couchsurfing.org and http://www.hostelworld.com/hostels/Beijing are awesome for finding sleeping arrangements. I have also emailed universities and made some contacts. After all, the goal of the trip is to experience Chinese, and there is no better way than to stay with locals and learn from them.

Study

For studying, I am most likely going to get a tutor(s) (家教). I am still waiting to see if there are short term programs available. I can google image search, skype chat, and look up words in a dictionary without stepping foot outside of my bedroom after all.

Getting There

Orbitz.com and http://www.hipmunk.com for flight tickets. The best tickets seem to be leave on the weekend and come back Monday or Wednesday.

Budget

I have been trying to leave out the budget as I figure out what things cost and not letting the price deter me from what I want to experience, but alas, it is about time to calculate costs.

  • $1050 round trip ticket to Beijing
  • $400 tutoring
  • $400 lodging
  • $400 tours and entertainment
  • $300 food
  • $160 Beijing visa
  • $100 miscellaneous
  • $70 round trip train ticket to Harbin
  • $50 airport taxi service (hopefully can find a friend)

Total: $2930

Timeline (Rough – to be thought out later — prereq is finding tutoring / language program information)

Official school break is from December 15th to January 9th. I am working with my professors to take finals early and return a week later. I want to stretch the time from December 8 to January 14 +/- for the cheapest flights. This gives me 4 to 5 weeks.

  • Weeks 1: Beijing
  • Weeks 2-4: Harbin?
  • Week 5: Back to Beijing and fly out

How to tie a C# .NET GUI to a callable C# .NET class library dll from Excel VBA: Guided Minimum Framework Example

Dev

Summary:

A minimum working example of how to tie a C# .NET GUI to a callable C# .NET class library dll from Excel VBA or another C# application.

 

This is a follow up to the non GUI example posted earlier

 

Project: AutomationComExample.zip

 

  • 1 Summary:
  • 2 Framework Structure
    • 2.1 ExampleTargetApp (GUI Application)
      • 2.1.1 MainWindow.xaml.cs
      • 2.1.2 HelloWorldService.cs
    • 2.2 ServiceDefinition
      • 2.2.1 IHelloWorldService.cs
    • 2.3 CallingDll
      • 2.3.1 ServiceProxy.cs
      • 2.3.2 ICallTargetApp.cs
      • 2.3.3 CallTargetApp.cs
  • 3 Example access from VBA

Framework Structure

The goal is to connect the piping features of WCF named piping class with the GUI features of the MainWindow class. C# does not support multiple inheritance, but that is fine. We only need an interface and C# supports that of course. We can create an interface from the GUI that the DLL will utilize to allow changes to the GUI from another application.

The framework consists of three projects within visual studio: ExampleTargetApp, ServiceDefinition, and CallingDll.

  • ExampleTargetApp contains the information for the GUI and handles what happens when elements of the GUI interact with the user, presumably via mouse and keyboard but could also be via function piping. This project also contains a service to make use of the pipes interface.
  • ServiceDefinition contains an interface for the functions to go through WCF pipes.
  • CallingDll uses the service interface to access functionality contained and defined in the ExampleTargetApp project

ExampleTargetApp (GUI Application)

MainWindow.xaml.cs

Contains the elements of the GUI such as Button1_Click() and SelectRadio1()

HelloWorldService.cs

Contains the service class using the service interface

ServiceDefinition

IHelloWorldService.cs

Contains the service interface definition

CallingDll

ServiceProxy.cs

Set up the service to work using the service contract defined in the ServiceDefinition project

ICallTargetApp.cs

Interface for calling DLL

CallTargetApp.cs

Functions for calling DLL through the proxy

 

Example access from VBA

vbacallingdll

Load the dll “CallingDll” by selecting browse then going to the project build directory: C:\dev\AutomationComExample\CallingDll\bin\x86\Debug\CallingDll.tlb

Excel VBA Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Sub SelectHello()
    Dim targetApp As Object
    Set targetApp = CreateObject("CallingDll.CallTargetApp")
    targetApp.SelectHello
End Sub
Sub SelectGoodbye()
    Dim targetApp As Object
    Set targetApp = CreateObject("CallingDll.CallTargetApp")
    targetApp.SelectGoodbye
End Sub
Sub SelectButton()
    Dim targetApp As Object
    Set targetApp = CreateObject("CallingDll.CallTargetApp")
    targetApp.SelectButton
End Sub

How to call a C# .NET class library from Excel VBA: Guided Example

Dev

I have made a GUI in C#. Now I want to create an API to use in vba to ease automation and make use of the team’s existing vba code. This guide gives a basic example of how to do that. Examples I found online were overly complicated and/or not so useful. This short guide should get you started in calling your C# .NET functions from Excel VBA. If you plan on using a GUI, see the other guide as this approach will run into problems. Please let me know if you have trouble.

 

Update: As it turns out, this does not effortlessly lead into a COM accessible GUI as I originally suspected. This documentation below works great until you try to add in the actual GUI application. For the GUI application, see this guide: How to tie a C# .NET GUI to a callable C# .NET class library dll from Excel VBA: Guided Minimum Framework Example

After making different “HelloWorldGUI via VBA/C#” style minimal working solution examples, I picked Named Pipes for now because it was the easiest solution I found (outside of COM exposed DLL solution below for non-gui applications. .NET 3.5+ required

Possible solutions included:

  • Run the GUI from the VBA – No, I want a standalone GUI that can be attached to
  • Use AutoItX3.dll to literally click the buttons and type using virtual keyboard and mouse – No, doable but overly difficult and complicated
  • Use .NET’s UI automation to control UI elements found through Windows SDK inspect tool – Pretty good, but since we have the GUI source code, there should be a more direct solution\
  • Use UDP port on local machine to link programs
  • Communicate through set memory location on computer – too low level. Something should already exist that does this safely without problems
  • Use WCF (Windows Communication Foundation) Named Pipes to communicate between VBA/C# and WPF (Windows Presentation Foundation) – Looks the cleanest and easiest way

Step-By-Step Guided Example

  • Step-By-Step Guided Example
  • 1. Create C# Library Class
  • 2. Make Library Class Visible as COM Library
  • 3. Call Public Functions from Excel VBA
  • 4. Deployment
    • Unblock the DLL (Windows Security)
    • Registering the Assembly
    •  Related articles
  • References

1. Create C# Library Class

Put this code in a new C# file in a new Visual Studio project. It is bare bones with one simple function that will later be called from Excel vba.

I named the project and solution both ZZTEST_EXCEL_LIB for easy finding in the excel references list.

Sample Code Collapse source
1
2
3
4
5
6
7
8
9
10
11
12
13
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
namespaceZZVISIBLE_FROM_EXCEL_LIBRARY
{
    publicclassZZVISIBLE_FROM_EXCEL_CLASS
    {
        publicDouble DotNetMethod_SQR(Double input) //Return the square of the input
        {
            returninput * input;
        }
    }
}

2. Make Library Class Visible as COM Library

In the project properties, change the output type to Class Library

In Assembly Information, check “make assembly COM-Visible”

In the project properties under the build tab, check “Register for COM interop”

3. Call Public Functions from Excel VBA

In Excel, enable the developer tab and launch visual basic (google this step if unclear)

From visual basic, select tools and then references. Select the desired library, in this case “ZZTEST_EXCEL_LIB”

Run the VBA code
Collapse source
1
2
3
4
SubTest()
    Dimtest1 AsNewZZVISIBLE_FROM_EXCEL_CLASS
    MsgBox test1.DotNetMethod_SQR(5) 'The function made in C# should return the square the input, 5*5 = 25
EndSub

Voila

 

4. Deployment

This is great, but it will only work on your computer. You must follow these steps to register the DLL on another computer. TK I am looking into building an installer to do this

Everything in the C:\Program Files (x86)\Maxim\GUI_BRIDGE path must be placed in this exact path on the target computer.

Unblock the DLL (Windows Security)

Registering the Assembly

Start the command prompt as administrator

In the terminal window, run regasm with /codebase option on the dll.

“C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe” /codebase “C:\Program Files (x86)\Maxim\GUI_BRIDGE2\gui_bridge2_project\gui_bridge2_project\bin\Debug\ZZ_GUI_BRIDGE2_PROJECT.dll”

Regasm will warn about RA0000 ~ please give your assembly a strong name and re-register it. Types registered successfully.

References

http://msdn.microsoft.com/en-us/library/bb608604.aspx

http://www.codeproject.com/Articles/555660/Extend-your-VBA-code-with-Csharp-VB-NET-or-Cpluspl

http://msdn.microsoft.com/en-us/library/tzat5yw6(v=vs.110).aspx

http://www.geeksengine.com/article/create-dll.html

http://richnewman.wordpress.com/2007/04/15/a-beginner%E2%80%99s-guide-to-calling-a-net-library-from-excel/

http://msdn.microsoft.com/en-us/library/bb608613.aspx – debugging deployment issue

http://tech.pro/tutorial/855/wcf-tutorial-basic-interprocess-communication