I’ve discovered that there is one more functioning neon sign (or object) of interest in my town.
The statue decorated with the neon halo is part of an installation known as “Our Lady of Lourdes Grotto”, originally built as an intended source of inspiration for the orphans that lived in an orphanage that was once operated on the grounds.
It seems that there are two sorts of people who visit the site: Catholics, and fans of Jack Kerouac, who is said to have visited it frequently in childhood and mentioned it in his book, “Doctor Sax”.
Tonight, I went out to practice taking pictures. I try to avoid going out and about in my town, but I had made a resolution to choose tonight to finish taking pictures of the neon signs in my town.
There’s only one pair of neon signs in my town that pose any difficulty to photograph. My town’s newspaper has signs facing east and west on the top of a eight story building, and one can only get so close to the signs without the edge of the building or the side of a sidewalk tree getting in the way. I drove in at sunset, and walked around a few blocks to find a spot with a clear line of sight. I lined up to take a picture, and was informed that I had forgotten to return the memory card to the camera.
Whoops.
I figured I should just return later at night. I don’t really care about the other things around the signs. It isn’t far from my house, but I did loathe the thought of having to come back and having to find parking.
—
I returned, a few hours later, at the height of the evening, and the pub crawlers and clubbers were out in force. While taking pictures of the west-facing neon sign on the newspaper building, I kept getting the sense that there were people looking at me.
I thought maybe it was because I was taking pictures of the sign.
Eventually, someone spoke up.
“Take my picture.” said a female voice, from below me.
I looked down. I had been standing up on a brick wall, paying no attention to the people walking by on the sidewalk. As soon as I made eye contact, she spoke up again.
“Take my picture?” She started to question what I was doing, though she hinted with the tone of her voice that she was already displeased that I wasn’t preparing to take a picture of her. It felt like a command.
I was taken aback, and my arms drooped, lowering my camera to my chest. She straightened her posture in anticipation. I ignored her, raising my camera back up again and pointing it up to take a picture of the neon sign up over the line of buildings across the street.
“Hmpf!” she exclaimed, wrapping her purse strings tightly around her arm and clutching the body of her purse close. I could see her walk off with my other eye before I closed it to take yet another blurry picture of the newspaper building sign.
“Won’t take a picture, what’s wrong with this guy.” She muttered.
I was equally perplexed. I refrained from making a retort about being solicited for pictures.
Before I could look up to take another shot, another interruption.
“Hey bro, take my picture?”
Before I could even turn my head to look, that line brought the image of a certain stereotype to fore. I turned my head.
He was wearing a baseball cap, backwards, a wife-beater, cutoff jean shorts, no socks, and basketball shoes. He read my face.
“Oh, you’re not taking pictures of people, are you?”
I shook my head.
“Take my picture anyways?” he asked. “Bro?”
I shook my head. “I’m just here to take a picture of that-“, I said, looking across and pointing up over the buildings.
As soon as he saw me gesture, he gave up, and resumed walking.
After a few paces, he stopped. “Why?” he asked.
“Practice.” I replied.
He nodded and kept walking. He may have been dressed in a loose stereotype, but that nod affirmed that he was no stranger to rigor. “Practice. Yep. Gotta do it.” he said to himself, walking away.
—
“Hey!” said a shrill voice. I didn’t look down.
“HEY! Take her picture!” she said. I looked down. A small group of clubbers were walking past, three guys and two gals. She held her hands at her hips, glaring at me.
“Pay attention man- you have a camera and let a pretty girl walk past without wanting to take her picture?”
I wondered if I should tell her how creepy that would be. Also, I was confused by the ascent of the tone of her voice in that sentence. I tried to read her face for any tell or sign that would let me bow out of this conversation, now that she had my attention.
“Isn’t she pretty?” she asked, pointing to her friend with her left hand, extending a small leather clutch in her direction. She was wearing gold and silver bangles solely around her left wrist. They swayed towards her friend.
I nodded.
“Take her picture!” She waved the clutch.
I looked at her friend, then back to her, and I shook my head. “Look, she’s turning away. You’re embarrassing her. She doesn’t want her picture taken.”
“Come on! Take her picture! Doesn’t her hair look great?” she said. “Look at her hair.” The end of her clutch bobbed, pointing at her friend who had turned away and kept walking.
“Yes, it does.” I agreed. Her friend had great cheerful curls of black hair that tapered off at the small of her back. I don’t understand hair; but I couldn’t help conceding that ground.
“So you’re not taking pictures of people?” she asked. I had already raised my camera again to look up at the building.
“Come on. Look at her booty. Look.” she implored.
(Nope, not going to look, I told myself. Don’t even do it, I thought.)
“Come on, don’t you agree she has a fine booty? Look at it!” she demanded. I could hear the bangles jingle.
“I’m sure your friend would like to be left alone. I’m sorry.” I said.
She departed in a huff, making her opinion known with each heavy step down the sidewalk. “She’s pretty and you know it.” she said, firing one last salvo from down the block.
I didn’t respond nor look.
(In spite of my attempt to get out of that conversation, that was still really creepy, I thought.)
—
I left that location and headed down the street to walk a few blocks to the other side of the newspaper building. At a canal bridge, two males stood, eying me and my camera. I looked one of them in the eye.
“Yo. Take my picture.” he said.
I shook my head. “Only photographing buildings here.” I said.
“Yo?” he asked, as I approached to walk around them. The sidewalk was out on this side of the bridge street for repairs. I stepped into the street anyways.
Hopeful that I was merely walking in to take a picture, they put their arms around each other, posing with peace signs as I approached.
“Peace, bro. Take our picture.” They waved their peace signs.
I sidestepped them and kept walking over the bridge. In my periphery I could tell that they had retracted their index fingers.
I kept walking.
“Man. Assholes with cameras.” muttered the other male of the two, as they walked away.
—
Contrary to my assumptions, the other side of the newspaper building was easier to photograph. The sign was closer to the corner edge of the building, and there were plenty of spots to look up. I was done in five minutes. I proceeded to walk back the way I had arrived.
—
Walking towards my car, I came across a group of men talking to two women who were clearly unimpressed with the lot of them. I hung my head trying not to be noticed, but they saw the camera hanging from my neck. One of them singled me out. “Yo, check out the camera walking up.” he said.
“Damn, that’s a phat lens.” he said, as the other guys assembled around me.
“Thanks.” I said. I tried to walk through, but they had blocked the sidewalk. The two women looked on, one of them staring at the lens.
“You takin’?” He asked. I shook my head.
“Awww, c’mon man. Just one picture!” he said.
“This is a distance lens. I don’t think I can take a portrait of you all with this.” I said.
Unfazed, he kept at it. “Just take one!” he implored. “One picture. You got this.”
I looked down at my camera, I popped the flash just to see if it would work with this lens, and closed it.
“Yo, he’s going to take a picture!” he exclaimed. “Rally up!”
I shook my head. “This isn’t going to work.” I said.
“C’mon, just this once. It’ll be fun!” said his buddy. They locked into a pose, arms over shoulders, and started to chant- “Picture! Picture! Picture!”
(It’ll be fun. That saying has never led to anything good, I thought.)
Bemused, the two women were looking at me. The one who had eyed my camera made the click motion with her right hand.
“Alright. Don’t hate me if it’s bad.” I said. I had to get out of there.
I raised my camera. (Nope, I thought, looking through the viewfinder.)
I took five steps back.
Suspicious, the ringleader spoke up. “Hey man, are you doing this?”
I looked into the viewfinder. “I’m getting nothing here.” I said. I pointed to the weak alley light up and beyond them. “You gotta come out a little bit.” I said. I didn’t think it would help, but who knows.
I took five more steps back. I was now in the middle of the street.
I could fit two heads into the shot. There were five of them.
I motioned for them to stay put, and took ten more steps back, standing in between cars on the other side of the street.
The woman who had made the click motion piped up. “Whys he gotta stand so far back?” she asked. Fortunately, nobody else seemed to hear her voice of reason.
I took a few pictures. I tried to focus, but it was much too dark. My hands jittered, as they do, but I could do nothing about it. Ah well. I looked up from my camera.
The men cheered.
“Yeah man! Thanks for taking our picture! Can we see?” they asked.
(Oh shit, I thought. There’s nothing to see.)
I held out the preview on the back of my camera. “Not so great.” I said. “I’m sorry.”
“Yo man, it’s just dark. These are GREAT.” said the ringleader.
(What!?)
“Where you gonna post these? Facebook? You got a site, man?” he asked.
I was about to shake my head, and then I saw my opportunity to get out of this.
“I’m sure word will get around. You’ll get a link. You know what I mean.” I winked.
“Hell yeah. Thanks again man!” he said.
I thought I was in the clear. His nearest buddy came over. “Did I make it in the shot?” he asked.
I showed him the second picture.
He looked up at me, worried.
I improvised. “Don’t worry. I’ll fix it in post.” I said.
He paused and tried to read my face. I patted him on the shoulder, once, flashing a reassuring grin and a nod.
“Yeah man. Okay cool. Nice.” He said. He seemed satisfied, if tentatively so.
I looked around. The two women had already departed, knowing they would be hit up for conversation if they stuck around. The coast was clear.
“Alright guys. See you around. I have to go.” I said.
“Okay cool man. Thanks!” they said.
We parted ways. I could hear their commotion from two blocks away, perhaps still riding the euphoria of having their picture taken. Clearly I had underestimated how drunk these men were.
—
On my drive home, I thought about why I had bothered to go out. Had it been two years since that conversation?
-
“You wrote a tweet about neon lights.” she said.
“Yes. There’s not so many of them out there, they’re practically relics now.” I replied.
“Who needs them anyways? We have GIFs now.” I said. “For the animated lights, anyhow.”
“You should take pictures of them. We don’t have many here in Australia.” she said.
“Well, We don’t have many in my town, either. Just two, I think.” I said.
“Well, when you get around to it. Take pictures and show me, sometime. I have to go. Later.” she said.
—
As I pulled into my driveway, I remembered another conversation with another friend. We had been talking about a potential gig that fell through.
-
“So they want a site that has pictures? Why do they care so much about pictures? I can’t they just stick those up on facebook?” I asked.
“Man, you don’t even know.” he said. “They’re f-ing crazy about their pictures. I would use the word ‘loco’ but that isn’t even enough.”
“So who are these guys again?” I asked.
“Club promoters. They really insist on having management and ownership of those photos.” he said. “Otherwise it’s a dealbreaker.”
“You don’t say.” I said. “Who cares about pictures?” I added.
“It’s a weird thing man. You wouldn’t believe it until you see it.” he said.
-
I repeated it to myself again, in recollection while turning off my car.
“You won’t believe it until you see it.”
He warned me.
(You don’t say.)
fastest spider i’ve ever caught in my house. i estimate he can run at a top speed exceeding two feet a second. luckily, his reaction time is a lot slower than mine.
I saw a curious thing today.
Walking through a cemetery, I came across a headstone with a man’s face etched into it. Looking at the details inscribed into the headstone, this man died nearly twenty years ago. There was nothing particularly striking about the man’s face, his name, nor anything else written upon his headstone; but there was something eerie about the flowers over his grave.
His headstone lay flat in the ground, well kept, polished to a shine, and the edges were smoothed off with a slight bevel applied to all sides. Some visitors had been by recently, as some pansies and some geraniums stood vigil beside his headstone. Over his grave, someone had erected a hanging flower pot on a tripod, brimming with lobelia. And looking at the tripod and the planter, I came to a sudden realization; It was placed so that at sundown, the lobelia would cast a long shadow covering the headstone.
I’d only recently heard of lobelia being known as the flower of malevolence, a flower to wish death and ills upon other people. While I’m not a superstitious person; I did think to myself, “Now isn’t this a strange coincidence?” Then, I remembered a conversation that took place several years ago, when I first encountered the lobelia.
In the duty-free shopping zone on the island of St. Lucia, I was browsing through prints at an antique store, and came across a print of some intriguing blue flowers that were drawn slightly misshapen and a little bit contorted. There was something about the print that struck me as being very honest, as though someone had an affinity for this flower in the wild, and purposefully drew it with all its flaws intact.
As I went to pay for this print, the shopkeeper motioned me aside, and offered me a magnifying glass.
“In case you wish to look it over.” she said.
I declined. “I like it already.” I said. “I’m going to buy it as is.”
She looked at the print, and without reading the caption, recognized the flower.
“Ah, the lobelia. They grow all over England, you know?” she said. “I encountered many of these in my youth.”
Looking at me with some concern, she asked, “Is there a particular reason you chose this flower? Have you seen or heard of it before?”
I shook my head.
“What draws you to this print?” she asked. “This seems a curious choice, forgive me for saying this, for a guy to choose.”
“It seems carefully hand-drawn.” I said. “And the flowers are not corrected from what someone might see in the wild. They’re drawn with their flaws intact and it all looks pretty honest. I like it.”
“I see.” she said. She paused for a moment. “If that is what you like about it, then you’ve made a fine choice. Here; let me draw up the bill of sale for you and you can be on your way.”
She plucked two bags, one for some brooches that I bought for reasons I’ve long forgotten, and one for the print.
“They could go in the same bag.” I offered. “The print already has a sleeve.”
A shadow of a grin momentarily crossed her face. “They should travel in separate bags. You may do what you like and place them together once you’ve left the shop.”
I paid for my purchase, and turned to leave. Before leaving, I turned to ask: “Do you have any more prints of the lobelia?”
She shook her head. “No. I’m sure I’ve only had just the one that you have now; I’ve been here 17 years and that one print has been in my collection for sale since I first opened shop here on the island.”
She waved goodbye as I left. “Do take care now, and perhaps I’ll see you again someday.” She said.
At that time, I found it strange that this print elicited so much commentary from her, when she barely spoke a word at the huge bill of sale rung up by my friend, whom I accompanied into the shop.
But today, looking at the curious placement of the lobelia over this stranger’s grave, I had to wonder. Is it possible for a man to have an enemy whose vendetta hides in plain sight, decades after his passing? Most likely, I think, it was someone who just happened to be unlucky enough to pick a bright blue flower whose hue will stand out amongst the other graves.
Nonetheless, I wonder. I wouldn’t discount the idea that there are men who have lived and left behind an enemy or two. He could even be a father or grandfather who did something to spite his sons and grandsons. Most of us will never do anything egregious that might merit such a lasting grudge.
But, there just might be a few people left out there, stuck in their memories and observances, who haven’t let go of things that others might dismiss upon meeting for old time’s sake. There might just be someone out there who knows at least one thing about this deceased man better than anyone else; who may find it fitting to pay tribute to that one memory by leaving death flowers as his shadow by proxy, on a day that other people reserve to respect the fallen and the dead.
looks like it was a yellow sac spider. venomous, said to be very painful if it bites, but not lethal to humans other than infection risk.
While you don't have a trivial 1:1 Mapping from IEnumerable<Period> to List<CellViewModel>, you can still derive some value from Automapper by using it only at the place where you get class-to-class contact, which in your example is between Period and RowViewModel.
With this in mind, you can also make better use of LINQ and get everything done in one sweeping motion, provided you set up the projections that require re-shaping from Period to RowViewModel.
Here's a console code example that demonstrates exactly that. Note that we're using Automapper's notion of resolver classes via ValueResolve<TSource,TDestination> do the re-shaping, and I've added an extra constructor to CellViewModel to accept an IEnumerable<RowViewModel>, which helps improve our declarations.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
namespace GroupingMapping
{
public class PeriodRequest
{
public IEnumerable<Period> Periods { get; set; }
public IEnumerable<DateTime> Weeks { get; set; }
}
public class RowViewModel
{
public string DayName { get; set; }
public string SchoolclassCode { get; set; }
public string Content { get; set; }
public int DayIndex { get; set; }
public int LessonNumber { get; set; }
}
public class Period
{
public int PeriodId { get; set; }
public DateTime LessonDate { get; set; }
public int LessonNumber { get; set; }
public string SchoolclassCode { get; set; }
public string Content { get; set; }
public int SchoolyearId { get; set; }
// No definition provided for Schoolyear
//public Schoolyear Schoolyear { get; set; }
}
public class CellViewModel
{
public CellViewModel()
{
Rows = new List<RowViewModel>();
}
public CellViewModel(IEnumerable<RowViewModel> rowVMSet)
{
Rows = new List<RowViewModel>(rowVMSet);
}
public List<RowViewModel> Rows { get; set; }
}
public class PeriodListViewModelEx
{
public PeriodListViewModelEx(IEnumerable<Period> periods)
{
CellViewModels = new List<CellViewModel>(periods
.GroupBy(p => p.LessonNumber)
.OrderBy(grp => grp.Key)
.Select(grp =>
{
return new CellViewModel(
grp.Select(p => { return Mapper.Map<Period, RowViewModel>(p); }));
}));
}
public List<CellViewModel> CellViewModels { get; set; }
}
class DateTimeToDateNameResolver : ValueResolver<DateTime, string>
{
protected override string ResolveCore(DateTime source)
{
return source.ToShortDateString();
}
}
class DateTimeToDayOfWeekResolver : ValueResolver<DateTime, int>
{
protected override int ResolveCore(DateTime source)
{
return (int)source.DayOfWeek;
}
}
class Program
{
static void Main(string[] args)
{
Mapper.CreateMap<Period, RowViewModel>()
.ForMember(dest => dest.DayName, opt => opt.ResolveUsing<DateTimeToDateNameResolver>().FromMember(src => src.LessonDate))
.ForMember(dest => dest.DayIndex, opt => opt.ResolveUsing<DateTimeToDayOfWeekResolver>().FromMember(src => src.LessonDate));
Period[] periods = new Period[3];
periods[0] = new Period { PeriodId = 1, LessonDate = DateTime.Today.Add(new TimeSpan(1, 0, 0, 0)), LessonNumber = 101, SchoolclassCode = "CS101", Content = "Intro to CS", SchoolyearId = 2013 };
periods[1] = new Period { PeriodId = 2, LessonDate = DateTime.Today.Add(new TimeSpan(2, 0, 0, 0)), LessonNumber = 101, SchoolclassCode = "CS101", Content = "Intro to CS", SchoolyearId = 2013 };
periods[2] = new Period { PeriodId = 3, LessonDate = DateTime.Today.Add(new TimeSpan(1, 0, 0, 0)), LessonNumber = 102, SchoolclassCode = "EN101", Content = "English (I)", SchoolyearId = 2013 };
PeriodListViewModelEx pvModel = new PeriodListViewModelEx(periods);
Console.WriteLine("CellViews: {0}", pvModel.CellViewModels.Count);
foreach (CellViewModel cvm in pvModel.CellViewModels)
{
Console.WriteLine("{0} items in CellViewModel Group", cvm.Rows.Count);
}
Console.WriteLine("Inspecting CellViewModel Rows");
foreach (CellViewModel cvm in pvModel.CellViewModels)
{
foreach (RowViewModel rvm in cvm.Rows)
{
Console.WriteLine(" DayName: {0}", rvm.DayName);
Console.WriteLine(" SchoolclassCode: {0}", rvm.SchoolclassCode);
Console.WriteLine(" Content: {0}", rvm.Content);
Console.WriteLine(" DayIndex: {0}", rvm.DayIndex);
Console.WriteLine(" LessonNumber: {0}", rvm.LessonNumber);
Console.WriteLine(" -");
}
Console.WriteLine("--");
}
Console.ReadKey();
}
}
}
You can specify a transform at the moment just before the gradient is applied if you would like to declare the brush only once. Note that using transformations will override many of the constructor arguments that can be specified on a LinearGradientBrush.
LinearGradientBrush.Transform Property (System.Drawing.Drawing2D)
To modify the transformation, call the methods on the brush object corresponding to the desired matrix operations. Note that matrix operations are not commutative, so order is important. For your purposes, you'll probably want to do them in this order for each rendition of your rectangles: Scale, Rotate, Offset/Translate.
LinearGradientBrush.ResetTransform Method @ MSDN
LinearGradientBrush.ScaleTransform Method (Single, Single, MatrixOrder) @ MSDN
LinearGradientBrush.RotateTransform Method (Single, MatrixOrder) @ MSDN
LinearGradientBrush.TranslateTransform Method (Single, Single, MatrixOrder) @ MSDN
Note that the system-level drawing tools don't actually contain a stock definition for gradient brush, so if you have performance concerns about making multiple brushes, creating a multitude of gradient brushes shouldn't cost any more than the overhead of GDI+/System.Drawing maintaining the data required to define the gradient and styling. You may be just as well off to create a Brush per rectangle as needed, without having to dive into the math required to customize the brush via transform.
Brush Functions (Windows) @ MSDN
Here is a code example you can test in a WinForms app. This app paints tiles with a gradient brush using a 45 degree gradient, scaled to the largest dimension of the tile (naively calculated). If you fiddle with the values and transformations, you may find that it isn't worth using the technique setting a transform for all of your rectangles if you have non-trivial gradient definitions. Otherwise, remember that your transformations are applied at the world-level, and in the GDI world, the y-axis is upside down, whereas in the cartesian math world, it is ordered bottom-to-top. This also causes the angle to be applied clockwise, whereas in trigonometry, the angle progresses counter-clockwise in increasing value for a y-axis pointing up.
using System.Drawing.Drawing2D;
namespace TestMapTransform
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle rBrush = new Rectangle(0,0,1,1);
Color startColor = Color.DarkRed;
Color endColor = Color.White;
LinearGradientBrush br = new LinearGradientBrush(rBrush, startColor, endColor, LinearGradientMode.Horizontal);
int wPartitions = 5;
int hPartitions = 5;
int w = this.ClientSize.Width;
w = w - (w % wPartitions) + wPartitions;
int h = this.ClientSize.Height;
h = h - (h % hPartitions) + hPartitions;
for (int hStep = 0; hStep < hPartitions; hStep++)
{
int hUnit = h / hPartitions;
for (int wStep = 0; wStep < wPartitions; wStep++)
{
int wUnit = w / wPartitions;
Rectangle rTile = new Rectangle(wUnit * wStep, hUnit * hStep, wUnit, hUnit);
if (e.ClipRectangle.IntersectsWith(rTile))
{
int maxUnit = wUnit > hUnit ? wUnit : hUnit;
br.ResetTransform();
br.ScaleTransform((float)maxUnit * (float)Math.Sqrt(2d), (float)maxUnit * (float)Math.Sqrt(2d), MatrixOrder.Append);
br.RotateTransform(45f, MatrixOrder.Append);
br.TranslateTransform(wUnit * wStep, hUnit * hStep, MatrixOrder.Append);
e.Graphics.FillRectangle(br, rTile);
br.ResetTransform();
}
}
}
}
private void Form1_Resize(object sender, EventArgs e)
{
this.Invalidate();
}
}
}
Here's a snapshot of the output:
This happens when one has other threads that continue to run that have no relation (or have become disassociated from) the threads related to your service.
Note that a process may be multi-tenant and host multiple services, so a stop command doesn't always imply that the owner process must exit, just that the service should stop running in that process.
To debug further, when you encounter this limbo state, you should attach a debugger and stop all threads and inspect the call stacks on each thread. For a single service process, you are likely to find that a thread has hung while waiting for IO or other operations to complete, or that there are idle threads such as message loop threads that are awaiting signals that will never be raised.
Font names are localized if the font creator chooses to publish metadata for a specific locale, but all fonts have a system-known name, usually the PostScript name, that ensures that the same font can be referenced and retrieved with a reasonable amount of reliability.
For OpenType and TrueType fonts, you can find localized names in the name record of an OpenType file.
The Naming Table (OpenType Spec 1.6) @ Microsoft Typography
Font Names Table (TrueType Spec) @ Apple
For PostScript Type 1 fonts, you can locate the assigned names by their FontName declarations.
Adobe Type 1 Font Format @ Adobe (PDF)
Update:
I checked to see whether the PostScript name can be used to instantiate a font, and unfortunately it doesn't work. However, using the localized name (as retrieved from Mark Ransom's link in his comment) does work. This sample is in C#.
using System.Drawing;
namespace FontNameCheckApplication
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Font TimesNewRomanByPSName = new Font("TimesNewRomanPSMT", 16f);
Console.WriteLine("TimesNewRomanPSMT = {0}", TimesNewRomanByPSName.Name);
Font TimesNewRomanByName = new Font("Times New Roman", 16f);
Console.WriteLine("Times New Roman = {0}", TimesNewRomanByName.Name);
Font ArialByPSName = new Font("ArialMT", 16f);
Console.WriteLine("ArialMT = {0}", ArialByPSName.Name);
Font ArialByName = new Font("Arial", 16f);
Console.WriteLine("Arial = {0}", ArialByName.Name);
Font GulimByEnglishName = new Font("Gulim", 16f);
Console.WriteLine("Gulim = {0}", GulimByEnglishName.Name);
Font GulimByKoreanName = new Font("굴림", 16f);
Console.WriteLine("굴림 = {0}", GulimByKoreanName.Name);
Console.ReadKey();
}
}
}
Unfortunately we've butted heads with Font substitution, as "Microsoft Sans Serif" is definitely not Times New Roman nor Arial. This indicates that the PostScript name can't be used reliably to reference the same font.
Here's the output:
TimesNewRomanPSMT = Microsoft Sans Serif
Times New Roman = Times New Roman
ArialMT = Microsoft Sans Serif
Arial = Arial
Gulim = Gulim
?? = Gulim
Update #2:
Here's a sample for Win32.
One thing to note is that CreateFontIndirect() is subject to substitution. When running this sample, I never got an empty handle, even for PostScript names. To see whether we can get an unsubstituted match, we should use EnumFontFamiliesEx() to scan the available system font list. We get the same results as the C#, but without substitutions. For some fonts the results may depending on the graphics mode setting (see SetGraphicsMode() / GM_ADVANCED).
LOGFONT structure (Windows) @ MSDN
CreateFontIndirect function (Windows) @ MSDN
SetGraphicsMode function (Windows) @ MSDN
EnumFontFamiliesEx function (Windows) @ MSDN
EnumFontFamExProc callback function (Windows) @ MSDN
#include "stdafx.h"
#include <Windows.h>
void TestCreateFont(LPCTSTR lpczFontName, BYTE bCharSet)
{
LOGFONT lf;
lf.lfHeight = 0;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_DONTCARE;
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = FALSE;
lf.lfCharSet = bCharSet;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfPitchAndFamily = DEFAULT_PITCH;
// NOTE: LF_FACESIZE = 32, WinGdi.h
_tcsncpy_s(lf.lfFaceName, 32, lpczFontName, _tcsnlen(lpczFontName, 32));
HFONT hf = ::CreateFontIndirect(&lf);
// NOTE: LF_FACESIZE = 32, WinGdi.h
_tprintf_s(_T("TestCreateFont:\r\n%.32s = %.32s, bCharSet=%d, HFONT=0x%8.8x\r\n\r\n"), lpczFontName, lf.lfFaceName, bCharSet, hf);
::DeleteObject(hf);
}
int CALLBACK MyEnumFontFamExProc(const LOGFONT *lpelfe, const TEXTMETRIC *lpntme, DWORD FontType, LPARAM lParam)
{
_tprintf_s(_T(" Found: %.32s, bCharSet=%d\r\n"), lpelfe->lfFaceName, lpelfe->lfCharSet);
return 1;
}
void TestEnumFontFamiliesEx(LPCTSTR lpczFontName, BYTE bCharSet)
{
LOGFONT lf;
lf.lfHeight = 0;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_DONTCARE;
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = FALSE;
lf.lfCharSet = bCharSet;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfPitchAndFamily = DEFAULT_PITCH; // NOTE: DEFAULT_PITCH = 0, WinGdi.h
// NOTE: LF_FACESIZE = 32, WinGdi.h
_tcsncpy_s(lf.lfFaceName, 32, lpczFontName, _tcsnlen(lpczFontName, 32));
_tprintf_s(_T("TestEnumFontFamiliesEx: %.32s, bCharSet=%d\r\n"), lpczFontName, bCharSet);
HDC hdcAll = GetDC(NULL);
::EnumFontFamiliesEx(hdcAll, &lf, &MyEnumFontFamExProc, 0, 0);
}
int _tmain(int argc, _TCHAR* argv[])
{
TestCreateFont(_T("TimesNewRomanPSMT"), DEFAULT_CHARSET);
TestCreateFont(_T("Times New Roman"), DEFAULT_CHARSET);
TestCreateFont(_T("ArialMT"), DEFAULT_CHARSET);
TestCreateFont(_T("Arial"), DEFAULT_CHARSET);
TestCreateFont(_T("Gulim"), DEFAULT_CHARSET);
TestCreateFont(_T("굴림"), DEFAULT_CHARSET);
TestEnumFontFamiliesEx(_T("TimesNewRomanPSMT"), DEFAULT_CHARSET);
TestEnumFontFamiliesEx(_T("Times New Roman"), DEFAULT_CHARSET);
TestEnumFontFamiliesEx(_T("ArialMT"), DEFAULT_CHARSET);
TestEnumFontFamiliesEx(_T("Arial"), DEFAULT_CHARSET);
TestEnumFontFamiliesEx(_T("Gulim"), DEFAULT_CHARSET);
TestEnumFontFamiliesEx(_T("굴림"), DEFAULT_CHARSET);
return 0;
}
And here are the results:
TestCreateFont:
TimesNewRomanPSMT = TimesNewRomanPSMT, bCharSet=1, HFONT=0xda0a117c
TestCreateFont:
Times New Roman = Times New Roman, bCharSet=1, HFONT=0xdb0a117c
TestCreateFont:
ArialMT = ArialMT, bCharSet=1, HFONT=0xdc0a117c
TestCreateFont:
Arial = Arial, bCharSet=1, HFONT=0xdd0a117c
TestCreateFont:
Gulim = Gulim, bCharSet=1, HFONT=0xde0a117c
TestCreateFont:
?? = ??, bCharSet=1, HFONT=0xdf0a117c
TestEnumFontFamiliesEx: TimesNewRomanPSMT, bCharSet=1
TestEnumFontFamiliesEx: Times New Roman, bCharSet=1
Found: Times New Roman, bCharSet=0
Found: Times New Roman, bCharSet=177
Found: Times New Roman, bCharSet=178
Found: Times New Roman, bCharSet=161
Found: Times New Roman, bCharSet=162
Found: Times New Roman, bCharSet=186
Found: Times New Roman, bCharSet=238
Found: Times New Roman, bCharSet=204
Found: Times New Roman, bCharSet=163
Found: Times New Roman, bCharSet=0
Found: Times New Roman, bCharSet=177
Found: Times New Roman, bCharSet=161
Found: Times New Roman, bCharSet=162
Found: Times New Roman, bCharSet=186
Found: Times New Roman, bCharSet=238
Found: Times New Roman, bCharSet=204
Found: Times New Roman, bCharSet=163
Found: Times New Roman, bCharSet=0
Found: Times New Roman, bCharSet=177
Found: Times New Roman, bCharSet=178
Found: Times New Roman, bCharSet=161
Found: Times New Roman, bCharSet=162
Found: Times New Roman, bCharSet=186
Found: Times New Roman, bCharSet=238
Found: Times New Roman, bCharSet=204
Found: Times New Roman, bCharSet=163
Found: Times New Roman, bCharSet=0
Found: Times New Roman, bCharSet=177
Found: Times New Roman, bCharSet=161
Found: Times New Roman, bCharSet=162
Found: Times New Roman, bCharSet=186
Found: Times New Roman, bCharSet=238
Found: Times New Roman, bCharSet=204
Found: Times New Roman, bCharSet=163
TestEnumFontFamiliesEx: ArialMT, bCharSet=1
TestEnumFontFamiliesEx: Arial, bCharSet=1
Found: Arial, bCharSet=0
Found: Arial, bCharSet=177
Found: Arial, bCharSet=178
Found: Arial, bCharSet=161
Found: Arial, bCharSet=162
Found: Arial, bCharSet=186
Found: Arial, bCharSet=238
Found: Arial, bCharSet=204
Found: Arial, bCharSet=163
Found: Arial, bCharSet=0
Found: Arial, bCharSet=177
Found: Arial, bCharSet=161
Found: Arial, bCharSet=162
Found: Arial, bCharSet=186
Found: Arial, bCharSet=238
Found: Arial, bCharSet=204
Found: Arial, bCharSet=163
Found: Arial, bCharSet=0
Found: Arial, bCharSet=177
Found: Arial, bCharSet=178
Found: Arial, bCharSet=161
Found: Arial, bCharSet=162
Found: Arial, bCharSet=186
Found: Arial, bCharSet=238
Found: Arial, bCharSet=204
Found: Arial, bCharSet=163
Found: Arial, bCharSet=0
Found: Arial, bCharSet=177
Found: Arial, bCharSet=161
Found: Arial, bCharSet=162
Found: Arial, bCharSet=186
Found: Arial, bCharSet=238
Found: Arial, bCharSet=204
Found: Arial, bCharSet=163
TestEnumFontFamiliesEx: Gulim, bCharSet=1
Found: Gulim, bCharSet=0
Found: Gulim, bCharSet=129
Found: Gulim, bCharSet=161
Found: Gulim, bCharSet=162
Found: Gulim, bCharSet=186
Found: Gulim, bCharSet=238
Found: Gulim, bCharSet=204
TestEnumFontFamiliesEx: ??, bCharSet=1
Found: Gulim, bCharSet=0
Found: Gulim, bCharSet=129
Found: Gulim, bCharSet=161
Found: Gulim, bCharSet=162
Found: Gulim, bCharSet=186
Found: Gulim, bCharSet=238
Found: Gulim, bCharSet=204
Here's a snippet from wingdi.h for the CharSet values.
#define ANSI_CHARSET 0
#define DEFAULT_CHARSET 1
#define SYMBOL_CHARSET 2
#define SHIFTJIS_CHARSET 128
#define HANGEUL_CHARSET 129
#define HANGUL_CHARSET 129
#define GB2312_CHARSET 134
#define CHINESEBIG5_CHARSET 136
#define OEM_CHARSET 255
#define JOHAB_CHARSET 130
#define HEBREW_CHARSET 177
#define ARABIC_CHARSET 178
#define GREEK_CHARSET 161
#define TURKISH_CHARSET 162
#define VIETNAMESE_CHARSET 163
#define THAI_CHARSET 222
#define EASTEUROPE_CHARSET 238
#define RUSSIAN_CHARSET 204
#define MAC_CHARSET 77
#define BALTIC_CHARSET 186
IServiceProvider is an imported (or perhaps held-over) COM interface that is intended to be used for private features in the context of the object whom you interrogate for a Service. The term 'Service' is applied rather loosely here, it originally meant any COM object that could be returned based upon what GUID is given.
IServiceProvider @ MSDN (.NET reference)
IServiceProviderImpl Class @ MSDN (C++ ATL reference)
In .NET, you don't need to implement it unless you have a client that specifically supports it, and in many cases you won't need to add yet another level of indirection that is implied by using IServiceProvider. Also, you can devise your own scheme to share common objects or implement other use patterns based upon IoC / Dependency Injection that are more flexible or more rigid as dictated by your needs.
One good historical context for IServiceProvider is the IE Browser Plugin Spec. Here, it is used to allow plugin components to use Browser Host features in-context. In a COM context, this interface is useful because it hides the details of instantiation and also can be used as part of a object construction and utilization strategy to avoid reference loops.
Update:
Indeed, the response is malformed as well. I tried the URL with a different ticker symbol and it looks like there is a stray " mark in the output in the previous_close field. If you remove the stray " mark, it should validate properly.
"meta" :
{
"uri" :"/instrument/1.1/ITW/chartdata;type=close;range=1d/json/?callback=",
"ticker" : "itw",
"unit" : "MIN",
"timezone" : "EST",
"currency" : "USD",
"gmtoffset" : -18000,
"previous_close" : 62.9000"
}
~
Original:
The response returned is in JSONP format.
finance_charts_json_callback( {
...
} )
Off the cuff, you should be able to strip away finance_charts_json_callback( from the start and the trailing ) from the end and end up with valid JSON data.
Remoting in a COM context means "ability to reference an object in another scope" where that scope could be in another apartment in the same process, or in another process on the same machine or even a different machine. A COM apartment is a running context whose configuration defines the ways other COM objects may call COM objects inside the apartment.
Processes, Threads, and Apartments (COM) @ MSDN
In .NET, remoting means "ability to converse with an object in another location", and is an entire subsystem in itself for making calls across process and machine boundaries.
.NET Framework Remoting Overview @ MSDN
.NET has the concept of AppDomains, which have intents that are similar to COM apartments. Most applications written on .NET don't explicitly manage multiple AppDomains at anywhere near the same amount of awareness that is required in COM.
For your work items, Windows Workflow is probably your quickest means to refactor your service.
Windows Workflow Foundation @ MSDN
The most useful thing you'll get out of WF is workflow persistence, where a properly designed workflow may resume from a Persist point, should anything happen to the workflow from the last point at which it was saved.
This includes the ability for a workflow to be recovered from another process should any other process crash while processing the workflow. The resuming process doesn't need to be on the same machine if you use the shared workflow store. Note that all recoverable workflows require the use of the workflow store.
For work distribution, you have a couple options.
A service to produce messages combined with host-based load balancing via workflow invocation using WCF endpoints via the WorkflowService class. Note that you'll probably want to use the design-mode editor here to construct entry methods rather than manually setup Receive and corresponding SendReply handlers (these map to WCF methods). You would likely call the service for every Message, and perhaps also call the service for every Report. Note that the CanCreateInstance property is important here. Every invocation tied to it will create a running instance that runs independently.
~
WorkflowService Class (System.ServiceModel.Activities) @ MSDN
Receive Class (System.ServiceModel.Activities) @ MSDN
Receive.CanCreateInstance Property (System.ServiceModel.Activities) @ MSDN
SendReply Class (System.ServiceModel.Activities) @ MSDN
Use a service bus that has Queue support. At the minimum, you want something that potentially accepts input from any number of clients, and whose outputs may be uniquely identified and handled exactly once. A few that come to mind are NServiceBus, MSMQ, RabbitMQ, and ZeroMQ. Out of the items mentioned here, NServiceBus is exclusively .NET ready out-of-the-box. In a cloud context, your options also include platform-specific offerings such as Azure Service Bus and Amazon SQS.
~
NServiceBus
MSMQ @ MSDN
RabbitMQ
ZeroMQ
Azure Service Bus @ MSDN
Amazon SQS @ Amazon AWS
~
Note that the service bus is just the glue between a producer that will initiate Messages and a consumer that can exist on any number of machines to read from the queue. Similarly, you can use this indirection for Report generation. Your consumer will create workflow instances that may then use workflow persistence.
You're in luck, as there's already a container control called a FlowLayoutPanel that will get you 90% of the way there as a flowing tag host.
This control is available from the Toolbox in Visual Studio, so a good starting point would be to make a custom control based upon a FlowLayoutPanel, and another custom control to represent a tag based upon a Label or Checkbox, and update the drawing and behavior (in the case of a Label) to respond to clicks and to display the [x] to dismiss the tag.
Label Class @ MSDN
CheckBox Class @ MSDN
After making these two controls, you will need to do additional work to make your FlowLayoutPanel-derived control add/remove Label-based controls representing the state of the tags present.
Update: One thing I missed, a TextBox or other input field would need to be added in place to support adding new tags.
A brief walk through the source code provided by twitterizer suggests that their API target hasn't been updated yet.
The lines of code that call this into question are at Twitterizer/Twitterizer2/Core/OptionalProperties.cs at https://github.com/Twitterizer/Twitterizer starting at line 50. Here's a snippet.
public OptionalProperties()
{
// Set the default values for the properties
this.UseSSL = false;
this.APIBaseAddress = "http://api.twitter.com/1/";
}
There are quite a bit of source code that look like it will need to be checked against v1.1, but you could try building the library with the version number in the APIBaseAddress symbol changed from /1/ to /1.1/ to see what breaks, and perhaps send a pull request with updates if you're up to it.
A complete list of the REST API methods for 1.1 is here. (@ dev.twitter.com)
Footnote: Twitterizer3 has the same base endpoint URL too. (@ github)
The documentation for IDirect3D9Ex::CreateDeviceEx says the HWND parameter is optional if you are in windowed mode and your presentation HWND in your D3DPRESENT_PARAMETERS structure is set (late edit: oops, can't be blank).
From IDirect3D9Ex::CreateDeviceEx @ MSDN
hFocusWindow [in]
Type: HWND
The focus window alerts Direct3D when an application switches from foreground mode to background mode. For full-screen mode, the window specified must be a top-level window. For windowed mode, this parameter may be NULL only if the hDeviceWindow member of pPresentationParameters is set to a valid, non-NULL value.
D3DPRESENT_PARAMETERS struct @ MSDN
To get a window handle for use, you can make another top-level window via regular .NET framework methods and grab its window handle instead of going through the motions with Win32 method calls.
If you find can't use the Handle provided by WPF (per Hans Passant's comment), you can also make a dummy Windows Form and instantiate it as a hidden window, and use its handle instead.
WindowInteropHelper (WPF) @ MSDN
Control.Handle (Windows Forms) @ MSDN
Footnote: Your existing WPF main window handle is probably fine unless some mechanism in SharpDX or an existing Viewport3D has a conflict with using Direct3D9 in this manner.
3-D Graphics Overview (WPF) @ MSDN
Viewport3D Class (WPF) @ MSDN
You'll need to enumerate all the monitors and check on their mappings on the virtual screen (MSDN).
Monitors are enumerated via a call to EnumDisplayMonitors (MSDN). This will enumerate a series of HMONITOR handles that you can pass to GetMonitorInfo (MSDN) to get the location of the monitor on the virtual screen.
There's also a whole guide to Multi-Monitor support that may also be worth reading.
About Multiple Display Monitors (Windows) @ MSDN
Some Caveats: Because the virtual screen is a user-controlled mapping, there's nothing preventing a user from setting up a monitor on the opposite physical side of where the monitor is placed in virtual coordinate space, and vice versa, as well as any number of other weird placement scenarios. Also, some display cards try to assume where the monitor is upon plug-in detection, which may be wrong from your software's point of view but could be caused by the user not paying attention to which display port maps to a left-hand side (if it is even labeled at all).
To consume functions from DLLs as done in a Win32 context, these functions need to be export-visible from the DLL. These functions are usually flagged with dllexport and will show up in the export table of a DLL. You can verify that user32 and other Win32 DLLs do this by using a utility such as dumpbin (MSDN).
Unfortunately, .NET doesn't have immediate support for making functions export-visible, only for bringing in such functions via the DllImport (MSDN) Attribute.
COM is the easiest way to consume code written within .NET from a non-.NET environment, but if you must use the lower level bindings, you can make an intermediate DLL in C, C++/CLI, or any other language and framework combination that can write export headers to a dll, to call your .NET code.
Also, A few articles exist on making this happen via post-compilation automation or other workarounds, here are a few for your reference.
How to Automate Exporting .NET Function to Unmanaged Programs @ CodeProject
Unmanaged Exports @ Google Sites
DllExport - Provides C-style exports for pure .NET assemblies
The windows message you wish to handle is WM_EXITSIZEMOVE.
WM_EXITSIZEMOVE message (Windows) @ MSDN
Depending on what you wish to accomplish, there's also the possibility that you might be better served by reacting to WM_NCLBUTTONUP, which is sent when the mouse button is released in the non-client areas of a window, such as the title bar of any window with a caption, border chrome, etc.
ExpandoObject derives from IEnumerable<KeyValuePair<string, Object>>, and most serializers will recognize a dynamic as this type when you assign an ExpandoObject. This is why you see an array type on the javascript side with named Key::Value pairs.
ExpandoObject Class (System.Dynamic) @ MSDN
One alternative to using ExpandoObject is to use C# anonymous types. When serialized to json, these map field by field as you expect.
Anonymous Types (C# Programming Guide) @ MSDN
It is possible to access values declared with dynamic from jQuery, but most likely you won't be returning a MVC View() with the model to be consumed with jQuery, as any server-side view template engine (razor, etc.) can already perform the same template activities with less overhead. Instead, jQuery templates are better used with Ajax calls.
Here are code examples demonstrating three cases where a variable declared dynamic on the server is consumed with jQuery templates in the browser.
The first example uses an anonymous type for the member field SomeValue, and has a jQuery template that treats it as a member object.
The second example uses an array of anonymous types for the member field SomeValue and has a template that uses {{each}} syntax to enumerate the items. Note that this is a scenario where things can go badly with dynamic, as you get no strongly-typed support and must either know the correct type or discover it at the time you access it.
The third example uses an ExpandoObject for the member field SomeValue, and has a jQuery template like the first example (single member object). Note that in this case, we need to use a helper function pivotDictionaryMap() to pivot Key::Value pairs into object members.
Starting with a blank C# MVC3 Web Project, we need to modify three files to demonstrate these examples.
Inside _Layout.cshtml, add script includes for jQuery templates and a proper version of jQuery in your <head> element.
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.tmpl.js")" type="text/javascript"></script>
Inside HomeController.cs, we'll add some methods that return json ActionResults. Also, for brevity we'll just declare a class SomeModelType here; and note that a proper application would probably have this class declared in its Models.
using System.Dynamic; // up top...
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult SomeDataSource(int id)
{
dynamic d = new { innerId = 99, innerLabel = "inside object" };
SomeModelType obj = new SomeModelType(id, "new object");
obj.SomeValue = d;
return Json(obj, "text/plain");
}
public ActionResult SomeDataSourceWithArray(int id)
{
dynamic d1 = new { innerId = 99, innerLabel = "inside object (first array member)" };
dynamic d2 = new { innerId = 100, innerLabel = "inside object (second array member)" };
SomeModelType obj = new SomeModelType(id, "new object");
obj.SomeValue = new object[] {d1, d2};
return Json(obj, "text/plain");
}
public ActionResult SomeDataSourceWithExpando(int id)
{
dynamic d = new ExpandoObject();
d.innerId = 99;
d.innerLabel = "inside object";
SomeModelType obj = new SomeModelType(id, "new object");
obj.SomeValue = d;
return Json(obj, "text/plain");
}
}
public class SomeModelType
{
public SomeModelType(int initId, string initLabel)
{
Id = initId;
Label = initLabel;
}
public int Id { get; set; }
public string Label { get; set; }
public dynamic SomeValue { get; set; }
}
Finally, in the default view, we will add script tags for the templates and the javascript necessary to consume them. Note the use of $.post() and not $.get(), as a JsonResult in MVC disallows GET requests by default (you can turn these on with an attribute).
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<script id="someDataTemplate" type="text/x-jquery-tmpl">
Item <b>${Id}</b> is labeled "<i>${Label}</i>" and has an inner item with id <b>${SomeValue.innerId}</b> whose label is "<i>${SomeValue.innerLabel}</i>".
</script>
<h3>SomeDataSource Example #1 (Single Item)</h3>
<div id="someData">
</div>
<script id="someDataArrayTemplate" type="text/x-jquery-tmpl">
Item <b>${Id}</b> is labeled "<i>${Label}</i>" and has these inner items:
<ul>
{{each SomeValue}}
<li><b>${innerId}</b> has a label "<i>${innerLabel}</i>".</li>
{{/each}}
</ul>
</script>
<h3>SomeDataSource Example #2 (Array)</h3>
<div id="someArrayData">
</div>
<script id="someDataTemplateFromExpandoObject" type="text/x-jquery-tmpl">
Item <b>${Id}</b> is labeled "<i>${Label}</i>" and has an inner item with id <b>${SomeValue.innerId}</b> whose label is "<i>${SomeValue.innerLabel}</i>".
</script>
<h3>SomeDataSource Example #3 (Single Item, Expando Object)</h3>
<div id="someDataFromExpandoObject">
</div>
<script type="text/javascript">
function pivotDictionaryMap(src)
{
var retval = {};
$.each(src, function(index, item){
retval[item.Key] = item.Value;
});
return retval;
}
</script>
<script type="text/javascript">
$(document).ready(function() {
// Ajax Round-Trip to fill example #1
$.post("/Home/SomeDataSource/5", function(data) {
$("#someDataTemplate").tmpl(data).appendTo("#someData");
}, "json");
// Ajax Round-Trip to fill example #2
$.post("/Home/SomeDataSourceWithArray/67", function(data) {
$("#someDataArrayTemplate").tmpl(data).appendTo("#someArrayData");
}, "json");
// Ajax Round-Trip to fill example #3
$.post("/Home/SomeDataSourceWithExpando/33", function(data) {
data.SomeValue = pivotDictionaryMap(data.SomeValue);
$("#someDataTemplateFromExpandoObject").tmpl(data).appendTo("#someDataFromExpandoObject");
}, "json");
});
</script>
There's no bug in your code. Your graph is accurately drawing the values that are in your histogram[] array.
You mention that your array contains the following values:
histogram[0] = 34118
histogram[1] = 1521
histogram[2] = 522
...
If you inspect your screenshot, the plots are correct. The very first bar drawn is quite tall, and the other remaining values (to your expectations) are close to the 1x10^3 band. It is likely that your histogram[] array is being initialized with the wrong data, or faulty data at index [0].
I can only provide speculation about the significance of the value in at histogram[0] from this side of your code and data, but perhaps you are receiving an array that has the sum of all of the remaining data in index [0].
As a quick check of expectations, if you change your loop to start from index [1] instead of [0], you will see that the plot control you are using will perform correctly for all the other values that are expected to be near the 1x10^3 band, and you should check the data source that fills your histogram array to see if that first data point is relevant or has been set to an erroneous value.
for (int i = 1; i < histogram.Length; i++)
{
double x = (double)i + 1;
//double y = (double)i + 1;//rand.NextDouble() * 1000;
double z = i / 4.0;
list.Add(x, histogram[i], z);
}
The only other remaining places where your code could fail is in these two lines in your snippet for the SelectedDatabase property.
RaisePropertyChanged("SelectedDatabase");
// Update the can execute flag based on the save
((DelegateCommand)OpenDatabaseCommand).RaiseCanExecuteChanged();
There are others who have had some problems with RaisePropertyChanged() and it's use of magic strings; but this is probably not your immediate problem. Nonetheless, you can look at these links if you want to go down the path of removing the magic string dependency.
WPF, MVVM, and RaisePropertyChanged @ WilberBeast
MVVM - RaisePropertyChanged turning code into a mess
The RaiseCanExecuteChanged() method is the other suspect, and looking up documentation in PRISM reveals that this method expects to dispatch events on the UI thread. From mstest, there are no guarantees that a UI thread is being used to dispatch tests.
DelegateCommandBase.RaiseCanExecuteChanged @ MSDN
I recommend you add a try/catch block around it and see if any exceptions are thrown when RaiseCanExecuteChanged() is called. Note the exceptions thrown so that you can decide how to proceed next. If you absolutely need to test this event dispatch, you may consider writing a tiny WPF-aware app (or perhaps a STAThread console app) that runs the actual test and exits, and having your test launch that app to observe the result. This will isolate your test from any threading concerns that could be caused by mstest or your build server.
This snippet of code seems suspect. If your event fires from another thread, the original thread may exit the wait first before your assignment, causing your flag to be read with a stale value.
viewModel.OpenDatabaseCommand.CanExecuteChanged += (s, e) =>
{
resetEvent.Set();
canExecuteChanged = true;
};
Consider reordering the lines in the block to this:
viewModel.OpenDatabaseCommand.CanExecuteChanged += (s, e) =>
{
canExecuteChanged = true;
resetEvent.Set();
};
Another issue is that you don't check if your wait was satisfied. If 250ms did elapse without a signal, your flag will be false.
See WaitHandle.WaitOne to check what return values you'll receive and update this section of code to handle the case of an unsignaled exit.
// Allow the event to happen
resetEvent.WaitOne(250);
// Check that it worked
Assert.IsTrue(canExecuteChanged,
"OpenDatabaseCommand.CanExecuteChanged should be raised when SelectedDatabase is set");
You can't avoid the RichTextBox's intrinsic behavior to queue up at least one redraw whenever the text changes, but in the code snippet you've provided, you can just set prepare the text out of band instead of calling clear. This will cut the amount of visual activity change to a minimum without having to change it's normal operation. In addition, it looks like you wish to keep the contents the same as the view for your KeyValue set.
Use a StringBuilder to assemble your text before applying it to the RichTextBox, then assign the Text property if there is a difference. If there is no change to the contents of the RichTextBox, it will not redraw everything, which is the source of the flashing behavior that you are seeing.
private void clearRichtextBox()
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords)
{
for (int i = 0; i < kvp.Value.Count(); i++)
{
sb.AppendFormat("Url: {0} --- Localy KeyWord: {1}{2}", kvp.Key,kvp.Value[i],Environment.NewLine);
}
}
string viewString = sb.ToString();
if(viewString != richTextBox2.Text)
{
richTextBox2.Text = viewString;
}
}
Your source JSON is just a single object. Instead of loading into an array, loading straight into a JSONObject should suffice.
JSONObject jsonObject = new JSONObject(builder.toString());
This object will have a single property named ipinfo.
The out keyword (and ref keyword) are used to indicate that a variable is provided from the caller's scope. They don't change the nature of the type in question.
out parameter modifier (C# Reference) @ MSDN
If you're concerned requiring the caller being forced to specify out every time they use your method, you can use a Helper class or a Tuple to wrap the set of values returned.
You mention that you are concerned about reference-types being changed. This shouldn't be an issue to your method. The parameter specified by out is not shared by all cases where your method may used, they're local to the scope where your method is called. Only the caller needs to worry, and only in their own scope.
Last, if you want to indicate that a variable may be altered or used without being required to assign a value to it as out requires, use ref.
Your sample works if you populate a DataSet instead of a DataTable.
Here is a copy of your source with the minimum changes required. Note that when you're using a DataSet you should add code to check whether any tables were returned, and whether there are rows in the first table available, etc.
Caller:
SqlParameter[] Parameters = new SqlParameter[1];
Parameters[0] = new SqlParameter();
Parameters[0].ParameterName = "@TestId";
Parameters[0].Value = TestId;
Parameters[0].SqlDbType = SqlDbType.Int;
Parameters[0].Size = 50;
DataSet data = ExecuteDataSet("ExportTestAsXML", Parameters);
// Read First table (Tables[0]), First Row (Rows[0]), First Column of that Row (Rows[0][0])
System.Diagnostics.Debug.Write(data.Tables[0].Rows[0][0]);
Method:
private DataSet ExecuteDataSet(string storedProcName, SqlParameter[] parameters)
{
SqlCommand command = new SqlCommand();
command.CommandText = storedProcName;
command.Parameters.AddRange(parameters);
command.CommandType = CommandType.StoredProcedure;
command.Connection = (SqlConnection)dcMUPView.Connection;
command.Connection.Open();
command.Prepare();
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet ();
adapter.Fill(ds);
command.Connection.Close();
return ds;
}
The default packing is along 8-byte boundaries, according to the MIDL command line switch reference here:
/Zp switch @ MSDN (MIDL Language Reference)
Other parts of your code are more likely to break first if the pack value is changed, as the IDL file is usually pre-compiled ahead of time, and it is rare that someone will deliberately alter the command line switches given to MIDL (but not so rare that someone could fiddle with the C-scope #pragma pack and forget to restore the default state).
If you have a good reason to alter the setting, you can explicitly set the packing with a pragma pack statement.
pragma Attribute @ MSDN (MIDL Language Reference)
It is pretty good fortune that no party has changed any setting that would interfere with the default packing. Can it go wrong? Yes, if someone goes out of their way to change the defaults.
When using an IDL file, the details are typically compiled into a typelib (.tlb), and it is assumed that the platform are the same for both servers and clients when using the same typelib. This is suggested in the footnotes for the /Zp switch, as certain values will fail against certain non-x86 or 16-bit targets. There can also be 32bit <-> 64bit conversion cases that could cause expectations to break. Unfortunately I don't know if there are even more cases out there, but the defaults do work with minimal fuss.
C# and VB do not have any intrinsic behavior to handle information in a .tlb; instead, a tool like tlbimp is typically used to convert COM definitions into definitions usable from .NET. I can't verify whether all expectations succeed between C#/VB.NET and COM clients and servers; However, I can verify that using a specific pragma setting other than 8 will work if you reference a .tlb that was created from an IDL compiled under that setting. While I wouldn't recommend going against the default pragma pack, here are the steps to perform if you'd like a working example to use as a reference. I created a C++ ATL project and a C# project to check.
Here are the C++ side instructions.
SomeFoo to the project. Again, no defaults were altered. This creates a class called CSomeFoo that is added to your project.ISomeFoo and added a method called FooIt, that takes a struct BarStruct as an [in] parameter called theBar.Here is my IDL for the ATL project.
import "oaidl.idl";
import "ocidl.idl";
[uuid(D2240D8B-EB97-4ACD-AC96-21F2EAFFE100)]
struct BarStruct
{
byte a;
int b;
byte c;
byte d;
};
[
object,
uuid(E6C3E82D-4376-41CD-A0DF-CB9371C0C467),
dual,
nonextensible,
pointer_default(unique)
]
interface ISomeFoo : IDispatch{
[id(1)] HRESULT FooIt([in] struct BarStruct theBar);
};
[
uuid(F15B6312-7C46-4DDC-8D04-9DEA358BD94B),
version(1.0),
]
library SampleATLProjectLib
{
struct BarStruct;
importlib("stdole2.tlb");
[
uuid(930BC9D6-28DF-4851-9703-AFCD1F23CCEF)
]
coclass SomeFoo
{
[default] interface ISomeFoo;
};
};
Inside the CSomeFoo class, here is the implementation for FooIt().
STDMETHODIMP CSomeFoo::FooIt(struct BarStruct theBar)
{
WCHAR buf[1024];
swprintf(buf, L"Size: %d, Values: %d %d %d %d", sizeof(struct BarStruct),
theBar.a, theBar.b, theBar.c, theBar.d);
::MessageBoxW(0, buf, L"FooIt", MB_OK);
return S_OK;
}
Next, on the C# side:
Go to the debug or desired output directory for SampleATLProject and run tlbimp.exe on the .tlb file generated as part of the C++ project output. The following worked for me:
tlbimp SampleATLProject.tlb /out:Foo.dll /namespace:SampleATL.FooStuff
Next, I created a C# console application, and added a reference to Foo.dll to the project.
Foo and turn off Embed Interop Types by setting it to false.SampleATL.FooStuff as given to tlbimp, added the [STAThread] attribute to Main() (the COM apartment models have to match for in-proc consumption), and added some code to call the COM component.Tlbimp.exe (Type Library Importer) @ MSDN
Here is the source code for that console app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SampleATL.FooStuff;
namespace SampleATLProjectConsumer
{
class Program
{
[STAThread]
static void Main(string[] args)
{
BarStruct s;
s.a = 1;
s.b = 127;
s.c = 255;
s.d = 128;
ISomeFoo handler = new SomeFooClass();
handler.FooIt(s);
}
}
}
Finally, it runs and I get a modal popup with the following string displayed:
Size: 12, Values: 1 127 255 128
To be sure that a pragma pack change can be made (as 4/8 byte packing are the most common alignments used), I followed these steps to change it to 1:
Foo, but may disappear if you click on the reference. If it doesn't, you can remove and re-add the reference to the C# console project to be sure it is using the new updated version.I ran it from here and got this output:
Size: 12, Values: 1 1551957760 129 3
That's weird. But, if we forcefully edit the C-level pragma in SampleATLProject_i.h, we get the correct output.
#pragma pack(push, 1)
/* [uuid] */ struct DECLSPEC_UUID("D2240D8B-EB97-4ACD-AC96-21F2EAFFE100") BarStruct
{
byte a;
int b;
byte c;
byte d;
} ;
#pragma pack(pop)
SampleATLProject is recompiled here, no changes to the .tlb or .NET project, and we get the following:
Size: 7, Values: 1 127 255 128
Regarding IDispatch, it depends on whether your client is late-bound. Late-bound clients have to parse the type information side of IDispatch and discern the proper definitions for non-trivial types. The documentation for ITypeInfo and TYPEATTR suggests that it is possible, given that the cbAlignment field provides the information necessary. I suspect most will never alter or go against the defaults, as this would be tedious to debug if things went wrong or if the pack expectations had to change between versions. Also, structures are not typically supported by many scripting clients that can consume IDispatch. One can frequently expect that only the types governed by the IDL oleautomation keyword are supported.
IDispatch interface @ MSDN
IDispatch::GetTypeInfo @ MSDN
ITypeInfo interface @ MSDN
TYPEATTR structure @ MSDN
I don't think there is a trivial way to resolve the actual owner of a Mutex, but the process that owns it can create other secondary items whose lifetimes are tied to it. There are plenty of mechanisms that are suitable for calling back across-process without having a main window.
Here are reference links for the first two options.
MessageBox() has a windows message pump cycle built into it to service window messages.
Somewhere in your application at a very low level within your design, you need a windows message loop to service messages for the window hosting your openGL content. This should run from within the thread that created the window. The ill effects you are seeing in other places could easily be caused by contention side-effects when MessageBox() is invoked from a different thread.
Here is an intro to the operation of window messages at MSDN.
Using Messages and Message Queues @ MSDN
Very simply put (via a code sample from wikipedia), you need a standing loop akin to the following:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
while(GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
Depending on how you have handled updating the window, if you are using paint messages (WM_PAINT), you need to ensure these are dispatched as quickly as possible, or you may need to suppress them entirely if you are drawing direct to the the device DC. I'm mentioning this because you may find additional bugs once a message loop is properly setup.
The sample you've provided doesn't match the members of the class TwitterProfile. Notwithstanding this, you don't need a helper class to handle an array. You can simply target the array type directly at deserialization.
Here's a code sample that you can use to test. I've removed your TwitterProfiles class and stripped down TwitterProfile to just a field named CreatedAt.
Note the following line in the source below:
DataContractJsonSerializer js =
new DataContractJsonSerializer(typeof(TwitterProfile[]));
Here is the rest.
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace TwProfileJson
{
class Program
{
[STAThread]
static void Main(string[] args)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK) { return; }
string json = System.IO.File.ReadAllText(dlg.FileName);
using(MemoryStream stm = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(TwitterProfile[]));
TwitterProfile[] pps = (TwitterProfile[])js.ReadObject(stm);
foreach(TwitterProfile p in pps)
{
Console.WriteLine(p.CreatedAt);
}
}
Console.ReadKey();
}
[DataContract]
public class TwitterProfile
{
[DataMember(Name = "created_at")]
public string CreatedAt { get; set; }
}
}
}
The original specification for COM is old in age, but the specification as well as the concepts are still in use, and you can still create and consume COM objects.
For .NET, you can start by looking at the following links:
Com Interop Part 1: C# Client Tutorial (C#) @ MSDN
Interoperating with unmanaged code @ MSDN
In addition, there are other specs that are very similar to COM or have semantics that are the same. Most notably, XPCOM is in use in FireFox for their plugin spec and also used internally to FireFox to connectable objects.
WinRT is an upcoming platform update for windows that is also heavy in COM concepts.
There are some useful here: Why is WinRT unmanaged @ StackOverflow
For .NET developers, a lot of the declarative overhead is hidden as mentioned here: WinRT demystified - Miguel de Icaza
The head of the spec is here: The Windows Runtime @ MSDN
And in the context of COM, developing WinRT components with C++ has similarities, although some syntax is borrowed from managed C++: Creating Windows Runtime Components in C++ @ MSDN
You were quite close in syntax. The key here is that d["members"] is of type Object[] / object[]. Instead of Array, you can use dynamic[] and everything works just fine.
Also note that even this declaration isn't explicitly necessary, as shown in DPeden's updated sample.
Here is the code for your updated snippet (I used a console app to test):
JavaScriptSerializer js = new JavaScriptSerializer();
dynamic d = js.Deserialize<dynamic>(json);
string key = d["key"];
string status = d["status"];
dynamic[] members = d["members"];
Console.WriteLine("key = {0}", key);
Console.WriteLine("status = {0}", status);
Console.WriteLine("members.length = {0}", members.Length);
Console.WriteLine("members type name = {0}", members.GetType().Name);
Console.WriteLine("d[\"members\"] type name = {0}", d["members"].GetType().Name);
And here is additional code showing array and member access.
Console.WriteLine("--");
for (int i = 0; i < members.Length; i++)
{
Console.WriteLine("members[{0}][\"id\"] = {1}", i, members[i]["id"]);
Console.WriteLine("members[{0}][\"name\"] = {1}", i, members[i]["name"]);
}
Console.WriteLine("--");
Console.WriteLine("{0}", d["members"][0]["id"]);
Console.WriteLine("{0}", d["members"][0]["name"]);
Console.ReadKey();
Added after comment:
You would need to pickup some latent detail that you can exploit to be able to accomplish that goal.
One thing that comes to mind is creating your own Forms/WPF timer at construction time and then use this and some synchronization to hide the details of coordination across threads. We can infer from your sample that construction of your poller should always happen in context of your consumer's thread.
This is a rather hack-ish way to accomplish what you want, but it can accomplish the deed because the construction of your poll-listener happens from the consumer's thread (which has a windows message pump to fuel the dispatches of Forms/WPF timers), and the rest of the operation of the class could occur from any thread as the forms Timer's tick will heartbeat from the original thread. As other comments and answers have noted, it would be best to reassess and fix the operating relationship between your polling operations and the consumer.
Here is an updated version of the class, PollingListener2 that uses a ManualResetEvent and a concealed System.Windows.Forms.Timer to ferry the polling notice across threads. Cleanup code is omitted for the sake of brevity. Requiring the use of IDisposable for explicit cleanup would be recommended in a production version of this class.
public class PollingListener2
{
System.Timers.Timer timer = new System.Timers.Timer(1000);
public event EventHandler<EventArgs> Polled;
System.Windows.Forms.Timer formsTimer;
public System.Threading.ManualResetEvent pollNotice;
public PollingListener2()
{
pollNotice = new System.Threading.ManualResetEvent(false);
formsTimer = new System.Windows.Forms.Timer();
formsTimer.Interval = 100;
formsTimer.Tick += new EventHandler(formsTimer_Tick);
formsTimer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(PollNow);
timer.Start();
}
void formsTimer_Tick(object sender, EventArgs e)
{
if (pollNotice.WaitOne(0))
{
pollNotice.Reset();
var temp = Polled;
if (temp != null)
{
Polled(this, new EventArgs());
}
}
}
void PollNow(object sender, EventArgs e)
{
pollNotice.Set();
}
}
This has some precedent in the distant Win32 past where some people would use hidden windows and the like to maintain one foot in the other thread without requiring the consumer to make any significant changes to their code (sometimes no changes are necessary).
Original:
You could add a member variable on your helper class of type Control or Form and use that as the scope for a BeginInvoke() / Invoke() call on your event dispatch.
Here's a copy of your sample class, modified to behave in this manner.
public class PollingListener
{
System.Timers.Timer timer = new System.Timers.Timer(1000);
public event EventHandler<EventArgs> Polled;
public PollingListener(System.Windows.Forms.Control consumer)
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(PollNow);
timer.Start();
consumerContext = consumer;
}
System.Windows.Forms.Control consumerContext;
void PollNow(object sender, EventArgs e)
{
var temp = Polled;
if ((temp != null) && (null != consumerContext))
{
consumerContext.BeginInvoke(new Action(() =>
{
Polled(this, new EventArgs());
}));
}
}
}
Here's a sample that shows this in action. Run this in debug mode and look at your output to verify that it is working as expected.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listener = new PollingListener(this);
}
PollingListener listener;
private void Form1_Load(object sender, EventArgs e)
{
listener.Polled += new EventHandler<EventArgs>(listener_Poll);
}
void listener_Poll(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("ding.");
}
}
There are multiple ways to parse this; but in the style you've initially presented, you should try accessing it with [] indexers.
Note that your data has a root object with two properties, meta and response. Assuming response can't be null, you can access categories from it directly like this:
var root = JObject.Parse(/* your json string here */);
var categories = root["response"]["categories"];
var firstCategory = categories[0];
Note that you can use strings matching property names to descend into nested levels, and integers to index into arrays in scope.
Here is the rest of a sample program that can parse the json snippet you've provided.
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace _4sqCatResponse
{
class Program
{
[STAThread]
static void Main(string[] args)
{
OpenFileDialog dlg = new OpenFileDialog();
if(dlg.ShowDialog() != DialogResult.OK){return;}
string json = System.IO.File.ReadAllText(dlg.FileName);
var root = JObject.Parse(json);
var categories = root["response"]["categories"];
var firstCategory = categories[0];
Console.WriteLine("id: {0}", firstCategory["id"]);
Console.WriteLine("name: {0}", firstCategory["name"]);
Console.WriteLine("pluralName: {0}", firstCategory["pluralName"]);
Console.WriteLine("shortName: {0}", firstCategory["shortName"]);
var icon = firstCategory["icon"];
Console.WriteLine("icon.prefix: {0}", icon["prefix"]);
Console.WriteLine("icon.sizes[0]: {0}", icon["sizes"][0]);
Console.WriteLine("icon.name: {0}", icon["name"]);
Console.ReadKey();
}
}
}
Also I'm a little confused by your json sample; I think you may have overlaid part of your sample or cut something out as you have categories nested in categories. If there is indeed a 2nd level categories inside your categories element and that's what you want, you can access it with this:
var categories2 = root["response"]["categories"][0]["categories"][0];
Console.WriteLine("inner categories id: {0}", categories2["id"]);
Here is the json source I used to test, copied from yours but with closing } and ] marks where needed to make it parse.
{
"meta": {
"code": 200
},
"response": {
"categories": [{
"id": "4d4b7104d754a06370d81259",
"name": "Arts & Entertainment",
"pluralName": "Arts & Entertainment",
"shortName": "Arts & Entertainment",
"icon": {
"prefix": "https:\/\/foursquare.com\/img\/categories\/arts_entertainment\/default_",
"sizes": [32, 44, 64, 88, 256],
"name": ".png"
},
"categories": [{
"id": "4bf58dd8d48988d1e1931735"
}]
}]
}
}
The byte array arguments to Socket.IOControl() are specific to the IOControlCode that is specified as the first argument.
The first array is for input data, the second array is for output data.
To find more information about the specific layout for these arrays, it is helpful to start by looking at the enumeration, which lists all the possible operations for you. From there, you should cross reference with the documentation listed for the C-operable functions that Socket.IOControl() wraps. These are WSAIoctl() and ioctlsocket().
IOControlCode Enumeration @ MSDN
WSAIoctl() function @ MSDN
ioctlsocket() function @ MSDN
Per the documentation for IOControlCode.ReceiveAll:
Enable receiving all IPv4 packets on the network. The socket must have address family InterNetwork, the socket type must be Raw, and the protocol type must be IP. The current user must belong to the Administrators group on the local computer, and the socket must be bound to a specific port. This control code is supported on Windows 2000 and later operating systems. This value is equal to the Winsock 2 SIO_RCVALL constant.
Cross referencing SIO_RCVALL, we find it has an entry in the winsock documentation.
SIO_RCVALL control code @ MSDN
Reading through this entry, it mentions that the input buffer is required to select a mode of operation, with minimum size corresponding to a RCVALL_VALUE. In your statement you are passing the value 1 in the input argument array. We can check header files to see what this should mean.
You should double check this with C header files at hand, but the interface-compatible copy for wine (windows emulator) says the value for mode RCVALL_ON is 1. The .NET method should wrap the details of managing array size for you, so the code snippet you encountered is trying to enable RCVALL_ON for the socket.
Here is the link to the C header file at winehq.org: mstcpip.h at winehq.org
If you've installed C/C++ support for visual studio, you may be able to locate mstcpip.h and winsock2.h locally at a path similar to the following:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\
My copy says:
//
// Values for use with SIO_RCVALL* options
//
typedef enum {
RCVALL_OFF = 0,
RCVALL_ON = 1,
RCVALL_SOCKETLEVELONLY = 2,
RCVALL_IPLEVEL = 3,
} RCVALL_VALUE, *PRCVALL_VALUE;
I couldn't find any documentation that specifically says what size byte array should be used to pass a RCVALL_VALUE, but if you look at the the samples for IOControl(), they use BitConverter.GetBytes(0) for default parameters which would have a size of 4 bytes (corresponding to a .NET int) and matches your example. This is large enough to fit a RCVALL_VALUE in C operation as well.
if there is any chance name is null, then you would have to do: object o = d["members"][i]["name"];
string name = null == o ? null : (string)o;, but otherwise, (string)(d["members"][i]["name"]) works
System.Runtime.Caching is an alternative
Aha, valid point. Automapper is quite well tested; most would skip testing the mapping feature or would just check the results after assignment. If you want tests to cover customized behavior (ValueResolvers, etc.), you could cover those in separate tests targeting only the assumptions that rely on features in Automapper.
I suppose I'm missing other details that are not shown here for the PeriodListViewModel. Could you explain what makes this solution untestable? Also, I agree that there isn't much benefit to using Automapper for only 5 properties; the benefits by LoC measure don't accrue until you have two projections to cover between compatible classes/interfaces; it appears to me that you might only get value out of mappings into RowViewModels and RowViewModel to RowViewModel.
For the reverse, you could write a model that contains a IEnumerable<Period> that can be instantiated from a PeriodListViewModel or IEnumerable<CellViewModel> (note that List<> can be treated as IList<> which derives from IEnumerable<>). One problem, though, is that your RowViewModel doesn't have close correspondence to a Period. If this isn't a problem (perhaps you only intend to make new Period items from the partial information in a set of RowViewModels), you can still use Automapper as a means to project data back, just setup a reverse mapping as you see fit.
The ValueResolver classes are a bit of overhead; but if you're using Automapper, that should already be a tradeoff you're willing to make in the hopes of spending less time writing and verifying code. Also, while you can write adapters manually on a class-relation basis, using Automapper's facilities allows you to write just the one line of mapping code when you need the projection. As many things are in programming, you can perform the same action in many ways; but Automapper's main advantage is the ability to be brief when performing projection, at the cost of being verbose in preparation.
Is there any specific benefit that mandates using a TextBox? You would probably be better served by a DataGridView, or at the very least, a ListBox with tab-columns. See msdn.microsoft.com/en-us/library/… and msdn.microsoft.com/en-us/library/…
+1, also it appears HttpRuntime.CodegenDir is the proper base path in System.Web.dll 4.0.30319, not HttpRuntime.CodegenDirInternal
it is still worth going over the service dispatcher code, at the very least to log what the thread ID is of the thread that responds to each of the messages. you could potentially reveal a race between that thread and other worker threads or an idle state at service close.
What is the method signature or SOAP packet expected by the C# endpoint?
Also, you could use a Dictionary or HashSet to track the tags that are present.
There's a property named Tag that you can read/write as a moniker to identify controls, which coincidentally is perfect for your purposes. See Control.Tag at: msdn.microsoft.com/en-us/library/…
should note that the values the OP wants will be enumerable from result.Files.Keys
Given your comment to the reporting solution comment on your question, I should warn you that the persistence store that ships with WF relies on MS SQL Server, which may be a dealbreaker for your company. It might be worth seeing if you can get MSDE working as a persistence store to avoid having to setup a MSSQL instance.
Labels support the MouseClick event implemented by Control, so if you add a handler for it, you can add a context-specific version for your tag control. See: msdn.microsoft.com/en-us/library/…
The folks at Ch9 have just released (today) a video announcing details on a computing appliance for Azure.
Some time ago, when Azure was first announced, I spoke with a number of colleagues about whether this would work out for Microsoft. There seemed to be some trepidation about whether it would be worth targeting Azure, as it is essentially a new OS and platform to support.
I felt it had some merit, until I looked at the cost. Ouch. The only competitor with higher operating cost was Amazon. But, it does allow most windows developers to continute to write code to something familiar. Perhaps if it were possible to host Azure on-site, this would have a lot of value to developers.
One thing that isn’t mentioned in the video on Ch9, is how the Azure box will be setup. I don’t think people will settle for single units. Also, it would be huge if the boxes can be scaled horizontally by merely adding more to a group and deploying (within reasonable limits).
I can definitely see some of these being purchased for testing purposes, if the price of the box is low enough. It seems debatable whether local use is also worthwhile against the compute/traffic cost.
Finally, the failover abstraction may be lost if one does switch to local hosting. This may not be a big deal for people who are wary of things such as PCI/PABP compliance; as they have a lot of hurdles to conquer to be able to use cloud hosting. But, some of those who actually need the abstraction over any other benefits may fool themselves into thinking they don’t. The number of nines of uptime possible with a local solution remains to be seen.
Sometime this summer, use of Basic Authentication with the twitter API will be coming to an end. During the transition period, all of the third-party services that delegate calls have to stop using Basic Auth and will now have to use OAuth Echo for authorization.
Fortunately, OAuth Echo is pretty straightforward, with two catches that aren’t initially obvious but trivial to overcome. For reference, here is a link to the documentation of twitpic’s upload method.
http://dev.twitpic.com/docs/2/upload/
The two required headers are X-Verify-Credentials-Authorization and X-Auth-Service-Provider. The verify-credentials header is the same as a properly signed Authorization header pointed at the auth-service endpoint at twitter.
Herein lies the first snag that caught me. The current value used by twitpic is the following (not a clickable link):
https://api.twitter.com/1/account/verify_credentials.json
When signing the string for OAuth Echo, the URL you send in should be this, not the endpoint for twitpic (not https://api.twitpic.com/2/upload.json ).
The second snag that caught me was the HTTP method call. Calls to verify_credentials at twitter are GET, but calls to upload at twitpic are POST. The generated OAuth signature should use GET.
At first this didn’t make sense to me, but after some muddling about, I realize that this is about the easiest way for twitter’s third parties to be delegated control over a single call. The OAuth signature ensures that the only thing they can do at twitter is lookup credentials, and the middleman (twitpic) already has the work of generating the signature done for them by the client. The only thing that twitpic or others would have to do is copy the verify-credentials header into the authorization header when making the checkup call to twitter.
This is hardly just the first chapter, though, in what I expect will be further adventures in OAuth. The other, more important, API call at twitpic is the uploadAndPost call. This call, I speculate, is the root of where a ton of their homefront traffic is eventually generated. Right now, there is no equivalent OAuth Echo procedure that can allow twitpic to post to twitter. I’d imagine it isn’t too much effort (if any at all) to allow the twitter update-status method to be the target of the auth-service provider.
Some possible hijinks stand out with that particular method. One, is that the delegate may not necessarily be 100% trusted. Since the signer has already created a valid access token, the delegate could post content as it sees fit for that one call. It is unlikely anyone would do this, as that would open up a breach in trust, possibly causing them to lose access to twitter. There are some high-follow accounts where it may be worth it to a malicious insider to attempt this once, though.
Another potential issue is in error handling. Because a delegate is being used, the caller may be misinformed in a number of scenarios. The first is if twitter reports an error but succeeds, causing the delegate to report an error on the relayed call. The second is if the delegate fails internally after a call to twitter, leaving the potential result completely unknown to the caller. In recent times, under load, there have been gateway errors reported by twitter while API calls were actually succeeding; fortunately there were only two nights (that I recall) where this resulted in double-posts.
Last, it is unknown whether it will be possible to delegate by a single call to cover cases where the delegate needs to make several calls to the twitter api in a single unit of work. This will probably open up a number of questions as to whose API limit pays for the calls. I haven’t checked the results of rate-limit-headers yet, but I would guess that the client’s tally pays for the expense. This may not be good for delegates if they are performing tasks that might significantly cut into the caller’s hourly limit, which might make some clients wary of using their services.
My best friend, who is also a developer/engineer, asked me today if there were any VS add-ons that I’d ever dreamed of creating.
Well, to be honest, I’ve spent a lot of time in the past, writhing and bitter over broken Macro projects that no longer worked between versions of Visual Studio. And thus, given up on trying to extend the environment to suit me. One thing, though, stands out as something that I think would be useful. I’ve always wanted to be able to right-click on any project/file/solution item; and go to the physical location where that item is stored.
My friend feels this is useful as well. But, he warned, what about the case of temporary projects?
Whoa, hold the presses, temporary projects?
A little bit of digging, and sure enough, temporary projects that may be thrown away are a new feature in VS2010.
I have some reservations about this feature. It isn’t that much work to make a throwaway project. Also, I usually have an extra prototype-only solution open that I use for reference. Not really impressed, here.
Well, as they say, a rising tide lifts all boats. Maybe it is just too hard to preach a good workflow to the developer masses. I’m sure there are many things that I’ve missed out on; but I do try to keep my eyes and ears open to new things that make me better. My friend and I agree, though, that sometimes there is too much effort spent on features that demo well; but haven’t added real value to those who get things done.
Someday, I hope my VS plugin exists, whether via add-on or native integration. I think I would pay for someone else to make it for me, too. I also think people would find it useful, when importing files extraneous to VS; like unit test-case data.
I’ve been working on writing a library that provides functionality using fluent syntax, as a practice exercise. During the course of mapping an existing prototype into the syntax, I came across a rather bizarre bit of .NET language functionality.
In .NET, it is well known by now to any ASP.NET or Forms developer that you can have partial classes, where the body of the class’s source is split up among a number of locations. Similarly, an interface and structure may be declared using the partial keyword with the same segmentation as well.
In C# 3.0, lesser known, is the fact that you may also declare partial methods, where the body is defined in one place, and the declaration in another. These appear to act as forward declarations in C/C++. But in .NET they are restricted, as any partial method must return void.
This seems strange to me, but in digging through some articles written by other people, it became clear the body of the function doesn’t necessarily need to be defined. How bizarre. But, with this capability, things make sense. These partial methods now become optional- if an implementation exists, it will be called. If not, then they won’t. One of the blog articles I read, points out that this is similar to how conditional methods are supported.
http://bartdesmet.net/blogs/bart/archive/2007/07/28/c-3-0-partial-methods-what-why-and-how.aspx
Partial methods must return void because no action occurs if there is no body, and no return value can exist if there is no implementation.
In all, this is a rather curious thing, but I think this has some decent uses. The first thing that comes to mind is the creation of logging stubs. If the logging methods are present, they get called. If not, then no action. I don’t know if this is necessarily better than conditional compilation, but the ability to defer the actual handling would be nice. Separation of Concerns, as usual.
Found a few more interesting things in the past week.
SortedSet - Sorted version of HashSet, which should allow you to do foreach() on items with a determinate order. Regarding LINQ, this is a good alternative to doing a Take() on the first N after a sortby, as you can avoid repeating the LINQ query over and over, especially if the taken portion is not necessarily the same amount each time, and if the data set is always the same group.
Here’s the link:
http://msdn.microsoft.com/en-us/library/dd412070.aspx (SortedSet)
System.Numerics - A namespace containing two new classes, BigInteger, and Complex (complex numbers).
BigInteger is .NET’s native arbitrary-precision integer class, while Complex is a complex number class (a + bi).
Here are the links to each:
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx (BigInteger)
http://msdn.microsoft.com/en-us/library/system.numerics.complex.aspx (Complex)
Finally, parallel extensions to LINQ are pretty sweet. My current favorite is ForAll(), which significantly reduces the amount of code to run heavyweight processing of items on a list in parallel fashion. This is incredibly powerful, given that you can also write a lambda / anonymous method in place for the Action() parameter.
http://msdn.microsoft.com/en-us/library/dd383744.aspx (ParallelEnumerable.ForAll())
Haven’t tested this out just yet, but it compiles, and while i’m sure there is a better way of doing this, I spent more time thinking about the implications than I did on writing the actual code.
Ready? Check this out.
public class ChannelMultiplex
{
public static IEnumerable<Tuple<short, short>> MonoToStereo(IEnumerable<short> source)
{
foreach (short sample in source)
{
yield return new Tuple<short, short>(sample, sample);
}
}
}
Too easy, right? Of course, this probably isn’t going to run very fast. But nonetheless… I <3 you Tuple<>.
1. WPF Text rendering is gorgeous
2. VS2010 is pretty. Superfluous, but other than that, no complaints here.
3. DispatchTimer feels different. Seems that AppIdle priority really means when the application is idle, not when the message queue is empty. Had to adjust for this.
Also, I can’t really make any claim to this, but using ThreadPool feels different too.
I look forward to trying out the DLR languages as well.
This is not as accurate as putting a Stopwatch in your source code, but for quick and dirty profiling, good enough. I feel it is handy to be able to /abuse/use/ using() semantics for this scenario. I think this could also be improved by adding another constructor that takes a delegate to handle printing out the timer element; or perhaps a delegate to a given logging method of choice.
Syntax is straightforward.
using(new AutoTimer())
{
// do stuff here
}
using(new AutoTimer(“working in fn()”))
{
// stuff that allegedly is inside of fn()
}
One drawback is that the using() semantics become overhead even if you #ifdef away code for non-debug builds. I might be wrong about that, though. I’m sure someone with more knowledge than me can figure out a way for the using() block to be optimized away for a retail build.
quick and dirty converter that calls blip.fm’s api to pickup recent blips from a user.
some notes:
only plucks the most recent 25
embeds youtube players if the content was sourced from youtube
silverlight support redacted, as i was unable to source the xap from my domain and use it on flavors.me
individual song links on blip.fm are not documented, but the following URL layout works, replace USERNAME and BLIPID with respective items from the api
-> http://blip.fm/profile/USERNAME/blip/BLIPID
i used a stringbuilder because the output size is pretty small, and if the handler dies, i can still override the output and set the content type too.
REF: http://api.blip.fm/
see the results in action here: http://flavors.me/meklarian
I’ve been thinking… there really isn’t a metafile format out there for WPF or Silverlight. While Processing wouldn’t cover all the bases, it would certainly do enough to allow people to program meta-elements for the canvas tag.
Just a thought.
All things have representation.
There’s really nothing groundbreaking about it. However, if you keep this line in mind and close to your heart, all things are possible.
What is data?
Bytes.
What does it look like in memory?
00 01 02 03 04 05 … if you’re looking at bytewise hex values. Is it in endian order? Some bytes may be swapped about, if this is the case.
How do I get it from point A to point B?
Well, this depends. Here is where you need to remember a couple things.
Is it text? What is the character set? Is it numeric data? Is it arbitrary blobs?
Ultimately, all data is transferred with a wrapper of some kind.
In the old days, these wrappers were headers. Usually length, followed by data.
Now we have XML. JSON. All still wrappers.
Then there are wires. Serial cables. Ethernet. Internet.
Why does this matter?
This matters because no matter what programming language, what operating system, whatever computer is in use; to date, they all must store data in some form somewhere. Bytes. Formatting.
If you remember that all things are mere bytes, then you may start from anywhere by looking up what it should look like, how you can manipulate it, how you can transfer it, how you can display it.
Exitmusic - "The Hours" (Official Video) ♫ blipped by meklarian
El Ten Eleven - Every Direction is North ♫ blipped by meklarian
Luke Chable - Skyline Road (Original Mix) ♫ blipped by meklarian
The Decemberists - Calamity Song ♫ blipped by meklarian
Miles Davis & John Coltrane - Kind of blue ♫ blipped by meklarian
(blue in green)
The War on Drugs - "Come to the City" (Official Video) ♫ blipped by meklarian
via [reply]idlewild577[/reply]
- The Octopus Project- Hallucinists ♫ blipped by meklarian
- Looking for Astronauts, The National ♫ blipped by meklarian
Nina Semone - I Shall Be Released - garlandgrey ♫ blipped by meklarian
via [reply]bildungsroman[/reply]: "Nina Simone singing Dylan. Beautiful."
Pepper Rabbit - Harvest Moon ♫ blipped by meklarian
via [reply]orangekittypie[/reply]
Film School - Heart Full Of Pentagons ♫ blipped by meklarian
via [reply]orangekittypie[/reply]
- Nicola Conte: Jazz Pour Dadine ♫ blipped by meklarian
The Last Shadow Puppets - My Mistakes Were Made For You ♫ blipped by meklarian
noofficialmusic - Black Gold by Foals ♫ blipped by meklarian
Generationals - Ten-Twenty-Ten ♫ blipped by meklarian
via [reply]orangekittypie[/reply]