You are here

Feed aggregator

修改域密码后对Windows Azure Pack 的影响和解决办法(虚拟机云)

MSDN Blogs - 8 hours 13 min ago

在Windows Azure Pack (后简称WAP)的实际使用场景中我们无法避免的会遇到各种密码到期需要更改的情况。而在WAP的环境中又有许多的组件都依赖于域密码,那么究竟改动一次密码后会有多大影响我们来做一个测试。

 

在我的测试环境中我使用BC-TEST\WAPadmin作为所有组件的管理员密码(包括:Admin Site ; SCVMM ; SPF ; Automation;SQL)

在确保Windows Azure Pack 当前运行状态正常的前提下,我将WAPadmin的密码更改.(如下图)

之后我再次登录和检查了WAP admin site , SCVMM admin Console ,SQL server都可以正常登录和使用,由此可见大部分的组件是支持和DC同步密码的。

而问题主要出现在Automation(自动化) 组件上有报错。(如下图)尝试在Admin Site直接更改Automation信息时会发现:Automation 组件无法选择而通过VM 云进入的Automation 注册界面为灰色无法更改。

 

解决方法

我们需要强制移除当前SMA(Service Management Automation)的信息,并再将它重新注册到Admin Site 内。

参照博客 http://kristiannese.blogspot.no/2014/01/troubleshooting-windows-azure-pack-re.html 我们可以在WAP服务器运行下列几步Power Shell 命令来解决这个问题:

 

1.    $Credential = Get-Credential   (输入后会弹出需要输入当前管理员帐号密码的需求,如下图)

2. $Token = Get-MgmtSvcToken -Type Windows -AuthenticationSite https://请输入当前WAP portal 的地址:30072 -ClientRealm http://azureservices/AdminSite -User $Credential -DisableCertificateValidation   

    Get-MgmtSvcResourceProvider -AdminUri "https://localhost:30004"-Token $Token -DisableCertificateValidation -name "Automation"  

     命令执行成功后请记录下图中的Instance ID 用于下一条命令

3. Remove-MgmtSvcResourceProvider -AdminUri "https://localhost:30004" -Token $Token -DisableCertificateValidation -Name "Automation" -InstanceId "将上条命令中得到的Instance ID 填入此"

   命令成功执行后按照提示(如下图)选择 Y 之后即可成功移除SMA组件

之后我们回到WAP的 Admin Site 检查状态,可以看到Automation的红色惊叹号报错已经消失,并出现了可以注册新的SMA终结点的选项。

  

5. 重新注册并输入新的密码之后故障排除。

 

 

 

 

 

 

 

Connect Cloudera to Azure ML Hive Reader

MSDN Blogs - Fri, 07/03/2015 - 18:33

Azure Machine Learning supports Hive as a data source using WebHCat API.  In this post, I will show you how to configure Cloudera to connect to Azure ML through WebHCat.  These steps have been verified on a Cloudera cluster created from Azure Marketplace.  If you don't already have a cluster, you can follow this blog post to deploy one.  We will use Cloudera Manager to configure the cluster.     

Step 1: Enable WebHCat 

By default, Cloudera cluster created from Azure Marketplace doesn't have WebHCat enabled.  To enable it, go to Cloudera Manager, select Hive, and Add Role Instances:

 You can see WebHCat server doesn't have a host, so click Select Hosts:

 

Follow the wizard to select a host, and start the WebHCat server.  

Step 2: Expose WebHCat Endpoint

In order to run Hive queries, we need to configure the Azure VM endpoint to expose WebHCat.  To do this, login to the Azure Portal, select the VM that's running WebHCat server, then go to the ENDPOINTS tab to add an endpoint.  By default, WebHCat runs on 50111.  You can choose a public port that's different from the private port.  But for simplicity, we will keep them same here:

Now we can run DDL commands using WebHCat.  For example, to list Hive databases, run:

http://<webhcatserver>.cloudapp.net:50111/templeton/v1/ddl/database?user.name=hdfs

To list tables in the default database, run:

http://<webhcatserver>.cloudapp.net:50111/templeton/v1/ddl/database/default/table?user.name=hdfs

However, we are not able to run Hive queries yet.  This is because the default WebHCat configuration includes jars that are not in the Cloudera cluster environment, and Hive meta store URIs need to be updated.   

Step 3: Configure WebHCat

To update WebHCat configuration, go to Cloudera Manager, select Hive, Configuration, and type "webhcat" in the Search box to narrow down the configuration.  Update "WebHCat Server Advanced Configuration Snippet (Safety Valve) for webhcat-site.xml" section as following: 

The configuration should include the following.  Note that the settings here correspond to the Cloudera environment deployed by Azure Marketplace, if you are using a different cluster, you might need to adjust the settings to match your cluster.

<property>
    <name>templeton.libjars</name>
    <value>/opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper.jar</value>
    <description>Jars to add to the classpath.</description>
</property>
<property>
    <name>templeton.hive.path</name>
    <value>/opt/cloudera/parcels/CDH/lib/hive/bin/hive</value>
    <description>The path to the Hive executable.</description>
</property>
<property>
    <name>templeton.hive.properties</name>
    <value>hive.metastore.uris=thrift://<hivemetastoreserver>:9083</value>
    <description>Properties to set when running hive.</description>
</property>

After the configuration is updated, restart WebHCat server for the update to take effect.  Now, we should be able to run Hive queries via WebHCat. For example, to select all rows from table "example1" in the default database, run:

curl -s -d user.name=hdfs -d execute="select+*+from+default.example1;" 'http://<webhcatserver>.cloudapp.net:50111/templeton/v1/hive'

WebHCat writes its job output to /templeton-hadoop, so Hive user must have access to this hdfs folder.  You can go to Hadoop UI or Hue to view the job status. 

Step 4: Connect to Azure ML

Log in to Azure ML Studio, click on your Reader module, and select "Hive Query".  Configure Hive as following with your own WebHCat server URL, HDFS user, and HDFS Server URL:

Run the experiment, and verify that the result of the job is written to /user/hive/warehouse/ in HDFS:

Azure ML also logs job status to /DataLabReaderStore:

Updates to ASP.NET 5 yeoman generators for beta 5

MSDN Blogs - Fri, 07/03/2015 - 16:39

Hi everyone the blog post below is written by Peter Blazejewicz, who is a core contributor to the yeoman generators for ASP.NET 5. Peter took care of the majority of the updates for beta 5. I hope you enjoy, please leave your thoughts below in the comments.

Hi folks!

This week marks the release of ASP.NET 5 Beta5 and the related update to Yeoman generator for ASP.NET 5! There are many new things that are introduced to ASP.NET 5 generator with this update, both to client and server side. Here is the list of the most important additions:

  • New simple Web MVC application project template (without Membership and Authorization)
  • AngularJS 1.* templates
  • React template
  • TypeScript templates updates
  • CSS/Less/SCSS templates
  • Interface, Middleware, TagHelper templates

Nearly all existing templates have been updated, rewritten and revised during beta5 development. We have also expanded tests to cover nearly all content generation by generator too!.

Here's an animated gif showing yo aspnet in action on Mac OSX.

There are also changes in how templates are organized within the project, we use the same files structure now both in template content and in generated content, we unified files and subgenerators names and character-case. There is a simple pattern used during subgenerator implementation, which we hope will be easy to follow. As we changed templates organization, the futures changes and upgrades are expected to be easier to add and develop.

We hope this will ease contribution to the project - and we have already received PRs after beta5 update <3!

If you want to shape future of ASP.NET with us, help us by submitting issue or just discussing a topic and adding your own contribution to the project.

In case you missed them we have blogged on the ASP.NET 5 yo generators in the past.

Thanks!
Peter Blazejewicz

Freakonomics by Steven Levitt and Stephen Dubner

MSDN Blogs - Fri, 07/03/2015 - 15:46

This post originally appeared on my old blog, dirtyDogStink, which has since been removed. I'm adding it here for reference purposes.

 

Freakonomics by Steven Levitt and Stephen Dubner

I could not believe how fast this book read. I started it last Thursday and finished it Saturday afternoon. Especially for a book on economics...I am completely astounded at how easy this was to read and comprehend. The authors have a great knack for taking the complicated and translating it into layman's terms that make sense and deliver their points succinctly. Economics is not the sexiest topic nor is it the easiest to comprehend, but the two Steves actually made it interesting and thought provoking.

Just look at these chapter titles, does this sound like an economics book?

  1. What Do Schoolteachers and Sumo Wrestlers Have in Common?
  2. How is the Ku Klux Klan Like a Group of Real-Estate Agents?
  3. Why Do Drug Dealers Still Live with Their Moms?
  4. Where Have All the Ciminals Gone?
  5. What Makes a Perfect Parent?
  6. Perfect Parenting, Part II; or: Would a Roshanda by Any Other Name Smell as Sweet?

 

Here are some interesting pieces of information taken from the book:

  • "There are enough guns in the United States that if you gave one to every adult, you would run out of adults before you ran out of guns. Nearly two-thirds of U.S. homicides involve a gun, a far greater fraction than in other industrialized countries. Our homicide rate is also much higher than in those countries....In Switzerland, every adult male is issued an assault rifle for militia duty and is allowed to keep the gun at home. On a per capita basis, Switzerland has more firearms than just about any other country, and yet it is one of the safest places in the world. In other words, guns do not cause crime."
  • "Cheating is a primordial economic act: getting more for less....Consider what happened one spring evening at midnight in 1987: seven million American children suddenly disappeared....It was the night of April15, and the Internal Revenue Service had just changed a rule. Instead of merely listing each dependent child, tax filers were now required to provide a Social Security number for each child. Suddenly, seven million children...vanished, representing about one in ten of all dependent children in the United States."
  • "Had the Internet been around when Kennedy infiltrated the Klan, he probably would have rushed home after each meeting and blogged his brains out." This one made me laugh-out-loud. 
  • "If you were to assume that many experts use their information to your detriment, you'd be right. Experts depend on the fact that you don't have the information they do. Or that you are so befuddled by the complexity of their operation that you wouldn't know what to do with the information if you had it. Or that you are so in awe of their expertise that you wouldn't dare challenge them."
  • "Listed below are ten terms commonly used in real-estate ads. Five of them have strong positive correlation to the ultimate sales price, and five have a strong negative correlation....Higher Sales Price: Granite, State-of-the-Art, Corian, Maple, Gourmet.... Lower Sales Price: Fantastic, Spacious, !, Charming, Great Neighborhood....
  • "Consider the parents of an eight-year-old girl named, say, Molly. Her two best friends, Amy and Imani, each live nearby. Molly's parents know that Amy's parents keep a gun in their house, so they have forbidden Molly to play there. Instead, Molly spends a lot of time at Imani's house, which has a swimming pool in the backyard. Molly's parents feel good about having made such a smart choice to protect their daughter....The likelihood of death by pool (1 in 11,000) versus death by gun (1 in 1 million-plus) isn't even close: Molly is roughly 100 times more likely to die in a swimming accident at Imani's house than in gunplay at Amy's."
  • "Compare the four hundred lives that a few swimming pool precautions might save to the number of lives saved by far noisier crusades: child-resistant packaging (an estimated fifty lives a year), flame-retardant pajamas (ten lives), keeping children away from airbags in cars (fewer than five young children a year have been killed by airbags since their introduction), and safety drawstrings on children's clothing (two lives)."
  • "Fryer cites the recollections of a young Kareem Abdul-Jabbar, known then as Lew Alcindor, who had just entered the fourth grade in a new school and discovered that he was a better reader than even the seventh graders: 'When the kids found this out, I became a target....It was my first time away from home, my first experience in an all-black situation, and I found myself being punished for everything I'd ever been taught was right. I got all A's and was hated for it; I spoke correctly and was called a punk. I had to learn a new language simply to be able to deal with the threats. I had good manners and was a good little boy and paid for it with my hide.'" This is taken out of a section discussing the black-white income and education gaps and I simply found Kareem's experience with discrimination interesting.
  • "...a child with many books in his home has indeed been found to do well on school tests. But regularly reading to a child doesn't affect test scores." I found this particularly interesting and his explanation is way too long to put here...so go read it. 

This quote sums up the book nicely: "What this book is about is stripping a layer or two from the surface of modern life and seeing what is happening underneath."

Update: I forgot to add that the authors have a blog [and it is posted to regularly] at Freakonomics.com.

~tod

Getting Things Done by David Allen

MSDN Blogs - Fri, 07/03/2015 - 15:40

This post originally appeared on my old blog, dirtyDogStink, which has since been removed. I'm adding it here for reference purposes.

 

  

Getting Things Done: The Art of Stress-Free Productivity by David Allen

A month or more ago I attended a day-long class about improving my productivity through organizing my tasks and information in Outlook.  In fact, I discuss getting my email organized with the 4 Ds using the techniques from the class. I'm really digging it. I decided to take the class a few steps further and see what else I can do in my life to get more organized so I went to our group's organizational expert [hi Ed!] for some advice. He pointed me in the direction of David Allen so I picked up Getting Things Done and started reading. 

I liked it and found a lot of value. Honestly, it was another pretty easy read. I didn't do too many of [read that as 'none of'] the exercises in the book and was able to finish it in less than a week. I figured with my first read through I would just try to digest the overall concepts and then see where/how I could fit them into my life. It helped solidify several of the concepts I pulled out of the day-long class.

As is my custom, here are some specific areas that I found interesting and helpful:

  • Allen bases his methodology on two key objectives:
    • "capturing all the things that need to get done -- now, later, someday, big, little, or in between -- into a logical and trusted system outside of your head and off your mind"
    • "disciplining yourself to make front-end decisions about all of the 'inputs' you let into your life so that you'll always have a plan for 'next actions' that you can implement or renegotiate at any moment"
    • Both of these objectives really rang true for me. I have always been organized, but with a bad habit of procrastinating with my decisions. Forcing myself to make decisions up front [like applying the 4 Ds when processing email] has been a tremendously positive change.
  • "if it's on your mind, your mind isn't clear." Allen discusses a zen-like approach to clarity of thought and how it leads to drastic advances in our thought processes. The gist of it is that if your mind is freed from having to keep track of grocery lists, project to-dos, meeting reminders, etc. then you can let it work on the bigger issues in your life like how to design a new product or what it really might take for you to go on that dream vacation to Europe. If you write it down (physically or electronically) and store it somewhere you trust, the mental benefits/gains are exponential.
  • "The big difference between what I do and what others do is that I capture and organize 100 percent of my 'stuff' in and with objective tools at  hand, not in my mind. And that applies to everything -- little or big, personal or professional, urgent or not. Everything." - I have started doing this using Outlook tasks and it really is refreshing to know that I have one place to go whenever I need to look up notes, lists or next-actions. It takes a certain amount of discipline to capture everything, as David does, but it really is liberating after awhile.
  • "What's the Next Action? ... The 'next action' is the next physical, visible activity that needs to be engaged in, in order to move the current reality toward completion." - This is often an elusive thing when dealing with projects or even worse, multiple projects at the same time. Simplifying a project down to the single next action that needs to take place in order to move forward can provide clear direction...not only for yourself, but others you are working with. I see way too many project meetings that end without any clear action items and these are the projects that inevitably stall and then fizzle into nothing. Months later you find yourself asking someone 'whatever happened to project X?' Ugh.
  • The Natural Planning Model -
    1. Defining purpose and principles
    2. Outcome visioning
    3. Brainstorming
    4. Organizing
    5. Identifying next actions
    • I see so many projects that exclude, ignore or forget one or more of these pieces and they always seem so unorganized. In fact, just a few weeks ago I was in a 3 hour meeting that included loads of brainstorming.  Early in the meeting I became confused [I am a late-comer to the project] and asked for # 1 or 2 above to give me some clarity. I got blank stares in return. D'oh! How can we effectively brainstorm a design or concept if we don't even know what the purpose and vision are?
  • Don't be afraid to ask why. Why are we meeting? Why am I in this meeting? Why are we trying to accomplish this? Why do the requestors think they need this solution? Yada-yada-yada... Here are Allen's listed benefits of asking "why?" and I couldn't agree more:
    • It defines success.
    • It creates decision-making criteria.
    • It aligns resources.
    • It motivates.
    • It clarifies focus.
    • It expands options.
  • Mind-mapping as a brainstorming exercise. This looks pretty interesting.
  • Filing systems: "the lack of a good general-reference system can be one of the greatest obstacles to implementing a personal management system, and for more of the executives I have personally coached, it represents one of the biggest opportunities for improvement." - I'm a pack-rat when it comes to documents and such. I had a huge file cabinet full of stuff going back 20+ years. A lot of it was irrelevant, but more importantly it was filed very inefficiently. The system only made sense to me and was cumbersome. In a nutshell, Allen recommends making your filing system as simple as possible. Start with a simple set of folders labeled A-Z and only make specific-labeled folders for those things you need. So I spent a weekend purging my files and re-organizing them. Not only was I able to shred 65% of the files, but I simplified the system so that everything is easy to find. Bills are under B instead of a separate folder for each company, house information is in H, medical stuff is under M, etc. That was a big monkey off my back. 
  • Organizing action reminders - I'm still working this one out to find a way that works well for me, but Allen gives a lot of good suggestions. Basically, if something needs to be done on a certain date/time then put it on your calendar. Other next actions should be organized by context, whatever context makes the most sense to you (phone calls, errands, office, read/review, at computer, etc.).
  • Weekly review - Probably one of the most important aspects to implementing Allen's system! Once you start collecting all of your thoughts/ideas/actions in a trusted place you need to review them regularly so they're not missed. The weekly review is one such point-in-time where you spend a few hours organizing the loose things (email, papers, notes, lists, etc.), reviewing your next actions, clearing your mind and double-checking yourself. Here are the things that Allen suggests for a weekly review:
    • Process all loose papers.
    • Process your notes from journal entries, meetings or scribbled reminders.
    • Review past calendar dates for remaining action items, reference information, etc.
    • Look at future calendar events for any prep work you might need to do.
    • Clear your mind by writing down all of your project ideas, action items, etc.
    • Evaluate your projects for status and any action items.
    • Review your lists (next actions, waiting for, someday/maybe) for any items that can be marked as finished or needs to be updated.
  • "Your negative feelings are simply the result of breaking those agreements." Allen is referring to our agreements with ourselves when we have something in our 'inbox' or tell ourselves we will do something, but then we don't complete it. "If you tell yourself to draft a strategic plan, when you don't do it, you'll feel bad. Tell yourself to get organized, and if you fail to, welcome to guilt and frustration." We are our own worst critic, right?

Interesting quotes from the book:

  • It is hard to fight an enemy who has outposts in your head. - Sally Kempton
  • It does not take much strength to do things, but it requires a great deal of strength to decide what to do. - Elbert Hubbard
  • Fanaticism consists of redoubling your efforts when you have forgotten your aim. - George Santayana
  • The best way to get a good idea is to get lots of ideas. - Linus Pauling
  • If you're not totally sure what your job is, it will always feel overwhelming. - David Allen
  • Let our advance worrying become advance thinking and planning. - Winston Churchill
  • People are always blaming their circumstances for what they are. I don't believe in circumstances. The people who get on in this world are the people who get up and look for the circumstances they want, and, if they can't find them, make them. - George Bernard Shaw

The thing I really liked about this book, besides all of the organizational tips/suggestions, is that Allen's basic premise is that you should find a system that works best for you. The same system will not work for everyone and he states that frequently. He suggests you use his processes, but also realizes that you might want to take a hybrid approach [what I have done] and is ok with that. He writes the book with an open mind which, in my opinion, makes him even more credible.

~tod

Don't Make Me Think by Steve Krug

MSDN Blogs - Fri, 07/03/2015 - 15:28

This post originally appeared on my old blog, dirtyDogStink, which has since been removed. I'm adding it here for reference purposes.

 

 

Don't Make Me Think: A Common Sense Approach to Web Usability by Steve Krug

I especially like this book because it is exactly what it claims to be: a relatively short, easy to read book about web usability. In fact, the author explicitly states that he "worked hard to keep this book short - hopefully short enough you can read it on a long plane ride." Being a very busy person at work and home I really, really appreciate this!

I highly recommend this book for: anyone who is the slightest bit involved in developing or designing a web site's user interface...period. The reason I say this is because:

  • it's a great starting point for someone who has no experience with web site usability.
  • it seems like a great [and quick] refresher for anyone who does have usability experience.
  • it's an interesting read because the author's character really comes through [versus being dry and boring].
  • it really is short enough for a long plane ride or a few nights 'bedtime reading.'

A few highlights of things I learned and/or appreciated:

  • First and foremost, don't make your users think! For example, descriptions [for categories, products, lists, etc.] should be clear and concise.
  • Users really don't read web pages, they just scan them for keywords.
  • Users satisfice when selecting where to go next on any given page. This basically means we tend to choose the first reasonable option instead of examining all of them before selecting one. And yes, I realized that I do this. 
  • Following conventions is a good thing. Forget about reinventing the wheel and just use techniques and design patterns that people are already comfortable with.
  • Keep the visual noise to a minimum [don't try to cram in everything and the kitchen sink].
  • Omit needless words. Get rid of half of the words on every single page. When you're done with that...do it again. It may sound harsh, but it's true.
  • The "You Are Here" theory. Make it blatantly obvious where you are in the site structure at all times [using page titles, highlighting, home link, tabs, etc.].
  • Always have a search box...unless your site is a single static .htm page. 
  • Keep the home page simple! Remember, it's purpose is simply to get across the big picture.
  • Usability testing doesn't have to be hard, in fact, it can be down right simple. Just grab your neighbor for 15 minutes.
  • Usability tests...small scope frequent testing is better than a single (or few) large scope test(s).
  • "The Reservoir of Goodwill" - Don't use it all up and try to refill it when you do use some!
  • Last, but certainly not least. Always keep accessibility in mind when designing. Steve is referring to Section 508 of the 1988 Amendments to the Rehabilitation Act, which specifies accessibility standards for information technology (like web sites).

Check out Steve's website, sensible.com, for more information about him and his book(s).

~tod

The Mythical Man-Month by Frederick P. Brooks, Jr.

MSDN Blogs - Fri, 07/03/2015 - 15:23

This post originally appeared on my old blog, dirtyDogStink, which has since been removed. I'm adding it here for reference purposes.

 

 

The Mythical Man-Month by Frederick P. Brooks, Jr.

Originally written in 1975 and then revised in 1995, I think this book truly withstands the test of time for the field of software development. It isn't full of checklists and to-dos that are guaranteed to make your projects work [no snake-oil here], but rather wisdom from an experienced software project manager. Several of the chapters are actually stand-alone essays and this book simply collates them in a logical manner. Most of the information is easy to read and moves pretty quickly, in fact, I actually finished it in about 10 days. As a busy person with several personal/professional interests and responsibilities, that means a lot to me because then I actually read the book instead of letting it drag out for months without ever finishing it.

Your first reaction might be "the book is 30 years old, what could possibly be relevant towards today's technologies?" You're right to be curious about that, as was I, since technology has made so many changes in the past 30 years. The wonderful thing about this book is that even in the initial publication the author recognizes the extreme rate at which technology advances and addresses it constantly. For the most part, Brooks speaks to technology as an idea/concept instead of talking directly to this or that programming language. That perspective allows the conversations to transcend most technological limitations that would have been present had he addressed explicit hardware or software technologies.

Although the title is The Mythical Man-Month, Brooks delves into several aspects of software development and highlights the challenges we face on a daily basis. As is my normal process, here are several points from the book that I found interesting:

  • Using the concept of a man-month [I suppose person-month would be the PC way of saying this] as a unit of estimating time to complete a project is really a fallacy. It is often assumed that men and months are "interchangeable commodities," but that only holds true if "a task can be partitioned among many workers with no communication among them." Adding more developers to a project will not result in it being completed sooner, in fact, most of the time it will increase the time due to the added complexities of communication.
  • Time estimation is the Achilles heel of software development projects [my words, not Brooks'] because "our techniques of estimating are poorly developed" and "fallaciously confuse effort with progress." Based on my 1-1/2 years of limited experience this still holds true today.
  • The surgical team concept as proposed by Harlan Mills - Each programming team should consist of a surgeon, copilot, administrator, editor, two secretaries, program clerk, toolsmith, tester and language lawyer. Some of the role responsibilities are obvious by their name, while the others are defined in the book. Suffice it to say that I equate this to the current process of agile programming with small teams.
  • "The Second-System Effect" - "As he designs the first work, frill after frill and embellishment after embellishment occur to him. These get stored away to be used 'next time.' ...This second is the most dangerous system a man ever designs....The general tendency is to over-design the second system....the result...is a 'big pile.'"
  • In the chapter, Why Did The Tower of Babel Fail?, Brooks states that lack of communication and the subsequent lack of organization are the culprits. He applies this theory to programming projects and how the increase of workers will drastically increase the likelihood of miscommunication, hence failure. Oh so true in my experience.
  • Catastrophic failures can be avoided by reducing a boss' role conflict. They must "distinguish between action information and status information. He must discipline himself not to act on problems his managers can solve, and never to act on problems when he is explicitly reviewing status." If front-line managers know their manager will not over react during status reports then they are much more likely to be honest in those status reports. Top-level management needs to trust their line managers to resolve conflicts and react only when asked to do so or when they absolutely have to.
  • One of the most interesting ideas presented [No Silver Bullet chapter] was that high-level languages (such as .NET and Java today) would not be a large breakthrough in the software development field. Brooks hypothesizes that "at some point the elaboration of a high-level language becomes a burden that increases, not reduces, the intellectual task of the user who rarely uses the esoteric constructs." I see his point, but I must disagree to an extent. While high-level languages obfuscate several fundamental concepts in software development they have broken down some of the traditional barriers by allowing non-CS graduates [like myself] to enter the field and be successful. I don't have a background in C or C++, but I am learning how to be a good developer through the massive resources available to me. Regardless of that, I was able to jump in and be productive within a very short time using .NET because I am a quick study and didn't have to learn memory management or object oriented programming first. Just to be clear, that first application I wrote looks un-Godly awful according to my standards today, but my point is that I was able to do it...not how well it was done.

I highly recommend this book for both software developers and project managers. Actually, I would like everyone involved in software development (developers, program managers, architects, testers, people managers, etc.) to read this book!

~tod

 

 

Friday Five on Windows

MSDN Blogs - Fri, 07/03/2015 - 12:45

Go into your weekend with these five tips on Windows from MVPs:

Windows Platform Development MVP – Brian Lagunas @brianlagunas
First Look at the Prism for Xamarin Forms

Windows Embedded MVP – Ken Marlin @WindowsChamp
It’s Time for Windows 10 IOT

Windows Platform Development MVP – Karthikeyan Anbarasan @f5Debug
Steps to Send Emails from Windows Store App for Developers

Windows Platform Development MVP – Michael Crump @mbcrump
5 Steps to an Ideal Windows 10 App Development Environment

Windows Platform Development MVP – Amr Khamise @amrKhamise
Build a Windows Universal App that Targets Windows 8.1 Devices

Part1: Introduction to N-Tier Modern Web Application

MSDN Blogs - Fri, 07/03/2015 - 12:35

We are living in the era of modern applications development where customer needs are changing all the time, I’ll be writing this blog Set to give the Developers who are struggling to build a modern, enterprise ready, that can scale based on customer needs. The Number of Technologies around us are too many and changing rapidly. So I’ll try to give everyone a startup architecture and design that they can use it to design and implement their solution as quickly as possible

Let’s Start this thread a start and think about what are the tools and Ideas We will be using to get this up and running.

We will be running our Solution on 2 Major Points, The Backend Planning and the Technology of Choice will be webAPIs on top of DBaaS and ASP.NET. The Front end will be JQuery Application and Will dicuss this in details after understanding what are we these 2 technologies provide us.

Back end Planning and What is Web APIs Web API Features
  1. It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
  2. Responses have an Accept header and HTTP status code.
  3. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
  4. It may accepts and generates the content which may not be object oriented like images, PDF files etc.
  5. It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  6. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.
Why to choose Web API ?
  1. If we need a Web Service and don’t need SOAP, then ASP.Net Web API is best choice.

  2. It is Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.

  3. Its Readable and Browser friendly it returns a string at the end of the day and how you want to format this string it’s all about your design needs

  4. It doesn't have tedious and extensive configuration like WCF REST service.

  5. Simple service creation with Web API. With WCF REST Services, service creation is difficult.

  6. It is only based on HTTP and easy to define, expose and consume in a REST-ful way.

  7. It is light weight architecture and good for devices which have limited bandwidth like smart phones.

  8. It is open source.

 

With that said our Backend will be designed on top of SQL and Web APIs N-Tier Architecture we will discuss this in details later on this blog.

 

Modern Web Apps

What is the Definition of a Modern web app this is a good question that comes to every developer mind when we think about their application is it a modern web app or no? The Answer is in the next few lines

 

Characteristics of Modern Web Applications

While there are many types of modern web applications, addressing many different needs, they all have some characteristics in common.

  • They are standards-focused. To have the broadest reach across multiple platforms and devices, applications attempt to implement the current and evolving standards and adopt future standards once ratified.
  • They are interactive. Modern web applications keep the user engaged by providing constant feedback on their actions. This feedback can come in the form of messages, animations to hide or show elements, mouse-over effects, drag and drop feedback, the automatic refreshing of screen data, animation of various elements, or the implementation of fade-in or fade-out effects. Interactive applications leverage the fast JavaScript engines in modern browsers to perform their client-side tasks.
  • They limit full-page reloads. Modern web applications seek to limit the number of full-page reloads. Reloads are much slower than a localized Ajax call to update a portion of the UI. Full-page reloads also limit the ability to animate state or page changes. By not performing a full-page reload, users can be kept in context, providing a fluid experience as they navigate from one task to another.
  • They are asynchronous. Modern web applications use Ajax to dynamically load data, page fragments, or other assets instead of performing a full-page reload to acquire data or HTML content. Because the loading of data is asynchronous, the UI is able to stay responsive and keep the user informed while the data request is being fulfilled. This asynchronous on-demand loading also reduces application response time because requests can be tuned to return only the data and other content that needs to change.
  • They manage data. When applicable, modern web applications provide client-side data caching and prefetching to boost client-side performance. This enables the UI to immediately respond to user input gestures because it does not have to make a call to the server for data. Data caching also serves to minimize the impact on server resources, increasing application scalability because fewer calls to the server are required.
Technologies

We will be using Lots of Technologies on this Project and since I am Just Getting Started to let’s List the Basic Technologies we will be using and More will be added based on the needs of each section.

Ajax

For over 10 years, the web has benefited from the ability to replace full-page reloads with Ajax calls. But given the advances in standards such as CSS3 and HTML5, browsers adherence to those standards, and the arrival of powerful, cross-browser JavaScript frameworks, we have all the tools necessary to build highly engaging client-side experiences.

Ajax facilitates a paradigm change in web development from the traditional full-page reload model of server-centric applications to rich, responsive client-centric applications. The client receives data and updates the UI using JavaScript. Bandwidth requirements are minimized because the server responds to requests by returning just the requested data instead of HTML pages (and all their elements) along with the data. The application runs faster because the data requests take less time to complete, and the UI is quickly updated without a full-page reload. Asynchronous calls are essential to keeping interactive and immersive applications responsive from the user's perspective.

JavaScript

JavaScript is a dynamic, functional, prototypal language that has a very close relationship with the document object model (DOM). For both JavaScript and the DOM, there are features you can use with confidence and others you should avoid. Over the past ten years, the web development community has learned a great deal about how to use these together to maximize success. See the "Further Reading" section for resources that explain the recommended ways of using JavaScript. Project Silk adheres to these practices, but we do not present a primer here.

As is true with all environments, you will be most successful using it as intended. If you aren't presently writing JavaScript code according to the patterns currently accepted in the JavaScript community, be sure your team has time to become familiar with them, because you may be surprised. For example, the Project Silk team members who had recently worked in the Microsoft .NET environment needed to ramp up on the following aspects of JavaScript:

  • JavaScript uses object-oriented concepts, but classes and inheritance hierarchies are not the same as in other .NET languages such as Visual C# and Visual Basic.NET.
  • Understanding closures and variable scoping is important. They are used intentionally and often by allowing variables defined within one scope to be used in another function.
  • The object that the this keyword refers to changes based on where it is used. For example in a single method, this may refer to the object the method is defined on, and in a loop within that same method this may refer to the current item of the collection being iterated over. You should understand its rules.
  • Objects without type definitions are very common and use an object literal syntax. The commas between properties and functions used in these object literals may cause syntax errors until you are familiar with them.
jQuery

jQuery is an open-source JavaScript library that addresses the challenges of working with the DOM across browsers. It has a straightforward API that can be divided into two calling conventions:

  • Functions are called on the jQuery object itself. For example, the extend function merges the properties and methods of two different objects together. It looks like this: $.extend(targetObject, objectToMerge).
  • Methods are called on the wrapped set. A wrapped set is the result of a query that uses a selector to find elements in the DOM. To call a method on a wrapped set of elements, a selector is used to select elements in the DOM. For example, to add the listing CSS class to all ul elements directly inside a div element, $('div ul').addClass('listing') can be used.

jQuery also provides features to raise and handle events, make Ajax requests, and process the data returned from Ajax requests. To be successful developing with jQuery, you should:

  • Know that the selector syntax uses and extends the CSS selector syntax. The better you're able to leverage this syntax, the cleaner your HTML can be.
  • Understand what the wrapped set is, how it's different from an array of DOM elements, and which you're working with at any given time. For example, when using $.each, inside the callback, this is not wrapped.
  • Understand that animations are asynchronous and are queued. Use a named queue or the stop method to gain more control over how the animations behave.
Modernizr

In the past, the client-side application would use navigator.userAgent to determine which browser was in use and choose its code paths accordingly. Today, the accepted practice is to explicitly detect each feature the application intends to use.

Modernizr is an open-source JavaScript library that detects the support for browser features (geolocation, canvas, SVG, border-radius, etc.) and exposes its findings in CSS and JavaScript. Once a script reference to Modernizr is included, Modernizr will add a CSS class to the html element for each feature it can detect. If the feature isn't supported, the CSS class will start with no-. For example, if a browser supports canvas and not webgl, its html element will look like this: <html class="canvas no-webgl ...">. Modernizr also exposes a Modernizr JavaScript object that has Boolean properties for each feature it can detect.

 

Lets Have a Break for now and The next Post will be about the Back end Basic Architecture so we can have something to kick of our Web Project with.

 

Windows 10 upgrade considerations for screen reader and magnifier users

MSDN Blogs - Fri, 07/03/2015 - 10:02

If you currently use Assistive Technologies (AT), like screen readers or magnifiers, your experience on Windows 10 will be similar in many ways to what you are accustomed to on Windows 7 and Windows 8.1. In addition, Windows 10 introduces new features and applications that will continue to improve as we deliver Windows as a service to our customers over time. Learn a few tips for a more accessible Windows 10 experience at the accessibility blog.

...(read more)

Why does the BackupWrite function take a pointer to a modifiable buffer when it shouldn't be modifying the buffer?

MSDN Blogs - Fri, 07/03/2015 - 07:00

The Backup­Write function takes a non-const pointer to the buffer to be written to the file being restored. Will it actually modify the buffer? Assuming it doesn't, why wasn't it declared const? It would be much more convenient if it took a const pointer to the buffer, so that people with const buffers didn't have to const_cast every time they called the function. Would changing the parameter from non-const to const create any compatibility problems?

Okay, let's take the questions in order.

Will it actually modify the buffer? No.

Why wasn't it declared const? My colleague Aaron Margosis explained that the function dates back to Windows NT 3.1, when const-correctness was rarely considered. A lot of functions from that area (particularly in the kernel) suffer from the same problem. For example, the computer name passed to the Reg­Connect­Registry function is a non-const pointer even though the function never reads from it.

Last question: Can the parameter be changed from non-const to const without breaking compatibility?

It would not cause problems from a binary compatibility standpoint, because a const pointer and a non-const pointer take the same physical form in Win32. However, it breaks source code compatiblity. Consider the following code fragment:

BOOL WINAPI TestModeBackupWrite( HANDLE hFile, LPBYTE lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, BOOL bAbort, BOOL bProcessSecurity, LPVOID *lpContext) { ... simulate a BackupWrite ... return TRUE; } BOOL (WINAPI *BACKUPWRITEPROC)(HANDLE, LPBYTE, DWORD, LPDWORD, BOOL, BOOL, LPVOID *); BACKUPWRITEPROC TestableBackupWrite; void SetTestMode(bool testing) { if (testing) { TestableBackupWrite = TestModeBackupWrite; } else { TestableBackupWrite = BackupWrite; } }

The idea here is that the program can be run in test mode, say to do a simulated restore. (You see this sort of thing a lot with DVD-burning software.) The program uses Testable­Backup­Write whenever it wants to write to a file being restored from backup. In test mode, Testable­Backup­Write points to the Test­Mode­Backup­Write function; in normal mode, it points to the Backup­Write function.

If the second parameter were changed from LPBYTE to const BYTE *, then the above code would hit a compiler error.

Mind you, maybe it's worth breaking some source code in order to get better const-correctness, but for now, the cost/benefit tradeoff biases toward leaving things alone.

UWP: How to handle changes of DependencyProperty

MSDN Blogs - Fri, 07/03/2015 - 04:30

Last time we discussed how to create our own state trigger. In order to do it we made some extensions of “view model” class in order to get information about changes in state of the model. We declared a delegate and an event there and additionally we injected code which initiated external event handlers. But in many cases you cannot modify a class which you are going to use in your trigger and the class doesn’t have needed events as well. In this case you can check dependency properties there.

Starting with Windows 10 you can handle changes in dependency properties even if the class doesn’t have any special events for it. It’s possible thanks to RegisterPropertyChangedCallback (and UnregisterPropertyChangedCallback) method which was included to DependencyObject class. Thanks to this method you can provide an event handler which fires when selected DependencyProperty is changed. This method is very useful for UWP controls when you need to track changes in existing controls but we can utilize this method in our classes as well.

Let’s try to modify classes from the previous post.

public enum StateEnum
{
Loading,
Loaded,
Error
}

public class PageViewModel: DependencyObject
{
public static readonly DependencyProperty StateProperty=DependencyProperty.Register("State",typeof(StateEnum), typeof(PageViewModel),new PropertyMetadata(null));

public StateEnum State
{
get
{
return (StateEnum)GetValue(StateProperty);
}
set
{
SetValue(StateProperty, value);
}
}

public void InitModel()
{
State = StateEnum.Loading;
//load data
State = StateEnum.Loaded;
}
}

You can see that I removed the delegate and the event and added a StateProperty dependency property. Right now code looks better and usually if you implement your own “view model” class you already have some dependency properties there and probably you should not change anything.

Of course, in order to work with dependency properties we use the SetValue and GetValue methods. We used standard approach there – created a wrapper property. It’s clear that all changes around DependencyProperty in UWP were implemented inside the SetValue method. It just executed all methods which were registered thanks to RegisterPropertyChangedCallback.

My state trigger will look different as well:

public class DataTrigger: StateTriggerBase
{
private PageViewModel model;

public PageViewModel Model
{
get
{
return model;
}
set
{
model = value;
model.RegisterPropertyChangedCallback(PageViewModel.StateProperty,
new DependencyPropertyChangedCallback(ChangeState));
}
}

private void ChangeState(DependencyObject obj, DependencyProperty pr)
{
SetActive(model.GetValue(PageViewModel.StateProperty).
ToString().Equals(StateOfModel));
}

public string StateOfModel { get; set; }
}

You can see that code looks better right now. Pay special attention that we use PageViewModel object to call RegisterPropertyChangedCallback method.

So, if you don’t have all needed events, check existing dependency properties and in many cases you find all that you need.

 

ConfigMgr 2012 : Supprimer un CAS au-dessus d’un primaire

MSDN Blogs - Fri, 07/03/2015 - 03:32

Comme vous le savez déjà si vous lisez régulièrement ce blog, je ne suis pas un fervent partisan de l’utilisation de site central d’administration ou CAS pour Central Administration Site. Je l’ai déjà évoqué ici, les principales raisons pour lesquelles de nombreux clients y ont recours ne sont généralement pas les bonnes.

Avec le service pack 1 de ConfigMgr 2012, il est apparu la possibilité de rajouter un CAS au-dessus d’un primaire autonome, mais l’inverse n’est, aujourd’hui, pas possible.

Comme je l’ai aussi évoqué ici, il existe une possibilité d’orienter les évolutions de ConfigMgr.

J’ai, donc, créé une entrée sur User Voice pour demander au groupe produit de développer une solution moins contraignante que de reconstruire une hiérarchie et d’utiliser l’assistant de migration, pour pouvoir supprimer un CAS devenu inutile.

Si vous trouvez l’idée séduisante, n’hésitez pas à voter pour cette idée !

Lessons in IT security: 5 rules small businesses need to follow by Matthew Stibbe

MSDN Blogs - Fri, 07/03/2015 - 02:30

When it comes to IT security, there’s no such thing as ‘too small to suffer.’


Cybercrime costs UK small businesses around £785 million per year. In 2014, over a third of spear-phishing attacks targeted small businesses and in the same year, the number of data breaches increased by 23 percent.

That’s why we’re sharing these top tips, which emerged from our latest small business mini-summit, ‘Safeguarding your Business’.

 1. Have an IT security policy

‘People think that security is a technical problem. It’s not. It’s a person problem,’ says Stuart Aston, National Security Officer for Microsoft UK.

Human behaviour is one of the biggest weaknesses in any defence system, so you need to inform and explain to your employees:

  • What the risks are
  • What data is valuable or critical to the business
  • How they should handle that data
  • The correct behaviour around and use of company systems and networks

Don’t be daunted by the thought of creating a deadweight document. An IT security policy can be short and to the point. Start by identifying what data matters most to your business and how you want it handled, and build from there. For example, insist on making use of the Information Rights Management feature in Office 365, to control changes and access to key documents.

2. Protect your passwords

Whether it’s remembering, storing or sharing them, passwords were a big topic at our summit. The key message from the experts? Passwords are private. They are there to protect both your data and your identity and they need to be treated with care. If you share a secret, like a password, it’s not a secret any more.

Think of them like credit card details: you wouldn’t store those on a post-it on your desk or give them away to contractors who need to make a one-off purchase for your business, so why do the same with a password.

  • Have a highly secure password for your most important login, a different one for a couple of the next most important, then another for the rest. While not ideal (you should have different passwords for everything) it does lower your risk of a breach to what matters most.
  • Do not use the same password for your primary work email and primary personal email.
  • Use a password management app such as LastPass, PassLock or 1Password.  
3. Make your devices ‘disposable’

Small businesses have benefited greatly from the increase in mobile and flexible working, but it has led to a reliance on easily lost or stolen devices.

Francesca Geens of Digital Dragonfly suggests using cloud services, like Office 365, cloud storage such as OneDrive for Business, and device encryption, such as BitLocker, to effectively make your tablets, laptops and mobiles ‘disposable.’

This means if one does go walkabouts, you can retract access to any cloud accounts remotely and ensure there’s no risk of a data leak.

At the same time you can buy a new device and have it up and running in no time, because all your data and applications are already in the cloud, ready to download to the new system.

4. Stay up to date

As quickly as new defences are created, cyber criminals evolve their tactics to find a way around them. That’s why it’s so important to stay on top of patches and updates. Every release includes a response to something new in the threat landscape and helps to keep you safe.

You should also make sure that every device has anti-virus software and a firewall enabled. Windows Defender, for example, comes built in to Windows 8 and Windows 10, and for those of you with something a little older, you can download Microsoft Security Essentials for free.

5. Get safe or go home

In today’s threat landscape, there’s no such thing as perfect security. That doesn’t mean it’s all doom and gloom: the better prepared you are, the smaller the impact on your business, so plan for ‘when’, not ‘if’, you suffer security incident.

Remember: nobody’s safe, but not everyone has to be a victim.

Check out more posts from Matthew Stibbe on his blog http://www.articulatemarketing.com/blog 

 

For more information on keeping your business secure you can also visit the Microsoft's Safeguard your business hub for further advice. 

Azure News on Friday (KW27/15)

MSDN Blogs - Fri, 07/03/2015 - 02:17

Auch diese Woche gab’s wieder viele Nachrichten zur Microsoft Azure Plattform. Hier sind nähere Infos dazu…

Aktuelle Neuigkeiten Datum Nachricht 02.07. Azure Preview Portal Improvements (June Update)
Neues im Azure Portal - Breadcrumb Navigation, List Refresh, kürzlich genutzte Ressourcen auf einen Blick etc. 02.07. A Brand New Docker Extension
Neue Docker Extension mit Docker Compose Support, Docker Hub/Registry Authentication Support etc. 02.07. Enabling Client Certificate Authentication for an Azure Web App
Authentifizierung bei Azure Web Apps via Client Zertifikat - hier steht wie's geht 01.07. Preview the new JDBC 4.2 for SQL Server Driver
Für alle Java Entwickler, die mit Azure SQL Database in der Public Cloud arbeiten wollen: JDBC 4.2 für SQL ist da! 01.07. Inside Azure Search: Chaos Engineering
Chaos Engineering in der Praxis - Design fehlertoleranter hoch-verfügbarer Cloud Dienste am Beispiel Azure Search 30.06. The Evolving Role of the Managed Service Provider
Ausführungen zum geänderten Verhältnis zwischen der Unternehmen und Service Providern und der Rolle der Cloud. 30.06. Azure SQL DB Previews Elastic Database Query
SQL Abfragen in einer Connection auf einen DB Pool absetzen mit der Azure SQL DB Elastic Database Query Preview 30.06. Tuesdays with Corey: Nano Coolness with Jeffrey Snover
In dieser Folge dreht sich bei Corey Sanders alles um den Nano Server 29.06. Try the new Azure Authenticator application!
Neue Azure Authenticator App veröffentlicht. Multi-Faktor Authentifizierung für Azure AD und weitere OAuth Dienste 26.06. Microsoft Named a Leader in Gartner’s Public Cloud Storage Services for Second Consecutive Year
Microsoft wiederholt als Leader in Gartners Magic Quadrant für Public Cloud Storage Services eingestuft Neue Kurse in der MVA Datum Nachricht 30.06. Building Infrastructure in Azure using Azure Resource Manager
Neuer kostenloser Kurs in der Microsoft Virtual Academy - Azure Umgebungen mit Azure Resource Manager aufbauen Neue Videos Datum Nachricht 02.07. Intro to Machine Learning with Seth Juarez
Einführung in Predictive Analytics mit Azure Machine Learning aka AzureML 02.07. What's new with the Azure CDN - June 2015
Neues im Azure CDN - Custom Origins, Multiple CDNs per Origin und flexiblerer Einsatz in Azure Web Apps

11

MSDN Blogs - Fri, 07/03/2015 - 00:54

sasa

10

MSDN Blogs - Fri, 07/03/2015 - 00:37

dsd

Change it!

change2

Experiencing Data Latency for Many Data Types - 7/3 - Investigating

MSDN Blogs - Thu, 07/02/2015 - 23:45
Update: Friday, 7/3/2015 07:15 UTC

Our DevOps team continues to investigate issues within Application Insights. Root cause is not fully understood at this time. Some customers continue to experience data latency for many data types. We are working to establish the start time for the issue, initial findings indicate that the problem began at 07/02 ~22:30 UTC. We currently have no estimate for resolution.

• Work Around: none
• Next Update: Before 07/03 15:00 UTC

-Application Insights Service Delivery Team

Initial Update: Friday, 7/3/2015 06:44 UTC

We are aware of issues within Application Insights and are actively investigating. Some customers may experience Data Latency. The following data types are affected: Customer Event, Dependency, Exception, Metric, Page Load, Page View, Performance Counter, Request.

• Work Around: none
• Next Update: Before 07/03 9:00 UTC

We are working hard to resolve this issue and apologize for any inconvenience.

-Application Insights Service Delivery Team
 

使用Visual C ++和Xamarin 进行Hyperlapse跨平台移动开发

MSDN Blogs - Thu, 07/02/2015 - 20:04
[原文发表地址] Hyperlapse cross-platform mobile development with Visual C++ and Xamarin [原文发表时间] 2015/06/26 11:14AM 微软 Hyperlapse Mobile 提供了一个机会,它可以把任何长视频变成短小精悍的版本,可以将一个在骑颠簸的自行车上拍摄的抖动视频转换为一个在家里花园散步时拍摄的平稳视频,您可以轻松地与朋友和家人分享。这项技术,在Windows Phone上是可用的, 在Android上也有一个beta版。它将是令人期待的,特别是那些有史以来通过实时视频记录短途旅行感到不满意的人。 对于专业的摄影者和视频爱好者, 微软Hyperlapse Pro 可以使用Windows计算机从任何的摄像机或设备上的视频镜头创建一个Hyperlapse,包括航拍镜头用无人机拍摄的视频设备。它开辟以前由于困难不能实现的可能性,即使不是不可能,那也只是对于经验老道的电影制片人。这篇博客谈论使用跨平台的Visual C ++和Xamarin如何开发Hyperlapse的解决方案。 ...(read more)

Dynamics CRM Online 2015 Update 1 新機能: Web API 開発者プレビュー その 11

MSDN Blogs - Thu, 07/02/2015 - 20:00

みなさん、こんにちは。

前回に引き続き Dynamics CRM Online 2015 Update 1 で提供される
Web API 開発者プレビューを T4 テンプレートで作成したクライアント
で利用する方法について紹介します。連載記事になるため以下の記事を
事前にご覧ください。

Web API 開発者プレビュー その 1
Web API 開発者プレビュー その 2
Web API 開発者プレビュー その 10

今回は前回作成した OData クライアントを利用したプログラムを
作成していきます。

OData クライアントの利用

プロジェクトの作成と準備

まずプロジェクトを準備します。

1. Visual Studio を起動して、新しいプロジェクトを作成します。

2. Visual C# | Windows デスクトップ | コンソールアプリケーション
を選択して、任意の名前を付けます。ここでは WebApiCrmClient と
しました。

3. プロジェクトを右クリック | NuGet パッケージの管理を選択します。

4. 左ペインでオンラインを選択して、”odata” で検索します。

5. 検索結果より ”OData Client for .NET” を選択してインストールします。

6. 同様に JSON.Net と Active Directory Authentication Library を追加します。

7. Program.cs ファイルを開き、以下の using ステートメントを追加します。

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using WebApiT4Client;

8.  クラスレベルのフィールドとして Main メソッドの前に以下を追加します。
clientId はこちらの記事で取得したものを入力してください。
※serverUrl をご利用の環境にアドレスに変更してください。

#region クラスレベルメンバー

static string serverUrl = "https://<CRM組織名>.crm7.dynamics.com";
static string authUrl = "https://login.windows.net/common";
static string clientId = "取得したIDを入力";
static string redirectUri = "http://localhost/webapipreview";

#endregion クラスレベルメンバー

9. Main メソッドに認証および実行部分とエラーハンドリングのコードを
追加します。

try
{
    AuthenticationContext authContext = new AuthenticationContext(authUrl);
    AuthenticationResult result = authContext.AcquireToken(serverUrl, clientId, new Uri(redirectUri));

    Program app = new Program();
    app.Run(result.AccessToken);
}          
catch (System.Exception ex)
{
    Console.WriteLine("エラーが発生しました。");
    Console.WriteLine(ex.Message);
}
finally
{
    Console.WriteLine("Press <Enter> to exit.");
    Console.ReadLine();

10. 最後に Run メソッドを追加します。

public void Run(string accessToken)
{
    // クライアントの作成
    CrmODataClient client = new CrmODataClient(new Uri(serverUrl + "/api/data/"));
    client.SendingRequest2 += (s, e) => { e.RequestMessage.SetHeader("Authorization", "Bearer " + accessToken); };

}

T4 テンプレートで作成したクライアントの追加

1. プロジェクトを右クリックして、追加 | 既存の項目を選択します。

2. 前回作成した CrmODataClient.cs ファイルを追加します。

3. 追加した CrmODataClient.cs を開きます。

4.  18 行目と 24 行目の System を CrmODataClient に変更します。

5. ソリューションを一旦ビルドします。

プログラムの実装

まず今回は取引先企業の取得を試します。

1. 上記追加した Run メソッドに以下のコードを追加します。
名前に「サンプル」を含むレコードを取得します。

// 取引先企業の取得
foreach (Account account in client.Accounts.Where(x => x.Name.Contains("サンプル")))
{
    Console.WriteLine("取引先企業名: {0}", account.Name);
}

2. 次に以下のコードを追加します。クエリを外だしにした
形です。

// クエリの作成
var query = from a in client.Accounts
            where a.Name.Contains("サンプル")
            select a;

// クエリの実行
foreach(var account in query)
{
    Console.WriteLine("取引先企業名: {0}", account.Name);
}

動作確認

1. F5 キーを押下してプログラムを実行します。

2. 認証ダイアログが表示されたらログインします。

3. 取引先企業の一覧が表示されることを確認します。

以下に Program.cs のコードを示します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using WebApiT4Client;

namespace WebApiCrmClient
{
    class Program
    {
        #region クラスレベルメンバー

         static string serverUrl = "https://<CRM組織名>.crm7.dynamics.com";
        static string authUrl = "https://login.windows.net/common";
        static string clientId = "取得したIDを入力";
        static string redirectUri = "http://localhost/webapipreview";

         #endregion クラスレベルメンバー

        public void Run(string accessToken)
        {
            // クライアントの作成
            CrmODataClient client = new CrmODataClient(new Uri(serverUrl + "/api/data/"));
            client.SendingRequest2 += (s, e) => { e.RequestMessage.SetHeader("Authorization", "Bearer " + accessToken); };


            // 取引先企業の取得
            foreach (Account account in client.Accounts.Where(x => x.Name.Contains("サンプル")))
            {
                Console.WriteLine("取引先企業名: {0}", account.Name);
            }
           
            // クエリの作成
            var query = from a in client.Accounts
                        where a.Name.Contains("サンプル")
                        select a;

            // クエリの実行
            foreach(var account in query)
            {
                Console.WriteLine("取引先企業名: {0}", account.Name);
            }
        }

        static void Main(string[] args)
        {
            try
            {
                AuthenticationContext authContext = new AuthenticationContext(authUrl);
                AuthenticationResult result = authContext.AcquireToken(serverUrl, clientId, new Uri(redirectUri));

                Program app = new Program();
                //Task.WaitAll(Task.Run(async () => await app.Run(result.AccessToken)));
                app.Run(result.AccessToken);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("エラーが発生しました。");
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }    
        }
    }
}

まとめ

HttpClient を利用した場合とは随分違う事が分かると思います。
次回はレコードの作成、読み取り、変更、削除を紹介します。
お楽しみに!

- 中村 憲一郎

Pages

Subscribe to Randy Riness @ SPSCC aggregator
Drupal 7 Appliance - Powered by TurnKey Linux